blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
feee20c620e42bd5440b720f168b2743b857df5e
7da6648b7b39329e49decc9f8103ce259ab37fbf
/TP/OnezFixMarket/include/ChangeNotice.h
08bfaa958749888a2a1b25be07016cc68b820251
[]
no_license
codingsf/source_code
8441775ccc89b0382b76bd9ceb6a6f8e47b7478c
7a247411a84386fa001882310e6478f9251b66f2
refs/heads/master
2020-03-22T03:37:04.588887
2018-06-12T06:25:12
2018-06-12T06:25:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,040
h
 /******************************************************************************************* *Department: TP *Decrible: spread change notice *Auhor: Savin *Createdtime: 2017-08-21 *ModifyTime: ********************************************************************************************/ #ifndef CHANGE_NOTICE_HEAD_H #define CHANGE_NOTICE_HEAD_H #include "tnode.h" using namespace snetwork_xservice_tnode; int ChangeNoticeInit(); class CChangeNoticeConsumer : public TNodeConsumer { public: CChangeNoticeConsumer(const char *bindingkey, const char *queuename ) { m_bindingkey = bindingkey ; m_queuename = queuename; } CChangeNoticeConsumer(){} std::string GetBindingkey(){ return m_bindingkey ; } std::string GetQueueName(){ return m_queuename ; } unsigned int ConsumerData(STTnodeDataPacketHeader *pHeader, char *pBody); private: std::string m_bindingkey ; std::string m_queuename ; }; #endif //CHANGE_NOTICE_HEAD_H
[ "kevin.fu@fintechstar.cn" ]
kevin.fu@fintechstar.cn
3119071abb7d7d27cdd5eb363316f2d6efb23a2e
184180d341d2928ab7c5a626d94f2a9863726c65
/issuestests/BNSL/inst/testfiles/Jeffreys_cmi/libFuzzer_Jeffreys_cmi/Jeffreys_cmi_DeepState_TestHarness.cpp
5ba40f08a98782f0aa1cf82040945ecaf3b4b00d
[]
no_license
akhikolla/RcppDeepStateTest
f102ddf03a22b0fc05e02239d53405c8977cbc2b
97e73fe4f8cb0f8e5415f52a2474c8bc322bbbe5
refs/heads/master
2023-03-03T12:19:31.725234
2021-02-12T21:50:12
2021-02-12T21:50:12
254,214,504
2
1
null
null
null
null
UTF-8
C++
false
false
3,024
cpp
#include <fstream> #include <RInside.h> #include <iostream> #include <RcppDeepState.h> #include <qs.h> #include <DeepState.hpp> double Jeffreys_cmi(NumericVector x, NumericVector y, NumericVector z, int m_x, int m_y, int m_z); TEST(BNSL_deepstate_test,Jeffreys_cmi_test){ static int rinside_flag = 0; if(rinside_flag == 0) { rinside_flag = 1; RInside R; } std::time_t current_timestamp = std::time(0); std::cout << "input starts" << std::endl; NumericVector x = RcppDeepState_NumericVector(); std::string x_t = "/home/akhila/R/x86_64-pc-linux-gnu-library/3.6/RcppDeepState/extdata/issuestests/BNSL/inst/testfiles/Jeffreys_cmi/libFuzzer_Jeffreys_cmi/libfuzzer_inputs/" + std::to_string(current_timestamp) + "_x.qs"; qs::c_qsave(x,x_t, "high", "zstd", 1, 15, true, 1); std::cout << "x values: "<< x << std::endl; NumericVector y = RcppDeepState_NumericVector(); std::string y_t = "/home/akhila/R/x86_64-pc-linux-gnu-library/3.6/RcppDeepState/extdata/issuestests/BNSL/inst/testfiles/Jeffreys_cmi/libFuzzer_Jeffreys_cmi/libfuzzer_inputs/" + std::to_string(current_timestamp) + "_y.qs"; qs::c_qsave(y,y_t, "high", "zstd", 1, 15, true, 1); std::cout << "y values: "<< y << std::endl; NumericVector z = RcppDeepState_NumericVector(); std::string z_t = "/home/akhila/R/x86_64-pc-linux-gnu-library/3.6/RcppDeepState/extdata/issuestests/BNSL/inst/testfiles/Jeffreys_cmi/libFuzzer_Jeffreys_cmi/libfuzzer_inputs/" + std::to_string(current_timestamp) + "_z.qs"; qs::c_qsave(z,z_t, "high", "zstd", 1, 15, true, 1); std::cout << "z values: "<< z << std::endl; IntegerVector m_x(1); m_x[0] = RcppDeepState_int(); std::string m_x_t = "/home/akhila/R/x86_64-pc-linux-gnu-library/3.6/RcppDeepState/extdata/issuestests/BNSL/inst/testfiles/Jeffreys_cmi/libFuzzer_Jeffreys_cmi/libfuzzer_inputs/" + std::to_string(current_timestamp) + "_m_x.qs"; qs::c_qsave(m_x,m_x_t, "high", "zstd", 1, 15, true, 1); std::cout << "m_x values: "<< m_x << std::endl; IntegerVector m_y(1); m_y[0] = RcppDeepState_int(); std::string m_y_t = "/home/akhila/R/x86_64-pc-linux-gnu-library/3.6/RcppDeepState/extdata/issuestests/BNSL/inst/testfiles/Jeffreys_cmi/libFuzzer_Jeffreys_cmi/libfuzzer_inputs/" + std::to_string(current_timestamp) + "_m_y.qs"; qs::c_qsave(m_y,m_y_t, "high", "zstd", 1, 15, true, 1); std::cout << "m_y values: "<< m_y << std::endl; IntegerVector m_z(1); m_z[0] = RcppDeepState_int(); std::string m_z_t = "/home/akhila/R/x86_64-pc-linux-gnu-library/3.6/RcppDeepState/extdata/issuestests/BNSL/inst/testfiles/Jeffreys_cmi/libFuzzer_Jeffreys_cmi/libfuzzer_inputs/" + std::to_string(current_timestamp) + "_m_z.qs"; qs::c_qsave(m_z,m_z_t, "high", "zstd", 1, 15, true, 1); std::cout << "m_z values: "<< m_z << std::endl; std::cout << "input ends" << std::endl; try{ Jeffreys_cmi(x,y,z,m_x[0],m_y[0],m_z[0]); } catch(Rcpp::exception& e){ std::cout<<"Exception Handled"<<std::endl; } }
[ "akhilakollasrinu424jf@gmail.com" ]
akhilakollasrinu424jf@gmail.com
616a011c055c83008ce0cb4db4ba21992e22275d
5ebd5cee801215bc3302fca26dbe534e6992c086
/blazetest/src/mathtest/smatsmatschur/MCaMCa.cpp
39f785121a4a4bfb9b0dfad76597796ad4037909
[ "BSD-3-Clause" ]
permissive
mhochsteger/blaze
c66d8cf179deeab4f5bd692001cc917fe23e1811
fd397e60717c4870d942055496d5b484beac9f1a
refs/heads/master
2020-09-17T01:56:48.483627
2019-11-20T05:40:29
2019-11-20T05:41:35
223,951,030
0
0
null
null
null
null
UTF-8
C++
false
false
4,326
cpp
//================================================================================================= /*! // \file src/mathtest/smatsmatschur/MCaMCa.cpp // \brief Source file for the MCaMCa sparse matrix/sparse matrix Schur product math test // // Copyright (C) 2012-2019 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. Redistribution and use in source and binary // forms, with or without modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // 3. Neither the names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <blaze/math/CompressedMatrix.h> #include <blazetest/mathtest/Creator.h> #include <blazetest/mathtest/smatsmatschur/OperationTest.h> #include <blazetest/system/MathTest.h> #ifdef BLAZE_USE_HPX_THREADS # include <hpx/hpx_main.hpp> #endif //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running 'MCaMCa'..." << std::endl; using blazetest::mathtest::TypeA; try { // Matrix type definitions using MCa = blaze::CompressedMatrix<TypeA>; // Creator type definitions using CMCa = blazetest::Creator<MCa>; // Running tests with small matrices for( size_t i=0UL; i<=6UL; ++i ) { for( size_t j=0UL; j<=6UL; ++j ) { for( size_t k=0UL; k<=i*j; ++k ) { for( size_t l=0UL; l<=i*j; ++l ) { RUN_SMATSMATSCHUR_OPERATION_TEST( CMCa( i, j, k ), CMCa( i, j, l ) ); } } } } // Running tests with large matrices RUN_SMATSMATSCHUR_OPERATION_TEST( CMCa( 67UL, 67UL, 7UL ), CMCa( 67UL, 67UL, 7UL ) ); RUN_SMATSMATSCHUR_OPERATION_TEST( CMCa( 67UL, 127UL, 13UL ), CMCa( 67UL, 127UL, 13UL ) ); RUN_SMATSMATSCHUR_OPERATION_TEST( CMCa( 128UL, 64UL, 8UL ), CMCa( 128UL, 64UL, 8UL ) ); RUN_SMATSMATSCHUR_OPERATION_TEST( CMCa( 128UL, 128UL, 16UL ), CMCa( 128UL, 128UL, 16UL ) ); } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during sparse matrix/sparse matrix Schur product:\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
[ "klaus.iglberger@gmail.com" ]
klaus.iglberger@gmail.com
357f8d5560b4fb1beedac9ec1ba392fc7f647380
aa75bbca0d604d998deaabe65ff543aacd60ff2b
/source/sprites/AudioSprite.cpp
4f722881a1dc13ba2a46c52d3a6ce3646485a27f
[ "MIT" ]
permissive
xzrunner/sprite2
0aa2d81f99c3d7e92eeb29259a61eafd69091ed5
2d5d8c6b79a63871bdd6cfdcd4805946fde95921
refs/heads/master
2021-01-12T12:00:50.408133
2018-03-23T03:47:21
2018-03-23T03:47:21
68,875,579
0
0
null
null
null
null
UTF-8
C++
false
false
4,226
cpp
#include "sprite2/AudioSprite.h" #include "sprite2/AudioSymbol.h" #ifndef S2_DISABLE_STATISTICS #include "sprite2/StatSprCount.h" #endif // S2_DISABLE_STATISTICS #include "sprite2/AudioContext.h" #include <uniaudio/Source.h> #include <uniaudio/Exception.h> #include <logger.h> namespace s2 { AudioSprite::AudioSprite() : m_volume(1) , m_offset(0) , m_duration(0) , m_fade_in(0) , m_fade_out(0) { #ifndef S2_DISABLE_STATISTICS StatSprCount::Instance()->Add(STAT_SYM_AUDIO); #endif // S2_DISABLE_STATISTICS } AudioSprite::AudioSprite(const AudioSprite& spr) : Sprite(spr) , m_volume(spr.m_volume) , m_offset(spr.m_offset) , m_duration(spr.m_duration) , m_fade_in(spr.m_fade_in) , m_fade_out(spr.m_fade_out) { #ifndef S2_DISABLE_STATISTICS StatSprCount::Instance()->Add(STAT_SYM_AUDIO); #endif // S2_DISABLE_STATISTICS if (spr.m_source) { m_source = spr.m_source->Clone(); } } AudioSprite& AudioSprite::operator = (const AudioSprite& spr) { Sprite::operator = (spr); if (spr.m_source) { m_source = spr.m_source->Clone(); } m_volume = spr.m_volume; m_offset = spr.m_offset; m_duration = spr.m_duration; m_fade_in = spr.m_fade_in; m_fade_out = spr.m_fade_out; return *this; } AudioSprite::AudioSprite(const SymPtr& sym, uint32_t id) : Sprite(sym, id) , m_volume(1) , m_offset(0) , m_duration(0) , m_fade_in(0) , m_fade_out(0) { #ifndef S2_DISABLE_STATISTICS StatSprCount::Instance()->Add(STAT_SYM_AUDIO); #endif // S2_DISABLE_STATISTICS } AudioSprite::~AudioSprite() { #ifndef S2_DISABLE_STATISTICS StatSprCount::Instance()->Subtract(STAT_SYM_AUDIO); #endif // S2_DISABLE_STATISTICS } void AudioSprite::OnMessage(const UpdateParams& up, Message msg) { switch (msg) { case MSG_PLAY: Play(); break; case MSG_STOP: Stop(); break; case MSG_TRIGGER: Play(); break; } } void AudioSprite::SetSource(const std::shared_ptr<ua::Source>& src) { m_source = src; m_volume = src->GetOriVolume(); m_offset = src->GetOffset(); m_duration = src->GetDuration(); m_fade_in = src->GetFadeIn(); m_fade_out = src->GetFadeOut(); } void AudioSprite::Play() { if (!AudioContext::IsEnable() || !m_source) { return; } try { m_source->Play(); } catch (ua::Exception& e) { LOGW("audio play err: %s\n", e.what()); } } void AudioSprite::Stop() { if (!AudioContext::IsEnable() || !m_source) { return; } try { m_source->Stop(); } catch (ua::Exception& e) { LOGW("audio stop err: %s\n", e.what()); } } void AudioSprite::Pause() { if (!AudioContext::IsEnable() || !m_source) { return; } try { m_source->Pause(); } catch (ua::Exception& e) { LOGW("audio pause err: %s\n", e.what()); } } void AudioSprite::Resume() { if (!AudioContext::IsEnable() || !m_source) { return; } try { m_source->Resume(); } catch (ua::Exception& e) { LOGW("audio resume err: %s\n", e.what()); } } void AudioSprite::Seek(float offset) { if (!AudioContext::IsEnable() || !m_source) { return; } try { m_source->Seek(offset); } catch (ua::Exception& e) { LOGW("audio seek err: %s\n", e.what()); } } void AudioSprite::SetVolume(float volume) { if (!m_source) { return; } m_volume = volume; try { m_source->SetOriVolume(volume); } catch (ua::Exception& e) { LOGW("audio set volume err: %s\n", e.what()); } } void AudioSprite::SetFadeIn(float fade_in) { if (!m_source) { return; } m_fade_in = fade_in; try { m_source->SetFadeIn(fade_in); } catch (ua::Exception& e) { LOGW("audio set fade in err: %s\n", e.what()); } } void AudioSprite::SetFadeOut(float fade_out) { if (!m_source) { return; } m_fade_out = fade_out; try { m_source->SetFadeOut(fade_out); } catch (ua::Exception& e) { LOGW("audio set fade out err: %s\n", e.what()); } } void AudioSprite::SetAudioOffset(float offset) { if (!m_source) { return; } m_offset = offset; try { m_source->SetOffset(offset); } catch (ua::Exception& e) { LOGW("audio set offset err: %s\n", e.what()); } } void AudioSprite::SetAudioDuration(float duration) { if (!m_source) { return; } m_duration = duration; try { m_source->SetDuration(duration); } catch (ua::Exception& e) { LOGW("audio set duration err: %s\n", e.what()); } } }
[ "zhuguang@ejoy.com" ]
zhuguang@ejoy.com
7d1ff8991bd4970228c7abebb20753c91fa0111c
4732d769727da7e6e190de03b96e3b905966651c
/MMI_main.cpp
4a71703d0848694304f7f5e90f08ae8c94fc5a4f
[]
no_license
GeekWenWang/iCNC-moblie-program
0f3b1a4f7058e4664312a787431a0a3007e775e3
ad5294ac9ebf06e43ac675e9cf5a33ef65de463b
refs/heads/master
2021-04-12T09:59:15.593882
2016-06-13T12:58:58
2016-06-13T12:58:58
59,886,064
0
0
null
null
null
null
UTF-8
C++
false
false
789
cpp
#include "stdafx.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "..\..\UTINITY\INC\utinity.h" #include "..\..\CNC\INC\cnc.h" extern CNC_DATA* cncDataPtr; //********************************************************* // //********************************************************* int mmiMain(MMI_DATA* mmiDataPtr) { bool run = true; while(run) { switch(mmiDataPtr->mmiState) { case MMI_IDLE: mmiIdle(mmiDataPtr); break; case MEM_STATE: mmiMemState(mmiDataPtr); run = false; break; case JOG_STATE: mmiJogState(mmiDataPtr); run = false; break; case MMI_RESET: mmiReset(mmiDataPtr); run = false; break; default: break; } }//while return 1; }//mmiMain
[ "wen850429@gmail.com" ]
wen850429@gmail.com
978ab7de5fe862696937d626014a0e7aef14e69e
fb6b653d2f1676b40ab75443edc2a3187cf00606
/Chapter13/exercises/13.13/Shape.h
3ca2d3cb09af520bee714c60ad3aa9a6182804e4
[]
no_license
wenjing219/Cpp-How-To-Program-9E
4cd923de658a90f3d3bfd0e4c0b3e8505d3a8472
8a6e2d1bc84e94fc598e258b9b151aa40895b21e
refs/heads/master
2021-01-22T22:16:24.824817
2017-03-14T22:14:40
2017-03-14T22:14:40
85,525,193
2
0
null
2017-03-20T02:04:41
2017-03-20T02:04:41
null
UTF-8
C++
false
false
812
h
/* * ===================================================================================== * * Filename: Shape.h * * Description: Exercie 13.13 - Shape Hierarchy * * Version: 1.0 * Created: 17/08/16 14:26:16 * Revision: none * Compiler: gcc * * Author: Siidney Watson - siidney.watson.work@gmail.com * Organization: LolaDog Studio * * ===================================================================================== */ #pragma once class Shape{ public: Shape(double = 0.0f, double = 0.0f); void setLength(double); double getLength() const; void setWidth(double); double getWidth() const; virtual void print() const = 0; private: double length; double width; };
[ "siidney.watson.work@gmail.com" ]
siidney.watson.work@gmail.com
8af16510b0e8117db01ed198dfed49b8ca560124
e480f4867a041bb4603b546e916ad8e02e0631b9
/t5/t5/myClass.cpp
ea19f9f0ec77b92ad81b93c3219e6e456ac67f5e
[]
no_license
barinova/pract1
e991ab87fbf70d639a923fead71fd3e9db234682
fb48f77f518f182f461cb5517f708862bf179425
refs/heads/master
2020-04-14T04:26:24.487505
2013-07-15T09:49:07
2013-07-15T09:49:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
852
cpp
#include "myClass.h" using namespace std; myClass::myClass(void) { createString(); } myClass::myClass(char* tmp) { str = tmp; } myClass::~myClass(void) { delete[] this; } void myClass::createString() { cout << "Enter a string: "; getline(cin, str); } void myClass::addString() { string tmp; int pos; cout << "Enter substring: "; getline(cin, tmp); cout << "Enter position: "; cin >> pos; str.insert( pos, tmp); cout << str; } void myClass::findString() { string tmp; int pos; cout << "Enter substring: " << endl; cin >> tmp; //getline(cin, tmp); pos = str.find(tmp); if (pos == string::npos) cout << "\nString not contain substring: " << tmp<< endl; else { cout << "\nString contain substring: " << viewSubstring(tmp) << " in position " << pos << endl; } } string myClass::viewSubstring(string tmp) { return tmp; }
[ "barinovaanastasija@gmail.com" ]
barinovaanastasija@gmail.com
e6fbd513047c6041735f17f71b912181d83ce592
27d319a8c9c41176e342911f38c9379dac819e33
/src/sync.h
9531480dd7d975fe60b2a9053070f1b0e7ad9094
[ "MIT" ]
permissive
HuntCoinDeveloper/huntcoin
6ec86d4904313408ad4a3e7721e01c650eab048e
99198152d21b58ce598f46783074b64113cc5e64
refs/heads/master
2020-05-18T18:00:54.723915
2019-05-17T15:09:06
2019-05-17T15:09:06
184,568,978
2
0
null
null
null
null
UTF-8
C++
false
false
7,736
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2017 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef HUNTCOIN_SYNC_H #define HUNTCOIN_SYNC_H #include <threadsafety.h> #include <condition_variable> #include <thread> #include <mutex> //////////////////////////////////////////////// // // // THE SIMPLE DEFINITION, EXCLUDING DEBUG CODE // // // //////////////////////////////////////////////// /* CCriticalSection mutex; std::recursive_mutex mutex; LOCK(mutex); std::unique_lock<std::recursive_mutex> criticalblock(mutex); LOCK2(mutex1, mutex2); std::unique_lock<std::recursive_mutex> criticalblock1(mutex1); std::unique_lock<std::recursive_mutex> criticalblock2(mutex2); TRY_LOCK(mutex, name); std::unique_lock<std::recursive_mutex> name(mutex, std::try_to_lock_t); ENTER_CRITICAL_SECTION(mutex); // no RAII mutex.lock(); LEAVE_CRITICAL_SECTION(mutex); // no RAII mutex.unlock(); */ /////////////////////////////// // // // THE ACTUAL IMPLEMENTATION // // // /////////////////////////////// /** * Template mixin that adds -Wthread-safety locking * annotations to a subset of the mutex API. */ template <typename PARENT> class LOCKABLE AnnotatedMixin : public PARENT { public: void lock() EXCLUSIVE_LOCK_FUNCTION() { PARENT::lock(); } void unlock() UNLOCK_FUNCTION() { PARENT::unlock(); } bool try_lock() EXCLUSIVE_TRYLOCK_FUNCTION(true) { return PARENT::try_lock(); } }; #ifdef DEBUG_LOCKORDER void EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry = false); void LeaveCritical(); std::string LocksHeld(); void AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, void* cs); void AssertLockNotHeldInternal(const char* pszName, const char* pszFile, int nLine, void* cs); void DeleteLock(void* cs); #else void static inline EnterCritical(const char* pszName, const char* pszFile, int nLine, void* cs, bool fTry = false) {} void static inline LeaveCritical() {} void static inline AssertLockHeldInternal(const char* pszName, const char* pszFile, int nLine, void* cs) {} void static inline AssertLockNotHeldInternal(const char* pszName, const char* pszFile, int nLine, void* cs) {} void static inline DeleteLock(void* cs) {} #endif #define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs) #define AssertLockNotHeld(cs) AssertLockNotHeldInternal(#cs, __FILE__, __LINE__, &cs) /** * Wrapped mutex: supports recursive locking, but no waiting * TODO: We should move away from using the recursive lock by default. */ class CCriticalSection : public AnnotatedMixin<std::recursive_mutex> { public: ~CCriticalSection() { DeleteLock((void*)this); } }; /** Wrapped mutex: supports waiting but not recursive locking */ typedef AnnotatedMixin<std::mutex> CWaitableCriticalSection; /** Just a typedef for std::condition_variable, can be wrapped later if desired */ typedef std::condition_variable CConditionVariable; /** Just a typedef for std::unique_lock, can be wrapped later if desired */ typedef std::unique_lock<std::mutex> WaitableLock; #ifdef DEBUG_LOCKCONTENTION void PrintLockContention(const char* pszName, const char* pszFile, int nLine); #endif /** Wrapper around std::unique_lock<CCriticalSection> */ class SCOPED_LOCKABLE CCriticalBlock { private: std::unique_lock<CCriticalSection> lock; void Enter(const char* pszName, const char* pszFile, int nLine) { EnterCritical(pszName, pszFile, nLine, (void*)(lock.mutex())); #ifdef DEBUG_LOCKCONTENTION if (!lock.try_lock()) { PrintLockContention(pszName, pszFile, nLine); #endif lock.lock(); #ifdef DEBUG_LOCKCONTENTION } #endif } bool TryEnter(const char* pszName, const char* pszFile, int nLine) { EnterCritical(pszName, pszFile, nLine, (void*)(lock.mutex()), true); lock.try_lock(); if (!lock.owns_lock()) LeaveCritical(); return lock.owns_lock(); } public: CCriticalBlock(CCriticalSection& mutexIn, const char* pszName, const char* pszFile, int nLine, bool fTry = false) EXCLUSIVE_LOCK_FUNCTION(mutexIn) : lock(mutexIn, std::defer_lock) { if (fTry) TryEnter(pszName, pszFile, nLine); else Enter(pszName, pszFile, nLine); } CCriticalBlock(CCriticalSection* pmutexIn, const char* pszName, const char* pszFile, int nLine, bool fTry = false) EXCLUSIVE_LOCK_FUNCTION(pmutexIn) { if (!pmutexIn) return; lock = std::unique_lock<CCriticalSection>(*pmutexIn, std::defer_lock); if (fTry) TryEnter(pszName, pszFile, nLine); else Enter(pszName, pszFile, nLine); } ~CCriticalBlock() UNLOCK_FUNCTION() { if (lock.owns_lock()) LeaveCritical(); } operator bool() { return lock.owns_lock(); } }; #define PASTE(x, y) x ## y #define PASTE2(x, y) PASTE(x, y) #define LOCK(cs) CCriticalBlock PASTE2(criticalblock, __COUNTER__)(cs, #cs, __FILE__, __LINE__) #define LOCK2(cs1, cs2) CCriticalBlock criticalblock1(cs1, #cs1, __FILE__, __LINE__), criticalblock2(cs2, #cs2, __FILE__, __LINE__) #define TRY_LOCK(cs, name) CCriticalBlock name(cs, #cs, __FILE__, __LINE__, true) #define ENTER_CRITICAL_SECTION(cs) \ { \ EnterCritical(#cs, __FILE__, __LINE__, (void*)(&cs)); \ (cs).lock(); \ } #define LEAVE_CRITICAL_SECTION(cs) \ { \ (cs).unlock(); \ LeaveCritical(); \ } class CSemaphore { private: std::condition_variable condition; std::mutex mutex; int value; public: explicit CSemaphore(int init) : value(init) {} void wait() { std::unique_lock<std::mutex> lock(mutex); condition.wait(lock, [&]() { return value >= 1; }); value--; } bool try_wait() { std::lock_guard<std::mutex> lock(mutex); if (value < 1) return false; value--; return true; } void post() { { std::lock_guard<std::mutex> lock(mutex); value++; } condition.notify_one(); } }; /** RAII-style semaphore lock */ class CSemaphoreGrant { private: CSemaphore* sem; bool fHaveGrant; public: void Acquire() { if (fHaveGrant) return; sem->wait(); fHaveGrant = true; } void Release() { if (!fHaveGrant) return; sem->post(); fHaveGrant = false; } bool TryAcquire() { if (!fHaveGrant && sem->try_wait()) fHaveGrant = true; return fHaveGrant; } void MoveTo(CSemaphoreGrant& grant) { grant.Release(); grant.sem = sem; grant.fHaveGrant = fHaveGrant; fHaveGrant = false; } CSemaphoreGrant() : sem(nullptr), fHaveGrant(false) {} explicit CSemaphoreGrant(CSemaphore& sema, bool fTry = false) : sem(&sema), fHaveGrant(false) { if (fTry) TryAcquire(); else Acquire(); } ~CSemaphoreGrant() { Release(); } operator bool() const { return fHaveGrant; } }; #endif // HUNTCOIN_SYNC_H
[ "github@huntcoin.africa" ]
github@huntcoin.africa
467272a842cc0f95d4b4bc252a73168b11c32c35
3b1ad16c4433c6a8dd4460758a459c16ae23531f
/source/config.hpp
80195e10e6d3180be92e0eab24b9457abece2568
[]
no_license
SRaimondi/OpenCLPlayground
ccb39774ed9392a8ccd534130e9a358fde67c021
4e0cdaa9208328b6f8bd53fe5af7a4d134ed84eb
refs/heads/master
2020-04-12T04:58:32.421939
2020-02-08T10:08:06
2020-02-08T10:08:06
162,199,787
0
0
null
null
null
null
UTF-8
C++
false
false
1,685
hpp
// // Created by simon on 12/18/2018. // #ifndef OPENCLPLAYGROUND_CONFIG_HPP #define OPENCLPLAYGROUND_CONFIG_HPP // Find the version of C++ #define CXX_98 199711L #define CXX_11 201103L #define CXX_14 201402L #define CXX_17 201702L #ifndef CXX_VERSION #if __cplusplus >= CXX_98 #define CXX_VERSION CXX_98 #endif #if __cplusplus >= CXX_11 #undef CXX_VERSION #define CXX_VERSION CXX_11 #endif #if __cplusplus >= CXX_14 #undef CXX_VERSION #define CXX_VERSION CXX_14 #endif #if __cplusplus >= CXX_17 #undef CXX_VERSION #define CXX_VERSION CXX_17 #endif #endif // Check if the CXX_VERSION was determined #ifndef CXX_VERSION #error "Could not define the C++ standard version" #endif // Check we have at least C++11 #if CXX_VERSION < CXX_11 #error "C++ version is too old, minimum required is C++11" #endif // Define inline keyword #ifndef CXX_INLINE #define CXX_INLINE inline #endif // Define noexcept keyword #if CXX_VERSION >= CXX_11 #define CXX_NOEXCEPT noexcept #else #define CXX_NOEXCEPT #endif // Check if constexpr is available #ifndef CXX_CONSTEXPR #if CXX_VERSION >= CXX_11 #define CXX_CONSTEXPR constexpr #else #define CXX_CONSTEXPR CXX_INLINE #endif #endif // Check if we can use constexpr for C++ 14 / 17 #ifndef CXX14_CONSTEXPR #if CXX_VERSION >= CXX_14 #define CXX14_CONSTEXPR constexpr #else #define CXX14_CONSTEXPR CXX_INLINE #endif #endif #ifndef CXX17_CONSTEXPR #if CXX_VERSION >= CXX_17 #define CXX17_CONSTEXPR constexpr #else #define CXX17_CONSTEXPR CXX_INLINE #endif #endif // Alignment specifier #if CXX_VERSION >= CXX_11 #define CXX_ALIGNAS(alignment) alignas(alignment) #else #define CXX_ALIGNAS(alignment) #endif #endif //OPENCLPLAYGROUND_CONFIG_HPP
[ "simone.raimondi@arbrea-labs.com" ]
simone.raimondi@arbrea-labs.com
36f71d30e6d51c539d531cede18eccc21af00221
04865343ed707b599957696ecf55440dc0e97fdc
/communicationmanager.h
fd2e18ed86d06e110c89eb52ad00fdf88f18e2f6
[]
no_license
jingedawang/ss-palm2015
c9d541b50f8f7dbebcfdc10a39755b5aef7895b2
d07a889f58ea8007000d1a3190f306f076c82766
refs/heads/master
2021-01-20T07:27:49.433736
2017-08-27T09:56:09
2017-08-27T09:56:09
101,540,075
1
0
null
null
null
null
UTF-8
C++
false
false
1,807
h
/************************************************************ * Copyright: IECAS * Author: WangJinge * Date: 2015-05-22 * Filename: communicationmanager.h * Description: CommunicationManager类的头文件。该类实现了单例模式, * 提供了使用地址创建Communication对象的方法,获取已创建的Communication * 对象的方法,以及进入或退出远程模式的方法。 * Version: 1.0 ************************************************************/ #ifndef COMMUNICATIONMANAGER_H #define COMMUNICATIONMANAGER_H #include <QObject> #include <QList> #include "communication.h" class CommunicationManager : public QObject { Q_OBJECT public: ~CommunicationManager(); //析构函数 static CommunicationManager *getInstance(); //[静态]本类型单例的获取方法 Communication *createCommunication(QString IP); //使用给定的IP获得Communication对象 Communication *getCommunication(); //获取已创建的Communication对象 void enterRemoteMode(); //进入远程模式 void quitRemoteMode(); //退出远程模式 void deleteCommunication(); //删除已创建的Communication对象 private: CommunicationManager(QObject *parent = 0); //构造函数 static CommunicationManager *manager; //[静态]本类型单例 QList<Communication *> communicationList; //保存本地连接的Communication列表 QList<Communication *> remoteCommunicationList; //保存远程连接的Communication列表 bool remoteMode; //远程模式标志 }; #endif // COMMUNICATIONMANAGER_H
[ "wjg172184@163.com" ]
wjg172184@163.com
181e6af8097b6e2ee9479e4f9c521fe768aa2d7b
3b0f743c2268f8d69bb51c1e0dd0aa4afcc03af0
/examples/C++/inheritance.h
0ce1de4c5455fa147f9edf88ded9be18697f80ca
[ "MIT" ]
permissive
koala-team/serializer
26413e8f24f88bbc20f06083754b8432dd41d445
04e8109fe3e4c2fc80c3ccb748d187417760d159
refs/heads/master
2020-03-15T18:10:22.621464
2019-09-02T23:20:13
2019-09-02T23:20:13
132,277,957
4
5
MIT
2018-08-10T13:01:38
2018-05-05T19:23:37
Python
UTF-8
C++
false
false
7,774
h
#ifndef _KS_INHERITANCE_H_ #define _KS_INHERITANCE_H_ #include <string> #include <vector> #include <map> #include <array> namespace ks { #ifndef _KS_OBJECT_ #define _KS_OBJECT_ class KSObject { public: static inline const std::string nameStatic() { return ""; } virtual inline const std::string name() const = 0; virtual std::string serialize() const = 0; virtual unsigned int deserialize(const std::string &, unsigned int = 0) = 0; }; #endif // _KS_OBJECT_ namespace inheritance { class Parent1 : public KSObject { protected: unsigned int __count; bool __has_count; public: // getters inline unsigned int count() const { return __count; } public: // reference getters inline unsigned int &ref_count() const { return (unsigned int&) __count; } public: // setters inline void count(const unsigned int &count) { __count = count; has_count(true); } public: // has_attribute getters inline bool has_count() const { return __has_count; } public: // has_attribute setters inline void has_count(const bool &has_count) { __has_count = has_count; } public: Parent1() { has_count(false); } static inline const std::string nameStatic() { return "Parent1"; } virtual inline const std::string name() const { return "Parent1"; } std::string serialize() const { std::string s = ""; // serialize count s += __has_count; if (__has_count) { unsigned int tmp1 = __count; auto tmp2 = reinterpret_cast<char*>(&tmp1); s += std::string(tmp2, sizeof(unsigned int)); } return s; } unsigned int deserialize(const std::string &s, unsigned int offset=0) { // deserialize count __has_count = *((unsigned char*) (&s[offset])); offset += sizeof(unsigned char); if (__has_count) { __count = *((unsigned int*) (&s[offset])); offset += sizeof(unsigned int); } return offset; } }; class Parent2 : public KSObject { protected: long long __number; bool __has_number; public: // getters inline long long number() const { return __number; } public: // reference getters inline long long &ref_number() const { return (long long&) __number; } public: // setters inline void number(const long long &number) { __number = number; has_number(true); } public: // has_attribute getters inline bool has_number() const { return __has_number; } public: // has_attribute setters inline void has_number(const bool &has_number) { __has_number = has_number; } public: Parent2() { has_number(false); } static inline const std::string nameStatic() { return "Parent2"; } virtual inline const std::string name() const { return "Parent2"; } std::string serialize() const { std::string s = ""; // serialize number s += __has_number; if (__has_number) { long long tmp4 = __number; auto tmp5 = reinterpret_cast<char*>(&tmp4); s += std::string(tmp5, sizeof(long long)); } return s; } unsigned int deserialize(const std::string &s, unsigned int offset=0) { // deserialize number __has_number = *((unsigned char*) (&s[offset])); offset += sizeof(unsigned char); if (__has_number) { __number = *((long long*) (&s[offset])); offset += sizeof(long long); } return offset; } }; class Parent3 : public KSObject { protected: public: // getters public: // reference getters public: // setters public: // has_attribute getters public: // has_attribute setters public: Parent3() { } static inline const std::string nameStatic() { return "Parent3"; } virtual inline const std::string name() const { return "Parent3"; } std::string serialize() const { std::string s = ""; return s; } unsigned int deserialize(const std::string &s, unsigned int offset=0) { return offset; } }; class Child : public Parent1, Parent2 { protected: std::string __firstname; bool __has_firstname; public: // getters inline std::string firstname() const { return __firstname; } public: // reference getters inline std::string &ref_firstname() const { return (std::string&) __firstname; } public: // setters inline void firstname(const std::string &firstname) { __firstname = firstname; has_firstname(true); } public: // has_attribute getters inline bool has_firstname() const { return __has_firstname; } public: // has_attribute setters inline void has_firstname(const bool &has_firstname) { __has_firstname = has_firstname; } public: Child() { has_firstname(false); } static inline const std::string nameStatic() { return "Child"; } virtual inline const std::string name() const { return "Child"; } std::string serialize() const { std::string s = ""; // serialize parents s += Parent1::serialize(); s += Parent2::serialize(); // serialize firstname s += __has_firstname; if (__has_firstname) { std::string tmp6 = ""; unsigned int tmp8 = __firstname.size(); auto tmp9 = reinterpret_cast<char*>(&tmp8); tmp6 += std::string(tmp9, sizeof(unsigned int)); while (tmp6.size() && tmp6.back() == 0) tmp6.pop_back(); unsigned char tmp11 = tmp6.size(); auto tmp12 = reinterpret_cast<char*>(&tmp11); s += std::string(tmp12, sizeof(unsigned char)); s += tmp6; s += __firstname; } return s; } unsigned int deserialize(const std::string &s, unsigned int offset=0) { // deserialize parents offset = Parent1::deserialize(s, offset); offset = Parent2::deserialize(s, offset); // deserialize firstname __has_firstname = *((unsigned char*) (&s[offset])); offset += sizeof(unsigned char); if (__has_firstname) { unsigned char tmp13; tmp13 = *((unsigned char*) (&s[offset])); offset += sizeof(unsigned char); std::string tmp14 = std::string(&s[offset], tmp13); offset += tmp13; while (tmp14.size() < sizeof(unsigned int)) tmp14 += '\x00'; unsigned int tmp15; tmp15 = *((unsigned int*) (&tmp14[0])); __firstname = s.substr(offset, tmp15); offset += tmp15; } return offset; } }; class GrandChild : public Child, Parent3 { protected: float __height; bool __has_height; public: // getters inline float height() const { return __height; } public: // reference getters inline float &ref_height() const { return (float&) __height; } public: // setters inline void height(const float &height) { __height = height; has_height(true); } public: // has_attribute getters inline bool has_height() const { return __has_height; } public: // has_attribute setters inline void has_height(const bool &has_height) { __has_height = has_height; } public: GrandChild() { has_height(false); } static inline const std::string nameStatic() { return "GrandChild"; } virtual inline const std::string name() const { return "GrandChild"; } std::string serialize() const { std::string s = ""; // serialize parents s += Child::serialize(); s += Parent3::serialize(); // serialize height s += __has_height; if (__has_height) { float tmp17 = __height; auto tmp18 = reinterpret_cast<char*>(&tmp17); s += std::string(tmp18, sizeof(float)); } return s; } unsigned int deserialize(const std::string &s, unsigned int offset=0) { // deserialize parents offset = Child::deserialize(s, offset); offset = Parent3::deserialize(s, offset); // deserialize height __has_height = *((unsigned char*) (&s[offset])); offset += sizeof(unsigned char); if (__has_height) { __height = *((float*) (&s[offset])); offset += sizeof(float); } return offset; } }; } // namespace inheritance } // namespace ks #endif // _KS_INHERITANCE_H_
[ "mdan.hagh@gmail.com" ]
mdan.hagh@gmail.com
72614d183c688b89f47c6041d50d8f0d0efca863
97b523dc133b27b35c00b76d210af5256202a7dd
/32blit-pico/input_usb_hid.cpp
0dd4e68525c3294a4c130fe504e8fb7d098b9235
[ "MIT" ]
permissive
ntwyman/32blit-beta
68e9e4944f1d8e6056f0cd28d0af87bd31a541e6
9418bddcc70c614078cdb5197a29e068447ee29f
refs/heads/master
2023-08-05T09:38:50.305050
2023-07-17T15:01:01
2023-07-17T15:01:01
230,447,412
0
0
MIT
2019-12-27T13:17:59
2019-12-27T13:17:58
null
UTF-8
C++
false
false
3,578
cpp
// GPIO dpad + ABXY #include "input.hpp" #include "hardware/gpio.h" #include "pico/binary_info.h" #include "class/hid/hid.h" #include "engine/api_private.hpp" #include "engine/input.hpp" // from USB code extern uint32_t hid_gamepad_id; extern bool hid_keyboard_detected; extern uint8_t hid_joystick[2]; extern uint8_t hid_hat; extern uint32_t hid_buttons; extern uint8_t hid_keys[6]; struct GamepadMapping { uint32_t id; // vid:pid uint8_t a, b, x, y; uint8_t menu, home, joystick; }; static const GamepadMapping gamepad_mappings[]{ {0x15320705, 0, 1, 3, 4, 16, 15, 13}, // Razer Raiju Mobile {0x20D6A711, 2, 1, 3, 0, 8, 12, 10}, // PowerA wired Switch pro controller {0x00000000, 0, 1, 2, 3, 4, 5, 6} // probably wrong fallback }; // hat -> dpad const uint32_t dpad_map[]{ blit::Button::DPAD_UP, blit::Button::DPAD_UP | blit::Button::DPAD_RIGHT, blit::Button::DPAD_RIGHT, blit::Button::DPAD_DOWN | blit::Button::DPAD_RIGHT, blit::Button::DPAD_DOWN, blit::Button::DPAD_DOWN | blit::Button::DPAD_LEFT, blit::Button::DPAD_LEFT, blit::Button::DPAD_UP | blit::Button::DPAD_LEFT, 0 }; void init_input() { } void update_input() { using namespace blit; // keyboard if(hid_keyboard_detected) { uint32_t new_buttons = 0; for(int i = 0; i < 6; i++) { switch(hid_keys[i]) { case HID_KEY_ARROW_UP: case HID_KEY_W: new_buttons |= uint32_t(Button::DPAD_UP); break; case HID_KEY_ARROW_DOWN: case HID_KEY_S: new_buttons |= uint32_t(Button::DPAD_DOWN); break; case HID_KEY_ARROW_LEFT: case HID_KEY_A: new_buttons |= uint32_t(Button::DPAD_LEFT); break; case HID_KEY_ARROW_RIGHT: case HID_KEY_D: new_buttons |= uint32_t(Button::DPAD_RIGHT); break; case HID_KEY_Z: case HID_KEY_U: new_buttons |= uint32_t(Button::A); break; case HID_KEY_X: case HID_KEY_I: new_buttons |= uint32_t(Button::B); break; case HID_KEY_C: case HID_KEY_O: new_buttons |= uint32_t(Button::X); break; case HID_KEY_V: case HID_KEY_P: new_buttons |= uint32_t(Button::Y); break; case HID_KEY_1: new_buttons |= uint32_t(Button::HOME); break; case HID_KEY_2: case HID_KEY_ESCAPE: new_buttons |= uint32_t(Button::MENU); break; case HID_KEY_3: new_buttons |= uint32_t(Button::JOYSTICK); break; } } api.buttons = new_buttons; } if(!hid_gamepad_id) return; // gamepad auto mapping = gamepad_mappings; while(mapping->id && mapping->id != hid_gamepad_id) mapping++; api.buttons = dpad_map[hid_hat > 8 ? 8 : hid_hat] | (hid_buttons & (1 << mapping->a) ? uint32_t(Button::A) : 0) | (hid_buttons & (1 << mapping->b) ? uint32_t(Button::B) : 0) | (hid_buttons & (1 << mapping->x) ? uint32_t(Button::X) : 0) | (hid_buttons & (1 << mapping->y) ? uint32_t(Button::Y) : 0) | (hid_buttons & (1 << mapping->menu) ? uint32_t(Button::MENU) : 0) | (hid_buttons & (1 << mapping->home) ? uint32_t(Button::HOME) : 0) | (hid_buttons & (1 << mapping->joystick) ? uint32_t(Button::JOYSTICK) : 0); api.joystick.x = (float(hid_joystick[0]) - 0x80) / 0x80; api.joystick.y = (float(hid_joystick[1]) - 0x80) / 0x80; }
[ "charlie@daft.games" ]
charlie@daft.games
6f1c946907ede9286375476e7b1d9e6b01e42d15
083973f506ea3a2d575e102acc2babd6dfa6bc93
/leetcode/Easy/7.反转整数.cpp
033c3b6ff5ef7cd08b877c87c5ba2b32024e4a49
[]
no_license
gsscsd/Code_Training
dd5ab4ef2a789ca84b372327b9a5a780d080f089
60efc5248c1bd30162b4b44b21cced66f4723059
refs/heads/master
2020-03-29T11:07:46.049496
2019-07-05T04:47:53
2019-07-05T04:47:53
149,837,404
0
0
null
null
null
null
UTF-8
C++
false
false
2,415
cpp
/** 给定一个 32 位有符号整数,将整数中的数字进行反转。 假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−231, 231 − 1]。 根据这个假设,如果反转后的整数溢出,则返回 0。 */ /** 解题思路: */ #include <iostream> #include <vector> #include <algorithm> // 先定义边界,然后判定是否出界 #define INT_MAX 0x7FFFFFFF #define INT_MIN -INT_MAX-1 // #define int_min 0x8FFFFFFF using namespace std; class Solution { public: // 网上似乎还有不用区分正负数的算法 // 实际上代码不用区分正负数 int reverse(int x) { // bool flag = x < 0; // 假设x是-2147483648,那么对x取反会溢出,所以,先赋值给long的类型,防止溢出 long t = x; // 首先如果是负数,那么对t取反 // if(flag) t = - t; // 定义反转的数 long m = 0; while(t != 0) { m = m * 10 + (t % 10); t /= 10; } // 计算完成后,将负数在转换回去 // if(flag) m = -m; // 判定是否溢出 if(m > INT_MAX || m < INT_MIN) { return 0; } // 注意m是long的类型,所以此时需要向下取整 return (int)m; } // 网上处理的方式,不用考虑正负数,然后边界放在循环里面来考虑 int reverse_(int x) { int result(0); while (x != 0) { int newResult = result * 10 + x % 10; if ((newResult - x % 10) / 10 != result) { return 0; } result = newResult; x = x / 10; } return result; } // 第三种 int reverse_1(int x) { int rev = 0; while (x != 0) { int pop = x % 10; x /= 10; // 每次组成的时候,进行溢出检查 // 这一句检查是否是正数溢出 if (rev > INT_MAX/10 || (rev == INT_MAX / 10 && pop > 7)) return 0; // 这一句检查是否是负数溢出 if (rev < INT_MIN/10 || (rev == INT_MIN / 10 && pop < -8)) return 0; rev = rev * 10 + pop; } return rev; } }; int main() { int x ; cin >> x; Solution s; int m = s.reverse(x); cout << "result is " << m << endl; return 0; }
[ "gsscsd@outlook.com" ]
gsscsd@outlook.com
773fc55b555a79f037e4352241d884d131e0f3b1
ebad58c2cdb320097ff3e9f586c2dec276979a34
/src/tool/backup/map_combine/src/map_combine.cpp
aa1fdced2575e9610eae9c5e02261d2138f3d690
[]
no_license
joseph-ntut/lab314
88fee91a86e39289c9eb9caffa7a2f7fc02d2ec4
2e250e53e992e0d950bc2813e0c746b7163ff427
refs/heads/master
2022-11-20T16:31:11.493778
2020-07-14T13:03:03
2020-07-14T13:03:03
224,435,825
1
0
null
null
null
null
UTF-8
C++
false
false
3,245
cpp
#include <ros/ros.h> #include <nav_msgs/Odometry.h> #include <sensor_msgs/PointCloud2.h> #include <geometry_msgs/PoseStamped.h> #include <std_msgs/String.h> #include <pcl/io/pcd_io.h> #include <pcl/point_cloud.h> #include <pcl_conversions/pcl_conversions.h> #include <stdio.h> #include <map_load/load.h> float dis; float pose_x, pose_y; std::string floors; ros::Subscriber floor_sub; ros::Subscriber sub; ros::Publisher point_pub; ros::ServiceClient client; void floor_callback(const std_msgs::String& f) { floors = f.data; } void callback(const geometry_msgs::PoseStamped& p) { pose_x = p.pose.position.x; pose_y = p.pose.position.y; } main (int argc, char **argv) { ros::init (argc, argv, "map_combine"); ros::NodeHandle nh; floor_sub = nh.subscribe("floor", 100, floor_callback); sub = nh.subscribe("ndt_pose", 100, callback); point_pub = nh.advertise<sensor_msgs::PointCloud2>("points_map", 100); client = nh.serviceClient<map_load::load>("map_load"); pcl::PointCloud<pcl::PointXYZI> cloud_1, cloud_2, cloud_3, cloud_4, cloud_5; pcl::PointCloud<pcl::PointXYZI> cloud_6, cloud_7, cloud_8, cloud_9; pcl::PointCloud<pcl::PointXYZI> cloud; sensor_msgs::PointCloud2 out; map_load::load srv; dis = 7.0; ros::Rate r(100); while (nh.ok()) { ros::spinOnce(); srv.request.x = pose_x; srv.request.y = pose_y; srv.request.dis = dis; client.call(srv); std::string str[9] = {srv.response.a, srv.response.b, srv.response.c, srv.response.d, srv.response.e, srv.response.f, srv.response.g, srv.response.h, srv.response.i}; char cstr[9][50]; sprintf(cstr[0],"/home/joseph/map2/%s",(floors + "/" +str[0]).c_str()); sprintf(cstr[1],"/home/joseph/map2/%s",(floors + "/" +str[1]).c_str()); sprintf(cstr[2],"/home/joseph/map2/%s",(floors + "/" +str[2]).c_str()); sprintf(cstr[3],"/home/joseph/map2/%s",(floors + "/" +str[3]).c_str()); sprintf(cstr[4],"/home/joseph/map2/%s",(floors + "/" +str[4]).c_str()); sprintf(cstr[5],"/home/joseph/map2/%s",(floors + "/" +str[5]).c_str()); sprintf(cstr[6],"/home/joseph/map2/%s",(floors + "/" +str[6]).c_str()); sprintf(cstr[7],"/home/joseph/map2/%s",(floors + "/" +str[7]).c_str()); sprintf(cstr[8],"/home/joseph/map2/%s",(floors + "/" +str[8]).c_str()); pcl::io::loadPCDFile(cstr[0],cloud_1); pcl::io::loadPCDFile(cstr[1],cloud_2); pcl::io::loadPCDFile(cstr[2],cloud_3); pcl::io::loadPCDFile(cstr[3],cloud_4); pcl::io::loadPCDFile(cstr[4],cloud_5); pcl::io::loadPCDFile(cstr[5],cloud_6); pcl::io::loadPCDFile(cstr[6],cloud_7); pcl::io::loadPCDFile(cstr[7],cloud_8); pcl::io::loadPCDFile(cstr[8],cloud_9); cloud = cloud_1 + cloud_2; cloud += cloud_3; cloud += cloud_4; cloud += cloud_5; cloud += cloud_6; cloud += cloud_7; cloud += cloud_8; cloud += cloud_9; pcl::toROSMsg(cloud,out); out.header.stamp = ros::Time::now(); out.header.frame_id = "map"; point_pub.publish(out); r.sleep(); } }
[ "t106310205@ntut.org.tw" ]
t106310205@ntut.org.tw
98dad95babba8b4b07d08c9724091189bb19924c
2d8f71adc40b086c2d7f0fdd7b9756bf548dd063
/SaveTheKing/Brick.cpp
f8de213bf63a47b9ad7d5da72de30be89e03e7ed
[]
no_license
gotlibsh/SaveTheKing
86aff96dbf059e5ebd84e5faf80130160132dd72
3e64feeeabcb5f4793955ef0fdcc98a904c57470
refs/heads/master
2020-01-23T22:02:40.106164
2016-12-06T20:24:34
2016-12-06T20:24:34
74,708,182
0
0
null
null
null
null
UTF-8
C++
false
false
877
cpp
#include "Brick.h" //+---------------------------------------------------------+ //| Constructors | //+---------------------------------------------------------+ Brick::Brick() {} //+---------------------------------------------------------+ //| Public Member Functions | //+---------------------------------------------------------+ /* * Returns the point (x,y) of the brick. */ Point Brick::getPlace() const { return m_place; } /* * Returns the state of the brick. */ BrickState Brick::getState() const { return m_state; } /* * Sets the point (x,y) of the brick. */ void Brick::setPlace(int x, int y) { m_place.m_x = x; m_place.m_y = y; } /* * Sets the state of the brick. */ void Brick::setState(BrickState state) { m_state = state; } /* * Returns the character representing this brick. */ char Brick::print() const { return (char)m_state; }
[ "HaimGotlib@HAIM-LP" ]
HaimGotlib@HAIM-LP
0a52ddc3cd7c6ce13df93eb567e2ccdeecd0f300
8faee0b01b9afed32bb5b7ef1ab0dcbc46788b5b
/source/include/algo/blast/igblast/igblast.hpp
2f25299b96f47f91fc49d61eb6bd9f6c5ab8682b
[]
no_license
jackgopack4/pico-blast
5fe3fa1944b727465845e1ead1a3c563b43734fb
cde1bd03900d72d0246cb58a66b41e5dc17329dd
refs/heads/master
2021-01-14T12:31:05.676311
2014-05-17T19:22:05
2014-05-17T19:22:05
16,808,473
2
0
null
null
null
null
UTF-8
C++
false
false
12,530
hpp
/* $Id: igblast.hpp 383081 2012-12-11 19:44:04Z jianye $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: Ning Ma * */ /// @file igblast.hpp /// Declares CIgBlast, the C++ API for the IG-BLAST engine. #ifndef ALGO_BLAST_IGBLAST___IGBLAST__HPP #define ALGO_BLAST_IGBLAST___IGBLAST__HPP #include <algo/blast/api/setup_factory.hpp> #include <algo/blast/api/uniform_search.hpp> #include <algo/blast/api/local_db_adapter.hpp> #include <objmgr/scope.hpp> /** @addtogroup AlgoBlast * * @{ */ BEGIN_NCBI_SCOPE BEGIN_SCOPE(blast) /// Keeps track of the version of IgBLAST in the NCBI C++ toolkit. /// Used to perform run-time version checks /// /// For reference, please refer to http://apr.apache.org/versioning.html class CIgBlastVersion : public CVersionInfo { public: CIgBlastVersion() : CVersionInfo(1, 0, 0) {} }; class IQueryFactory; class CIgBlastOptions : public CObject { public: // the germline database search must be carried out locally bool m_IsProtein; // search molecular type string m_Origin; // the origin of species string m_DomainSystem; // domain system for annotation string m_SequenceType; //ig or tcr? int m_Min_D_match; //the word size for D gene search string m_AuxFilename; // auxulary file name string m_IgDataPath; // internal data path CRef<CLocalDbAdapter> m_Db[4]; // user specified germline database // 0-2: - user specified V, D, J // 3: - the default V gl db int m_NumAlign[3]; // number of VDJ alignments to show bool m_FocusV; // should alignment restrict to V bool m_Translate; // should translation be displayed }; class CIgAnnotation : public CObject { public: bool m_MinusStrand; // hit is on minus strand of the query vector<string> m_TopGeneIds; // Top match germline gene ID vector<string> m_ChainType; // chain types of the query ([0]) and subjects ([1:]) string m_ChainTypeToShow; // chain type to show to user. Normally this is //the same as m_ChainType[0] but could be different // in case o TCRA/D chains which can use both JA and JD int m_GeneInfo[6]; // The (start) and (end offset + 1) for VDJ int m_FrameInfo[3]; // Coding frame start offset for V start, V end, // and V start. int m_DomainInfo[12]; // The (start) and (end offset) for FWR1, // CDR1, FWR2, CDR2, FWR3, CDR3 domains // note: the first and last domains are be extended int m_DomainInfo_S[10]; // The (start) and (end offset) for FWR1, // CDR1, FWR2, CDR2, FWR3, CDR3 domains on topV sequence /// Constructor CIgAnnotation() : m_MinusStrand (false) { for (int i=0; i<3; i++) m_TopGeneIds.push_back("N/A"); for (int i=0; i<6; i++) m_GeneInfo[i] = -1; for (int i=0; i<3; i++) m_FrameInfo[i] = -1; for (int i=0; i<12; i++) m_DomainInfo[i] = -1; for (int i=0; i<10; i++) m_DomainInfo_S[i] = -1; } }; class CIgAnnotationInfo { public: CIgAnnotationInfo(CConstRef<CIgBlastOptions> &ig_options); bool GetDomainInfo(const string sid, int * domain_info) { if (m_DomainIndex.find(sid) != m_DomainIndex.end()) { int index = m_DomainIndex[sid]; for (int i=0; i<10; ++i) { domain_info[i] = m_DomainData[index + i]; } return true; } return false; } const string GetDomainChainType(const string sid) { if (m_DomainChainType.find(sid) != m_DomainChainType.end()) { return m_DomainChainType[sid]; } return "N/A"; } int GetFrameOffset(const string sid) { if (m_FrameOffset.find(sid) != m_FrameOffset.end()) { return m_FrameOffset[sid]; } return -1; } const string GetDJChainType(const string sid) { if (m_DJChainType.find(sid) != m_DJChainType.end()) { return m_DJChainType[sid]; } return "N/A"; } private: map<string, int> m_DomainIndex; vector<int> m_DomainData; map<string, string> m_DomainChainType; map<string, int> m_FrameOffset; map<string, string> m_DJChainType; }; class CIgBlastResults : public CSearchResults { public: int m_NumActualV; int m_NumActualD; int m_NumActualJ; const CRef<CIgAnnotation> & GetIgAnnotation() const { return m_Annotation; } CRef<CIgAnnotation> & SetIgAnnotation() { return m_Annotation; } CRef<CSeq_align_set> & SetSeqAlign() { return m_Alignment; } /// Constructor /// @param query List of query identifiers [in] /// @param align alignments for a single query sequence [in] /// @param errs error messages for this query sequence [in] /// @param ancillary_data Miscellaneous output from the blast engine [in] /// @param query_masks Mask locations for this query [in] /// @param rid RID (if applicable, else empty string) [in] CIgBlastResults(CConstRef<objects::CSeq_id> query, CRef<objects::CSeq_align_set> align, const TQueryMessages &errs, CRef<CBlastAncillaryData> ancillary_data) : CSearchResults(query, align, errs, ancillary_data), m_NumActualV(0), m_NumActualD(0), m_NumActualJ(0) { } private: CRef<CIgAnnotation> m_Annotation; }; class CIgBlast : public CObject { public: /// Local Igblast search API /// @param query_factory Concatenated query sequences [in] /// @param blastdb Adapter to the BLAST database to search [in] /// @param options Blast search options [in] /// @param ig_options Additional Ig-BLAST specific options [in] CIgBlast(CRef<CBlastQueryVector> query_factory, CRef<CLocalDbAdapter> blastdb, CRef<CBlastOptionsHandle> options, CConstRef<CIgBlastOptions> ig_options) : m_IsLocal(true), m_NumThreads(1), m_Query(query_factory), m_LocalDb(blastdb), m_Options(options), m_IgOptions(ig_options), m_AnnotationInfo(ig_options) { } /// Remote Igblast search API /// @param query_factory Concatenated query sequences [in] /// @param blastdb Remote BLAST database to search [in] /// @param subjects Subject sequences to search [in] /// @param options Blast search options [in] /// @param ig_options Additional Ig-BLAST specific options [in] CIgBlast(CRef<CBlastQueryVector> query_factory, CRef<CSearchDatabase> blastdb, CRef<IQueryFactory> subjects, CRef<CBlastOptionsHandle> options, CConstRef<CIgBlastOptions> ig_options) : m_IsLocal(false), m_NumThreads(1), m_Query(query_factory), m_Subject(subjects), m_RemoteDb(blastdb), m_Options(options), m_IgOptions(ig_options), m_AnnotationInfo(ig_options) { } /// Destructor ~CIgBlast() {}; /// Run the Ig-BLAST engine CRef<CSearchResultSet> Run(); /// Set MT mode void SetNumberOfThreads(size_t nthreads) { m_NumThreads = nthreads; } private: bool m_IsLocal; size_t m_NumThreads; CRef<CBlastQueryVector> m_Query; CRef<IQueryFactory> m_Subject; CRef<CLocalDbAdapter> m_LocalDb; CRef<CSearchDatabase> m_RemoteDb; CRef<CBlastOptionsHandle> m_Options; CConstRef<CIgBlastOptions> m_IgOptions; CIgAnnotationInfo m_AnnotationInfo; /// Prohibit copy constructor CIgBlast(const CIgBlast& rhs); /// Prohibit assignment operator CIgBlast& operator=(const CIgBlast& rhs); /// Prepare blast option handle and query for V germline database search void x_SetupVSearch(CRef<IQueryFactory> &qf, CRef<CBlastOptionsHandle> &opts_hndl); /// Prepare blast option handle and query for D, J germline database search void x_SetupDJSearch(const vector<CRef <CIgAnnotation> > &annots, CRef<IQueryFactory> &qf, CRef<CBlastOptionsHandle> &opts_hndl, int db_type); /// Prepare blast option handle and query for specified database search void x_SetupDbSearch(vector<CRef <CIgAnnotation> > &annot, CRef<IQueryFactory> &qf); /// Annotate the V gene based on blast results void x_AnnotateV(CRef<CSearchResultSet> &results, vector<CRef <CIgAnnotation> > &annot); /// Annotate the D and J genes based on blast results void x_AnnotateDJ(CRef<CSearchResultSet> &results_D, CRef<CSearchResultSet> &results_J, vector<CRef <CIgAnnotation> > &annot); /// Annotate the query chaintype and domains based on blast results void x_AnnotateDomain(CRef<CSearchResultSet> &gl_results, CRef<CSearchResultSet> &dm_results, vector<CRef <CIgAnnotation> > &annot); /// Set the subject chain type and frame info void x_SetChainType(CRef<CSearchResultSet> &results, vector<CRef <CIgAnnotation> > &annot); /// Convert bl2seq result to database search mode void x_ConvertResultType(CRef<CSearchResultSet> &results); /// Sort blast results according to evalue static void s_SortResultsByEvalue(CRef<CSearchResultSet> &results); /// Append blast results to the final results static void s_AppendResults(CRef<CSearchResultSet> &results, int num_aligns, int gene, CRef<CSearchResultSet> &final_results); /// Append annotation info to the final results static void s_SetAnnotation(vector<CRef <CIgAnnotation> > &annot, CRef<CSearchResultSet> &final_results); void x_FindDJ(CRef<CSearchResultSet>& results_D, CRef<CSearchResultSet>& results_J, CRef <CIgAnnotation> & annot, CRef<CSeq_align_set>& align_D, CRef<CSeq_align_set>& align_J, string q_ct, bool q_ms, ENa_strand q_st, int q_ve, int iq); void x_FindDJAln(CRef<CSeq_align_set>& align_D, CRef<CSeq_align_set>& align_J, string q_ct, bool q_ms, ENa_strand q_st, int q_ve, int iq, bool va_or_vd_as_heavy_chain); }; END_SCOPE(blast) END_NCBI_SCOPE /* @} */ #endif /* ALGO_BLAST_IGBLAST___IGBLAST__HPP */
[ "jackgopack4@gmail.com" ]
jackgopack4@gmail.com
c655120ba2029eb47de0965855d692f19cfa1a9b
96b6ed490eada4e5864000681c587aa7060cf938
/34-QtreadWaiting/main.cpp
0f13fd3b61c7c29737f07611b69e806d01771526
[]
no_license
AlessandroScrem/Qt_samples
f2cdfc7cd858432ee96497f7b64e69c1188fb3b9
5a07b49e10f948dc12ab6dc0720b30e9225af2f2
refs/heads/master
2020-12-04T07:12:06.644337
2020-01-13T18:10:04
2020-01-13T18:10:04
231,672,644
0
0
null
null
null
null
UTF-8
C++
false
false
254
cpp
#include <QCoreApplication> #include "mythread.h" #include <QDebug> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); MyThread mThread; mThread.start(); mThread.wait(); qDebug() << "Done"; return a.exec(); }
[ "48774358+AlessandroScrem@users.noreply.github.com" ]
48774358+AlessandroScrem@users.noreply.github.com
06330d141af0b15deefad10e4371950e3f9515be
8242d218808b8cc5734a27ec50dbf1a7a7a4987a
/Intermediate/Build/Win64/Netshoot/Inc/Engine/DialogueVoice.gen.cpp
0f7d1965847e6880bccfd05d26032582e3724169
[]
no_license
whyhhr/homework2
a2e75b494a962eab4fb0a740f83dc8dc27f8f6ee
9808107fcc983c998d8601920aba26f96762918c
refs/heads/main
2023-08-29T08:14:39.581638
2021-10-22T16:47:11
2021-10-22T16:47:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,956
cpp
// Copyright Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/GeneratedCppIncludes.h" #include "Engine/Classes/Sound/DialogueVoice.h" #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable : 4883) #endif PRAGMA_DISABLE_DEPRECATION_WARNINGS void EmptyLinkFunctionForGeneratedCodeDialogueVoice() {} // Cross Module References ENGINE_API UClass* Z_Construct_UClass_UDialogueVoice_NoRegister(); ENGINE_API UClass* Z_Construct_UClass_UDialogueVoice(); COREUOBJECT_API UClass* Z_Construct_UClass_UObject(); UPackage* Z_Construct_UPackage__Script_Engine(); ENGINE_API UEnum* Z_Construct_UEnum_Engine_EGrammaticalGender(); ENGINE_API UEnum* Z_Construct_UEnum_Engine_EGrammaticalNumber(); COREUOBJECT_API UScriptStruct* Z_Construct_UScriptStruct_FGuid(); // End Cross Module References void UDialogueVoice::StaticRegisterNativesUDialogueVoice() { } UClass* Z_Construct_UClass_UDialogueVoice_NoRegister() { return UDialogueVoice::StaticClass(); } struct Z_Construct_UClass_UDialogueVoice_Statics { static UObject* (*const DependentSingletons[])(); #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[]; #endif #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_Gender_MetaData[]; #endif static const UE4CodeGen_Private::FBytePropertyParams NewProp_Gender; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_Plurality_MetaData[]; #endif static const UE4CodeGen_Private::FBytePropertyParams NewProp_Plurality; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_LocalizationGUID_MetaData[]; #endif static const UE4CodeGen_Private::FStructPropertyParams NewProp_LocalizationGUID; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; static const FCppClassTypeInfoStatic StaticCppClassTypeInfo; static const UE4CodeGen_Private::FClassParams ClassParams; }; UObject* (*const Z_Construct_UClass_UDialogueVoice_Statics::DependentSingletons[])() = { (UObject* (*)())Z_Construct_UClass_UObject, (UObject* (*)())Z_Construct_UPackage__Script_Engine, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UDialogueVoice_Statics::Class_MetaDataParams[] = { { "BlueprintType", "true" }, { "HideCategories", "Object" }, { "IncludePath", "Sound/DialogueVoice.h" }, { "ModuleRelativePath", "Classes/Sound/DialogueVoice.h" }, }; #endif #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UDialogueVoice_Statics::NewProp_Gender_MetaData[] = { { "Category", "DialogueVoice" }, { "ModuleRelativePath", "Classes/Sound/DialogueVoice.h" }, }; #endif const UE4CodeGen_Private::FBytePropertyParams Z_Construct_UClass_UDialogueVoice_Statics::NewProp_Gender = { "Gender", nullptr, (EPropertyFlags)0x0010010000000001, UE4CodeGen_Private::EPropertyGenFlags::Byte, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UDialogueVoice, Gender), Z_Construct_UEnum_Engine_EGrammaticalGender, METADATA_PARAMS(Z_Construct_UClass_UDialogueVoice_Statics::NewProp_Gender_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UDialogueVoice_Statics::NewProp_Gender_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UDialogueVoice_Statics::NewProp_Plurality_MetaData[] = { { "Category", "DialogueVoice" }, { "ModuleRelativePath", "Classes/Sound/DialogueVoice.h" }, }; #endif const UE4CodeGen_Private::FBytePropertyParams Z_Construct_UClass_UDialogueVoice_Statics::NewProp_Plurality = { "Plurality", nullptr, (EPropertyFlags)0x0010010000000001, UE4CodeGen_Private::EPropertyGenFlags::Byte, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UDialogueVoice, Plurality), Z_Construct_UEnum_Engine_EGrammaticalNumber, METADATA_PARAMS(Z_Construct_UClass_UDialogueVoice_Statics::NewProp_Plurality_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UDialogueVoice_Statics::NewProp_Plurality_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UDialogueVoice_Statics::NewProp_LocalizationGUID_MetaData[] = { { "ModuleRelativePath", "Classes/Sound/DialogueVoice.h" }, }; #endif const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UClass_UDialogueVoice_Statics::NewProp_LocalizationGUID = { "LocalizationGUID", nullptr, (EPropertyFlags)0x0010000000000000, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UDialogueVoice, LocalizationGUID), Z_Construct_UScriptStruct_FGuid, METADATA_PARAMS(Z_Construct_UClass_UDialogueVoice_Statics::NewProp_LocalizationGUID_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UDialogueVoice_Statics::NewProp_LocalizationGUID_MetaData)) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UClass_UDialogueVoice_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UDialogueVoice_Statics::NewProp_Gender, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UDialogueVoice_Statics::NewProp_Plurality, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UDialogueVoice_Statics::NewProp_LocalizationGUID, }; const FCppClassTypeInfoStatic Z_Construct_UClass_UDialogueVoice_Statics::StaticCppClassTypeInfo = { TCppClassTypeTraits<UDialogueVoice>::IsAbstract, }; const UE4CodeGen_Private::FClassParams Z_Construct_UClass_UDialogueVoice_Statics::ClassParams = { &UDialogueVoice::StaticClass, nullptr, &StaticCppClassTypeInfo, DependentSingletons, nullptr, Z_Construct_UClass_UDialogueVoice_Statics::PropPointers, nullptr, UE_ARRAY_COUNT(DependentSingletons), 0, UE_ARRAY_COUNT(Z_Construct_UClass_UDialogueVoice_Statics::PropPointers), 0, 0x000810A0u, METADATA_PARAMS(Z_Construct_UClass_UDialogueVoice_Statics::Class_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UClass_UDialogueVoice_Statics::Class_MetaDataParams)) }; UClass* Z_Construct_UClass_UDialogueVoice() { static UClass* OuterClass = nullptr; if (!OuterClass) { UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_UDialogueVoice_Statics::ClassParams); } return OuterClass; } IMPLEMENT_CLASS(UDialogueVoice, 4157397108); template<> ENGINE_API UClass* StaticClass<UDialogueVoice>() { return UDialogueVoice::StaticClass(); } static FCompiledInDefer Z_CompiledInDefer_UClass_UDialogueVoice(Z_Construct_UClass_UDialogueVoice, &UDialogueVoice::StaticClass, TEXT("/Script/Engine"), TEXT("UDialogueVoice"), false, nullptr, nullptr, nullptr); DEFINE_VTABLE_PTR_HELPER_CTOR(UDialogueVoice); PRAGMA_ENABLE_DEPRECATION_WARNINGS #ifdef _MSC_VER #pragma warning (pop) #endif
[ "49893309+whyhhr@users.noreply.github.com" ]
49893309+whyhhr@users.noreply.github.com
9e0d037b11ce735e73ddaa551f855a700ad702c7
2ba11aaabd0676ae2d768df28b19c88c6027525f
/IRTKSimple2/packages/registration/src/irtkImageAffineRegistration2D.cc
c6431c5323fec3312b37b1a512e6b11976532d62
[]
no_license
handong32/EbbRT_fetalRecon
ce5dce0db9ac0b5180e3342c9ca0bf934da3ab30
e468846eddced8f12bc3f77c62e9b30e25a8c5e5
refs/heads/master
2021-01-13T05:34:44.159441
2017-01-25T21:10:10
2017-01-25T21:10:10
80,054,792
0
1
null
null
null
null
UTF-8
C++
false
false
880
cc
/*========================================================================= Library : Image Registration Toolkit (IRTK) Module : $Id: irtkImageAffineRegistration2D.cc 2 2008-12-23 12:40:14Z dr $ Copyright : Imperial College, Department of Computing Visual Information Processing (VIP), 2008 onwards Date : $Date: 2008-12-23 12:40:14 +0000 (Tue, 23 Dec 2008) $ Version : $Revision: 2 $ Changes : $Author: dr $ =========================================================================*/ #include <irtkRegistration.h> void irtkImageAffineRegistration2D::SetOutput(irtkTransformation *transformation) { if (strcmp(transformation->NameOfClass(), "irtkAffineTransformation") != 0) { cerr << "irtkImageAffineRegistration::SetOutput: Transformation must be affine" << endl; exit(0); } _transformation = transformation; }
[ "handong@bu.edu" ]
handong@bu.edu
8d4c8de1dc469d57267f6fdb96e84bfca4cbfdac
256022d2e1ae66e89ba06804690f5bae09914c86
/project/code/Timer.h
6c292bad057ab0d277a307f3c8d8c14904d6f785
[]
no_license
elingg/cognitive-dissonance
d7a6da49d48cb3119aa20541a9504b2cfc09703b
156a869cf9605632a33e65303fecad09fa625c51
refs/heads/master
2021-01-01T17:57:42.187178
2009-03-21T06:51:21
2009-03-21T06:51:21
40,203,227
0
0
null
null
null
null
UTF-8
C++
false
false
711
h
#pragma once #include <ctime> #include <iostream> #include <string> using namespace std; /* Class: Timer * Simple utility for printing timing messages to profile our code. * Use by instantiating on the stack within the scope of the function * trying to profile. */ class Timer { public: Timer(string tag=string(""), bool print=true):m_tag(tag), m_print(print) { m_start = clock(); } ~Timer() { if(m_print) { cerr << "Time taken in " << m_tag << ": " << get_time_in_sec()<< " seconds\n"; } } double get_time_in_sec() { return (clock()-m_start)/double(CLOCKS_PER_SEC); } private: string m_tag; clock_t m_start; bool m_print; };
[ "madhavan.anand@257f2f30-e9bf-11dd-b00f-9fabb4b2ff13" ]
madhavan.anand@257f2f30-e9bf-11dd-b00f-9fabb4b2ff13
a3e041a7b963e73399772fd2b1df7fd82ed362a8
4ba9c9fd72e86eda1e42608962b41733d9ee3377
/Android/signage/app/src/main/cpp/MediaPlayer/Texture.h
c4fb371cd5bf53749f3313afe1ad29910daeda60
[]
no_license
GovanGova/MediaPlayer
e709cbd7e12f782a7746f345799ae0f39afbed4f
4aafcabfab6ca25cd587a937136f1dbc74bd9f92
refs/heads/master
2020-04-10T13:28:18.919932
2019-11-02T11:13:02
2019-11-02T11:13:02
161,051,544
0
0
null
null
null
null
UTF-8
C++
false
false
538
h
// // Created by G on 5/29/2018. // #ifndef SIGNAGE_TEXTURE_H #define SIGNAGE_TEXTURE_H #include "Element.h" class Texture : public Element { protected: void createTexture(); void loadTextureData(int w, int h, const void *data, int bpp); GLuint m_textureID=0; GLuint m_textureBuf=0; public: Texture(shared_ptr<screenManager> screenMng); virtual void tick(float tSecs); virtual void render(); virtual void unload(); ~Texture(); }; #endif //SIGNAGE_TEXTURE_H
[ "gova.intec@gmail.com" ]
gova.intec@gmail.com
47ca90d39ef2acaecd791276f47f5f5a0feb646f
51635684d03e47ebad12b8872ff469b83f36aa52
/external/gcc-12.1.0/libstdc++-v3/testsuite/25_algorithms/upper_bound/2.cc
500434e6838992d1de4b5993aa15ca4670ac7c13
[ "LGPL-2.1-only", "GPL-3.0-only", "GCC-exception-3.1", "GPL-2.0-only", "LGPL-3.0-only", "LGPL-2.0-or-later", "Zlib", "LicenseRef-scancode-public-domain" ]
permissive
zhmu/ananas
8fb48ddfe3582f85ff39184fc7a3c58725fe731a
30850c1639f03bccbfb2f2b03361792cc8fae52e
refs/heads/master
2022-06-25T10:44:46.256604
2022-06-12T17:04:40
2022-06-12T17:04:40
30,108,381
59
8
Zlib
2021-09-26T17:30:30
2015-01-31T09:44:33
C
UTF-8
C++
false
false
2,094
cc
// Copyright (C) 2001-2022 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // 25.3.3 [lib.alg.binary.search] Binary search algorithms. #include <algorithm> #include <testsuite_hooks.h> const int A[] = {1, 2, 3, 3, 3, 5, 8}; const int C[] = {8, 5, 3, 3, 3, 2, 1}; const int N = sizeof(A) / sizeof(int); // A comparison, equalivalent to std::greater<int> without the // dependency on <functional>. struct gt { bool operator()(const int& x, const int& y) const { return x > y; } }; // Each test performs general-case, bookend, not-found condition, // and predicate functional checks. // 25.3.3.2 upper_bound, with and without comparison predicate void test02() { using std::upper_bound; const int first = A[0]; const int last = A[N - 1]; const int* p = upper_bound(A, A + N, 3); VERIFY(p == A + 5); const int* q = upper_bound(A, A + N, first); VERIFY(q == A + 1); const int* r = upper_bound(A, A + N, last); VERIFY(r == A + N); const int* s = upper_bound(A, A + N, 4); VERIFY(s == A + 5); const int* t = upper_bound(C, C + N, 3, gt()); VERIFY(t == C + 5); const int* u = upper_bound(C, C + N, first, gt()); VERIFY(u == C + N); const int* v = upper_bound(C, C + N, last, gt()); VERIFY(v == C + 1); const int* w = upper_bound(C, C + N, 4, gt()); VERIFY(w == C + 2); } int main() { test02(); return 0; }
[ "rink@rink.nu" ]
rink@rink.nu
794a74431b86947c325f89288019d5ea9c514722
789453153a02870f4d8f4a330a589cafc00c9731
/Software/usb-to-ps2-gameport-hat/lib/GlobalStringBuffer/src/GlobalStringBuffer.cpp
f7a2276c79acc504263d63bcf164538b4b8a3fea
[ "MIT" ]
permissive
ChrisDeadman/usb-to-ps2-gameport-hat
bccdbfd4d8ae5aa53050360b0515803f5850590f
293ae4437f0b8091a51ddb91e8117a18e35a159a
refs/heads/master
2022-02-21T00:08:19.489757
2022-02-04T14:24:51
2022-02-04T14:36:54
216,358,651
8
0
null
null
null
null
UTF-8
C++
false
false
1,006
cpp
#include "GlobalStringBuffer.h" inline uint16_t safeSize(uint16_t maxSize, uint16_t offset, uint16_t size) { return (size <= (maxSize - offset)) ? size : (maxSize - offset); } GlobalStringBuffer::GlobalStringBuffer(uint16_t maxSize) : maxSize(maxSize), buffer(new char[maxSize + 1]) { this->buffer[0] = 0; } GlobalStringBuffer* const GlobalStringBuffer::alloc(uint16_t maxSize) { return new GlobalStringBuffer(maxSize); } const char* const GlobalStringBuffer::get() { return buffer; } uint16_t GlobalStringBuffer::length() { return strlen(buffer); } bool GlobalStringBuffer::isEmpty() { return length() <= 0; } GlobalStringBuffer* const GlobalStringBuffer::clear() { buffer[0] = 0; return this; } GlobalStringBuffer* const GlobalStringBuffer::concat(char const* const str) { strncat(buffer, str, safeSize(maxSize, length(), strlen(str))); return this; } GlobalStringBuffer* const GlobalStringBuffer::concatln(char const* const str) { return this->concat(str)->concat(CR_LF); }
[ "christopher.hubmann@gmail.com" ]
christopher.hubmann@gmail.com
52252c59c61d708ac6f9a149ba9d00c6140ac4a8
28a2a5912ec6fc9d18d002dd5e1cdc6e31f0a78d
/rightBrother.cpp
8fd0b227b61eabeadf9f4222503cb646ceda3ad5
[]
no_license
karthi-dp/algorithms
0417fc92c8616558119312ebf71cac9d3c563601
86924da10d6a463ce09f3703e7b6849cb5fcba73
refs/heads/master
2021-09-08T10:41:25.357595
2018-03-09T09:06:02
2018-03-09T09:06:02
119,841,889
0
0
null
null
null
null
UTF-8
C++
false
false
1,948
cpp
/* * Problem: Given a binary tree with an additional pointer right brother which is Null by default. Write a function such that right brother points to the node on the right, in the same level * Author: Kartheek Diwakar Pingali * */ #include <bits/stdc++.h> using namespace std; struct Node { int val; Node* left; Node* right; Node* rb; //Right Brother Node(int value) { val = value; left = NULL; right = NULL; rb = NULL; } }; void RightBrother(Node* root) { queue<Node* >q; q.push(root); while(!q.empty()) { Node* t = q.front(); q.pop(); if(t->left && t->right) { t->left->rb = t->right; if(t->rb) { if(t->rb->left) { t->right->rb = t->rb->left; } else if(t->rb->right) { t->right->rb = t->rb->right; } } q.push(t->left); q.push(t->right); } else if(t->left && !(t->right)) { if(t->rb) { if(t->rb->left) { t->left->rb = t->rb->left; } else if(t->rb->right) { t->left->rb = t->rb->right; } } q.push(t->left); } else if(t->right && !(t->left)) { if(t->rb) { if(t->rb->left) { t->right->rb = t->rb->left; } else if(t->rb->right) { t->right->rb = t->rb->right; } } q.push(t->right); } } } void verifyRB(Node* root) { cout << "prints only those nodes that are connected by right brother" << "\n"; queue<Node* >q; q.push(root); while(!q.empty()) { Node* t = q.front(); q.pop(); if(t->rb) { cout << t->val << "->" << t->rb->val << " "; } if(t->left) { q.push(t->left); } if(t->right) { q.push(t->right); } } cout << "\n"; } int main() { Node* n = new Node(1); n->left = new Node(2); n->right = new Node(3); n->left->left = new Node(4); n->left->right = new Node(5); n->right->left = new Node(6); n->right->right = new Node(7); RightBrother(n); verifyRB(n); return 0; }
[ "kartheekdpingali@outlook.com" ]
kartheekdpingali@outlook.com
0d82af1b9104f8d8bcd64e91813d0a388a455d09
bc9a442b7d9fee24ff8fcdde42af6016cd7c5c14
/src/yb/rpc/tcp_stream.h
4c69600d4697dc4a38f7427fb22c6d6ee97fd307
[ "Apache-2.0", "BSD-3-Clause", "CC0-1.0", "Unlicense", "bzip2-1.0.6", "dtoa", "MIT", "BSL-1.0", "LicenseRef-scancode-public-domain", "OpenSSL" ]
permissive
shaunstanislauslau/yugabyte-db
722cdd5ff15f3749c9baaba3bb4e6dd4b1f2c58c
d6eaf9c5e69dced184fa76bb6869a191c1426c98
refs/heads/master
2023-06-23T19:53:05.738408
2018-12-04T03:26:26
2018-12-04T14:04:16
160,453,137
0
0
Apache-2.0
2023-06-15T16:20:31
2018-12-05T03:10:09
C
UTF-8
C++
false
false
3,774
h
// Copyright (c) YugaByte, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express // or implied. See the License for the specific language governing permissions and limitations // under the License. // #ifndef YB_RPC_TCP_STREAM_H #define YB_RPC_TCP_STREAM_H #include <ev++.h> #include "yb/rpc/growable_buffer.h" #include "yb/rpc/stream.h" #include "yb/util/net/socket.h" #include "yb/util/ref_cnt_buffer.h" namespace yb { namespace rpc { class TcpStream : public Stream { public: TcpStream( const Endpoint& remote, Socket socket, GrowableBufferAllocator* allocator, size_t limit); ~TcpStream(); Socket* socket() { return &socket_; } std::string ToString() const; static const rpc::Protocol* StaticProtocol(); static StreamFactoryPtr Factory(); private: CHECKED_STATUS Start(bool connect, ev::loop_ref* loop, StreamContext* context) override; void Close() override; void Shutdown(const Status& status) override; void Send(OutboundDataPtr data) override; CHECKED_STATUS TryWrite() override; bool Idle(std::string* reason_not_idle) override; bool IsConnected() override { return connected_; } void DumpPB(const DumpRunningRpcsRequestPB& req, RpcConnectionPB* resp) override; const Endpoint& Remote() override { return remote_; } const Endpoint& Local() override { return local_; } const Protocol* GetProtocol() override { return StaticProtocol(); } void ParseReceived() override; CHECKED_STATUS DoWrite(); void HandleOutcome(const Status& status, bool enqueue); void ClearSending(const Status& status); void Handler(ev::io& watcher, int revents); // NOLINT CHECKED_STATUS ReadHandler(); CHECKED_STATUS WriteHandler(bool just_connected); Result<bool> Receive(); // Try to parse received data and process it. Result<bool> TryProcessReceived(); // Updates listening events. void UpdateEvents(); const std::string& LogPrefix() const; int FillIov(iovec* out); void DelayConnectHandler(ev::timer& watcher, int revents); // NOLINT CHECKED_STATUS DoStart(ev::loop_ref* loop, bool connect); // The socket we're communicating on. Socket socket_; // The remote address we're talking from. Endpoint local_; // The remote address we're talking to. const Endpoint remote_; StreamContext* context_; mutable std::string log_prefix_; // Notifies us when our socket is readable or writable. ev::io io_; ev::timer connect_delayer_; // Set to true when the connection is registered on a loop. // This is used for a sanity check in the destructor that we are properly // un-registered before shutting down. bool is_epoll_registered_ = false; bool connected_ = false; // Data received on this connection that has not been processed yet. GrowableBuffer read_buffer_; bool read_buffer_full_ = false; typedef boost::container::small_vector<RefCntBuffer, 4> SendingBytes; struct SendingData { explicit SendingData(OutboundDataPtr data_); size_t bytes_size() const { size_t result = 0; for (const auto& entry : bytes) { result += entry.size(); } return result; } OutboundDataPtr data; SendingBytes bytes; bool skipped = false; }; std::deque<SendingData> sending_; size_t send_position_ = 0; bool waiting_write_ready_ = false; }; } // namespace rpc } // namespace yb #endif // YB_RPC_TCP_STREAM_H
[ "spolitov@users.noreply.github.com" ]
spolitov@users.noreply.github.com
7a55fad3a58bd00ca45cc6584b33ebcddf75bc5e
bd5b975eb16d7167ddcb37715146e2962b2b7592
/otl4_examples/ex658_odbc.cpp
99465c032efc31eed8df4a83e1942625b8bbae63
[]
no_license
HJolin1986/otl
5bfa1c98dfbe34c1cf38964cd114ef09a4bf454a
d3d12b0bb8749455a0e5fd9a1ee222e3b77323a5
refs/heads/master
2020-08-26T09:41:58.977048
2013-12-09T16:02:13
2013-12-09T16:02:13
15,051,842
2
2
null
null
null
null
UTF-8
C++
false
false
2,725
cpp
#include <iostream> using namespace std; #include <stdio.h> // Compile OTL 4.0/ODBC in Windows. Informix CLI uses the // regular ODBC header files in Windows #define OTL_ODBC // Uncomment the #defines below in Linux / Unix //#define OTL_ODBC_UNIX //#define OTL_INFORMIX_CLI #include <otlv4.h> // include the OTL 4.0 header file otl_connect db; // connect object void insert() // insert rows into table { otl_stream o; o.setBufSize(50); // Send a message (SQL statement) to the otl_connect object. db<<="insert into test_tab values(:f1<int>,:f2<char[31]>)"; // Send a message (SQL statement) from the connect object // to the otl_stream object. db>>o; // By and large, this is all syntactical sugar, but "some like it hot". char tmp[32]; for(int i=1;i<=100;++i){ #if defined(_MSC_VER) #if (_MSC_VER >= 1400) // VC++ 8.0 or higher sprintf_s(tmp,sizeof(tmp),"Name%d",i); #else sprintf(tmp,"Name%d",i); #endif #else sprintf(tmp,"Name%d",i); #endif o<<i<<tmp; } } void select() { otl_stream i; i.setBufSize(50); // Send a message (SQL statement) to the otl_connect object. db<<="select * from test_tab where f1>=:f11<int> and f1<=:f12<int>*2"; // Send a message (SQL statement) from the connect object // to the otl_stream object. db>>i; // By and large, this is all syntactical sugar, but "some like it hot". int f1; char f2[31]; i<<8<<8; // assigning :f11 = 8, :f12 = 8 // SELECT automatically executes when all input variables are // assigned. First portion of output rows is fetched to the buffer while(!i.eof()){ // while not end-of-data i>>f1>>f2; cout<<"f1="<<f1<<", f2="<<f2<<endl; } i<<4<<4; // assigning :f11 = 8, :f12 = 8 // SELECT automatically executes when all input variables are // assigned. First portion of output rows is fetched to the buffer while(!i.eof()){ // while not end-of-data i>>f1>>f2; cout<<"f1="<<f1<<", f2="<<f2<<endl; } } int main() { otl_connect::otl_initialize(); // initialize the database API environment try{ db<<"informix/tigger@informixsql"; // connect to the database // Send SQL statements to the connect obejct for immediate execution. // Ignore any exception for the first statement. try{ db<<"drop table test_tab"; } catch(otl_exception&){} db<<"create table test_tab(f1 int, f2 varchar(30))"; insert(); // insert records into table select(); // select records from table } catch(otl_exception& p){ // intercept OTL exceptions cerr<<p.msg<<endl; // print out error message cerr<<p.stm_text<<endl; // print out SQL that caused the error cerr<<p.var_info<<endl; // print out the variable that caused the error } db.logoff(); // disconnect from the database return 0; }
[ "hjolin1986@gmail.com" ]
hjolin1986@gmail.com
42361aa978aabf77b854d62a7c524efa619e8beb
ecc574079122277e1b75052808b3e01955b050d8
/LeetCode/My-LeetCode-Program/Regular Expression Matching/Regular Expression Matching/源.cpp
11aea4d7469c3c63fd9dcd894bd5fa71c35e2447
[]
no_license
southernriver/My-LeetCode-Program
695b4a8e903449090aaf34ab2d7f71a7aee80331
c461ff836e92513acf89720a3576bfc2e5f462f5
refs/heads/master
2021-01-09T20:23:14.774687
2016-08-09T09:55:23
2016-08-09T09:55:23
65,281,254
0
0
null
null
null
null
UTF-8
C++
false
false
685
cpp
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<ctype.h> bool isMatch(const char *s, const char *p) { int i=0,j=0; if (s==p) return true; if (p==".*") return true; for (; p[i] != '\0';i++) if (p[i]=='*') break; for (; j < i-1; j++) { if (s[j]!=p[j]) return false; } if (s[j] == p[j]){ for (int m = j + 1; s[m] != '\0'; m++) { if (s[s[j]!=s[m]]) } } } int main(){ isMatch("hello","dsfsgfg*gvfhg"); system("pause"); return 0; }
[ "southernriver@163.com" ]
southernriver@163.com
400a89ecbc414f6829e5d48090bc7cdb67bd5a44
c386648d921b9e7fcfa35a4ddfbaf5c518fb58ec
/deps/lcb/tests/socktests/t_ctx.cc
117e6ae3dd0a94f6ec1f0fa99fbaa728a76bfff0
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
frank-dspeed/couchnode
3c6cd00ea994aff5bcbae647a27211130496564e
a380baf54361c081f4f169374af6dcd59c5f5cb3
refs/heads/master
2021-05-09T13:18:06.511898
2020-03-01T19:02:47
2020-03-01T19:02:47
119,030,675
0
0
Apache-2.0
2020-04-06T19:51:35
2018-01-26T09:11:03
JavaScript
UTF-8
C++
false
false
1,638
cc
#include "socktest.h" using namespace LCBTest; using std::string; using std::vector; class SockCtxTest : public SockTest {}; /** * While some of the previous tests also used the 'Easy' context implicitly, * this will try to test some of the more advanced free/destroy functionality. * * This mainly relates to freeing the context and inspecting whether any * callbacks are invoked afterwards. */ TEST_F(SockCtxTest, testClose) { ESocket sock; loop->connect(&sock); for (unsigned ii = 0; ii < 100; ++ii) { sock.put("Hi"); sock.schedule(); } CtxCloseBreakCondition cbc(&sock); cbc.closeCtx(); loop->setBreakCondition(&cbc); loop->start(); } struct ReleaseInfo { lcbio_SOCKET *sock; bool reusable; ReleaseInfo() { sock = NULL; reusable = false; } void reset() { sock = NULL; reusable = false; } }; extern "C" { static void release_cb(lcbio_SOCKET *s, int reusable, void *arg) { ReleaseInfo *info = (ReleaseInfo *)arg; if (reusable) { info->sock = s; lcbio_ref(s); } info->reusable = !!reusable; } } TEST_F(SockCtxTest, testReleasable) { ESocket sock; loop->connect(&sock); ReleaseInfo ri; // Release the socket lcbio_ctx_close(sock.ctx, release_cb, &ri); sock.clear(); ASSERT_TRUE(ri.reusable); // Schedule some events on it. It should not be releaseable sock.assign(ri.sock, LCB_SUCCESS); sock.put("Hi!"); sock.schedule(); ri.reset(); lcbio_ctx_close(sock.ctx, release_cb, &ri); lcbio_unref(sock.sock); sock.clear(); ASSERT_FALSE(ri.reusable); }
[ "brett19@gmail.com" ]
brett19@gmail.com
d0e91c12f2b462c78563cfd39a7f291a4c66bda6
9b62cb953b73a4488eb6d93dcf7a8296823ce29e
/lib/sceneList.hpp
fed36f6df4ae62bb064237fc2cc22db6503f88da
[]
no_license
ivan-didyk/cpp-game
646a6e0e82c41d99a79c4112f216cdb2e589d136
457fc6fac5bfa3fc285dae96c5b0da0c9a65df32
refs/heads/master
2023-02-28T04:23:12.084213
2021-02-04T07:55:49
2021-02-04T07:55:49
328,356,980
0
0
null
null
null
null
UTF-8
C++
false
false
554
hpp
/**************************************\ * Некоторое количество хитрых макросов * * для описания списка сцен * \**************************************/ #define scenes Scene* Game::create(string s) { #define startScene(nm, z) if(s == "" || s == nm) \ return new z; \ else #define scene(nm, z) if(s == nm) \ return new z; \ else #define thatsall throw "No scene names \"" + s + "\""; }
[ "didyk.ivan.90@mail.ru" ]
didyk.ivan.90@mail.ru
bcb25869d7ae60a839d1eabde1d653a4f268e147
e9a8dd3b72faad93932ac87a83bd03b4da4d9a30
/components/leveldb/leveldb_apptest.cc
d9e443ce72e5ac6ff562a88ece1646a2a86e253c
[ "BSD-3-Clause", "LicenseRef-scancode-generic-cla" ]
permissive
MCherifiOSS/ChromiumGStreamerBackend
778683e58169e0dd3a6d6a1d8ffe2617429ad351
7b7d950a6688b8b48ddc872c03fcbff2f8f81872
refs/heads/master
2020-12-28T23:23:35.583848
2016-04-01T16:17:22
2016-04-01T16:17:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,458
cc
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/macros.h" #include "components/filesystem/public/interfaces/directory.mojom.h" #include "components/filesystem/public/interfaces/file_system.mojom.h" #include "components/filesystem/public/interfaces/types.mojom.h" #include "components/leveldb/public/interfaces/leveldb.mojom.h" #include "mojo/common/common_type_converters.h" #include "mojo/public/cpp/bindings/weak_binding_set.h" #include "mojo/shell/public/cpp/application_test_base.h" #include "mojo/shell/public/cpp/shell_connection.h" #include "mojo/util/capture_util.h" using filesystem::FileError; using mojo::Capture; namespace leveldb { namespace { class LevelDBApptest : public mojo::test::ApplicationTestBase { public: LevelDBApptest() {} ~LevelDBApptest() override {} protected: // Overridden from mojo::test::ApplicationTestBase: void SetUp() override { ApplicationTestBase::SetUp(); shell()->ConnectToInterface("mojo:filesystem", &files_); shell()->ConnectToInterface("mojo:leveldb", &leveldb_); } // Note: This has an out parameter rather than returning the |DirectoryPtr|, // since |ASSERT_...()| doesn't work with return values. void GetUserDataDir(filesystem::DirectoryPtr* directory) { FileError error = FileError::FAILED; files()->OpenPersistentFileSystem(GetProxy(directory), mojo::Capture(&error)); ASSERT_TRUE(files().WaitForIncomingResponse()); ASSERT_EQ(FileError::OK, error); } filesystem::FileSystemPtr& files() { return files_; } LevelDBServicePtr& leveldb() { return leveldb_; } private: filesystem::FileSystemPtr files_; LevelDBServicePtr leveldb_; DISALLOW_COPY_AND_ASSIGN(LevelDBApptest); }; TEST_F(LevelDBApptest, Basic) { filesystem::DirectoryPtr directory; GetUserDataDir(&directory); DatabaseError error; LevelDBDatabasePtr database; leveldb()->Open(std::move(directory), "test", GetProxy(&database), Capture(&error)); ASSERT_TRUE(leveldb().WaitForIncomingResponse()); EXPECT_EQ(DatabaseError::OK, error); // Write a key to the database. error = DatabaseError::INVALID_ARGUMENT; database->Put(mojo::Array<uint8_t>::From(std::string("key")), mojo::Array<uint8_t>::From(std::string("value")), Capture(&error)); ASSERT_TRUE(database.WaitForIncomingResponse()); EXPECT_EQ(DatabaseError::OK, error); // Read the key back from the database. error = DatabaseError::INVALID_ARGUMENT; mojo::Array<uint8_t> value; database->Get(mojo::Array<uint8_t>::From(std::string("key")), Capture(&error, &value)); ASSERT_TRUE(database.WaitForIncomingResponse()); EXPECT_EQ(DatabaseError::OK, error); EXPECT_EQ("value", value.To<std::string>()); // Delete the key from the database. error = DatabaseError::INVALID_ARGUMENT; database->Delete(mojo::Array<uint8_t>::From(std::string("key")), Capture(&error)); ASSERT_TRUE(database.WaitForIncomingResponse()); EXPECT_EQ(DatabaseError::OK, error); // Read the key back from the database. error = DatabaseError::INVALID_ARGUMENT; value.SetToEmpty(); database->Get(mojo::Array<uint8_t>::From(std::string("key")), Capture(&error, &value)); ASSERT_TRUE(database.WaitForIncomingResponse()); EXPECT_EQ(DatabaseError::NOT_FOUND, error); EXPECT_EQ("", value.To<std::string>()); } TEST_F(LevelDBApptest, WriteBatch) { filesystem::DirectoryPtr directory; GetUserDataDir(&directory); DatabaseError error; LevelDBDatabasePtr database; leveldb()->Open(std::move(directory), "test", GetProxy(&database), Capture(&error)); ASSERT_TRUE(leveldb().WaitForIncomingResponse()); EXPECT_EQ(DatabaseError::OK, error); // Write a key to the database. database->Put(mojo::Array<uint8_t>::From(std::string("key")), mojo::Array<uint8_t>::From(std::string("value")), Capture(&error)); ASSERT_TRUE(database.WaitForIncomingResponse()); EXPECT_EQ(DatabaseError::OK, error); // Create a batched operation which both deletes "key" and adds another write. mojo::Array<BatchedOperationPtr> operations; BatchedOperationPtr item = BatchedOperation::New(); item->type = BatchOperationType::DELETE_KEY; item->key = mojo::Array<uint8_t>::From(std::string("key")); operations.push_back(std::move(item)); item = BatchedOperation::New(); item->type = BatchOperationType::PUT_KEY; item->key = mojo::Array<uint8_t>::From(std::string("other")); item->value = mojo::Array<uint8_t>::From(std::string("more")); operations.push_back(std::move(item)); database->Write(std::move(operations), Capture(&error)); ASSERT_TRUE(database.WaitForIncomingResponse()); EXPECT_EQ(DatabaseError::OK, error); // Reading "key" should be invalid now. error = DatabaseError::INVALID_ARGUMENT; mojo::Array<uint8_t> value; database->Get(mojo::Array<uint8_t>::From(std::string("key")), Capture(&error, &value)); ASSERT_TRUE(database.WaitForIncomingResponse()); EXPECT_EQ(DatabaseError::NOT_FOUND, error); EXPECT_EQ("", value.To<std::string>()); // Reading "other" should return "more" error = DatabaseError::INVALID_ARGUMENT; database->Get(mojo::Array<uint8_t>::From(std::string("other")), Capture(&error, &value)); ASSERT_TRUE(database.WaitForIncomingResponse()); EXPECT_EQ(DatabaseError::OK, error); EXPECT_EQ("more", value.To<std::string>()); } TEST_F(LevelDBApptest, Reconnect) { DatabaseError error; { filesystem::DirectoryPtr directory; GetUserDataDir(&directory); LevelDBDatabasePtr database; leveldb()->Open(std::move(directory), "test", GetProxy(&database), Capture(&error)); ASSERT_TRUE(leveldb().WaitForIncomingResponse()); EXPECT_EQ(DatabaseError::OK, error); // Write a key to the database. error = DatabaseError::INVALID_ARGUMENT; database->Put(mojo::Array<uint8_t>::From(std::string("key")), mojo::Array<uint8_t>::From(std::string("value")), Capture(&error)); ASSERT_TRUE(database.WaitForIncomingResponse()); EXPECT_EQ(DatabaseError::OK, error); // The database should go out of scope here. } { filesystem::DirectoryPtr directory; GetUserDataDir(&directory); // Reconnect to the database. LevelDBDatabasePtr database; leveldb()->Open(std::move(directory), "test", GetProxy(&database), Capture(&error)); ASSERT_TRUE(leveldb().WaitForIncomingResponse()); EXPECT_EQ(DatabaseError::OK, error); // We should still be able to read the key back from the database. error = DatabaseError::INVALID_ARGUMENT; mojo::Array<uint8_t> value; database->Get(mojo::Array<uint8_t>::From(std::string("key")), Capture(&error, &value)); ASSERT_TRUE(database.WaitForIncomingResponse()); EXPECT_EQ(DatabaseError::OK, error); EXPECT_EQ("value", value.To<std::string>()); } } TEST_F(LevelDBApptest, GetSnapshotSimple) { DatabaseError error; filesystem::DirectoryPtr directory; GetUserDataDir(&directory); LevelDBDatabasePtr database; leveldb()->Open(std::move(directory), "test", GetProxy(&database), Capture(&error)); ASSERT_TRUE(leveldb().WaitForIncomingResponse()); EXPECT_EQ(DatabaseError::OK, error); uint64_t snapshot_id = 0; database->GetSnapshot(Capture(&snapshot_id)); ASSERT_TRUE(database.WaitForIncomingResponse()); EXPECT_NE(static_cast<uint64_t>(0), snapshot_id); } TEST_F(LevelDBApptest, GetFromSnapshots) { DatabaseError error; filesystem::DirectoryPtr directory; GetUserDataDir(&directory); LevelDBDatabasePtr database; leveldb()->Open(std::move(directory), "test", GetProxy(&database), Capture(&error)); ASSERT_TRUE(leveldb().WaitForIncomingResponse()); EXPECT_EQ(DatabaseError::OK, error); // Write a key to the database. error = DatabaseError::INVALID_ARGUMENT; database->Put(mojo::Array<uint8_t>::From(std::string("key")), mojo::Array<uint8_t>::From(std::string("value")), Capture(&error)); ASSERT_TRUE(database.WaitForIncomingResponse()); EXPECT_EQ(DatabaseError::OK, error); // Take a snapshot where key=value. uint64_t key_value_snapshot = 0; database->GetSnapshot(Capture(&key_value_snapshot)); ASSERT_TRUE(database.WaitForIncomingResponse()); // Change key to "yek". error = DatabaseError::INVALID_ARGUMENT; database->Put(mojo::Array<uint8_t>::From(std::string("key")), mojo::Array<uint8_t>::From(std::string("yek")), Capture(&error)); ASSERT_TRUE(database.WaitForIncomingResponse()); EXPECT_EQ(DatabaseError::OK, error); // (Ensure this change is live on the database.) error = DatabaseError::INVALID_ARGUMENT; mojo::Array<uint8_t> value; database->Get(mojo::Array<uint8_t>::From(std::string("key")), Capture(&error, &value)); ASSERT_TRUE(database.WaitForIncomingResponse()); EXPECT_EQ(DatabaseError::OK, error); EXPECT_EQ("yek", value.To<std::string>()); // But if we were to read from the snapshot, we'd still get value. error = DatabaseError::INVALID_ARGUMENT; value.SetToEmpty(); database->GetFromSnapshot( key_value_snapshot, mojo::Array<uint8_t>::From(std::string("key")), Capture(&error, &value)); ASSERT_TRUE(database.WaitForIncomingResponse()); EXPECT_EQ(DatabaseError::OK, error); EXPECT_EQ("value", value.To<std::string>()); } TEST_F(LevelDBApptest, InvalidArgumentOnInvalidSnapshot) { filesystem::DirectoryPtr directory; GetUserDataDir(&directory); LevelDBDatabasePtr database; DatabaseError error = DatabaseError::INVALID_ARGUMENT; leveldb()->Open(std::move(directory), "test", GetProxy(&database), Capture(&error)); ASSERT_TRUE(leveldb().WaitForIncomingResponse()); EXPECT_EQ(DatabaseError::OK, error); uint64_t invalid_snapshot = 8; error = DatabaseError::OK; mojo::Array<uint8_t> value; database->GetFromSnapshot( invalid_snapshot, mojo::Array<uint8_t>::From(std::string("key")), Capture(&error, &value)); ASSERT_TRUE(database.WaitForIncomingResponse()); EXPECT_EQ(DatabaseError::INVALID_ARGUMENT, error); } } // namespace } // namespace leveldb
[ "a.obzhirov@samsung.com" ]
a.obzhirov@samsung.com
a59ea2481e01ebf5416fe4d6d652483190db2969
a71582e89e84a4fae2595f034d06af6d8ad2d43a
/tensorflow/lite/experimental/micro/kernels/depthwise_conv.cc
ce821a94787796251ba4becc327e257352e0ad05
[ "Apache-2.0" ]
permissive
tfboyd/tensorflow
5328b1cabb3e24cb9534480fe6a8d18c4beeffb8
865004e8aa9ba630864ecab18381354827efe217
refs/heads/master
2021-07-06T09:41:36.700837
2019-04-01T20:21:03
2019-04-01T20:26:09
91,494,603
3
0
Apache-2.0
2018-07-17T22:45:10
2017-05-16T19:06:01
C++
UTF-8
C++
false
false
8,839
cc
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/c/builtin_op_data.h" #include "tensorflow/lite/c/c_api_internal.h" #include "tensorflow/lite/kernels/internal/common.h" #include "tensorflow/lite/kernels/internal/quantization_util.h" #include "tensorflow/lite/kernels/internal/tensor_ctypes.h" #include "tensorflow/lite/kernels/kernel_util.h" #include "tensorflow/lite/kernels/padding.h" #include "tensorflow/lite/kernels/internal/reference/depthwiseconv_float.h" #include "tensorflow/lite/kernels/internal/reference/depthwiseconv_uint8.h" namespace tflite { namespace ops { namespace micro { namespace depthwise_conv { namespace { constexpr int kInputTensor = 0; constexpr int kFilterTensor = 1; constexpr int kBiasTensor = 2; constexpr int kOutputTensor = 0; struct OpData { TfLitePaddingValues padding; // The scaling factor from input to output (aka the 'real multiplier') can // be represented as a fixed point multiplier plus a left shift. int32_t output_multiplier; int output_shift; // The range of the fused activation layer. For example for kNone and // uint8_t these would be 0 and 255. int32_t output_activation_min; int32_t output_activation_max; }; TfLiteStatus CalculateOpData(TfLiteContext* context, TfLiteNode* node, TfLiteDepthwiseConvParams* params, int width, int height, int filter_width, int filter_height, int out_width, int out_height, const TfLiteType data_type, OpData* data) { data->padding.height = ComputePadding(params->stride_height, 1, height, filter_height, out_height); data->padding.width = ComputePadding(params->stride_width, 1, width, filter_width, out_width); // Note that quantized inference requires that all tensors have their // parameters set. This is usually done during quantized training. if (data_type != kTfLiteFloat32) { const TfLiteTensor* input = GetInput(context, node, kInputTensor); const TfLiteTensor* filter = GetInput(context, node, kFilterTensor); const TfLiteTensor* bias = GetOptionalInputTensor(context, node, kBiasTensor); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); double real_multiplier = 0.0; TF_LITE_ENSURE_STATUS(GetQuantizedConvolutionMultipler( context, input, filter, bias, output, &real_multiplier)); int exponent; QuantizeMultiplier(real_multiplier, &data->output_multiplier, &exponent); data->output_shift = -exponent; CalculateActivationRangeUint8(params->activation, output, &data->output_activation_min, &data->output_activation_max); } return kTfLiteOk; } } // namespace void* Init(TfLiteContext* context, const char* buffer, size_t length) { return nullptr; } void Free(TfLiteContext* context, void* buffer) {} TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { return kTfLiteOk; } void EvalFloat(TfLiteContext* context, TfLiteNode* node, TfLiteDepthwiseConvParams* params, OpData* data, const TfLiteTensor* input, const TfLiteTensor* filter, const TfLiteTensor* bias, TfLiteTensor* output) { float output_activation_min, output_activation_max; CalculateActivationRange(params->activation, &output_activation_min, &output_activation_max); tflite::DepthwiseParams op_params; // Padding type is ignored, but still set. op_params.padding_type = PaddingType::kSame; op_params.padding_values.width = data->padding.width; op_params.padding_values.height = data->padding.height; op_params.stride_width = params->stride_width; op_params.stride_height = params->stride_height; op_params.dilation_width_factor = 1; op_params.dilation_height_factor = 1; op_params.depth_multiplier = params->depth_multiplier; op_params.float_activation_min = output_activation_min; op_params.float_activation_max = output_activation_max; tflite::reference_ops::DepthwiseConv( op_params, GetTensorShape(input), GetTensorData<float>(input), GetTensorShape(filter), GetTensorData<float>(filter), GetTensorShape(bias), GetTensorData<float>(bias), GetTensorShape(output), GetTensorData<float>(output)); } void EvalQuantized(TfLiteContext* context, TfLiteNode* node, TfLiteDepthwiseConvParams* params, OpData* data, const TfLiteTensor* input, const TfLiteTensor* filter, const TfLiteTensor* bias, TfLiteTensor* output) { const int32_t input_offset = -input->params.zero_point; const int32_t filter_offset = -filter->params.zero_point; const int32_t output_offset = output->params.zero_point; tflite::DepthwiseParams op_params; // Padding type is ignored, but still set. op_params.padding_type = PaddingType::kSame; op_params.padding_values.width = data->padding.width; op_params.padding_values.height = data->padding.height; op_params.stride_width = params->stride_width; op_params.stride_height = params->stride_height; op_params.dilation_width_factor = 1; op_params.dilation_height_factor = 1; op_params.depth_multiplier = params->depth_multiplier; op_params.quantized_activation_min = data->output_activation_min; op_params.quantized_activation_max = data->output_activation_max; op_params.input_offset = input_offset; op_params.weights_offset = filter_offset; op_params.output_offset = output_offset; op_params.output_multiplier = data->output_multiplier; // Legacy ops used mixed left and right shifts. Now all are +ve-means-left. op_params.output_shift = -data->output_shift; tflite::reference_ops::DepthwiseConv( op_params, GetTensorShape(input), GetTensorData<uint8_t>(input), GetTensorShape(filter), GetTensorData<uint8_t>(filter), GetTensorShape(bias), GetTensorData<int32_t>(bias), GetTensorShape(output), GetTensorData<uint8_t>(output)); } TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { auto* params = reinterpret_cast<TfLiteDepthwiseConvParams*>(node->builtin_data); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); const TfLiteTensor* input = GetInput(context, node, kInputTensor); const TfLiteTensor* filter = GetInput(context, node, kFilterTensor); const TfLiteTensor* bias = (NumInputs(node) == 3) ? GetInput(context, node, kBiasTensor) : nullptr; const TfLiteType data_type = input->type; int width = SizeOfDimension(input, 2); int height = SizeOfDimension(input, 1); int filter_width = SizeOfDimension(filter, 2); int filter_height = SizeOfDimension(filter, 1); int out_width = ComputeOutSize(params->padding, width, filter_width, params->stride_width); int out_height = ComputeOutSize(params->padding, height, filter_height, params->stride_height); OpData local_data_object; OpData* data = &local_data_object; TF_LITE_ENSURE_STATUS(CalculateOpData(context, node, params, width, height, filter_width, filter_height, out_width, out_height, data_type, data)); // TODO(aselle): Consider whether float conv and quantized conv should be // separate ops to avoid dispatch overhead here. switch (input->type) { // Already know in/out types are same. case kTfLiteFloat32: EvalFloat(context, node, params, data, input, filter, bias, output); break; case kTfLiteUInt8: EvalQuantized(context, node, params, data, input, filter, bias, output); break; default: context->ReportError(context, "Type %d not currently supported.", input->type); return kTfLiteError; } return kTfLiteOk; } } // namespace depthwise_conv TfLiteRegistration* Register_DEPTHWISE_CONV_2D() { static TfLiteRegistration r = {depthwise_conv::Init, depthwise_conv::Free, depthwise_conv::Prepare, depthwise_conv::Eval}; return &r; } } // namespace micro } // namespace ops } // namespace tflite
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
7865b1b6a716965ab3747c968fe98ec10c34035c
0fed3d6c4a6dbdb49029913b6ce96a9ede9eac6c
/Misc/ICPC2017/Beijing/C.cpp
1e2f3bb9b38024de18cddee895397b48e3519895
[]
no_license
87ouo/The-road-to-ACMer
72df2e834027dcfab04b02ba0ddd350e5078dfc0
0a39a9708a0e7fd0e3b2ffff5d1f4a793b031df5
refs/heads/master
2021-02-18T17:44:29.937434
2019-07-31T11:30:27
2019-07-31T11:30:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,844
cpp
#include <bits/stdc++.h> using namespace std; #define clr(a, x) memset(a, x, sizeof(a)) #define mp(x, y) make_pair(x, y) #define pb(x) push_back(x) #define X first #define Y second #define fastin \ ios_base::sync_with_stdio(0); \ cin.tie(0); typedef long long ll; typedef long double ld; typedef pair<int, int> PII; typedef vector<int> VI; const int INF = 0x3f3f3f3f; const int mod = 1e9 + 7; const double eps = 1e-6; const int maxn = 305; int a[maxn][maxn]; int b[maxn], mm[maxn]; int dp[maxn]; int main() { #ifndef ONLINE_JUDGE freopen("1.in", "r", stdin); freopen("1.out", "w", stdout); #endif int n, m, P; dp[0] = -INF; while (~scanf("%d%d%d", &n, &m, &P)) { int tot = 0, minv = INF; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) { scanf("%d", &a[i][j]); tot += a[i][j]; minv = min(minv, a[i][j]); } int ans = -INF; for (int i = 1; i <= n; i++) { clr(b, 0); clr(mm, 0x3f); for (int j = i; j <= n; j++) { int sum = 0; bool flag = 0; for (int k = 1; k <= m; k++) { b[k] += a[j][k]; mm[k] = min(mm[k], a[j][k]); sum = max(sum, 0); sum += b[k]; dp[k] = max(dp[k - 1] + b[k], sum - mm[k] + P); if (i == 1 && j == n && k == m && tot == sum && !flag) ans = max(ans, sum - minv + P); else ans = max(ans, max(dp[k], sum)); if (sum <= 0) flag = 1; } } } printf("%d\n", ans); } return 0; }
[ "zbszx040504@126.com" ]
zbszx040504@126.com
9a6e532e263e35686db413f71fd51b459d395dbe
4200b16d40f5bbf5b813f2bdf5215b39168d076e
/04-addon-event-emitter/01/src/native-emitter.h
e1ee7e54dbe6363635ba7ab8cfca51f7bd47a639
[ "Apache-2.0" ]
permissive
NickNaso/conf-cd-rome-2018
4c49573644d22ee62f0b1824afdd188b4df1dbf6
7aaa39ff1b959f0fe2a4d841cc34fdf251716a57
refs/heads/master
2021-05-04T18:00:56.497302
2018-04-13T23:13:10
2018-04-13T23:13:10
120,283,715
2
0
null
null
null
null
UTF-8
C++
false
false
1,280
h
/******************************************************************************* * Copyright (c) 2018 Nicola Del Gobbo * 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 * * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY * IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, * MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing * permissions and limitations under the License. * * Contributors - initial API implementation: * Nicola Del Gobbo <nicoladelgobbo@gmail.com> ******************************************************************************/ #include <napi.h> class NativeEmitter : public Napi::ObjectWrap<NativeEmitter> { public: static Napi::Object Init(Napi::Env env, Napi::Object exports); NativeEmitter(const Napi::CallbackInfo& info); private: static Napi::FunctionReference constructor; Napi::Value CallAndEmit(const Napi::CallbackInfo& info); };
[ "nicoladelgobbo@gmail.com" ]
nicoladelgobbo@gmail.com
bf50cd3cd9b50508d31a08adbd4ecdfcca521ad6
df9740b3119e74a793fa333d4354026aa44a13fe
/src/txdb.h
3f07f0edec38a66ea9de65415ba16591dc49e269
[ "MIT" ]
permissive
fabianojedao/Celcoin-Core-v3
654a72424ba0ded9a7431ddfb3f84cdb04609324
fcc16414c1d24be5adbac04086140bfa90803b1a
refs/heads/master
2020-03-28T11:49:22.657486
2018-09-05T18:54:28
2018-09-05T18:54:28
148,249,295
0
2
MIT
2018-09-11T02:35:00
2018-09-11T02:35:00
null
UTF-8
C++
false
false
1,784
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_TXDB_LEVELDB_H #define BITCOIN_TXDB_LEVELDB_H #include "main.h" #include "leveldb.h" /** CCoinsView backed by the LevelDB coin database (coins/) */ class CCoinsViewDB : public CCoinsView { protected: CLevelDB db; public: CCoinsViewDB(bool fMemory = false); bool GetCoins(uint256 txid, CCoins &coins); bool SetCoins(uint256 txid, const CCoins &coins); bool HaveCoins(uint256 txid); CBlockIndex *GetBestBlock(); bool SetBestBlock(CBlockIndex *pindex); bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex); bool GetStats(CCoinsStats &stats); }; /** Access to the block database (blktree/) */ class CBlockTreeDB : public CLevelDB { public: CBlockTreeDB(bool fMemory = false); private: CBlockTreeDB(const CBlockTreeDB&); void operator=(const CBlockTreeDB&); public: bool WriteBlockIndex(const CDiskBlockIndex& blockindex); bool ReadBestInvalidTrust(CBigNum& bnBestInvalidTrust); bool WriteBestInvalidTrust(CBigNum bnBestInvalidTrust); bool ReadBlockFileInfo(int nFile, CBlockFileInfo &fileinfo); bool WriteBlockFileInfo(int nFile, const CBlockFileInfo &fileinfo); bool ReadLastBlockFile(int &nFile); bool WriteLastBlockFile(int nFile); bool ReadSyncCheckpoint(uint256& hashCheckpoint); bool WriteSyncCheckpoint(uint256 hashCheckpoint); bool ReadCheckpointPubKey(std::string& strPubKey); bool WriteCheckpointPubKey(const std::string& strPubKey); bool LoadBlockIndexGuts(); }; #endif // BITCOIN_TXDB_LEVELDB_H
[ "ing.daimon96@gmail.com" ]
ing.daimon96@gmail.com
1da18e7d93589c354d223773c93a67879a32ed26
b538ad8b58864b4d206ed07a00dc9c37c482d280
/Module03/ex04/src/ClapTrap.cc
dda9b3caeec83c11f551a3d59eb5fa1f16df685f
[]
no_license
aberry-21/CPP_Module
0083035a4bc7be7cf83035738458660c23a2389c
42f08b10e6ebada9d0034464a0bed9a8a2dfada6
refs/heads/main
2023-04-21T21:37:51.882909
2021-04-29T17:30:32
2021-04-29T17:30:32
357,558,067
0
0
null
null
null
null
UTF-8
C++
false
false
4,885
cc
// // Created by Aaron Berry on 4/20/21. // #include <iostream> #include "includes/ClapTrap.h" ClapTrap::ClapTrap() : level_(1), name_("No name"), max_energy_points_(100), max_hit_points_(100), hit_points_(100), energy_points_(100), melee_attack_damage_(30), ranged_attack_damage_(20), armor_damage_reduction_(3) { std::cout << name_ << " ClapTrap default constructor called" << std::endl; } ClapTrap::ClapTrap(const std::string &name) : level_(1), name_(name), max_energy_points_(100), max_hit_points_(100), hit_points_(100), energy_points_(100), melee_attack_damage_(30), ranged_attack_damage_(20), armor_damage_reduction_(3) { std::cout << name_ << " ClapTrap default constructor called" << std::endl; } ClapTrap::~ClapTrap() { std::cout << name_ << " ClapTrap default destructor called" << std::endl; } ClapTrap::ClapTrap(const ClapTrap &other) : level_(other.level_), name_(other.name_), max_energy_points_(other.max_energy_points_), max_hit_points_(other.max_energy_points_), hit_points_(other.hit_points_), energy_points_(other.energy_points_), melee_attack_damage_(other.melee_attack_damage_), ranged_attack_damage_(other.armor_damage_reduction_), armor_damage_reduction_(other.ranged_attack_damage_) { std::cout << name_ << " ClapTrap default constructor called" << std::endl; } ClapTrap &ClapTrap::operator=(const ClapTrap &other) { if (this == &other) { return *this; } max_energy_points_ = other.max_energy_points_; max_hit_points_ = other.max_energy_points_; name_ = other.name_; hit_points_ = other.hit_points_; energy_points_ = other.energy_points_; level_ = other.level_; melee_attack_damage_ = other.melee_attack_damage_; armor_damage_reduction_ = other.armor_damage_reduction_; ranged_attack_damage_ = other.ranged_attack_damage_; return *this; } void ClapTrap::RangedAttack(const std::string &target) { std::cout << "FR4G-TP " << name_ << "attacks " << target << " at range, causing " << ranged_attack_damage_ << " points of damage!" << std::endl; } void ClapTrap::MeleeAttack(const std::string &target) { std::cout << "FR4G-TP " << name_ << "attacks " << target << ", causing " << melee_attack_damage_ << " points of damage!" << std::endl; } void ClapTrap::TakeDamage(unsigned int amount) { std::cout << "FR4G-TP " << name_ << " take damage: " << amount << std::endl; amount -= armor_damage_reduction_; hit_points_ -= static_cast<int>(amount); if (hit_points_ < 0) { hit_points_ = 0; } std::cout << "FR4G-TP " << name_ << " has hp: " << hit_points_ << std::endl; } void ClapTrap::BeRepaired(unsigned int amount) { std::cout << "FR4G-TP " << name_ << " be repaired: " << amount << std::endl; hit_points_ += static_cast<int>(amount); if (hit_points_ > max_hit_points_) { hit_points_ = max_hit_points_; } std::cout << "FR4G-TP " << name_ << " has hp: " << hit_points_ << std::endl; } const std::string &ClapTrap::getName() const { return name_; } void ClapTrap::setName(const std::string &name) { name_ = name; } int ClapTrap::getHitPoints() const { return hit_points_; } void ClapTrap::setHitPoints(int hitPoints) { if (hitPoints < 0) { hitPoints = 0; } hit_points_ = hitPoints; if (hit_points_ > max_hit_points_) { hit_points_ = 100; } } int ClapTrap::getEnergyPoints() const { return energy_points_; } void ClapTrap::setEnergyPoints(int energyPoints) { if (energyPoints < 0) { energyPoints = 0; } energy_points_ = energyPoints; if (energy_points_ > max_energy_points_) { energy_points_ = 100; } } int ClapTrap::getLevel() const { return level_; } void ClapTrap::setLevel(int level) { if (level < 0) { level = 0; } level_ = level; } int ClapTrap::getMeleeAttackDamage() const { return melee_attack_damage_; } void ClapTrap::setMeleeAttackDamage(int meleeAttackDamage) { if (meleeAttackDamage < 0) { meleeAttackDamage = 0; } melee_attack_damage_ = meleeAttackDamage; } int ClapTrap::getRangedAttackDamage() const { return ranged_attack_damage_; } void ClapTrap::setRangedAttackDamage(int rangedAttackDamage) { if (rangedAttackDamage < 0) { rangedAttackDamage = 0; } ranged_attack_damage_ = rangedAttackDamage; } int ClapTrap::getArmorDamageReduction() const { return armor_damage_reduction_; } void ClapTrap::setArmorDamageReduction(int armorDamageReduction) { if (armorDamageReduction < 0) { armorDamageReduction = 0; } armor_damage_reduction_ = armorDamageReduction; } int ClapTrap::getMaxEnergyPoints() const { return max_energy_points_; } void ClapTrap::setMaxEnergyPoints(int maxEnergyPoints) { max_energy_points_ = maxEnergyPoints; } int ClapTrap::getMaxHitPoints() const { return max_hit_points_; } void ClapTrap::setMaxHitPoints(int maxHitPoints) { max_hit_points_ = maxHitPoints; }
[ "lot.lebedevok@gmail.com" ]
lot.lebedevok@gmail.com
fa023aa6b7977bb5ebc0a539fde18d5613f56e8f
14f87486014374292251903e3f1067dd37984aeb
/DCEL/Delaunay.cpp
fc371446eac77eaf9029ab4b002181c5cf377c55
[]
no_license
daniel-kish/PathSearch
5bf849dc4428fee5aeb4a7e3f44d1adf593e07c3
d372e1ed48ba6421f6222059b2aad2cc5540c7a7
refs/heads/master
2020-06-19T15:51:50.555767
2017-06-28T20:00:07
2017-06-28T20:00:07
74,901,430
0
1
null
null
null
null
UTF-8
C++
false
false
8,709
cpp
#define _USE_MATH_DEFINES #include "Delaunay.h" #include "Kirkpatrick.h" #include <cmath> #include <cassert> #include <random> #include <queue> #include <iomanip> DCEL::EdgeList::iterator clip_ear(DCEL& d, DCEL::EdgeList::iterator h) { auto a = h->prev->target; auto b = h->target; auto c = h->next->target; if (h->next->next->target == a) // it's a triangle return h; if (side(a->p, c->p, b->p) != Side::right) // not an ear return h->next; auto i = h->next->next; do { if (insideTriangle(a->p, b->p, c->p, i->target->p) != Position::out) // not an ear return h->next; i = i->next; } while (i != h->prev); d.split_face(h->next, a); return h->next->next->twin; } DCEL::EdgeList::iterator clip_delaunay_ear(DCEL& d, DCEL::EdgeList::iterator h) { // preconditions: at least two faces should already be present assert(d.faces.size() > 1); assert(h->face != d.out_face); if (h->next->next->next == h) return h; auto a = h->prev->target; auto b = h->target; auto c = h->next->target; if (side(a->p, c->p, b->p) != Side::right) return h->next; Circle circle = circumCircle(a->p, b->p, c->p); auto i = h->next->next; do { if (inCircle(circle, i->target->p)) return h->next; i = i->next; } while (i != h->prev); d.split_face(h->next, a); return h->prev->twin; } void polygon_delaunay_triangulation(DCEL& d, DCEL::FaceList::iterator in_face) { assert(d.faces.size() > 1); assert(in_face != d.out_face); auto h = in_face->halfedge; DCEL::EdgeList::iterator rh{h}; do { h = rh; rh = clip_delaunay_ear(d,h); } while (rh != h); } bool localDelaunay(DCEL& dcel, DCEL::EdgeList::iterator h) { // preconditions: assert(h->face != dcel.out_face && h->twin->face != dcel.out_face); auto g = h->twin; auto a = h->next->target; auto b = g->next->target; auto c = h->target; auto d = g->target; Point ac = c->p - a->p; Point ad = d->p - a->p; Point bc = c->p - b->p; Point bd = d->p - b->p; double alpha = std::acos((ac*ad) / norm(ac) / norm(ad)); double beta = std::acos((bc*bd) / norm(bc) / norm(bd)); return alpha + beta < M_PI; } DCEL::EdgeList::iterator flip(DCEL& d, DCEL::EdgeList::iterator h) { // preconditions: assert(h->face != d.out_face && h->twin->face != d.out_face); auto g = h->next; auto v = h->twin->next->target; d.join_face(h); d.split_face(g, v); return g->next->twin; } // {h,true} if inside std::tuple<DCEL::EdgeList::iterator,bool> localize(DCEL& d, Point const& p) { for (auto f = d.faces.begin(); f != d.faces.end(); ++f) { if (f == d.out_face) continue; auto h = f->halfedge; Point const& a = h->prev->target->p; Point const& b = h->target->p; Point const& c = h->next->target->p; Position pos = insideTriangle(a, b, c, p); switch (pos) { case Position::out: continue; case Position::in: return {h,true}; case Position::edge01: return {h,false}; case Position::edge12: return {h->next,false}; case Position::edge02: return{h->prev,false}; } } // if 'p' is an outer point - ignore it return {d.halfedges.end(),false}; } void insert_point_inside(DCEL& d, DCEL::EdgeList::iterator h, Point const& p) { d.add_vertex(p, h); auto g = h->next; d.split_face(g,h->prev->target); g = g->next->twin; d.split_face(g, g->prev->prev->target); } void insert_point_on_edge(DCEL& d, DCEL::EdgeList::iterator h, Point const& p) { d.split_edge(h, p); d.split_face(h, h->prev->prev->target); if (h->twin->face != d.out_face) d.split_face(h->twin->prev, h->twin->next->target); } void insert_point(DCEL& d, Point const& p) { DCEL::VertexList::iterator vertex; DCEL::EdgeList::iterator h; bool inside; std::tie(h,inside) = localize(d, p); if (h == d.halfedges.end()) return; Queue q; if (inside) { insert_point_inside(d, h, p); vertex = h->next->target; q.push(h); h = h->next->twin->next; q.push(h); h = h->next->twin->next; q.push(h); } else { insert_point_on_edge(d, h, p); vertex = h->target; h = h->prev; q.push(h); if (h->next->twin->face != d.out_face) { h = h->next->twin->next; q.push(h); h = h->next->twin->next; q.push(h); h = h->next->twin->next; q.push(h); } else { h = h->prev->twin->prev; q.push(h); } } while (!q.empty()) { auto h = q.front(); q.pop(); if (h->twin->face == d.out_face) continue; if (!localDelaunay(d, h)) { h = flip(d, h); q.push(h->prev); q.push(h->twin->next); } } //return vertex; } bool is_CCW_triangle(DCEL::FaceList::iterator f) { auto h = f->halfedge; auto i{h}; int n{0}; do { n++; i = i->next; } while (i != h); if (n != 3) { std::cout << "face " << f->i << " is not a triangle\n"; return false; } Point const& a = h->prev->target->p; Point const& b = h->target->p; Point const& c = h->next->target->p; if (a == b || b == c || c == a) { std::cout << "face " << f->i << " contains coinciding points\n"; return false; } else if (h->prev->target == h->target || h->target == h->next->target) { std::cout << "face " << f->i << " contains coinciding vertices\n"; return false; } auto x = [](Point const& p) {return p.x; }; auto y = [](Point const& p) {return p.y; }; double det = (x(b) - x(a))*(y(c) - y(a)) - (x(c) - x(a))*(y(b) - y(a)); if (det < 0.0) {// PolyOrientation::CW; std::cout << "face " << f->i << "is CW\n"; return false; } return true; } bool check_triangulation(DCEL& d) { if (!is_out_face(d.out_face)) { std::cout << "out_face is not out\n"; return false; } for (auto f = d.faces.begin(); f != d.faces.end(); ++f) { if (f == d.out_face) continue; if (!is_CCW_triangle(f)) return false; auto h = f->halfedge; Point const& a = h->prev->target->p; Point const& b = h->target->p; Point const& c = h->next->target->p; for (auto v = d.vertices.begin(); v != d.vertices.end(); ++v) { if (v == h->target || v == h->prev->target || v == h->next->target) continue; if (insideTriangle(a, b, c, v->p) == Position::in) { is_CCW_triangle(f); insideTriangle(a, b, c, v->p); std::cout << std::setprecision(12) << "point " << v->p << " is inside the face " << '(' << a <<' '<< b <<' '<< c << ')' << '\n'; return false; } } } return true; } std::vector<Point> rectHull(Rect r, int x_pts, int y_pts) { double wid = std::abs(r.dir.x); double height = std::abs(r.dir.y); double xStep = wid / x_pts; double yStep = height / y_pts; std::vector<Point> pts; pts.reserve(2 * x_pts + 2 * x_pts); for (double x = 0.0; x < wid; x += xStep) pts.push_back(Point{x,0.0}); for (double y = 0.0; y < height; y += yStep) pts.push_back(Point{wid,y}); for (double x = wid; x > 0.0; x -= xStep) pts.push_back(Point{x,height}); for (double y = height; y > 0.0; y -= yStep) pts.push_back(Point{0.0,y}); auto le = std::unique(pts.begin(), pts.end(), [](Point const& p, Point const& q) { if (abs(p.x - q.x) < 1.0e-5 && abs(p.y - q.y) < 1.0e-5) return true; return false; }); pts.erase(le, pts.end()); if (abs(pts.back().x - pts.front().x) < 1.0e-5 && abs(pts.back().y - pts.front().y) < 1.0e-5) pts.pop_back(); pts.shrink_to_fit(); if (r.origin != Point{0.0,0.0}) for (Point& p : pts) p = p + r.origin; return pts; } std::vector<Point> rectInsides(Rect r, int x_pts, int y_pts) { std::vector<Point> pts; double xb = r.origin.x, xe = r.origin.x + r.dir.x; double yb = r.origin.y, ye = r.origin.y + r.dir.y; double x_step = (xe - xb) / x_pts; double y_step = (ye - yb) / y_pts; for (double x = xb + x_step; x < xe; x += x_step) for (double y = yb + y_step; y < ye; y += y_step) pts.push_back({x,y}); return pts; } std::vector<Point> rectInsidesRand(Rect r, int n_pts) { std::vector<Point> pts; pts.reserve(n_pts); double xb = r.origin.x, xe = r.origin.x + r.dir.x; double yb = r.origin.y, ye = r.origin.y + r.dir.y; std::random_device rd; std::mt19937 mt{/*rd()*/}; std::uniform_real_distribution<double> xd(xb, xe); std::uniform_real_distribution<double> yd(yb, ye); while (n_pts--) pts.push_back({xd(mt),yd(mt)}); return pts; } std::vector<Point> circleHull(Circle c, int nsteps) { double step = 2.0*M_PI / nsteps; std::vector<Point> pts; pts.reserve(nsteps); for (double phi = 0.0; phi < 2.0*M_PI; phi += step) { double rho = c.rad /*+ 0.4*c.rad*sin(3 * phi)*/; pts.push_back(Point{rho*cos(phi), rho*sin(phi)} + c.center); } auto le = std::unique(pts.begin(), pts.end(), [](Point const& p, Point const& q) { if (abs(p.x - q.x) < 1.0e-5 && abs(p.y - q.y) < 1.0e-5) return true; return false; }); pts.erase(le, pts.end()); if (abs(pts.back().x - pts.front().x) < 1.0e-5 && abs(pts.back().y - pts.front().y) < 1.0e-5) pts.pop_back(); pts.shrink_to_fit(); return pts; }
[ "daniel_kish@outlook.com" ]
daniel_kish@outlook.com
e885a40344ea8f3b0606ffa5729cde316f4bc641
552a92d34f6daffb7ce347342258e0c717a1bdde
/Taylor.h
e17b7e0aadc4f258958439af5af24efdbb3154a5
[]
no_license
phamnguyenquang/STAM
98447644433cb563c60a1ceaf4588608800fa659
78652aaefe9c31fc54fd258361b7fbc223db8d23
refs/heads/master
2020-03-12T18:36:30.910415
2018-04-23T22:41:36
2018-04-23T22:41:36
130,764,589
0
0
null
null
null
null
UTF-8
C++
false
false
322
h
#ifndef Talor_H #define Taylor_H #include"General.h" namespace solver { class taylor_sin { private: double input; int term; public: taylor_sin(double x, int i); double compute(); double error_cal() { double r = sin(input*PI / 180); } }; int factorial(int n); double power(double a, int b); } #endif
[ "phamnguyenquang91@gmail.com" ]
phamnguyenquang91@gmail.com
0204cd130f5448e85b477039958390ff93f397f8
71cdd1aada94c07a1672705b15b232a117998d2d
/src/main.h
95d325c044f3b9ac8e097de59944d10d9e74e40b
[ "MIT" ]
permissive
Tatvam/PingPong
77def703ea1992a50acfc6dabf9a5f6becbb3a7e
f8c98516cab86a8c5b70fcdd49afa091967132fa
refs/heads/master
2020-04-25T21:12:07.391962
2019-03-14T06:18:08
2019-03-14T06:18:08
173,073,240
2
0
null
null
null
null
UTF-8
C++
false
false
1,397
h
#ifndef MAIN_H #define MAIN_H #include<stdio.h> #include<stdlib.h> #include<GL/glew.h> #include<glm/glm.hpp> #include<GLFW/glfw3.h> #include<iostream> #include<fstream> #include<string> #include<sstream> #include<vector> #include<sys/socket.h> #include<sys/types.h> #include <netinet/in.h> #include <arpa/inet.h> #include<pthread.h> #include<unistd.h> using namespace std; struct color_t { int r; int g; int b; }; struct VAO *create2DObject(GLenum primitive_mode, int numVertices, const float *vertex_buffer_data); // struct VAO *create3DObject(GLenum primitive_mode, int numVertices, const GLfloat *vertex_buffer_data, const GLfloat red, const GLfloat green, const GLfloat blue, GLenum fill_mode = GL_FILL); // struct VAO *create3DObject(GLenum primitive_mode, int numVertices, const GLfloat *vertex_buffer_data, const color_t color, GLenum fill_mode = GL_FILL); void draw2DObject(struct VAO *vao, GLenum mode, int numVertices, const float *vertex_buffer); struct VAO { GLuint VertexArrayID; GLuint VertexBuffer; GLuint ColorBuffer; int NumVertices; }; typedef struct VAO VAO; extern const color_t COLOR_RED; extern const color_t COLOR_GREEN; extern const color_t COLOR_BLACK; extern const color_t COLOR_BACKGROUND; extern const color_t COLOR_GROUND_1; extern const color_t COLOR_LOG; extern const color_t COLOR_HONEY; extern const color_t COLOR_BLUE; #endif
[ "td14@iitbbs.ac.in" ]
td14@iitbbs.ac.in
004f3e13d9508c0ce294292490c13f38f1999f62
0a7c429c78853d865ff19f2a75f26690b8e61b9c
/Usul/Interfaces/ITranslationSpeed.h
8ef602da2d1a3931a0917dacdf5d7a0c754266c4
[]
no_license
perryiv/cadkit
2a896c569b1b66ea995000773f3e392c0936c5c0
723db8ac4802dd8d83ca23f058b3e8ba9e603f1a
refs/heads/master
2020-04-06T07:43:30.169164
2018-11-13T03:58:57
2018-11-13T03:58:57
157,283,008
2
2
null
null
null
null
UTF-8
C++
false
false
1,110
h
/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007, Arizona State University // All rights reserved. // BSD License: http://www.opensource.org/licenses/bsd-license.html // Author(s): Adam Kubach // /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // // Interface for returning the translation speed. // /////////////////////////////////////////////////////////////////////////////// #ifndef _USUL_INTERFACES_TRANSLATION_SPEED_H_ #define _USUL_INTERFACES_TRANSLATION_SPEED_H_ #include "Usul/Interfaces/IUnknown.h" namespace Usul { namespace Interfaces { struct ITranslationSpeed : public Usul::Interfaces::IUnknown { // Smart-pointer definitions. USUL_DECLARE_QUERY_POINTERS ( ITranslationSpeed ); // Id for this interface. enum { IID = 4002239526u }; // Add the new model. virtual float translationSpeed () const = 0; }; } // namespace Interfaces } // namespace Usul #endif // _USUL_INTERFACES_TRANSLATION_SPEED_H_
[ "pep4@73d323f7-f32a-0410-a0ec-c7cf9bc3a937" ]
pep4@73d323f7-f32a-0410-a0ec-c7cf9bc3a937
9acb3effbb00ba818ffdb63ced6c97ab2ff142e5
22541302015c82ed7b13dd9bdaf33e75c96239a5
/codeforces/Young Explorers.cpp
24b99f16702afda0190c452390829426cc59984b
[]
no_license
Shubhamag12/Data-Structures-and-Algorithms
a596feaf7831d38c06299bd31a997d90a267ce2d
bb80cb0d176e0fcf6ad3cbb8e051c076e69999c3
refs/heads/main
2023-05-27T21:46:00.249048
2021-06-14T20:13:18
2021-06-14T20:13:18
376,948,240
0
0
null
2021-06-14T20:29:50
2021-06-14T20:29:50
null
UTF-8
C++
false
false
503
cpp
#include <bits/stdc++.h> using namespace std; #define pi 3.1415926536 #define ll long long int #define mod 1000000007 #define fastio ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int main(){ fastio int tc=1; cin >> tc; for(int casess=0;casess<tc;casess++){ ll n; cin>>n; vector<ll>arr(n); for( ll i=0;i<n;i++) cin>>arr[i]; sort(arr.begin(),arr.end()); int res=0; int mems=0; for(int i=0;i<n;i++){ mems++; if(mems==arr[i]){ mems=0; res++; } } cout<<res<<"\n"; } }
[ "b180062@nitsikkim.ac.in" ]
b180062@nitsikkim.ac.in
5975e09390e23f0118d8e439235cbe3eefa15a56
29a1c3393eb3ec72a05613b833baed1b6b57c971
/Homework/Project Submission/OperationGraduation_V7_4/statchild.cpp
928bb7895685f1e25a1d307d9221be5461ada002
[]
no_license
Bhitt/Hitt_Branden_CIS17B_48037
c1d4c1283b1a8e808f3b96f74c3d9a749c6426cb
dd93fb423b865beda85398c904bbc07ba22259c9
refs/heads/master
2020-11-30T14:51:31.957144
2016-12-15T00:31:04
2016-12-15T00:31:04
67,568,592
0
0
null
null
null
null
UTF-8
C++
false
false
3,484
cpp
#include "statchild.h" #include "ui_statchild.h" StatChild::StatChild(QWidget *parent) : QMdiSubWindow(parent), ui(new Ui::StatChild) { ui->setupUi(this); //ui->bgGraphic->setPixmap(QPixmap("StatusBG.jpg")); //set style for health, xp and special bars ui->healthBar->setStyleSheet("#healthBar {border: 3px solid rgb(83, 75, 50);" " border-radius:10px; background-color: rgb(114, 97, 75);" " padding:0px;} #healthBar::chunk {background-color: red;" " border-radius:10px;}"); ui->xpBar->setStyleSheet("#xpBar {border: 3px solid rgb(88, 75, 50); border-radius:10px;" " background-color: rgb(114, 97, 75); padding:0px;} " "#xpBar::chunk {background-color: rgb(170, 170, 170);" " border-radius:10px;}"); ui->specialBar->setStyleSheet("#specialBar {border: 3px solid rgb(80, 75, 50);" " border-radius:10px; background-color: rgb(114, 97, 75);" " padding:0px;} #specialBar::chunk {background-color:" " rgb(85, 255, 255); border-radius:10px;}"); //set value examples. to be removed. updateHealth(0); updateXp(0); updateXpBar(0); updateCharge(0); updateCrit(0); updateDmg(7); updateAC(11); updateVel(57); } StatChild::~StatChild() { delete ui; } void StatChild::setName(std::string name) { ui->charName->setText(QString::fromStdString(name)); } void StatChild::updateDmg(int amount) { if (amount < 10) { ui->attackNumber->setText("0" + QString::number(amount)); } else { ui->attackNumber->setText(QString::number(amount)); } } void StatChild::updateAC(int amount) { if (amount < 10) { ui->armorNumber->setText("0" + QString::number(amount)); } else { ui->armorNumber->setText(QString::number(amount)); } } void StatChild::updateCrit(int amount) { if (amount < 10) { ui->critNumber->setText("0" + QString::number(amount)); } else { ui->critNumber->setText(QString::number(amount)); } } void StatChild::updateVel(int amount) { if (amount < 10) { ui->speedNumber->setText("0" + QString::number(amount)); } else { ui->speedNumber->setText(QString::number(amount)); } } void StatChild::updateLvl(int amount) { if (amount < 10) { ui->levelNumber->setText("0" + QString::number(amount)); } else { ui->levelNumber->setText(QString::number(amount)); } } void StatChild::updateHealth(int amount) { ui->healthBar->setValue(amount); } void StatChild::updateMaxHealth(int amount) { ui->healthBar->setMaximum(amount); } void StatChild::updateXpBar(int amount) { ui->xpBar->setValue(amount); } void StatChild::updateXpBarMax(int amount) { ui->xpBar->setMaximum(amount); } void StatChild::updateXp(int amount) { ui->xpCurrentNumber->setText(QString::number(amount)); } void StatChild::updateXpMax(int amount) { ui->xpNextLvlNumber->setText("/" + QString::number(amount)); } void StatChild::updateCharge(int amount) { ui->specialBar->setValue(amount); } //for test only. to be removed. void StatChild::on_pushButton_clicked() { val+=2; updateHealth(val); //change to any function to test }
[ "bhitt@student.rcc.edu" ]
bhitt@student.rcc.edu
d7bc7cca81ebdb23381ba9856ecbf3a97c40314a
d09945668f19bb4bc17087c0cb8ccbab2b2dd688
/leetcode/biweekly/001-040/014/1273.cpp
f519687611ba49d27a34d8dd00f31cb80d20f861
[]
no_license
kmjp/procon
27270f605f3ae5d80fbdb28708318a6557273a57
8083028ece4be1460150aa3f0e69bdb57e510b53
refs/heads/master
2023-09-04T11:01:09.452170
2023-09-03T15:25:21
2023-09-03T15:25:21
30,825,508
23
2
null
2023-08-18T14:02:07
2015-02-15T11:25:23
C++
UTF-8
C++
false
false
975
cpp
typedef signed long long ll; #undef _P #define _P(...) (void)printf(__VA_ARGS__) #define FOR(x,to) for(x=0;x<(to);x++) #define FORR(x,arr) for(auto& x:arr) #define ITR(x,c) for(__typeof(c.begin()) x=c.begin();x!=c.end();x++) #define ALL(a) (a.begin()),(a.end()) #define ZERO(a) memset(a,0,sizeof(a)) #define MINUS(a) memset(a,0xff,sizeof(a)) //------------------------------------------------------- vector<int> E[10101]; int P[10101]; int S[10101]; int C[10101]; class Solution { public: pair<int,int> dfs(int cur) { C[cur]=1; FORR(e,E[cur]) { auto p=dfs(e); S[cur]+=p.first; C[cur]+=p.second; } if(S[cur]==0) C[cur]=0; return {S[cur],C[cur]}; } int deleteTreeNodes(int nodes, vector<int>& parent, vector<int>& value) { int i; FOR(i,nodes) E[i].clear(); FOR(i,nodes) S[i]=value[i]; FOR(i,nodes) P[i]=parent[i]; FOR(i,nodes) if(i) E[parent[i]].push_back(i); return dfs(0).second; } };
[ "kmjp@users.noreply.github.com" ]
kmjp@users.noreply.github.com
5ed96775b5d2a15048b63b770a13419d09fc8264
f53a79a1cee7e2ba44e06fe0a94d4032bb9ee43f
/BOJ/2346.cpp
5449bca9428480a548fdc52f7f2d718a0b753b35
[]
no_license
SOFTK2765/PS
f576a416da21034d5ebea60538fcd263b6d042f3
a9215bc9c41530ad6a1a7352716c64e6d73354a7
refs/heads/master
2021-06-21T00:39:34.065445
2021-01-01T12:45:51
2021-01-01T12:45:51
152,511,667
2
0
null
null
null
null
UTF-8
C++
false
false
648
cpp
#include <bits/stdc++.h> using namespace std; int main() { int n; scanf("%d", &n); list<pair<int, int>> lt; for(int i=0;i<n;i++) { int tmp; scanf(" %d", &tmp); lt.push_back({tmp, i+1}); } list<pair<int, int>>::iterator it = lt.begin(); while(!lt.empty()) { printf("%d ", (*it).second); int lsize = lt.size()-1; if(lsize==0) break; int mtmp = (*it).first<0?((*it).first%lsize)+lsize:((*it).first-1)%lsize; it = lt.erase(it); if(it==lt.end()) it = lt.begin(); while(mtmp--) if(++it==lt.end()) it = lt.begin(); } return 0; }
[ "44043820+SOFTK2765@users.noreply.github.com" ]
44043820+SOFTK2765@users.noreply.github.com
4ed2cd6f60ba3cffeb5f6367cb6fe3e2d6256448
860cb56899bf8ab13b8fe386d7621769ac012fc8
/scene.cpp
a4c8307bdad20b719b732f9f19372a7b81200737
[]
no_license
jjzhang166/FaceRecognizer2
85e4b2ae4288d2c64a63fb47e47ba2843eb73a29
1cdb5f250cda47d9e7c56c1312b38a6324d17e51
refs/heads/master
2021-01-23T19:26:25.010066
2016-07-29T09:05:52
2016-07-29T09:05:52
102,823,380
0
1
null
null
null
null
UTF-8
C++
false
false
4,502
cpp
#include <scene.hpp> #include <iostream> Scene::Scene() { haar_cascade.load(fn_haar); nestedCascade.load(fn_nested_haar); } vector<Face>* Scene::getFaces() { return &(this->faces); } void Scene::detect(Mat &frame) { //cout << "Faces: " << faces->size() << endl; this->frame = frame; Mat gray; cvtColor(frame, gray, CV_BGR2GRAY); equalizeHist(gray, gray); // Face detector vector< Rect_<int> > rects; haar_cascade.detectMultiScale(gray, rects, 1.1, 3, 0|CASCADE_SCALE_IMAGE, Size(30, 30)); bool found = false; unsigned nfaces = faces.size(); vector< Face > updated; for (size_t i=0; i<rects.size(); i++) { // Eye detector vector<Rect> nestedObjects; //Mat canvas; //frame.copyTo(canvas); Point center; Scalar color(255,0,0); int radius; Rect r = rects[i]; Mat smallImgROI = gray(r); nestedCascade.detectMultiScale( smallImgROI, nestedObjects, 1.1, 2, 0 //|CASCADE_FIND_BIGGEST_OBJECT //|CASCADE_DO_ROUGH_SEARCH //|CASCADE_DO_CANNY_PRUNING |CASCADE_SCALE_IMAGE, Size(20, 20)); for ( size_t j = 0; j < nestedObjects.size(); j++ ) { Rect nr = nestedObjects[j]; center.x = cvRound((r.x + nr.x + nr.width*0.5)); center.y = cvRound((r.y + nr.y + nr.height*0.5)); radius = cvRound((nr.width + nr.height)*0.25); } int m=0; unsigned min = INT_MAX; for (size_t j=0; j<faces.size(); j++) { unsigned distance = abs(rects[i].x - faces.at(j).getPosition().x) + abs(rects[i].y - faces.at(j).getPosition().y); //std::cout << "Distance: " << distance << std::endl; if (distance < min) { min = distance; m=j; } } if (min < 100) { // Aggiorna la posizione faces.at(m).setPosition(rects[i]); updated.push_back(faces.at(m)); } //cout << "Updated: " << updated.size() << endl; else { Face face(frame, rects[i]); faces.push_back(face); //cout << "Created." << endl; } } // Cancellazione vector<int> delete_list; for (unsigned k=0; k<nfaces; k++) { for (size_t i=0; i<updated.size(); i++) { if (updated[i] == faces.at(k)) { found = true; break; } } if (!found) { delete_list.push_back(k); } found = false; } for (size_t i=0; i<delete_list.size(); i++) { int k = delete_list.at(i); faces.erase(faces.begin()+(k-i)); } } void Scene::draw(string parameters) { for (size_t i=0; i<faces.size(); i++) { string output = ""; rectangle(frame, faces.at(i).getPosition(), CV_RGB(0, 255,0), 1); if (faces.at(i).getLeftEye().getRadius() != 0) { circle(frame, faces.at(i).getLeftEye().getCenter(), faces.at(i).getLeftEye().getRadius(), CV_RGB(0, 255,0), 3, 8, 0 ); circle(frame, faces.at(i).getRightEye().getCenter(), faces.at(i).getRightEye().getRadius(), CV_RGB(0, 255,0), 3, 8, 0 ); } if (parameters.find("-g") != std::string::npos) { output += "G="; (faces.at(i).getGender()==Male) ? output+="Male " : output+="Female "; } if (parameters.find("-r") != std::string::npos) { output += "R="; (faces.at(i).getRace()==Black) ? output+="Black " : (faces.at(i).getRace()==White) ? output+="White " : output +="Asian "; } if (parameters.find("-a") != std::string::npos) { output += "A="; switch(faces.at(i).getAge()) { case Kid: output+="Kid "; break; case Teen: output+="Teen "; break; case Young: output+="Young "; break; case Mature: output+="Mature "; break; case Old: output+="Old "; break; } } if (parameters.find("-b") != std::string::npos) { output += "B="; (faces.at(i).getBeard()) ? output+="yes " : output+="no "; } int pos_x = std::max(faces.at(i).getPosition().x - 10, 0); int pos_y = std::max(faces.at(i).getPosition().y - 10, 0); putText(frame, output, Point(pos_x, pos_y), FONT_HERSHEY_PLAIN, 1.0, CV_RGB(0,255,0), 2.0); } }
[ "quarantalgu@gmail.com" ]
quarantalgu@gmail.com
08169a15946baccfe61924836ccc5679d48eb487
380ae1e0b0ee7bb895fb0ba9d8bf5958575d42ba
/src/nbla_utils/nnp_impl_dataset.cpp
421933ea90a3c9f65815ec7cc9567b2c5cebd61c
[ "Apache-2.0" ]
permissive
geojackass/nnabla
6e326402d528a774889d4e6ed079528aa5ceadaa
87a2f160080049a8ffd9641085d46dbd45ae4178
refs/heads/master
2020-04-03T02:31:38.382418
2018-10-26T13:00:55
2018-10-26T13:00:55
154,958,577
1
0
Apache-2.0
2018-10-27T11:45:36
2018-10-27T11:45:35
null
UTF-8
C++
false
false
8,580
cpp
// Copyright (c) 2018 Sony Corporation. 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 "nnp_impl.hpp" #include <fstream> #include <iostream> #ifndef _WIN32 #include <dirent.h> #endif #ifdef _WIN32 #include <fcntl.h> #include <io.h> #define open _open #define O_RDONLY _O_RDONLY #endif using namespace std; namespace nbla { namespace utils { namespace nnp { static const int MAX_NAME = 1024; const nbla::Context kCpuCtx{{"cpu:float"}, "CpuCachedArray", "0"}; #ifdef NBLA_UTILS_WITH_HDF5 #include <hdf5.h> #include <hdf5_hl.h> bool read_dataset(hid_t gid, const int id, string &data_name, NdArrayPtr ndarray) { char name[MAX_NAME]; if (H5Gget_objname_by_idx(gid, (hsize_t)id, name, (size_t)MAX_NAME) < 0) return false; data_name = string(name); hid_t did = H5Dopen(gid, name, H5P_DEFAULT); hid_t sp = H5Dget_space(did); int rank = H5Sget_simple_extent_ndims(sp); hsize_t dims[rank]; if (!H5Sget_simple_extent_dims(sp, dims, NULL)) return false; // NdArray ndarray;; Shape_t shape_x(rank); for (int i = 0; i < rank; i++) shape_x[i] = dims[i]; ndarray->reshape(shape_x, true); hid_t tid = H5Dget_type(did); if (H5Tequal(tid, H5T_NATIVE_CHAR)) { char *buffer = ndarray->cast(nbla::get_dtype<char>(), kCpuCtx)->pointer<char>(); H5Dread(did, H5T_NATIVE_CHAR, H5S_ALL, H5S_ALL, H5P_DEFAULT, buffer); } if (H5Tequal(tid, H5T_NATIVE_UCHAR)) { uint8_t *buffer = ndarray->cast(nbla::get_dtype<uint8_t>(), kCpuCtx)->pointer<uint8_t>(); H5Dread(did, H5T_NATIVE_UCHAR, H5S_ALL, H5S_ALL, H5P_DEFAULT, buffer); } if (H5Tequal(tid, H5T_NATIVE_SHORT)) { short *buffer = ndarray->cast(nbla::get_dtype<short>(), kCpuCtx)->pointer<short>(); H5Dread(did, H5T_NATIVE_SHORT, H5S_ALL, H5S_ALL, H5P_DEFAULT, buffer); } if (H5Tequal(tid, H5T_NATIVE_INT)) { int *buffer = ndarray->cast(nbla::get_dtype<int>(), kCpuCtx)->pointer<int>(); H5Dread(did, H5T_NATIVE_INT, H5S_ALL, H5S_ALL, H5P_DEFAULT, buffer); } if (H5Tequal(tid, H5T_NATIVE_UINT)) { unsigned int *buffer = ndarray->cast(nbla::get_dtype<unsigned int>(), kCpuCtx) ->pointer<unsigned int>(); H5Dread(did, H5T_NATIVE_UINT, H5S_ALL, H5S_ALL, H5P_DEFAULT, buffer); } if (H5Tequal(tid, H5T_NATIVE_LONG)) { long *buffer = ndarray->cast(nbla::get_dtype<long>(), kCpuCtx)->pointer<long>(); H5Dread(did, H5T_NATIVE_LONG, H5S_ALL, H5S_ALL, H5P_DEFAULT, buffer); } if (H5Tequal(tid, H5T_NATIVE_ULONG)) { unsigned long *buffer = ndarray->cast(nbla::get_dtype<unsigned long>(), kCpuCtx) ->pointer<unsigned long>(); H5Dread(did, H5T_NATIVE_ULONG, H5S_ALL, H5S_ALL, H5P_DEFAULT, buffer); } if (H5Tequal(tid, H5T_NATIVE_LLONG)) { long long *buffer = ndarray->cast(nbla::get_dtype<long long>(), kCpuCtx) ->pointer<long long>(); H5Dread(did, H5T_NATIVE_LLONG, H5S_ALL, H5S_ALL, H5P_DEFAULT, buffer); } if (H5Tequal(tid, H5T_NATIVE_FLOAT)) { float *buffer = ndarray->cast(nbla::get_dtype<float>(), kCpuCtx)->pointer<float>(); H5Dread(did, H5T_NATIVE_FLOAT, H5S_ALL, H5S_ALL, H5P_DEFAULT, buffer); } if (H5Tequal(tid, H5T_NATIVE_DOUBLE)) { double *buffer = ndarray->cast(nbla::get_dtype<double>(), kCpuCtx)->pointer<double>(); H5Dread(did, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, buffer); } H5Dclose(did); return true; } bool parse_hdf5_group(hid_t gid, vector<string> &data_names, vector<NdArrayPtr> &ndarrays) { hsize_t num = 0; if (H5Gget_num_objs(gid, &num) < 0) return false; char group_name[MAX_NAME]; if (H5Iget_name(gid, group_name, MAX_NAME) < 0) return false; char name[MAX_NAME]; vector<int> dataset_ids; for (int i = 0; i < num; i++) { if (H5Gget_objname_by_idx(gid, (hsize_t)i, name, (size_t)MAX_NAME) < 0) return false; if (H5Gget_objtype_by_idx(gid, i) == H5G_DATASET) dataset_ids.push_back(i); } const int n_stream = dataset_ids.size(); data_names.resize(n_stream); for (int n = 0; n < n_stream; n++) { ndarrays.push_back(make_shared<NdArray>()); } for (int i = 0; i < dataset_ids.size(); i++) { read_dataset(gid, dataset_ids[i], data_names[i], ndarrays[i]); } return true; } bool read_file_to_str(const std::string &filename, std::string &data) { std::ifstream file(filename.c_str(), std::ios::binary | std::ios::ate); if (!file) { std::cerr << "Error: could not open file " << filename << std::endl; return false; } size_t filesize = static_cast<size_t>(file.tellg()); if (filesize <= 0) { file.close(); std::cerr << "Error: file size 0" << std::endl; return false; } data.resize(filesize); file.seekg(0, file.beg); file.read(&data.front(), filesize); file.close(); return true; } #endif bool load_cache(const string &filename, vector<string> &data_names, vector<NdArrayPtr> &ndarrays) { #if NBLA_UTILS_WITH_HDF5 string h5data; if (!read_file_to_str(filename, h5data)) { return false; } hid_t id = H5LTopen_file_image((char *)&h5data.front(), h5data.size(), H5LT_FILE_IMAGE_DONT_RELEASE); if (0 <= id) { int root = H5Gopen(id, "/", H5P_DEFAULT); if (0 <= root) parse_hdf5_group(root, data_names, ndarrays); } return true; #else std::cerr << "Error: use -DNNABLA_UTILS_WITH_HDF5 options in cmake." << std::endl; return false; #endif } bool has_suffix(const string &s, const string &suffix) { return (s.size() >= suffix.size()) && equal(suffix.rbegin(), suffix.rend(), s.rbegin()); } bool create_cachefile_list(const string &path, vector<string> &filenames) { #ifndef _WIN32 DIR *dir = opendir(path.c_str()); if (!dir) { std::cerr << "Could not find directory " << path << std::endl; closedir(dir); return 1; } dirent *entry; while ((entry = readdir(dir)) != NULL) { if (has_suffix(entry->d_name, ".h5")) { string d_name(entry->d_name); filenames.push_back(path + d_name); } } closedir(dir); return true; #else std::cerr << "Error: Windows OS are not supported yet." << std::endl; return false; #endif } // ---------------------------------------------------------------------- // DatasetImpl // ---------------------------------------------------------------------- DatasetImpl::DatasetImpl(const ::Dataset &dataset) : dataset_proto_(dataset), n_data_(0), n_stream_(0) { vector<string> filenames; create_cachefile_list(this->cache_dir(), filenames); shapes_.clear(); n_data_ = 0; for (auto filename : filenames) { vector<NdArrayPtr> ndarrays; if (!load_cache(filename, data_names_, ndarrays)) std::cerr << "Error: file load." << std::endl; n_stream_ = ndarrays.size(); for (auto ndarray : ndarrays) shapes_.push_back(ndarray->shape()); n_data_ += shapes_[0][0]; cache_blocks_.push_back(ndarrays); } } string DatasetImpl::name() const { return dataset_proto_.name(); } string DatasetImpl::uri() const { return dataset_proto_.uri(); } string DatasetImpl::cache_dir() const { return dataset_proto_.cache_dir(); } bool DatasetImpl::create_cache_explicitly() const { return dataset_proto_.create_cache_explicitly(); } bool DatasetImpl::overwrite_cache() const { return dataset_proto_.overwrite_cache(); } bool DatasetImpl::shuffle() const { return dataset_proto_.shuffle(); } bool DatasetImpl::no_image_normalization() const { return dataset_proto_.no_image_normalization(); } const int DatasetImpl::batch_size() const { return dataset_proto_.batch_size(); } const int DatasetImpl::get_num_stream() const { return n_stream_; } const int DatasetImpl::get_num_data() const { return n_data_; } vector<string> DatasetImpl::get_data_names() { return data_names_; } vector<Shape_t> DatasetImpl::get_shapes() { return shapes_; } vector<vector<NdArrayPtr>> DatasetImpl::get_cache_blocks() { return cache_blocks_; } } } }
[ "naoki.ide@jp.sony.com" ]
naoki.ide@jp.sony.com
304c573e3b204f57d64b5b7f0e22c3279f214c7b
2605c626b0aedc3934a5da9d9daf7665611e35f2
/main_app/matrix/user_nn_matrix.cpp
45b042eeb4c0dde730c1dab6f759b664695cabf0
[]
no_license
TactictNLP/Deep-learning
21f0d2307f49d26d3b2db6ce02317487fcd092bd
79fab69d3ce822ca1b5da5382d859659f62916f3
refs/heads/master
2020-03-29T01:19:12.186791
2018-09-14T06:13:56
2018-09-14T06:13:56
null
0
0
null
null
null
null
GB18030
C++
false
false
63,330
cpp
#include "user_nn_matrix.h" #include "user_nn_matrix_cuda.h" //创建一个矩阵 //参数 //dest:指针对象 必需事先初始化 //width:矩阵的宽度 //height:矩阵的高度 user_nn_matrix *user_nn_matrix_create(int width, int height){ user_nn_matrix *dest; dest = (user_nn_matrix *)malloc(sizeof(user_nn_matrix));//分配保存矩阵空间的大小 dest->width = width; dest->height = height; dest->data = (float *)malloc(dest->width * dest->height * sizeof(float));//分配矩阵数据空间 dest->next = NULL; memset(dest->data, 0, dest->width * dest->height * sizeof(float));//清空数据 return dest; } //复制一个矩阵 //参数 //dest:指针对象 必需事先初始化 //width:矩阵的宽度 //height:矩阵的高度 //返回新的矩阵 user_nn_matrix *user_nn_matrix_cpy_create(user_nn_matrix *dest_matrix){ user_nn_matrix *result=NULL; result = (user_nn_matrix *)malloc(sizeof(user_nn_matrix));//分配保存矩阵空间的大小 result->width = dest_matrix->width; result->height = dest_matrix->height; result->data = (float *)malloc(result->width * result->height * sizeof(float));//分配矩阵数据空间 result->next = NULL; memcpy(result->data,dest_matrix->data,result->width * result->height * sizeof(float)); return result; } //矩阵转置 交换矩阵的width height包括数据 void user_nn_matrix_transpose(user_nn_matrix *src_matrix){ #ifdef USE_CUDA user_nn_matrix_transpose_cuda(src_matrix); #else user_nn_matrix *temp_matrix = NULL; float *temp_data = NULL; float *src_data = src_matrix->data; int width = 0; int height = 0; if ((src_matrix->width == 1) || (src_matrix->height == 1)){ //如果是一条矩阵向量 那么直接交换横纵坐标 不用交换数据 src_matrix->width = src_matrix->width ^ src_matrix->height; src_matrix->height = src_matrix->width ^ src_matrix->height; src_matrix->width = src_matrix->width ^ src_matrix->height; return;//直接退出 } temp_matrix = user_nn_matrix_create(src_matrix->width, src_matrix->height);//创建矩阵 user_nn_matrix_cpy_matrix(temp_matrix, src_matrix);//拷贝数据 temp_data = temp_matrix->data;//获取缓冲矩阵的数据指针 for (width = 0; width < temp_matrix->width; width++){ for (height = 0; height < temp_matrix->height; height++){ *src_data++ = *user_nn_matrix_ext_value(temp_matrix, width, height); } } src_matrix->height = width; src_matrix->width = height; user_nn_matrix_delete(temp_matrix); #endif } //返回矩阵中指定位置的值 //参数 //dest:矩阵 //post_index:坐标位置 float *user_nn_matrix_ext_value_index(user_nn_matrix *dest, int post_index){ float *value = dest->data; if (post_index >= (dest->width * dest->height)){ return NULL; } return (value + post_index); } //返回矩阵中指定位置的值 //参数 //dest:矩阵 //postx:x坐标 //posty:y坐标 float *user_nn_matrix_ext_value(user_nn_matrix *dest, int postx, int posty){ return user_nn_matrix_ext_value_index(dest,postx + posty * dest->width); } //返回矩阵中最大值的系数 //参数 //dest:矩阵 int user_nn_matrix_return_max_index(user_nn_matrix *dest){ int count = 0,max_index = 0; float *value = NULL; float max_value = *dest->data; count = 0; value = dest->data; for(;count<(dest->width * dest->height);count++){ if (*value > max_value){ max_value = *value; max_index = count; } value++; } return max_index; } //返回矩阵中最大值的指针 //参数 //dest:矩阵 float *user_nn_matrix_return_max_addr(user_nn_matrix *dest){ int count = dest->width * dest->height; float *value = dest->data; float *result = dest->data; float max_value = *dest->data; while (count--){ if (*value > max_value){ max_value = *value; result = value; } value++; } return result; } //返回矩阵中最小值的系数 //参数 //dest:矩阵 int user_nn_matrix_return_min_index(user_nn_matrix *dest){ int count = 0,min_index = 0; float *value = dest->data; float min_value = *dest->data; for(;count<(dest->width * dest->height);count++){ if (*value < min_value){ min_value = *value; min_index = count; } value++; } return min_index; } //返回矩阵中最小值的指针 //参数 //dest:矩阵 float *user_nn_matrix_return_min_addr(user_nn_matrix *dest){ int count = dest->width * dest->height; float *value = dest->data; float *result = dest->data; float min_value = *dest->data; while (count--){ if (*value < min_value){ min_value = *value; result = value; } value++; } return result; } //删除矩阵 void user_nn_matrix_delete(user_nn_matrix *dest){ if (dest != NULL){ if (dest->data != NULL){ free(dest->data);//释放数据 } free(dest);//释放结构体 } //dest = NULL; } //创建连续的矩阵 //参数 //total_w:连续矩阵的宽度 //total_h:连续矩阵的高度 //matrix_w matrix_h:连续矩阵的单个矩阵尺寸 user_nn_list_matrix *user_nn_matrices_create(int total_w, int total_h, int matrix_w, int matrix_h){ user_nn_list_matrix *list_matrix = NULL;//连续矩阵 user_nn_matrix *matrix = NULL;//单个矩阵大小 int n = total_w * total_h;//计算需要创建多少个矩阵 if (n == 0){ return NULL; }//创建矩阵如果为空 list_matrix = (user_nn_list_matrix *)malloc(sizeof(user_nn_list_matrix));//分配空间 list_matrix->width = total_w;//设置总矩阵宽度 list_matrix->height = total_h;//设置总矩阵高度 list_matrix->matrix = user_nn_matrix_create(matrix_w, matrix_h);//创建首个矩阵 matrix = list_matrix->matrix;//转化矩阵对象 while (--n) { matrix->next = user_nn_matrix_create(matrix_w, matrix_h);//添加一个矩阵 matrix = matrix->next;//更新指针对象 //printf("create matrix=%d\n", width * height - n + 1); } return list_matrix; } //创建连续的矩阵头 //参数 //total_w:连续矩阵的宽度 //total_h:连续矩阵的高度 user_nn_list_matrix *user_nn_matrices_create_head(int total_w, int total_h) { user_nn_list_matrix *list_matrix = NULL;//连续矩阵 user_nn_matrix *matrix = NULL;//单个矩阵大小 list_matrix = (user_nn_list_matrix *)malloc(sizeof(user_nn_list_matrix));//分配空间 list_matrix->width = total_w;//设置总矩阵宽度 list_matrix->height = total_h;//设置总矩阵高度 list_matrix->matrix = NULL;//创建首个矩阵 return list_matrix; } //删除连续矩阵 //src_matrices:连续矩阵对象 //返回值:无 void user_nn_matrices_delete(user_nn_list_matrix *src_matrices){ int count = src_matrices->width * src_matrices->height;//获取总矩阵大小 user_nn_matrix *matrix = src_matrices->matrix;//指向单个矩阵 user_nn_matrix *matrix_next = NULL; while (matrix != NULL){ matrix_next = matrix->next; user_nn_matrix_delete(matrix);//删除当前矩阵 matrix = matrix_next;//更新矩阵 } } //在连续矩阵中末尾添加一个矩阵 限制 连续矩阵必须是单行或者单列矩阵 //参数 //list_matrix:矩阵链表 //end_matirx:需要添加的矩阵 //返回 成功失败 bool user_nn_matrices_add_matrix(user_nn_list_matrix *list_matrix,user_nn_matrix *end_matirx) { user_nn_matrix *matrix = list_matrix->matrix;//获取第一个矩阵对象 if ((list_matrix->height != 1) && (list_matrix->width != 1)) { return false;//添加矩阵需要按照一维矩阵方式添加 } if (matrix == NULL) { list_matrix->matrix = end_matirx; } else { while (matrix->next != NULL) { matrix = matrix->next; } matrix->next = end_matirx; if (list_matrix->width == 1) { list_matrix->height++; } else { list_matrix->width++; } } return true; } //在连续矩阵中返回指定位置矩阵 //参数 //list_matrix:矩阵链表 //index:位置 //参数 矩阵指针 user_nn_matrix *user_nn_matrices_ext_matrix_index(user_nn_list_matrix *list_matrix, int index){ user_nn_matrix *matrix = list_matrix->matrix;//获取第一个矩阵对象 if (index >= (list_matrix->width * list_matrix->height) || (index < 0)){ return NULL; } while (index--){ matrix = matrix->next; } return matrix; } //在连续矩阵中返回指定位置矩阵 //参数 //list_matrix:矩阵链表 //postx:x坐标 <=list_matrix->width //posty:y坐标 <=list_matrix->height //参数 矩阵指针 user_nn_matrix *user_nn_matrices_ext_matrix(user_nn_list_matrix *list_matrix, int postx, int posty){ return user_nn_matrices_ext_matrix_index(list_matrix,postx + posty * list_matrix->width); } //获取一个随机浮点数0-1.0之间 float user_nn_rand_0_1(void){ //srand((unsigned)time(NULL)); return (float)(rand() / double(RAND_MAX)); } //数据归一化处理 返回数据 -1 - +1 范围 float user_nn_rand__1_1(float post){ //return 1; return (float)((user_nn_rand_0_1() - 0.5) * 2 * sqrt(6 / post)); } //设置单个居中里面的值 随机设置 void user_nn_matrix_rand_vaule(user_nn_matrix *src_matrix, float post){ int total = src_matrix->height * src_matrix->width;//设置高度与宽度 float *data = src_matrix->data;//获取内存指针 while (total--){ *data++ = user_nn_rand__1_1(post);//设置值 } } //设置连续矩阵里面的值 随机设置 void user_nn_matrices_rand_vaule(user_nn_list_matrix *list_matrix, float post){ user_nn_matrix *matrix = list_matrix->matrix;//获取第一个矩阵对象 float *data = 0; int total = 0; if (matrix == NULL){ return; } while (matrix != NULL){ user_nn_matrix_rand_vaule(matrix, post); matrix = matrix->next;//继续处理下一个数据 } } //按照指定上、下、左、右扩充并创建新的矩阵,并且拷贝数据到新的矩阵中 //参数 //src_matrix :原矩阵 //above:上面界 //below:下边界 //left:左边界 //right:右边界 //返回 新的矩阵 user_nn_matrix *user_nn_matrix_expand(user_nn_matrix *src_matrix, int above, int below, int left, int right){ user_nn_matrix *result = NULL;// float *src_data = src_matrix->data;//数据指针 float *result_data; int count;// int index = 0; result = user_nn_matrix_create(left + src_matrix->width + right, above + src_matrix->height + below);//创建矩阵 result_data = result->data;//取得数据指针 result_data = result_data + (result->width * above + left);//跳过开头位置 //拷贝数据 for (count = 0; count < (src_matrix->width * src_matrix->height); count++){ *result_data++ = *src_data++; if (++index >= src_matrix->width){ index = 0; result_data = result_data + left + right; } } return result; } // //在src_matrix矩阵指定(x,y)位置保存save_data指向的数据其中大小为width*height,返回失败或成功 //参数 //src_matrix:矩阵对象 //save_data:需要保存的矩阵 //x: 起始点 <=src_matrix->width //y:起始点 <=src_matrix->height //返回:成功或者失败 bool user_nn_matrix_save_array(user_nn_matrix *dest_matrix, float *src_data, int startx, int starty, int width, int height) { user_nn_matrix *result = NULL; int post_x, post_y; float *dest_data = dest_matrix->data;//数据指针 if (((startx + width) > dest_matrix->width) || ((starty + height) > dest_matrix->height) || (width == 0) || (height == 0)) { return false;//如果超出范围那么直接返回空 } dest_data += starty * dest_matrix->width + startx;//跳转到开始位置 for (post_y = 0; post_y < height; post_y++) { for (post_x = 0; post_x < width; post_x++) { *dest_data++ = *src_data++; } dest_data += dest_matrix->width - width; } return true; } // //在src_matrix矩阵指定(x,y)位置叠加save_data*alpha指向的数据其中大小为width*height,返回失败或成功 //参数 //src_matrix:矩阵对象 //save_data:需要保存的矩阵 //alpha:系数 //x: 起始点 <=src_matrix->width //y:起始点 <=src_matrix->height //返回:成功或者失败 bool user_nn_matrix_sum_array_mult_alpha(user_nn_matrix *dest_matrix, float *src_data, float alpha,int startx, int starty, int width, int height) { user_nn_matrix *result = NULL; int post_x, post_y; float *dest_data = dest_matrix->data;//数据指针 if (((startx + width) > dest_matrix->width) || ((starty + height) > dest_matrix->height) || (width == 0) || (height == 0)) { return false;//如果超出范围那么直接返回空 } dest_data += starty * dest_matrix->width + startx;//跳转到开始位置 for (post_y = 0; post_y < height; post_y++) { for (post_x = 0; post_x < width; post_x++) { *dest_data++ += *src_data++ * alpha; } dest_data += dest_matrix->width - width; } return true; } // //在src_matrix矩阵指定(x,y)位置保存值,返回失败或成功 //参数 //src_matrix:矩阵对象 //startx: 起始点 <=src_matrix->width //starty:起始点 <=src_matrix->height //vaule:需要保存的数据 //返回:成功或者失败 bool user_nn_matrix_save_float(user_nn_matrix *src_matrix, int startx, int starty, float vaule) { if ((startx >= src_matrix->width) || (starty >= src_matrix->height)) { return false;//如果超出范围那么直接返回空 } src_matrix->data[starty * src_matrix->width + startx] = vaule; return true; } // //在src_matrix矩阵指定(x,y)位置保存save_matrix矩阵,返回失败或成功 //参数 //src_matrix:矩阵对象 //save_matrix:需要保存的矩阵 //x: 起始点 <=src_matrix->width //y:起始点 <=src_matrix->height //返回:成功或者失败 bool user_nn_matrix_save_matrix(user_nn_matrix *src_matrix, user_nn_matrix *save_matrix, int startx, int starty) { user_nn_matrix *result = NULL; int post_x, post_y; float *src_data = src_matrix->data;//数据指针 float *save_data = save_matrix->data; if (((startx + save_matrix->width) > src_matrix->width) || ((starty + save_matrix->height) > src_matrix->height) || (save_matrix->width == 0) || (save_matrix->height == 0)) { return false;//如果超出范围那么直接返回空 } src_data += starty * src_matrix->width + startx;//跳转到开始位置 for (post_y = 0; post_y < save_matrix->height; post_y++) { for (post_x = 0; post_x < save_matrix->width; post_x++) { *src_data++ = *save_data++; } src_data += src_matrix->width - save_matrix->width; } return true; } // //从矩阵指定(x,y)位置截取(w,h)大小的矩阵。并且返回新截取的矩阵 //参数 //src_matrix:矩阵对象 //x: 起始点 <=src_matrix->width //y:起始点 <=src_matrix->height //w:横范围 <=src_matrix->width //h:纵范围 <=src_matrix->height //返回:成功或者失败 user_nn_matrix *user_nn_matrix_ext_matrix(user_nn_matrix *src_matrix, int startx, int starty, int width, int height){ user_nn_matrix *result = NULL; int post_x, post_y, post_index; float *src_data = src_matrix->data;//数据指针 float *result_data; if (((startx + width) > src_matrix->width) || ((starty + height) > src_matrix->height) || (width == 0) || (height == 0)){ return NULL;//如果超出范围那么直接返回空 } result = user_nn_matrix_create(width, height);//创建矩阵 result_data = result->data;//取得数据指针 //post_index = startx + starty* src_matrix->width;//指向通过(postx,posty)转化一维数组的位置 公式:index=横坐标+纵坐标*矩阵宽度 for (post_y = 0; post_y < height; post_y++){ for (post_x = 0; post_x < width; post_x++){ post_index = (startx + post_x) + (starty + post_y)* src_matrix->width;//指向通过(postx,posty)转化一维数组的位置 公式:index=横坐标+纵坐标*矩阵宽度 *result_data++ = src_data[post_index];//获取数据 //printf("x:%d,y:%d,%d ", startx+i, starty+j, post_index); } //printf("\n"); } return result; } //把连续的矩阵的数据拷贝到一个矩阵中 //参数 //src_matrix:被转化矩阵 //返回 无 void user_nn_matrices_to_matrix(user_nn_matrix *src_matrix, user_nn_list_matrix *sub_matrices){ user_nn_matrix *sub_matrix = sub_matrices->matrix; int count_matrix, count_data;// float *src_data = src_matrix->data;//指向对象数据 float *sub_data = NULL; //result_data = result->data;//获取数据指针 for (count_matrix = 0; count_matrix < (sub_matrices->width * sub_matrices->height); count_matrix++){ //user_nn_matrix_exc_width_height(sub_matrix);//交换矩阵 matlab同步 sub_data = sub_matrix->data;//获取数据指针 for (count_data = 0; count_data < (sub_matrix->width * sub_matrix->height); count_data++){ *src_data++ = *sub_data++;//保存数据 } sub_matrix = sub_matrix->next; } } //拷贝一个连续的矩阵到另外一个连续矩阵中 void user_nn_matrices_cpy_matrices(user_nn_list_matrix *src_matrices, user_nn_list_matrix *dest_matrices){ int count = dest_matrices->width * dest_matrices->height; user_nn_matrix *src_m = src_matrices->matrix; user_nn_matrix *dest_m = dest_matrices->matrix; while (count--){ user_nn_matrix_cpy_matrix(src_m, dest_m); src_m = src_m->next; dest_m = dest_m->next; } } // //拷贝src_matrix矩阵(x,y)起点大小为width*height的数据至dest_data,其中,返回失败或成功 //参数 //dest_data:需要保存的矩阵 //src_matrix:矩阵对象 //x: 起始点 <=src_matrix->width //y:起始点 <=src_matrix->height //返回:成功或者失败 bool user_nn_matrix_cpy_array(float *dest_data, user_nn_matrix *src_matrix, int startx, int starty, int width, int height){ user_nn_matrix *result = NULL; int post_x, post_y; float *src_data = src_matrix->data;//数据指针 if (((startx + width) > src_matrix->width) || ((starty + height) > src_matrix->height) || (width == 0) || (height == 0)) { return false;//如果超出范围那么直接返回空 } src_data += starty * src_matrix->width + startx;//跳转到开始位置 for (post_y = 0; post_y < height; post_y++) { for (post_x = 0; post_x < width; post_x++) { *dest_data++ = *src_data++; } src_data += src_matrix->width - width; } return true; } // //拷贝src_matrix*constant矩阵(x,y)起点大小为width*height的数据至dest_data,其中,返回失败或成功 //参数 //dest_data:需要保存的矩阵 //src_matrix:矩阵对象 //x: 起始点 <=src_matrix->width //y:起始点 <=src_matrix->height //返回:成功或者失败 bool user_nn_matrix_cpy_array_mult_constant(float *dest_data, user_nn_matrix *src_matrix, int startx, int starty, int width, int height, float constant) { user_nn_matrix *result = NULL; int post_x, post_y; float *src_data = src_matrix->data;//数据指针 if (((startx + width) > src_matrix->width) || ((starty + height) > src_matrix->height) || (width == 0) || (height == 0)) { return false;//如果超出范围那么直接返回空 } src_data += starty * src_matrix->width + startx;//跳转到开始位置 for (post_y = 0; post_y < height; post_y++) { for (post_x = 0; post_x < width; post_x++) { *dest_data++ = *src_data++ * constant; } src_data += src_matrix->width - width; } return true; } //把一个矩阵转化为连续的矩阵链表 //src_matrix:矩阵对象 //width:目标宽度 //height:目标高度 //返回 连续矩阵 void user_nn_matrix_to_matrices(user_nn_list_matrix *src_matrices, user_nn_matrix *sub_matrix){ user_nn_matrix *matrix = src_matrices->matrix; int count_matrix, count_data;// float *result_data = sub_matrix->data;//指向对象数据 float *src_data = NULL; for (count_matrix = 0; count_matrix < (src_matrices->width * src_matrices->height); count_matrix++){ src_data = matrix->data;//获取保存数据指针 for (count_data = 0; count_data < (matrix->width * matrix->height); count_data++){ *src_data++ = *result_data++;//保存数据 } //user_nn_matrix_exc_width_height(matrix);//交换矩阵 matlab同步 matrix = matrix->next; } } //矩阵扩充 均值扩充 //src_matrix: //width:扩充倍数 //height:扩充倍数 //返回 新的矩阵 user_nn_matrix *user_nn_matrix_expand_mult_constant(user_nn_matrix *src_matrix, int width, int height, float constant){ user_nn_matrix * result = NULL; float *src_data = src_matrix->data; float *result_data = NULL; int x, y,wi,hi; result = user_nn_matrix_create(src_matrix->width * width, src_matrix->height * height);//创建扩充后的矩阵 result_data = result->data; for (y = 0; y < src_matrix->height; y++){ for (hi = 0; hi < height; hi++){ for (x = 0; x < src_matrix->width; x++){ for (wi = 0; wi < width; wi++){ *result_data++ = (float)*src_data * constant;//更新数据 } src_data++; } src_data = src_data - src_matrix->width;//跳转到开始位置 } src_data = src_data + src_matrix->width;//跳转到结束位置 } return result; } //设置矩阵值 //参数 //src_matrix:目标矩阵 求和值会覆盖此矩阵 //v:设置的值 //返回 无 void user_nn_matrix_memset(user_nn_matrix *save_matrix, float constant){ int count = save_matrix->width * save_matrix->height;//获取矩阵数据大小 float *src_data = save_matrix->data; while (count--){ *src_data++ = constant; } } //设置矩阵值 //参数 //src_matrix:目标矩阵 求和值会覆盖此矩阵 //data:数据指针 大于矩阵 //返回 无 void user_nn_matrix_memcpy(user_nn_matrix *save_matrix, float *data){ int count = save_matrix->width * save_matrix->height;//获取矩阵数据大小 float *src_data = save_matrix->data; while (count--){ *src_data++ = *data++; } } //设置矩阵值 //参数 //src_matrix:目标矩阵 求和值会覆盖此矩阵 //data:数据指针 大于矩阵 //返回 无 void user_nn_matrix_memcpy_uchar_mult_constant(user_nn_matrix *save_matrix, unsigned char *input_array, float constant){ int count = save_matrix->width * save_matrix->height;//获取矩阵数据大小 float *src_data = save_matrix->data; while (count--){ *src_data++ = *input_array++ * constant; } } //拷贝数据至数组中 //参数 //src_matrix:目标矩阵 求和值会覆盖此矩阵 //data:数据指针 大于矩阵 //返回 无 void user_nn_matrix_uchar_memcpy(unsigned char *save_array, user_nn_matrix *src_matrix){ int count = src_matrix->width * src_matrix->height;//获取矩阵数据大小 float *src_data = src_matrix->data; while (count--){ *save_array++ = (unsigned char)*src_data++; } } //排序矩阵 //src_matrix:目标对象 排序后会自动删除 //type:表示降序或者升序 //返回:排序后的链表 // user_nn_matrix *user_nn_matrix_sorting(user_nn_matrix *src_matrix, sorting_type type){ user_nn_matrix *result = NULL; user_nn_matrix *cpy_matrix = NULL;//临时矩阵 int count = 0;//获取矩阵数据大小 float *post_index = NULL; float *result_data = NULL; cpy_matrix = user_nn_matrix_cpy_create(src_matrix);//复制一个矩阵 count = cpy_matrix->width * cpy_matrix->height;//获取矩阵数据大小 result = user_nn_matrix_create(cpy_matrix->width,cpy_matrix->height);//创建一个新的矩阵 result_data = result->data;// while(count--){ if(type == sorting_up){ post_index = user_nn_matrix_return_min_addr(cpy_matrix);//获取最小值的位置 *result_data++ = *post_index;//保存最小值 *post_index = FLT_MAX;//删除最小值 赋值最大即可 }else if(type == sorting_down){ post_index = user_nn_matrix_return_max_addr(cpy_matrix);//获取最小值的位置 *result_data++ = *post_index;//保存最小值 *post_index = -FLT_MAX;//删除最大值 赋值最小即可 } } user_nn_matrix_delete(cpy_matrix); return result; } //求和矩阵与常数 //参数 //src_matrix:目标矩阵 求和值会覆盖此矩阵 //bias:偏置参数 //返回 无 void user_nn_matrix_sum_constant(user_nn_matrix *src_matrix, float constant){ int count = src_matrix->width * src_matrix->height;//获取矩阵数据大小 float *src_data = src_matrix->data; while (count--){ *src_data++ = *src_data + constant; } } //矩阵save_matrix求和矩阵src_matrix与alpha的乘积 save_matrix=save_matrix+src_matrix*alpha //参数 //save_matrix:目标矩阵 求和值会覆盖此矩阵 //src_matrix:被求和矩阵 //alpha:参数 //返回 无 void user_nn_matrix_sum_matrix_mult_alpha(user_nn_matrix *save_matrix, user_nn_matrix *src_matrix, float alpha){ int count = save_matrix->width * save_matrix->height;//获取矩阵数据大小 float *save_data = save_matrix->data; float *src_data = src_matrix->data; while (count--){ *save_data++ = *save_data + *src_data++ * alpha; } } //求和矩阵所有数据 //参数 //src_matrix: //bias:偏置参数 //返回 无 float user_nn_matrix_cum_element(user_nn_matrix *src_matrix){ float result = 0; float *src_data = src_matrix->data; int count = src_matrix->width * src_matrix->height; while (count--){ result += *src_data++; } return result; } //求和两个矩阵 save_matrix = src_matrix + sub_matrix //参数 //src_matrix:目标矩阵 求和值会覆盖此矩阵 //sub_matrix:被求和矩阵 //返回 无 void user_nn_matrix_cum_matrix(user_nn_matrix *save_matrix, user_nn_matrix *src_matrix, user_nn_matrix *sub_matrix){ int count = sub_matrix->width * sub_matrix->height;//获取矩阵数据大小 float *save_data = save_matrix->data; float *src_data = src_matrix->data; float *sub_data = sub_matrix->data; if ((src_matrix->width != sub_matrix->width) || (src_matrix->height != sub_matrix->height)){ return; } while (count--){ *save_data++ = *src_data++ + (*sub_data++); } } //求和两个矩阵 save_matrix = src_matrix + sub_matrix * alpha //参数 //src_matrix:目标矩阵 求和值会覆盖此矩阵 //sub_matrix:被求和矩阵 //返回 无 void user_nn_matrix_cum_matrix_mult_alpha(user_nn_matrix *save_matrix, user_nn_matrix *src_matrix, user_nn_matrix *sub_matrix, float alpha) { int count = sub_matrix->width * sub_matrix->height;//获取矩阵数据大小 float *save_data = save_matrix->data; float *src_data = src_matrix->data; float *sub_data = sub_matrix->data; if ((src_matrix->width != sub_matrix->width) || (src_matrix->height != sub_matrix->height)) { return; } while (count--) { *save_data++ = *src_data++ + ((*sub_data++) * alpha); } } //拷贝sub_matrix矩阵值到src_matrix矩阵 //参数 要求矩阵相同 //src_matrix:矩阵 //sub_matrix:矩阵 //返回 无 void user_nn_matrix_cpy_matrix(user_nn_matrix *save_matrix, user_nn_matrix *sub_matrix){ int count = sub_matrix->width * sub_matrix->height;//获取矩阵数据大小 float *save_data = save_matrix->data; float *sub_data = sub_matrix->data; if ((save_matrix->width != sub_matrix->width) && (save_matrix->height != sub_matrix->height)){ return; } while (count--){ *save_data++ = *sub_data++; } } //拷贝sub_matrix矩阵值到src_matrix矩阵 并且在给定位置进行求和参数 //参数 要求矩阵相同 //src_matrix:矩阵 //sub_matrix:矩阵 //index:给定位置 //constant:求和参数 //返回 无 void user_nn_matrix_cpy_matrix_sum_constant(user_nn_matrix *save_matrix, user_nn_matrix *sub_matrix, int index, float constant){ int count = sub_matrix->width * sub_matrix->height;//获取矩阵数据大小 float *save_data = save_matrix->data; float *sub_data = sub_matrix->data; for (count = 0; count<(sub_matrix->width * sub_matrix->height); count++){ if (count == index){ *save_data++ = *sub_data++ + constant; } else{ *save_data++ = *sub_data++; } } } //两个一维矩阵相乘 两个矩阵的大小需要一样且都是一维数组类型 //参数 //src_matrix:矩阵a //sub_matrix:矩阵b //返回 结果 float user_nn_matrix_mult_cum_matrix(user_nn_matrix *src_matrix, user_nn_matrix *sub_matrix){ int count = sub_matrix->width * sub_matrix->height; float *src_data = src_matrix->data; float *sub_data = sub_matrix->data; float result = 0; while (count--){ result += (*src_data++) * (*sub_data++); } return result; } //矩阵乘法 //1.当矩阵A的列数等于矩阵B的行数时,A与B可以相乘。 //2.矩阵C的行数等于矩阵A的行数,C的列数等于B的列数。 //3.乘积C的第m行第n列的元素等于矩阵A的第m行的元素与矩阵B的第n列对应元素乘积之和。 //参数 //src_matrix:矩阵A //sub_matrix:矩阵B //返回值 无 user_nn_matrix *user_nn_matrix_mult_matrix(user_nn_matrix *src_matrix, user_nn_matrix *sub_matrix){ #ifdef WIN64 return user_nn_matrix_mult_matrix_cuda(src_matrix, sub_matrix); #else user_nn_matrix *result = NULL;//结果矩阵 float *src_data = NULL;// float *sub_data = NULL;// float *result_data = NULL; int width, height,point;//矩阵列数 if (src_matrix->width != sub_matrix->height){//矩阵乘积只有当第一个矩阵的列数=第二个矩阵的行数才有意义 return NULL; } result = user_nn_matrix_create(sub_matrix->width, src_matrix->height);//创建新的矩阵 result_data = result->data;//获取数据指针 for (height = 0; height < result->height; height++){ for (width = 0; width < result->width; width++){ src_data = src_matrix->data + height * src_matrix->width;//指向行开头 sub_data = sub_matrix->data + width;//指向列开头 for (point = 0; point < sub_matrix->height; point++){ *result_data += *src_data * *sub_data; sub_data += sub_matrix->width; src_data++; } result_data++; } } return result; #endif } //两个矩阵进行点乘操作 对应数据进行相乘 //src_matrix:矩阵A //sub_matrix:矩阵B //返回值 无 void user_nn_matrix_poit_mult_matrix(user_nn_matrix *save_matrix, user_nn_matrix *src_matrix, user_nn_matrix *sub_matrix){ int count = sub_matrix->width * sub_matrix->height; float *save_data = save_matrix->data; float *src_data = src_matrix->data; float *sub_data = sub_matrix->data; while (count--){ *save_data++ = (*src_data++) * (*sub_data++); } } //矩阵每个元素*常数 //参数 //src_matrix:矩阵 //返回值 无 void user_nn_matrix_mult_constant(user_nn_matrix *src_matrix, float constant){ int count = src_matrix->width * src_matrix->height;//获取矩阵数据大小 float *src_data = src_matrix->data; while (count--){ *src_data++ = (float)*src_data * constant; } } //矩阵除法 //参数 //src_matrix:矩阵 //返回值 无 void user_nn_matrix_divi_constant(user_nn_matrix *src_matrix, float constant){ int count = src_matrix->width * src_matrix->height;//获取矩阵数据大小 float *src_data = src_matrix->data; while (count--){ *src_data++ = (float)*src_data / constant; } } //将矩阵旋转180° //参数 //output:输出图像 //input:输入图像 //返回 成功或失败 // user_nn_matrix *user_nn_matrix_rotate180(user_nn_matrix *src_matrix){ user_nn_matrix *result = NULL; int count = src_matrix->width * src_matrix->height; float *input_data = src_matrix->data; float *result_data; result = user_nn_matrix_create(src_matrix->width, src_matrix->height); result_data = result->data;//取得数据指针 while (count--){ *result_data++ = input_data[count];//直接首尾进行交换 } return result; } //对矩阵进行pooling操作 此操作针对cnn使用 //参数 //save_matrix:池化后的矩阵对象 //src_matrix:池化对象 //kernel_matrix:池化矩阵大小 //返回 池化后的矩阵 void user_nn_matrix_pooling(user_nn_matrix *save_matrix, user_nn_matrix *src_matrix, user_nn_matrix *kernel_matrix){ user_nn_matrix *temp_matrix = NULL;//创建一个零时保存被卷积数据的矩阵 int start_x, start_y;//这里保存开始的x和y位置 float *save_data = save_matrix->data;//保存数据的指针 for (start_y = 0; start_y < (src_matrix->height / kernel_matrix->height); start_y++){//纵轴移动一次 横轴需要移动整个行 for (start_x = 0; start_x < (src_matrix->width / kernel_matrix->width); start_x++){ temp_matrix = user_nn_matrix_ext_matrix(src_matrix, start_x * kernel_matrix->width, start_y * kernel_matrix->height, kernel_matrix->width, kernel_matrix->height);//从被卷积对象中获取卷积数据 数据大小为模板大小 *save_data++ = user_nn_matrix_mult_cum_matrix(temp_matrix, kernel_matrix);//乘积累加 user_nn_matrix_delete(temp_matrix);//删除矩阵 } } } //对矩阵进行卷积操作 //参数 //src_matrix:卷积对象 //kernel_matrix:卷积核 //type:卷积类型 full same valid 等 //返回 无 user_nn_matrix *user_nn_matrix_conv2(user_nn_matrix *src_matrix, user_nn_matrix *kernel_matrix, user_nn_conv2_type type){ user_nn_matrix *conv_matrix = NULL;//被卷积对象 user_nn_matrix *mode_matrix = NULL;//创建一个零时保存卷积核大小的矩阵 用于矩阵翻转180° user_nn_matrix *temp_matrix = NULL;//缓存 user_nn_matrix *full_matrix = NULL;//缓存 user_nn_matrix *same_matrix = NULL;//缓存 user_nn_matrix *result = NULL;//结果矩阵 int start_x, start_y;//这里保存开始的x和y位置 float *result_data = NULL; if (type == u_nn_conv2_type_valid){ result = user_nn_matrix_create(src_matrix->width - kernel_matrix->width + 1, src_matrix->height - kernel_matrix->height + 1);//创建一个用户返回结果的矩阵 result_data = result->data;//指向输出矩阵的数据指针 conv_matrix = src_matrix;//卷积对象指针 }else if (type == u_nn_conv2_type_full){ full_matrix = user_nn_matrix_expand(src_matrix, kernel_matrix->height - 1, kernel_matrix->height - 1, kernel_matrix->width - 1, kernel_matrix->width - 1);//边界扩展 result = user_nn_matrix_create(full_matrix->width - kernel_matrix->width + 1, full_matrix->height - kernel_matrix->height + 1);//创建一个用户返回结果的矩阵 result_data = result->data;//指向输出矩阵的数据指针 conv_matrix = full_matrix;//卷积对象指针 } else if (type == u_nn_conv2_type_same){ same_matrix = user_nn_matrix_expand(src_matrix, (kernel_matrix->height - 1) / 2, (kernel_matrix->height) / 2, (kernel_matrix->width - 1) / 2, (kernel_matrix->width) / 2);//扩充矩阵 返回一个新的矩阵 result = user_nn_matrix_create(same_matrix->width - kernel_matrix->width + 1, same_matrix->height - kernel_matrix->height + 1);//创建一个用户返回结果的矩阵 result_data = result->data;//指向输出矩阵的数据指针 conv_matrix = same_matrix;//卷积对象指针 } else{} mode_matrix = user_nn_matrix_rotate180(kernel_matrix);//模板翻转180° for (start_y = 0; start_y < result->height; start_y++){//纵轴移动一次 横轴需要移动整个行 for (start_x = 0; start_x < result->width; start_x++){ temp_matrix = user_nn_matrix_ext_matrix(conv_matrix, start_x, start_y, kernel_matrix->width, kernel_matrix->height);//从被卷积对象中获取卷积数据 数据大小为模板大小 *result_data++ = user_nn_matrix_mult_cum_matrix(temp_matrix, mode_matrix);//卷积运算 user_nn_matrix_delete(temp_matrix);//删除矩阵 } } user_nn_matrix_delete(mode_matrix); user_nn_matrix_delete(full_matrix);//删除矩阵 return result; } //计算矩阵的均方误差 //src_matrix:倍计算的矩阵 //返回 损失函数 float user_nn_matrix_get_rms(user_nn_matrix *src_matrix) { //user_nn_matrix_poit_mult_matrix(error_matrix_temp, error_matrix_temp, error_matrix_temp);//矩阵乘法 //*loss_vaule = *loss_vaule + user_nn_matrix_cum_element(error_matrix_temp) / (error_matrix_temp->height*error_matrix_temp->width);//计算损失函数 float loss = 0.0f; float *src_data = src_matrix->data; int count = src_matrix->width * src_matrix->height; while (count--) { loss = *src_data * *src_data; src_data++; } return float(loss / (src_matrix->width*src_matrix->height)); } //矩阵复制 //dest:原矩阵 //m:复制垂直排列个数 //n:复制水平排列个数 //返回 新的矩阵 user_nn_matrix *user_nn_matrix_repmat(user_nn_matrix *dest, int m, int n) { user_nn_matrix *result = user_nn_matrix_create(dest->width * n, dest->height * m); int loca_x = 0; int loca_y = 0; for (loca_y = 0; loca_y < m; loca_y++) { for (loca_x = 0; loca_x < n; loca_x++) { user_nn_matrix_save_array(result, dest->data, loca_x*dest->width, loca_y*dest->height, dest->width, dest->height); } } return result; } //把一个矩阵对角线设置为1 目前仅仅支持方阵 //dest:目标矩阵 //返回 坐标矩阵 void user_nn_matrix_eye(user_nn_matrix *dest) { int count = 0; for (count = 0; count < dest->width; count++) { *user_nn_matrix_ext_value(dest, count, count) = 1.0f; } } //求解givens 旋转后的值 //x:x值 //y:y值 //参考matlab进行编写 //返回矩阵 user_nn_matrix *user_nn_givens(float x, float y) { user_nn_matrix *result = user_nn_matrix_create(2, 2);//创建矩阵2x2 float c = 0.0f; float s = 0.0f; float nrm = 0.0f; float absx = 0.0f; absx = abs(x); if (absx == 0.0f) { c = 0; s = 1; } else { /* //matlab nrm = (float)hypot(x,y); c = absx / nrm; s = (float)(x / absx)*(y/ nrm); */ //维基百科 nrm = (float)hypot(x, y); c = x / nrm; s = y / nrm; } result->data[0] = c; result->data[1] = s; result->data[2] = -s; result->data[3] = c; return result; } //householder reflection方式求解矩阵的QR值 //dest:数据矩阵 //coordinate:坐标数据 //参考:https://en.wikipedia.org/wiki/Householder_transformation //返回 QR矩阵 user_nn_list_matrix *user_nn_householder_qr(user_nn_matrix *dest) { user_nn_list_matrix *result = user_nn_matrices_create(2, 1, dest->width, dest->height);//创建两个连续矩阵第一个保存Q 第二个保存R user_nn_matrix *matrix_G = user_nn_matrix_create(dest->width, dest->width);//创建矩阵 user_nn_matrix *matrix_Q = result->matrix;//第一个矩阵保存Q user_nn_matrix *matrix_R = result->matrix->next;//第二个矩阵保存R user_nn_matrix *matrix_m = NULL; user_nn_matrix *matrix_e = NULL; user_nn_matrix *matrix_c = NULL; user_nn_matrix *matrix_temp = NULL; int index = 0; float norm_m = 0.0f; user_nn_matrix_cpy_matrix(matrix_R, dest);//拷贝到matrix_R中 user_nn_matrix_eye(matrix_Q);//设置Q的对角线为1 for (index = 0; index < dest->height - 1; index++) { user_nn_matrix_memset(matrix_G, 0);//设置G为0 user_nn_matrix_eye(matrix_G);//设置G的对角线为1 matrix_m = user_nn_matrix_ext_matrix(matrix_R, index, index, 1, matrix_R->height - index);//提取矩阵 matrix_e = user_nn_matrix_create(matrix_m->width, matrix_m->height);//重新创建矩阵 matrix_e->data[0] = user_nn_matrix_norm(matrix_m);//求取范数 user_nn_matrix_cum_matrix_mult_alpha(matrix_m, matrix_m, matrix_e,-1.0f);//计算矩阵之差 user_nn_matrix_divi_constant(matrix_m, user_nn_matrix_norm(matrix_m));//除法计算 matrix_c = user_nn_matrix_outer(matrix_m, matrix_m);//求解矩阵outer user_nn_matrix_sum_array_mult_alpha(matrix_G, matrix_c->data,-2.0f, index, index, matrix_c->width, matrix_c->height);//叠加数据 matrix_temp = user_nn_matrix_mult_matrix(matrix_G, matrix_R);//矩阵乘法 user_nn_matrix_cpy_matrix(matrix_R, matrix_temp);//拷贝到matrix_R中 user_nn_matrix_delete(matrix_temp);//删除矩阵 //Q=G1*G2*..Gn Q就是特征向量Q matrix_temp = user_nn_matrix_mult_matrix(matrix_Q, matrix_G);//矩阵乘法 user_nn_matrix_cpy_matrix(matrix_Q, matrix_temp);//拷贝到matrix_Q中 user_nn_matrix_delete(matrix_temp);//删除矩阵 user_nn_matrix_delete(matrix_m);//删除矩阵 user_nn_matrix_delete(matrix_e);//删除矩阵 user_nn_matrix_delete(matrix_c);//删除矩阵 } user_nn_matrix_delete(matrix_G);//删除矩阵 return result; } //givens rotation方式求解矩阵的QR值 //dest:数据矩阵 //coordinate:坐标数据 //参考:https://en.wikipedia.org/wiki/Givens_rotation //返回 QR矩阵 user_nn_list_matrix *user_nn_givens_qr(user_nn_matrix *dest) { user_nn_list_matrix *result = user_nn_matrices_create(2, 1, dest->width, dest->height);//创建两个连续矩阵第一个保存Q 第二个保存R user_nn_matrix *matrix_G = user_nn_matrix_create(dest->width, dest->height);//创建矩阵 user_nn_matrix *matrix_Q = result->matrix;//第一个矩阵保存Q user_nn_matrix *matrix_R = result->matrix->next;//第二个矩阵保存R user_nn_matrix *matrix_temp = NULL;//临时矩阵 user_nn_matrix *triangle_axis = NULL;//左三角坐标数据 user_nn_matrix *givens_vaule = NULL; int posit_x = 0; float *axis_x = NULL; float *axis_y = NULL; float givens_r = 0.0f; float givens_c = 0.0f; float givens_s = 0.0f; user_nn_matrix_cpy_matrix(matrix_R, dest);//拷贝到matrix_R中 user_nn_matrix_eye(matrix_Q);//设置Q的对角线为1 triangle_axis = user_nn_tril_indices(dest->width, dest->height, 0.0f);//求取坐标数据 axis_x = triangle_axis->data;//获取X坐标 axis_y = triangle_axis->data + triangle_axis->width;//获取Y坐标 for (posit_x = 0; posit_x < triangle_axis->width; posit_x++) { //循环所有坐标 if (*user_nn_matrix_ext_value(matrix_R, (int)*axis_x, (int)*axis_y) != 0) {//判断目标坐标数据是否为0 如果是0那么不用计算 user_nn_matrix_memset(matrix_G, 0);//设置G为0 user_nn_matrix_eye(matrix_G);//设置G的对角线为1 givens_vaule = user_nn_givens(*user_nn_matrix_ext_value(matrix_R, (int)*axis_x, (int)*axis_x), *user_nn_matrix_ext_value(matrix_R, (int)*axis_x, (int)*axis_y));//求解givens旋转后的值 *user_nn_matrix_ext_value(matrix_G, (int)*axis_x, (int)*axis_x) = givens_vaule->data[0]; *user_nn_matrix_ext_value(matrix_G, (int)*axis_y, (int)*axis_x) = givens_vaule->data[1]; *user_nn_matrix_ext_value(matrix_G, (int)*axis_x, (int)*axis_y) = givens_vaule->data[2]; *user_nn_matrix_ext_value(matrix_G, (int)*axis_y, (int)*axis_y) = givens_vaule->data[3]; user_nn_matrix_delete(givens_vaule);//删除矩阵 //G1*A1=A2 G2*A2=A3 ... Gn-1*An-1=An An就是特征向量R matrix_temp = user_nn_matrix_mult_matrix(matrix_G, matrix_R);//矩阵乘法 user_nn_matrix_cpy_matrix(matrix_R, matrix_temp);//拷贝到matrix_R中 user_nn_matrix_delete(matrix_temp);//删除矩阵 //Q=G1*G2*..Gn Q就是特征向量Q user_nn_matrix_transpose(matrix_G);//进行转置 matrix_temp = user_nn_matrix_mult_matrix(matrix_Q, matrix_G);//矩阵乘法 user_nn_matrix_cpy_matrix(matrix_Q, matrix_temp);//拷贝到matrix_Q中 user_nn_matrix_delete(matrix_temp);//删除矩阵 } axis_x++; axis_y++; } user_nn_matrix_delete(matrix_G);//删除矩阵 user_nn_matrix_delete(triangle_axis);//删除矩阵 return result; } //从目标矩阵提取矩阵特征向量值 //dest:目标矩阵 //coordinate:矩阵坐标 //iter:迭代次数 //返回:特征值、特征向量 user_nn_list_matrix *user_nn_eigs(user_nn_matrix *dest, float epsilon, eigs_type type) { user_nn_list_matrix *result = user_nn_matrices_create(2, 1, dest->width, dest->height);//创建两个连续矩阵第一个保存LATENT 第二个保存COEFF user_nn_list_matrix *QR_list = NULL; user_nn_matrix *matrix_latent = NULL; user_nn_matrix *matrix_coeff = NULL; user_nn_matrix *matrix_tmp = NULL; float n_latent_trace = 0.0f;//保存当前特征值和 float o_latent_trace = 0.0f;//保存历史特征值和 matrix_latent = result->matrix;//LATENT matrix_latent matrix_coeff = result->matrix->next;//COEFF matrix_coeff user_nn_matrix_cpy_matrix(matrix_latent, dest);//拷贝数据 user_nn_matrix_eye(matrix_coeff);//设置G的对角线为1 for (;;) { if (type == qr_givens) { QR_list = user_nn_givens_qr(matrix_latent);//采用givens计算一次QR } else if(type == qr_householder){ QR_list = user_nn_householder_qr(matrix_latent);//采用householder计算一次QR值 } matrix_tmp = user_nn_matrix_mult_matrix(QR_list->matrix->next, QR_list->matrix);//继续迭代,需要计算新的矩阵 user_nn_matrix_cpy_matrix(matrix_latent, matrix_tmp);//更新数据 user_nn_matrix_delete(matrix_tmp); // matrix_tmp = user_nn_matrix_mult_matrix(matrix_coeff, QR_list->matrix);//求取特征值 user_nn_matrix_cpy_matrix(matrix_coeff, matrix_tmp);//更新数据 user_nn_matrix_delete(matrix_tmp); user_nn_matrices_delete(QR_list);//删除链表矩阵 //对角线特征值不在变化那么迭代结束 n_latent_trace = user_nn_matrix_trace(matrix_latent);//求和特征值的对角线和 if (abs(n_latent_trace - o_latent_trace) <= epsilon) { break; } else { o_latent_trace = n_latent_trace; } } return result; } //求解矩阵的平均值 //src_matrix:原始矩阵 //返回平均值矩阵 user_nn_matrix *user_nn_matrix_mean(user_nn_matrix *src_matrix) { int height_index = 0; user_nn_matrix *matrix_mean = user_nn_matrix_create(src_matrix->width, 1);//创建一个保存平均值的矩阵 user_nn_matrix *matrix_temp = user_nn_matrix_create(src_matrix->width, 1);// for (height_index = 0; height_index < src_matrix->height; height_index++) { user_nn_matrix_cpy_array(matrix_temp->data, src_matrix, 0, height_index, matrix_temp->width, matrix_temp->height);//拷贝一行数据 user_nn_matrix_sum_matrix_mult_alpha(matrix_mean, matrix_temp, 1.0f);//求和矩阵 } user_nn_matrix_divi_constant(matrix_mean, (float)src_matrix->height);//求平均数 user_nn_matrix_delete(matrix_temp);//删除矩阵 return matrix_mean; } //求解协方差矩阵 //src_matrix:需要求解的矩阵 //返回求解后的结果 user_nn_matrix *user_nn_matrix_cov(user_nn_matrix *src_matrix) { user_nn_matrix *result = NULL; user_nn_matrix *src_matrix_s = NULL;//临时矩阵 user_nn_matrix *src_matrix_t = NULL;//转置矩阵 user_nn_matrix *matrix_mean = user_nn_matrix_create(src_matrix->width, 1);//创建一个保存平均值的矩阵 int height_index = 0; matrix_mean = user_nn_matrix_mean(src_matrix);//求取平均值 src_matrix_s = user_nn_matrix_cpy_create(src_matrix);//复制矩阵 for (height_index = 0; height_index < src_matrix_s->height; height_index++) { user_nn_matrix_sum_array_mult_alpha(src_matrix_s, matrix_mean->data, -1.0f, 0, height_index, matrix_mean->width, matrix_mean->height);//减去平均值 } src_matrix_t = user_nn_matrix_cpy_create(src_matrix_s);//创建保存转置矩阵AT的矩阵 user_nn_matrix_transpose(src_matrix_t);//进行转置 result = user_nn_matrix_mult_matrix(src_matrix_t, src_matrix_s);//矩阵相乘 user_nn_matrix_divi_constant(result, (float)(result->width - 1));//除以n-1 user_nn_matrix_delete(matrix_mean);//删除矩阵 user_nn_matrix_delete(src_matrix_s);//删除矩阵 user_nn_matrix_delete(src_matrix_t);//删除矩阵 return result; } //求取方阵的三角矩阵坐标 返回左下角所有坐标不包含中线 //width:矩阵宽度 //height:矩阵高度 //details:旋转角度 //返回 坐标矩阵 user_nn_matrix *user_nn_tril_indices(int width, int height, float details) { user_nn_matrix *result = NULL; float *result_x = NULL; float *result_y = NULL; float posit_m = 0.0f; int posit_x = 0; int posit_y = 0; result = user_nn_matrix_create((width*(width - 1) / 2), 2);//等差数列求和得到总共多少个x坐标点 result_x = result->data; result_y = result->data + result->width; for (posit_y = 0; posit_y < height; posit_y++) { posit_m = (float)(posit_y * width) / height;//y=u*x直线函数 if (modf(posit_m, &posit_m) > 0.0f) { posit_m += 1; if (posit_m >= width) { posit_m -= 1; }//不能超过最大值坐标 } for (posit_x = 0; posit_x < posit_m; posit_x++) { //printf("\n(%d,%d)", post_x, post_y);//取斜线下部左三角矩阵 *result_y++ = (float)posit_y; *result_x++ = (float)posit_x; } } return result; } //求和对角线元素 //src_matrix:矩阵 必须是方阵 //返回求和值 float user_nn_matrix_trace(user_nn_matrix *src_matrix) { int count = 0; float result = 0.0f; for (count = 0; count < src_matrix->width; count++) { result += *user_nn_matrix_ext_value(src_matrix, count, count); } return result; } //返回对角线元素 //src_matrix:矩阵 必须是方阵 //返回结果矩阵 user_nn_matrix *user_nn_matrix_diag(user_nn_matrix *src_matrix) { user_nn_matrix *result = NULL; float *result_data = NULL; int count = 0; result = user_nn_matrix_create(src_matrix->width,1); result_data = result->data; for (count = 0; count < src_matrix->width; count++) { *result_data++ = *user_nn_matrix_ext_value(src_matrix, count, count); } return result; } //求解矩阵的范数 2D方式 //src_matrix:矩阵 必须是方阵 //返回结果矩阵 float user_nn_matrix_norm(user_nn_matrix *src_matrix) { int count = src_matrix->width*src_matrix->height; float *src_matrix_data = src_matrix->data; float result = 0.0f; while (count--) { result += *src_matrix_data * *src_matrix_data;//平方和开根号 src_matrix_data++; } result = sqrt(result); return result; } //计算两个矩阵的outer值 //src_matrix:矩阵A //sub_matrix:矩阵B //返回结果矩阵 user_nn_matrix *user_nn_matrix_outer(user_nn_matrix *src_matrix, user_nn_matrix *sub_matrix) { user_nn_matrix *result = NULL; float *src_matrix_data = NULL; float *sub_matrix_data = NULL; float *result_data = NULL; int height = 0; int width = 0; result = user_nn_matrix_create(sub_matrix->width*sub_matrix->height,src_matrix->width*src_matrix->height); result_data = result->data; src_matrix_data = src_matrix->data; for (height = 0; height < src_matrix->width*src_matrix->height; height++) { sub_matrix_data = sub_matrix->data; for (width = 0; width < sub_matrix->width*sub_matrix->height; width++) { *result_data++ = *src_matrix_data * *sub_matrix_data++; } src_matrix_data++; } return result; } //通过对角矩阵的元素来从新排序新的矩阵 //src_matrix:矩阵 //diag:排序列表 //epsilon:排序值 //返回 新的值特征值 user_nn_matrix *user_nn_matrix_cut_vector(user_nn_matrix *src_matrix, user_nn_matrix *diag_matrix, float epsilon) { user_nn_matrix *result = NULL; float total_diag_vaule = 0.0f; float target_diag_vaule = 0.0f; float *diag_vaule_data = NULL; int total_width = 0; total_diag_vaule = user_nn_matrix_cum_element(diag_matrix); diag_vaule_data = diag_matrix->data; for (;;) {//求出需要多少列 total_width++; target_diag_vaule += *diag_vaule_data++; if (float(target_diag_vaule / total_diag_vaule) >= epsilon) { break;//跳出 } } result = user_nn_matrix_ext_matrix(src_matrix,0,0, total_width, src_matrix->height); return result; } //打印矩阵数据 //参数 //list_matrix:矩阵数据 //返回 无 void user_nn_matrix_printf(FILE *debug_file, user_nn_matrix *src_matrix){ int width, height; float *input_data = src_matrix->data; //FILE *debug_file = NULL; //debug_file = fopen("debug.txt", "w+"); printf("matrix: \n width:%d,height:%d\n\n", src_matrix->width, src_matrix->height); if (debug_file != NULL) fprintf(debug_file,"matrix: \n width:%d,height:%d\n\n", src_matrix->width, src_matrix->height);//保存数据 for (height = 0; height < src_matrix->height; height++){ for (width = 0; width < src_matrix->width; width++){ //printf("%-10.6f ", *input_data); if (*input_data == FLT_MAX) { printf("%s ", " max "); } else { printf("%-10.6f ", *input_data); } if (debug_file != NULL) { if (*input_data == FLT_MAX) { fprintf(debug_file, "%s", " max "); } else { fprintf(debug_file, "%-10.6f ", *input_data); } } input_data++; } printf("\n\n"); if (debug_file != NULL) fprintf(debug_file, "\n"); } //fclose(debug_file); if (debug_file != NULL) fflush(debug_file); } //打印链表矩阵数据 //参数 //list_matrix:矩阵数据 //返回 无 void user_nn_matrices_printf(FILE *debug_file,char *title, user_nn_list_matrix *src_matrix){ int width, height; int count = src_matrix->width * src_matrix->height; printf("%s matrices: \n width:%d,height:%d\n\n\n", title, src_matrix->width, src_matrix->height); if (debug_file != NULL) fprintf(debug_file, "%s matrices: \n width:%d,height:%d\n\n\n", title, src_matrix->width, src_matrix->height); for (height = 0; height < src_matrix->height; height++){ for (width = 0; width < src_matrix->width; width++){ user_nn_matrix_printf(debug_file, user_nn_matrices_ext_matrix(src_matrix, width, height)); } printf("\n\n"); if (debug_file != NULL) fprintf(debug_file,"\n\n"); } } /* //把一个矩阵数据拷贝到另外一个矩阵中 user_nn_matrix *matrix = NULL; user_nn_matrix *dest = NULL; matrix = user_nn_matrix_create(6, 6);//创建3*3大小的二维矩阵 dest = user_nn_matrix_create(2, 2);//创建2*2大小的二维矩阵 user_nn_matrix_rand_vaule(matrix,1); user_nn_matrix_printf(NULL, matrix);//打印矩阵 bool is_success = user_nn_matrix_save_matrix(matrix, dest, 1, 4); printf("\n%s\n", is_success==true?"true":"false"); user_nn_matrix_printf(NULL, matrix);//打印矩阵 getchar(); return 0; */ /* //把一个内存数据拷贝到另外一个矩阵中 按照规定参数 user_nn_matrix *matrix = NULL; user_nn_matrix *dest = NULL; matrix = user_nn_matrix_create(6, 6);//创建3*3大小的二维矩阵 dest = user_nn_matrix_create(2, 2);//创建2*2大小的二维矩阵 user_nn_matrix_rand_vaule(matrix, 1); user_nn_matrix_printf(NULL, matrix);//打印矩阵 bool is_success = user_nn_matrix_save_array(matrix, dest->data, 2, 3, dest->width, dest->height); printf("\n%s\n", is_success == true ? "true" : "false"); user_nn_matrix_printf(NULL, matrix);//打印矩阵 getchar(); return 0; */ /* 池化矩阵 user_nn_matrix *src_matrix = NULL; user_nn_matrix *sub_matrix = NULL; user_nn_matrix *res_matrix = NULL; float *result = NULL; src_matrix = user_nn_matrix_create(28, 28); sub_matrix = user_nn_matrix_create(2, 2); user_nn_matrix_memset(src_matrix, 2.5);//设置矩阵值 user_nn_matrix_memset(sub_matrix, 0.25);//设置矩阵值 result = user_nn_matrix_ext_value(src_matrix, 27, 27); *result = 1; res_matrix = user_nn_matrix_pool(src_matrix, sub_matrix); if (res_matrix != NULL){ user_nn_matrix_printf(res_matrix);//打印矩阵 } else{ printf("null\n"); } */ /* 矩阵卷积测试 user_nn_matrix *src_matrix = NULL; user_nn_matrix *sub_matrix = NULL; user_nn_matrix *res_matrix = NULL; src_matrix = user_nn_matrix_create(28, 28); sub_matrix = user_nn_matrix_create(5, 5); user_nn_matrix_memset(src_matrix, 2.5);//设置矩阵值 user_nn_matrix_memset(sub_matrix, 1.0);//设置矩阵值 res_matrix = user_nn_matrix_conv2(src_matrix, sub_matrix, u_nn_conv2_type_valid); if (res_matrix != NULL){ user_nn_matrix_printf(res_matrix);//打印矩阵 } else{ printf("null\n"); } */ /* 二维矩阵 提取 user_nn_list_matrix *list = NULL; user_nn_matrix *dest = NULL; list = user_nn_matrices_create(2, 2, 1, 1);//创建2*2个1*1大小的二维矩阵 user_nn_matrix_memset(list->matrix, 1); user_nn_matrix_memset(list->matrix->next, 2); user_nn_matrix_memset(list->matrix->next->next, 3); user_nn_matrix_memset(list->matrix->next->next->next, 4); dest = user_nn_matrices_ext_matrix(list, 1, 0);//获取其中一个矩阵 if (dest != NULL){ user_nn_matrix_printf(NULL,dest);//打印矩阵 } else{ printf("null\n"); } */ /* 矩阵截取测试 user_nn_matrix *matrix = NULL; user_nn_matrix *dest = NULL; matrix = user_nn_matrix_create(2, 2);//创建2*2大小的二维矩阵 matrix->data[0] = 1.0; matrix->data[1] = 2.0; matrix->data[2] = 3.0; matrix->data[3] = 4.0; dest = user_nn_matrix_ext_matrix(matrix, 1, 1, 1, 1);//截取矩阵 if (dest != NULL){ user_nn_matrix_printf(NULL,dest);//打印矩阵 } else{ printf("null\n"); } */ /*获取矩阵中的一个值 user_nn_matrix *matrix = NULL; float *p; matrix = user_nn_matrix_create(2, 2);//创建2*2大小的二维矩阵 matrix->data[0] = 1.0; matrix->data[1] = 2.0; matrix->data[2] = 3.0; matrix->data[3] = 4.0; p = user_nn_matrix_ext_value(matrix, 1, 1);//获取矩阵值 if (p != NULL) printf("%f \n", *p); */ /*偏置参数测试 user_nn_list_biases *biases = NULL; user_nn_bias *dest = NULL; biases = user_nn_biases_create(4); biases->bias->bias = 1.0; biases->bias->next->bias = 2.0; biases->bias->next->next->bias = 3.0; biases->bias->next->next->next->bias = 4.0; dest = user_nn_biases_ext_bias(biases,0); if (dest != NULL) printf("%f \n", dest->bias); */ /* 矩阵乘法 user_nn_matrix *src_matrix = NULL; user_nn_matrix *sub_matrix = NULL; user_nn_matrix *res_matrix = NULL; src_matrix = user_nn_matrix_create(1, 1); sub_matrix = user_nn_matrix_create(1, 1); user_nn_matrix_memset(src_matrix, 2.5);//设置矩阵值 user_nn_matrix_memset(sub_matrix, 1.0);//设置矩阵值 res_matrix = user_nn_matrix_mult_matrix(src_matrix, sub_matrix);//矩阵相乘 if (res_matrix != NULL){ user_nn_matrix_printf(res_matrix);//打印矩阵 } else{ printf("null\n"); } */ /*单个矩阵转化为 高度为1的连续链表矩阵 user_nn_list_matrix *list = NULL; user_nn_matrix *dest = NULL; dest = user_nn_matrix_create(2,2); dest->data[0] = 1.0; dest->data[1] = 2.0; dest->data[2] = 3.0; dest->data[3] = 4.0; list = user_nn_matrix_to_matrices(dest,1,1);//获取其中一个矩阵 if (list != NULL){ user_nn_matrix_printf(list->matrix);//打印矩阵 user_nn_matrix_printf(list->matrix->next);//打印矩阵 user_nn_matrix_printf(list->matrix->next->next);//打印矩阵 user_nn_matrix_printf(list->matrix->next->next->next);//打印矩阵 } else{ printf("null\n"); } */ /*链表矩阵转化为高度为1的单个矩阵 user_nn_list_matrix *list = NULL; user_nn_matrix *dest = NULL; list = user_nn_matrices_create(5, 2, 1, 1);//创建2*2个1*1大小的二维矩阵 user_nn_matrix_memset(list->matrix, 1); user_nn_matrix_memset(list->matrix->next, 2); user_nn_matrix_memset(list->matrix->next->next, 3); user_nn_matrix_memset(list->matrix->next->next->next, 4); dest = user_nn_matrices_to_matrix(list);//获取其中一个矩阵 if (dest != NULL){ user_nn_matrix_printf(NULL,dest);//打印矩阵 } else{ printf("null\n"); } */ /*链表偏置参数转矩阵测试 user_nn_list_biases *list = NULL; user_nn_matrix *dest = NULL; list = user_nn_biases_create(1); list->bias->bias = 1.0; list->bias->next->bias = 2.0; list->bias->next->next->bias = 3.0; list->bias->next->next->next->bias = 4.0; list->bias->next->next->next->next->bias = 5.0; dest = user_nn_biases_to_matrix(list); if (dest != NULL){ user_nn_matrix_printf(NULL,dest);//打印矩阵 } else{ printf("null\n"); } */ /*矩阵均值扩充 user_nn_matrix *matrix = NULL; user_nn_matrix *dest = NULL; matrix = user_nn_matrix_create(2, 2);//创建2*2大小的二维矩阵 matrix->data[0] = 1.0; matrix->data[1] = 2.0; matrix->data[2] = 3.0; matrix->data[3] = 4.0; dest = user_nn_matrix_expand_matrix(matrix, 2, 3);// if (dest != NULL){ user_nn_matrix_printf(NULL,dest);//打印矩阵 } else{ printf("null\n"); } */ /*矩阵扩充 边框扩充 user_nn_matrix *matrix = NULL; user_nn_matrix *dest = NULL; matrix = user_nn_matrix_create(1, 1);//创建2*2大小的二维矩阵 matrix->data[0] = 1.0; //matrix->data[1] = 2.0; //matrix->data[2] = 3.0; //matrix->data[3] = 4.0; dest = user_nn_matrix_expand(matrix, 1, 1);// if (dest != NULL){ user_nn_matrix_printf(NULL,dest);//打印矩阵 } else{ printf("null\n"); } */ /*连续矩阵拷贝 user_nn_list_matrix *list = NULL; user_nn_list_matrix *dest = NULL; list = user_nn_matrices_create(5, 2, 1, 1);//创建2*2个1*1大小的二维矩阵 dest = user_nn_matrices_create(5, 2, 1, 1);//创建2*2个1*1大小的二维矩阵 user_nn_matrix_memset(list->matrix, 1); user_nn_matrix_memset(list->matrix->next, 2); user_nn_matrix_memset(list->matrix->next->next, 3); user_nn_matrix_memset(list->matrix->next->next->next, 4); user_nn_matrices_cpy_matrices(dest, list);//获取其中一个矩阵 if (dest != NULL){ user_nn_matrices_printf(NULL,"TEST", dest);//打印矩阵 } else{ printf("null\n"); } */ /* 矩阵交换 unsigned char src[] = { 1, 2, 3, 4, 5, 6 }; unsigned char sub[] = { 1, 2, 3 }; user_nn_matrix *src_matrix = NULL; user_nn_matrix *sub_matrix = NULL; user_nn_matrix *res_matrix = NULL; src_matrix = user_nn_matrix_create(2, 3); sub_matrix = user_nn_matrix_create(1, 3); user_nn_matrix_memcpy_char(src_matrix, src); user_nn_matrix_memcpy_char(sub_matrix, sub); user_nn_matrix_exc_width_height(src_matrix);//交换output_kernel_maps 的 width与height res_matrix = user_nn_matrix_mult_matrix(src_matrix, sub_matrix);//计算feature vector delta ######如果不能相乘需要变化横纵大小###### user_nn_matrix_exc_width_height(src_matrix);//交换output_kernel_maps 的 width与height 交换回来 if (res_matrix != NULL){ user_nn_matrix_printf(NULL,res_matrix);//打印矩阵 } else{ printf("null\n"); } */ /* 矩阵与连续矩阵变化 unsigned char src[192] ; int i = 0; for (i = 0; i < 192; i++){ src[i] = i; } user_nn_list_matrix *list = NULL; user_nn_matrix *dest = NULL; dest = user_nn_matrix_create(1, 192); user_nn_matrix_memcpy_char(dest, src); list = user_nn_matrix_to_matrices(dest, 4, 4);//获取其中一个矩阵 dest = user_nn_matrices_to_matrix(list); if (dest != NULL){ user_nn_matrix_printf(NULL, dest);//打印矩阵 } else{ printf("null\n"); } */ /*矩阵返回最大值测试 user_nn_matrix *matrix = NULL; matrix = user_nn_matrix_create(6, 6);//创建2*2大小的二维矩阵 user_nn_matrix_rand_vaule(matrix, 1); int max_value_index = user_nn_matrix_return_max_index(matrix);// int min_value_index = user_nn_matrix_return_min_index(matrix);// user_nn_matrix_printf(NULL,matrix);//打印矩阵 printf("\nmax_value_index=%d,vaule=%f\n",max_value_index,*user_nn_matrix_return_max_addr(matrix)); printf("\nmin_value_index=%d,vaule=%f\n",min_value_index,*user_nn_matrix_return_min_addr(matrix)); */ /* 矩阵转置时间测试 FILE *debug_file = NULL; debug_file = fopen("debug.txt", "w+"); user_nn_matrix *src_matrix = NULL; user_nn_matrix *sub_matrix = NULL; user_nn_matrix *res_matrix = NULL; int matrix_w = 128, matrix_h = 128; src_matrix = user_nn_matrix_create(matrix_w, matrix_h); sub_matrix = user_nn_matrix_create(matrix_w, matrix_h); clock_t test_start_time, test_end_time; float *src_data = src_matrix->data; float *sub_data = sub_matrix->data; int count = 0,total_count=499; while (count++ < (src_matrix->width * src_matrix->height)){ *src_data++ = count * 0.01f; *sub_data++ = count * 0.01f; } printf("test start:\n"); printf("width:%d,height:%d\n", src_matrix->width ,src_matrix->height); user_nn_matrix_transpose_cuda(sub_matrix);//启动显卡 Sleep(1000); //user_nn_matrix_printf(debug_file, src_matrix);//打印矩阵 while (1){ test_start_time = clock(); count = total_count; while (count--){ //user_nn_matrix_transpose_cuda(src_matrix);//GPU加速 user_nn_matrix_transpose(src_matrix);//CPU转置 } src_data = src_matrix->data;//获取数据 sub_data = sub_matrix->data;//获取数据 count = 0; while (count++ < (src_matrix->width * src_matrix->height)){ if (*src_data++ != *sub_data++){ break; } } if ((count - 1) != src_matrix->width * src_matrix->height){ printf("count:%d ", count); printf("test error \n"); break; } else{ test_end_time = (clock() - test_start_time);//获取结束时间 printf("total time : %f ms\n", (float)test_end_time / total_count); break; } } //res_matrix = user_nn_matrix_mult_matrix(src_matrix, sub_matrix);//矩阵相乘 //user_nn_matrix_transpose(src_matrix); if (src_matrix != NULL){ //user_nn_matrix_printf(debug_file, src_matrix);//打印矩阵 } else{ printf("null\n"); } fclose(debug_file); getchar(); return 1; */
[ "2863515010@qq.com" ]
2863515010@qq.com
735854f4dd2d3920581cd653b1d426bcc7326eec
0260ee4eb298e862b7385b2f7d7ce333be8595bb
/Productos/Producto.h
0de664c689e409686d1a3db0f1c3cb27a92d9b75
[]
no_license
walterstamm/Gestion-Restaurant
8777d6af6260f14803b53cd752f25c57bb408b7d
e7e2a41f394f7e26efa85130231449c465f56c3c
refs/heads/master
2023-02-16T02:45:24.639690
2020-12-31T00:57:14
2020-12-31T00:57:14
302,492,253
0
0
null
null
null
null
UTF-8
C++
false
false
1,384
h
#ifndef PRODUCTO_H_INCLUDED #define PRODUCTO_H_INCLUDED #include "Fecha.h" class Producto{ private: int ID; bool Estado; char Nombre [50]; float Precio; int Cantidad; int Cantidad_Minima; public: Producto(); bool Cargar(); void cabecera(); void Mostrar(); void Cargar_Cantidad(); ///gets int getID(){return ID;} bool getEstado(){return Estado;} char *getNombre(){return Nombre;} float getPrecio(){return Precio;} int getCantidad(){return Cantidad;} int getCantidad_Minima(){return Cantidad_Minima;} ///sets void setID(int _ID){ID=_ID;} void setEstado(int _Estado){Estado= _Estado;} void setCantidad(int _cantidad){Cantidad=_cantidad;} void setPrecio(float _Precio){Precio=_Precio;} void setCantidad_Minima(int _cantidadMinima){Cantidad_Minima=_cantidadMinima;} ///archivos bool Guardar(); bool Modificar(int); bool LeerPos(int); int GenerarID(); }; bool ValidarID_Producto(int);///validad ID (existe=true, no existe=false) ///funciones para los menus void Modificar_Precio(); void Modificar_CantMin(); void Eliminar_Producto(); void Mostrar_Todos_Productos(); void Mostrar_x_Producto(); void alertas(); #endif // PRODUCTO_H_INCLUDED
[ "matias.sanchez@alumnos.frgp.utn.edu.ar" ]
matias.sanchez@alumnos.frgp.utn.edu.ar
f19f98f2ca1f6de2f112062ab9fdc0294419e630
08e39cc0f19d4f8cb9d3120f22e4105903b72fdf
/frontend/gm_rw_analysis_check2.cc
e010ea94e7b8d4f1a2f6d120bcb06409c2a06962
[]
no_license
luoyulong/GM_LLVM_src
9d74a2d848e4ae3386cbbcfead9da4ed9be42d13
c224541466a75cdfc652a9c14db0aaabe8f9b013
refs/heads/master
2021-01-16T00:27:54.335745
2012-07-20T09:16:49
2012-07-20T09:16:49
5,094,415
0
1
null
null
null
null
UTF-8
C++
false
false
17,978
cc
#include <utility> #include "gm_ast.h" #include "gm_typecheck.h" #include "gm_error.h" #include "gm_misc.h" #include "gm_traverse.h" #include "gm_rw_analysis.h" #include "gm_frontend.h" //------------------------------------- // Defined in gm_rw_analysis.cc //------------------------------------- struct range_cond_t { range_cond_t(int r, bool b) : range_type(r), is_always(b) {} range_cond_t() {} int range_type; bool is_always; }; typedef std::map<gm_symtab_entry*, range_cond_t> temp_map_t; extern temp_map_t Default_DriverMap; extern void traverse_expr_for_readset_adding(ast_expr* e, gm_rwinfo_map& rset, temp_map_t& DrvMap=Default_DriverMap); // Type of conflicts enum { RW_CONFLICT, // Read-Write conflict (warning) WW_CONFLICT, // Write-Write conflict (warning) RD_CONFLICT, // Read-Reduce WD_CONFLICT, // Write-Reduce RM_CONFLICT, // Read-Mutate (warning) WM_CONFLICT, // Write-Mutate MM_CONFLICT, // Mutate-Mutate (warning) }; //-------------------------------------------- // Avoid same report //-------------------------------------------- struct conf_info_t { gm_symtab_entry* sym1; gm_symtab_entry* sym2; int conflict_type; }; typedef std::list<conf_info_t*> conf_list_t; static bool is_reported(conf_list_t& errors, gm_symtab_entry* t, gm_symtab_entry* b, int y) { std::list<conf_info_t*>::iterator i; for(i = errors.begin(); i!= errors.end(); i++) { conf_info_t* db = *i; if ((db->sym1 == t) && (db->sym2 == b) && (db->conflict_type == y)) return true; } return false; } static void add_report(conf_list_t& errors, gm_symtab_entry* t, gm_symtab_entry* b, int y) { conf_info_t *T = new conf_info_t(); T->sym1 = t; T->sym2 = b; T->conflict_type = y; errors.push_back(T); } //--------------------------------------------------------- // [Read-Write conflict] // Foreach(t: G.Nodes) { // Forach(u: t.Nbrs) { // t.C += u.A; // read A (random) // } // t.A = t.B + 3; // write A (linear) --> Error // } // // Foreach(t: G.Nodes) { // Foreach(u: t.Nbrs) // u.A <= t.A; // defer // t.A = t.B + 3; // write (okay) // } // // BFS(t:G.nodes) { // t.B = Sum(u:G.UpNbrs) u.A; // read A (LEV +1) // t.A = t.B + 3; // write A (LEV) --> Okay // } //--------------------------------------------------------- // [Write-Write conflict] // Foreach(t: G.Nodes) { // Forach(u: t.Nbrs) { // u.A += t.A + u.B; // write A (random) [-->Error] // } // } // // BFS(t:G.nodes) { // t.B = Sum(u:G.UpNbrs) u.A; // read A (LEV +1) // t.A = t.B + 3; // write A (LEV) --> Okay // } //---------------------------------------------------------- //---------------------------------------------------------- // Examine two lists (for the same symbol) // returns true if conflict // - If they have different level, they do not conflict // - (R-W, W-W) If they have the same driver, they do not conflict // - (R-D) => If D is 'deferring write', no conflict //---------------------------------------------------------- static int check_leveled_access(gm_rwinfo* e1) { //----------------------- // -1: no level // 0: lev-1 // 1: lev // 2: lev+1 //----------------------- int lev = -1; int a_range; if (e1->driver == NULL) { a_range = e1->access_range; } else { int t = e1->driver->getType()->get_typeid(); a_range = gm_get_range_from_itertype(t); } if (a_range == GM_RANGE_LEVEL) lev = 1; else if (a_range == GM_RANGE_LEVEL_UP) lev = 2; else if (a_range == GM_RANGE_LEVEL_DOWN) lev = 0; return lev; } static bool check_if_conflict(gm_rwinfo_list* l1, gm_rwinfo_list* l2, gm_rwinfo*& e1, gm_rwinfo*& e2, int conf_type) { gm_rwinfo_list::iterator i1; gm_rwinfo_list::iterator i2; for(i1 = l1->begin(); i1 != l1->end(); i1++) { e1 = *i1; for(i2 = l2->begin(); i2 != l2->end(); i2++) { e2 = *i2; // check if different level int lev1 = check_leveled_access(e1); int lev2 = check_leveled_access(e2); if ((lev1 >= 0) && (lev2 >= 0) && (lev1 != lev2)) // different level continue; if ((conf_type == RW_CONFLICT) || (conf_type == WW_CONFLICT) || (conf_type == RM_CONFLICT) || (conf_type == WM_CONFLICT)) { if ((e1->driver != NULL) && (e1->driver == e2->driver)) continue; } if (conf_type == RD_CONFLICT) { if (e2->reduce_op == GMREDUCE_DEFER) continue; } if (conf_type == MM_CONFLICT) { if (e1->mutate_direction == e2->mutate_direction) continue; } //printf("lev1 = %d, lev2 = %d\n", lev1, lev2); return true; // found conflict! } } return false; // no conflict } //------------------------------------------------------------ // [todo] Handling Scalar conflict (need scope info as well) // check if two sets may conflict with each other // return is_okay. //------------------------------------------------------------ static bool check_rw_conf_error(gm_rwinfo_map& S1, gm_rwinfo_map& S2, int conf_type, conf_list_t& Report ) { bool is_okay = true; bool is_warning; int error_code; switch(conf_type) { case RW_CONFLICT: error_code = GM_ERROR_READ_WRITE_CONFLICT; is_warning = true; break; case WW_CONFLICT: error_code = GM_ERROR_WRITE_WRITE_CONFLICT; is_warning = true; break; case RD_CONFLICT: error_code = GM_ERROR_READ_REDUCE_CONFLICT; is_warning = false; break; case WD_CONFLICT: error_code = GM_ERROR_WRITE_REDUCE_CONFLICT; is_warning = false; break; case RM_CONFLICT: error_code = GM_ERROR_READ_MUTATE_CONFLICT; is_warning = true; break; case WM_CONFLICT: error_code = GM_ERROR_WRITE_MUTATE_CONFLICT; is_warning = false; break; case MM_CONFLICT: error_code = GM_ERROR_MUTATE_MUTATE_CONFLICT; is_warning = true; break; default: assert(false); } gm_rwinfo_map::iterator i1, i2; for(i1 = S1.begin(); i1 != S1.end(); i1++) { gm_symtab_entry* sym1 = i1->first; gm_rwinfo_list* list1 = i1->second; gm_rwinfo* e1=NULL; // Damn o.O if (!sym1->getType()->is_property()) continue; // todo 'scalar' check for(i2 = S2.begin(); i2 != S2.end(); i2++) { gm_symtab_entry* sym2 = i2->first; gm_rwinfo_list* list2 = i2->second; gm_rwinfo* e2=NULL; // find same symbol if (sym1 != sym2) continue; // find if they conflict bool is_error_or_warn = check_if_conflict(list1, list2, e1, e2, conf_type); if (!is_warning) is_okay = is_okay && !is_error_or_warn; // find if they report if (is_error_or_warn) { if (!is_reported(Report, sym1, sym2, conf_type)) { add_report(Report, sym1, sym2, conf_type); gm_conf_error(error_code, sym1, e1->location, e2->location, is_warning); } } } } return is_okay; } //----------------------------------------------------------------------- // Traverse a subtree S. Assuming S is executed in parallel. // Find and report any conflicts in S. //----------------------------------------------------------------------- class gm_check_conf_t : public gm_apply { public: gm_check_conf_t() {is_okay = true; set_for_sent(true);} virtual bool apply(ast_sent* s); bool is_okay; private: conf_list_t Report; }; bool gm_check_parall_conflict_error(ast_sent* b) { gm_check_conf_t T; b->traverse_post(&T); // post apply return T.is_okay; } bool gm_check_conf_t::apply(ast_sent* s) { if (s->get_nodetype() == AST_FOREACH) { ast_foreach* fe = (ast_foreach*) s; if (fe->is_sequential()) return true; ast_sent* body = fe->get_body(); gm_rwinfo_map& R = get_rwinfo_sets(fe)->read_set; // body + filter gm_rwinfo_map& W = get_rwinfo_sets(body)->write_set; // gm_rwinfo_map& D = get_rwinfo_sets(body)->reduce_set; // gm_rwinfo_map& M = get_rwinfo_sets(body)->mutate_set; check_rw_conf_error(R, W, RW_CONFLICT, Report); // R-W (warning) check_rw_conf_error(W, W, WW_CONFLICT, Report); // W-W (warning) check_rw_conf_error(R, M, RM_CONFLICT, Report); // R-M (warning) check_rw_conf_error(M, M, MM_CONFLICT, Report); // M-M (warning) is_okay = is_okay && check_rw_conf_error(R, D, RD_CONFLICT, Report); // R-D is_okay = is_okay && check_rw_conf_error(W, D, WD_CONFLICT, Report); // W-D is_okay = is_okay && check_rw_conf_error(W, M, WM_CONFLICT, Report); // W-M } else if (s->get_nodetype() == AST_BFS) { // [TODO] consideration for DFS ast_bfs* bfs = (ast_bfs*) s; if (bfs->is_sequential()) return true; //------------------------------------ // reconstruct read-set filter (WHY?) //------------------------------------ int iter_type = bfs->get_iter_type(); // should be GMTYPE_NODEITER_BFS gm_symtab_entry* it = bfs->get_source()->getSymInfo(); gm_rwinfo_map R_filter; if (bfs->get_navigator()!= NULL) { range_cond_t R(GM_RANGE_LEVEL_DOWN, true); Default_DriverMap[it] = R; traverse_expr_for_readset_adding(bfs->get_navigator(), R_filter); Default_DriverMap.erase(it); } if (bfs->get_f_filter() != NULL) { range_cond_t R(gm_get_range_from_itertype(iter_type), true); Default_DriverMap[it] = R; traverse_expr_for_readset_adding(bfs->get_f_filter(), R_filter); Default_DriverMap.erase(it); } if (bfs->get_b_filter() != NULL) { range_cond_t R(gm_get_range_from_itertype(iter_type), true); Default_DriverMap[it] = R; traverse_expr_for_readset_adding(bfs->get_b_filter(), R_filter); Default_DriverMap.erase(it); } //--------------------------------------------- // forward body //--------------------------------------------- if (bfs->get_fbody() != NULL) { ast_sent* body = bfs->get_fbody(); gm_rwinfo_map& R = get_rwinfo_sets(body)->read_set; // gm_rwinfo_map& W = get_rwinfo_sets(body)->write_set; // gm_rwinfo_map& D = get_rwinfo_sets(body)->reduce_set; // gm_rwinfo_map& M = get_rwinfo_sets(body)->mutate_set; check_rw_conf_error(R, W, RW_CONFLICT, Report); // R-W (warning) check_rw_conf_error(R_filter, W, RW_CONFLICT, Report); // R-W (warning) check_rw_conf_error(W, W, WW_CONFLICT, Report); // W-W (warning) check_rw_conf_error(R, M, RM_CONFLICT, Report); // R-M (warning) check_rw_conf_error(M, M, MM_CONFLICT, Report); // M-M (warning) is_okay = is_okay && check_rw_conf_error(R, D, RD_CONFLICT, Report); // R-D is_okay = is_okay && check_rw_conf_error(R_filter, D, RD_CONFLICT, Report); // R-D is_okay = is_okay && check_rw_conf_error(W, D, WD_CONFLICT, Report); // W-D is_okay = is_okay && check_rw_conf_error(W, M, WM_CONFLICT, Report); // W-M } //--------------------------------------------- // backward body //--------------------------------------------- if (bfs->get_bbody() != NULL) { ast_sent* body = bfs->get_bbody(); gm_rwinfo_map& R = get_rwinfo_sets(body)->read_set; // gm_rwinfo_map& W = get_rwinfo_sets(body)->write_set; // gm_rwinfo_map& D = get_rwinfo_sets(body)->reduce_set; // gm_rwinfo_map& M = get_rwinfo_sets(body)->mutate_set; check_rw_conf_error(R, W, RW_CONFLICT, Report); // R-W (warning) check_rw_conf_error(R_filter, W, RW_CONFLICT, Report); // R-W (warning) check_rw_conf_error(W, W, WW_CONFLICT, Report); // W-W (warning) check_rw_conf_error(R, M, RM_CONFLICT, Report); // R-M (warning) check_rw_conf_error(M, M, MM_CONFLICT, Report); // M-M (warning) is_okay = is_okay && check_rw_conf_error(R, D, RD_CONFLICT, Report); // R-D is_okay = is_okay && check_rw_conf_error(R_filter, D, RD_CONFLICT, Report); // R-D is_okay = is_okay && check_rw_conf_error(W, D, WD_CONFLICT, Report); // W-D is_okay = is_okay && check_rw_conf_error(W, M, WM_CONFLICT, Report); // W-M } } return true; } //========================================================= // called from gm_typecheck.cc //========================================================= void gm_fe_rw_analysis_check2::process(ast_procdef* p) { set_okay(gm_check_parall_conflict_error(p->get_body())); } //================================================================== // For depenendcy detection //================================================================== bool gm_does_intersect(gm_rwinfo_map& S1, gm_rwinfo_map& S2, bool regard_mutate_direction) { gm_rwinfo_map::iterator i; for(i = S1.begin(); i != S1.end(); i++) { gm_symtab_entry* e = i->first; if (S2.find(e) != S2.end()) { if(regard_mutate_direction) { if(i->first->find_info_int("GM_BLTIN_INFO_MUTATING") != S2.find(e)->first->find_info_int("GM_BLTIN_INFO_MUTATING")) { return true; } } else { return true; } } // access through driver while driver is modified /* if (e->getType()->is_nodeedge()) { gm_rwinfo_map::iterator j; for(j=S2.begin();j!=S2.end();j++) { gm_symtab_entry* e2 = i->first; if (!e2->getType()->is_property()) continue; gm_rwinfo_list* l = i->second; gm_rwinfo_list::iterator J; for(J = l->begin(); J!= l->end(); J++) { gm_rwinfo* access_info = *J; if (access_info->driver == e) return true; } } } */ } return false; } bool gm_has_dependency(ast_sent* P, ast_sent *Q) { assert(P->get_nodetype()!=AST_VARDECL); // temporary hack //--------------------------------------------------------- // note: reduced set does not make dependency! (how great!) // [todo] consideration of modified set. //--------------------------------------------------------- gm_rwinfo_sets* P_SET = get_rwinfo_sets(P); gm_rwinfo_sets* Q_SET = get_rwinfo_sets(Q); return gm_has_dependency(P_SET, Q_SET); } bool gm_has_dependency(gm_rwinfo_sets* P_SET, gm_rwinfo_sets* Q_SET) { gm_rwinfo_map& P_R = P_SET->read_set; gm_rwinfo_map& P_W = P_SET->write_set; gm_rwinfo_map& P_M = P_SET->mutate_set; gm_rwinfo_map& Q_R = Q_SET->read_set; gm_rwinfo_map& Q_W = Q_SET->write_set; gm_rwinfo_map& Q_M = Q_SET->mutate_set; // true dependency if (gm_does_intersect(P_W, Q_R, false)) return true; // anti dependency if (gm_does_intersect(P_R, Q_W, false)) return true; // output dep if (gm_does_intersect(P_W, Q_W, false)) return true; // write & muate => dependency if (gm_does_intersect(P_W, Q_M, false)) return true; if (gm_does_intersect(P_M, Q_W, false)) return true; // read & mutate => dependency if (gm_does_intersect(P_R, Q_M, false)) return true; if (gm_does_intersect(P_M, Q_R, false)) return true; // mutate & mutate => it depends on mutate_direction if (gm_does_intersect(P_M, Q_M, true)) return true; return false; } gm_rwinfo_map& gm_get_write_set(ast_sent *S) { assert(S!=NULL); return get_rwinfo_sets(S)->write_set; } bool gm_is_modified(ast_sent* S, gm_symtab_entry *e) { gm_rwinfo_map& W = gm_get_write_set(S); gm_rwinfo_map::iterator i; for(i=W.begin();i!=W.end();i++) { gm_symtab_entry* w_sym = i->first; if (e == w_sym) return true; } return false; } bool gm_is_modified_with_condition(ast_sent* S, gm_symtab_entry *e, gm_rwinfo_query* Q) { assert(Q!=NULL); gm_rwinfo_map& W = gm_get_write_set(S); gm_rwinfo_map::iterator i; for(i=W.begin();i!=W.end();i++) { gm_symtab_entry* w_sym = i->first; if (e != w_sym) continue; // find exact match gm_rwinfo_list* list =i->second; gm_rwinfo_list::iterator j; for(j=list->begin(); j!=list->end();j++) { gm_rwinfo* R = *j; if (Q->_check_range && (Q->range != R->access_range)) {continue;} if (Q->_check_driver && (Q->driver != R->driver)) {continue;} if (Q->_check_always && (Q->always != R->always)) {continue;} if (Q->_check_reduceop && (Q->reduce_op != R->reduce_op)) {continue;} if (Q->_check_bound && (Q->bound != R->bound_symbol)) {continue;} return true; // exact match } return false; // no exact match } return false; } //----------------------------------------------------- // For debug //----------------------------------------------------- void gm_print_rwinfo_set(gm_rwinfo_map& m) { gm_rwinfo_map::iterator it; for(it = m.begin(); it!=m.end();it++) { gm_symtab_entry *e = it->first; gm_rwinfo_list *l = it->second; if (it!=m.begin()) printf(","); if (e->getType()->is_property()) printf("{%s(%s):", e->getId()->get_orgname(), e->getType()->get_target_graph_id()->get_orgname()); else printf("{%s:", e->getId()->get_orgname()); gm_rwinfo_list::iterator ii; for(ii=l->begin(); ii!=l->end();ii++) { if (ii!=l->begin()) printf(","); (*ii)->print(); } printf("}"); } printf("\n"); }
[ "luoceanskold@qq.com" ]
luoceanskold@qq.com
8652b14fab858bfc1ff0cdc46baf62cbef48e98d
c359614fa34bdef661ba35221a6e258b12370b3c
/SpaceEconSim/Production.cpp
8815dec4c2c1d0847b7997b3540db2751e1a2f7c
[]
no_license
mileswhiticker/gam302-assessment-03
8535d55fe43f7968da9a5afe6831ed265e01a9ab
70486fa2e6de21c5d651cbb7e749a13cdbfef73b
refs/heads/master
2021-01-11T19:34:03.735806
2012-05-17T06:24:38
2012-05-17T06:24:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,769
cpp
#include "HabitableObject.hpp" #include "Helpers.hpp" //re production - population directly affects productivity //if current pop greater than 50% of sustainable population, and there's a good labourforce //less than 50%, and there's labour shortages void HabitableObject::ProduceRawMaterials(double a_TimePassed) { double popFactor = 0.5f + m_CurPop / m_MaxPop; //produce some raw materials //amount produced is primarily affected by the development level for(int resType = 1; resType < END_RESOURCE; resType++) { //how much of the resource is produced double producedResources = ExploitableResources[(RESOURCE_TYPE)resType] * m_DevelopmentLevel * popFactor; //modify the avg quality of the pool by the quality of what's being produced //whichever is larger will have a stronger effect on the quality of the final pool double deltaQ = ResourceQuality[(RESOURCE_TYPE)resType] - ExploitableQuality[(RESOURCE_TYPE)resType]; deltaQ /= 2 * (producedResources / ResourcePool[(RESOURCE_TYPE)resType]); //add the produced resources and modify the pooled quality accordingly ResourceQuality[(RESOURCE_TYPE)resType] += (double)deltaQ; ResourcePool[(RESOURCE_TYPE)resType] += (double)producedResources; } } void HabitableObject::ProduceFinishedGoods(double a_TimePassed) { //finished goods to be hardcoded for now, unfortunately :( double popFactor = 0.5f + m_CurPop / m_MaxPop; //---------- metal ore > metal plates ----------// if(ResourcePool[RESOURCE_METALORE] > 0) { //amount produced is primarily affected by the industrial level double producedGoods = min((double)( (double)m_IndustrialLevel * 1000 * popFactor * (a_TimePassed/360.0) ), ResourcePool[RESOURCE_METALORE]); //avg quality between the stored pool and the produced amount double producedQ = ExploitableQuality[RESOURCE_METALORE] + m_IndustrialLevel / 10; double deltaQ = ResourceQuality[RESOURCE_METALPLATES] - producedQ; deltaQ /= 2 * (producedGoods / ResourcePool[RESOURCE_METALPLATES]); //add the produced resources and modify the pooled quality accordingly ResourceQuality[RESOURCE_METALPLATES] += (double)deltaQ; ResourcePool[RESOURCE_METALPLATES] += (double)producedGoods; } //---------- crystal ore > electrical components ----------// if(ResourcePool[RESOURCE_CRYSTALORE] > 0) { //amount produced is primarily affected by the industrial level double producedGoods = min((double)( (double)m_IndustrialLevel * 1000 * popFactor * (a_TimePassed/360.0) ), ResourcePool[RESOURCE_CRYSTALORE]); //avg quality between the stored pool and the produced amount double producedQ = ExploitableQuality[RESOURCE_CRYSTALORE] + m_IndustrialLevel / 10; double deltaQ = ResourceQuality[RESOURCE_COMPONENTS] - producedQ; deltaQ /= 2 * (producedGoods / ResourcePool[RESOURCE_COMPONENTS]); //add the produced resources and modify the pooled quality accordingly ResourceQuality[RESOURCE_COMPONENTS] += (double)deltaQ; ResourcePool[RESOURCE_COMPONENTS] += (double)producedGoods; } //---------- hydrogen > fuel ----------// if(ResourcePool[RESOURCE_CRYSTALORE] > 0) { //amount produced is primarily affected by the industrial level double producedGoods = min((double)( (double)m_IndustrialLevel * 1000 * popFactor * (a_TimePassed/360.0) ), ResourcePool[RESOURCE_HYDROGEN]); //avg quality between the stored pool and the produced amount double producedQ = ExploitableQuality[RESOURCE_HYDROGEN] + m_IndustrialLevel / 10; double deltaQ = ResourceQuality[RESOURCE_FUEL] - producedQ; deltaQ /= 2 * (producedGoods / ResourcePool[RESOURCE_FUEL]); //add the produced resources and modify the pooled quality accordingly ResourceQuality[RESOURCE_FUEL] += (double)deltaQ; ResourcePool[RESOURCE_FUEL] += (double)producedGoods; } }
[ "miles_whiticker@gmail.com" ]
miles_whiticker@gmail.com
18a062a4aa9f06a908a97bfe3ffc7cfff5214a63
795f0d7c1d39504416d6d9ffcd3302e2a7afeb1f
/hw/hw7/hw7I3A50鄭楊叡/raytrace_hint/texture.cpp
5e6b1e1a3e4a4c5b401c8209c85fc62f39e4cc09
[]
no_license
jhengyangrui/Computer-Graphics-of-TTU
d1e44bfec914714ad41595e78930bea2f5f44a12
08fa7adb95a023f2eaf7418cc40fe68c179fe57c
refs/heads/master
2020-08-09T01:02:32.752003
2019-10-09T16:35:39
2019-10-09T16:35:39
213,962,240
0
0
null
null
null
null
UTF-8
C++
false
false
1,162
cpp
#include <gl/glut.h> #define checkImageWidth 64 #define checkImageHeight 64 static GLubyte checkImage[checkImageHeight][checkImageWidth][4]; static GLuint texName; static void makeCheckImage(void) { int i, j, c; for (i = 0; i < checkImageHeight; i++) { for (j = 0; j < checkImageWidth; j++) { c = ((((i&0x8)==0)^((j&0x8))==0))*255; checkImage[i][j][0] = (GLubyte) c; checkImage[i][j][1] = (GLubyte) c; checkImage[i][j][2] = (GLubyte) 255; checkImage[i][j][3] = (GLubyte) 255; } } } void inittex(void) { makeCheckImage(); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glGenTextures(1, &texName); glBindTexture(GL_TEXTURE_2D, texName); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, checkImageWidth, checkImageHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, checkImage); // glEnable (GL_TEXTURE_2D); }
[ "i455763@gmail.com" ]
i455763@gmail.com
7ed2f48905a8274c6e0a4f855cea4c7df0242444
daba6e9665ba4294601180187e1cce6d2bcc7855
/src/fvfieldslice.h
41d1a8010e3351ce138b713317d029499609a5be
[ "Apache-2.0" ]
permissive
szmurlor/fiver
6c9fcfa0106f686ea2d584993338e117c41ee280
083251420eb934d860c99dcf1eb07ae5b8ba7e8c
refs/heads/master
2021-01-10T18:45:32.704247
2015-04-22T10:28:07
2015-04-22T10:28:07
34,375,842
0
0
null
null
null
null
UTF-8
C++
false
false
3,016
h
/*************************************************************************** * Copyright (C) 2006 by Robert Szmurlo * * robert@iem.pw.edu.pl * * * * 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. * ***************************************************************************/ #ifndef FVFIELDSLICE_H #define FVFIELDSLICE_H #include <fvobject.h> #include <fvboxmgr.h> #include <fvrequirefield.h> #include <fvrequiregrid.h> #include <fvinterface.h> #include <fvgridinterface.h> #include <fvfieldinterface.h> class FVBoxMgr; class Grid; class Field; class FVInteractionTranslation; class FVInteractionRotation; /** @author Robert Szmurlo <robert@iem.pw.edu.pl> */ class FVFieldSlice : public FVObject { Q_OBJECT public: FVFieldSlice(FVBoxMgr * manager, int x = 0, int y = 0); ~FVFieldSlice(); void slice(); virtual Grid * getGrid(); virtual Field * getField(); virtual QString classType() { return QString("FVFieldSlice"); } virtual void updateAttributes(); virtual FVInterface * getInterface( QString interfaceName ); virtual QString getName(); public slots: void slotDrawColormap(); void slotDrawVectors(); void slotDrawGrid(); void slotDrawBoundingBox(); void slotRotateManipulator(); void slotTranslateManipulator(); void slotRemoveManipulator(); void slotTranslate( double , double, double ); void slotRotate( double, double, double, double, double, double, double); protected: virtual void setupMenu(); virtual void setupAttributes(); virtual void readAttributes(); private: Grid * grid; Field * field; double P[3]; double N[3]; bool bFirstSlice; FVRequireGrid reqGrid; FVRequireField reqField; FVInteractionTranslation * fit; FVInteractionRotation * fir; FVFieldInterface * fvFieldInterface; FVGridInterface * fvGridInterface; void updateSlice(); virtual bool message( const QList<QString> &argv ); }; #endif
[ "szmurlor@f3fdd263-7064-37e0-4400-c306c3018cec" ]
szmurlor@f3fdd263-7064-37e0-4400-c306c3018cec
406af2a2383c01968237ff3905d9295772cc38c3
835934c3035770bd2fb0cea752bbe5c93b8ddc83
/VTKHeaders/vtkEnSightMasterServerReader.h
9f29a47a7c38d2f0b9e3b0c4aaeb249ab1db02b8
[ "MIT" ]
permissive
jmah/OsiriX-Quad-Buffered-Stereo
d257c9fc1e9be01340fe652f5bf9d63f5c84cde1
096491358a5d4d8a0928dc03d7183ec129720c56
refs/heads/master
2016-09-05T11:08:48.274221
2007-05-02T15:06:45
2007-05-02T15:06:45
3,008,660
2
0
null
null
null
null
UTF-8
C++
false
false
1,859
h
/*========================================================================= Program: Visualization Toolkit Module: $RCSfile: vtkEnSightMasterServerReader.h,v $ Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME vtkEnSightMasterServerReader - reader for compund EnSight files #ifndef __vtkEnSightMasterServerReader_h #define __vtkEnSightMasterServerReader_h #include "vtkGenericEnSightReader.h" class vtkCollection; class VTK_IO_EXPORT vtkEnSightMasterServerReader : public vtkGenericEnSightReader { public: vtkTypeRevisionMacro(vtkEnSightMasterServerReader, vtkGenericEnSightReader); void PrintSelf(ostream& os, vtkIndent indent); static vtkEnSightMasterServerReader* New(); // Description: // Determine which file should be read for piece int DetermineFileName(int piece); // Description: // Get the file name that will be read. vtkGetStringMacro(PieceCaseFileName); // Description: // Set or get the current piece. vtkSetMacro(CurrentPiece, int); vtkGetMacro(CurrentPiece, int); protected: vtkEnSightMasterServerReader(); ~vtkEnSightMasterServerReader(); void Execute(); void ExecuteInformation(); vtkSetStringMacro(PieceCaseFileName); char* PieceCaseFileName; int MaxNumberOfPieces; int CurrentPiece; private: vtkEnSightMasterServerReader(const vtkEnSightMasterServerReader&); // Not implemented. void operator=(const vtkEnSightMasterServerReader&); // Not implemented. }; #endif
[ "me@JonathonMah.com" ]
me@JonathonMah.com
b38eb5f24cd3b72b2c970a27269198921e64d9dc
fa76c737c06cfb150ab65eeaa274656fec5c5fa6
/include/UAV/state/State.hpp
68ae7b7c94514eb955c0a0845b96fcd5fcf3ffec
[]
no_license
UNL-UAV/uav-util
6877f4dc23e2c257d606e6461cf3a2264c8fb98c
176ffd7c9cc50178fddf4f4e7e332fad9b09dd1f
refs/heads/master
2022-04-08T21:12:51.579462
2020-02-19T03:38:58
2020-02-19T03:38:58
235,942,943
0
0
null
null
null
null
UTF-8
C++
false
false
691
hpp
#pragma once #include "pch.hpp" namespace UNL::UAV::State{ class State{ private: const std::string _name; public: State(const std::string& name="base") : _name(name){} inline const std::string getName() const {return this->_name;} virtual ~State() {}; /** * Enabled callback * Used when state has been set to the current object */ virtual void enable() = 0; /** * Running Callback * Used for when in a while(true) loop */ virtual void run() = 0; /** * Handle Callback * Used for when a single call situation */ virtual void handle()=0; /** * Disable Callback * Used when state has been switched off of this object */ virtual void disable() = 0; }; };
[ "tjgibbons10@gmail.com" ]
tjgibbons10@gmail.com
63d5d4ad9bc5b3ff90c4f336645b4ababf6e584f
156de3c57af4c6541b0c1cabfc933fb622aef44f
/RootCoreBin/include/AssociationUtils/IObjectAssociator.h
2c29ef3ef99429de81a6292ef4e7067beed7c26e
[]
no_license
Crashtime/ATLAS-JetCleaning
704937a36e2b7c1d6908745eef1d02923b274447
442f298bfcd9196bef86b978588cce0c430507d7
refs/heads/master
2021-01-21T09:06:30.007753
2016-09-16T21:48:22
2016-09-16T21:48:22
68,410,571
0
1
null
null
null
null
UTF-8
C++
false
false
663
h
#ifndef ASSOCIATIONUTILS_IOBJECTASSOCIATOR_H #define ASSOCIATIONUTILS_IOBJECTASSOCIATOR_H // EDM includes #include "xAODBase/IParticle.h" namespace ORUtils { /// @class IParticleAssociator /// @brief Interface for a class which checks for a match between IParticles. /// @author Steve Farrell <Steven.Farrell@cern.ch> /// class IParticleAssociator { public: /// Virtual destructor virtual ~IParticleAssociator(){}; /// Test association between two IParticles virtual bool objectsMatch(const xAOD::IParticle& p1, const xAOD::IParticle& p2) const = 0; }; } // namespace ORUtils #endif
[ "crashtime@gmail.com" ]
crashtime@gmail.com
1d9baca997f6f9b98c105c2d51e8d8097e51d03c
c09b256a1cb2dafb33a6149b840a96ac7bb5ea92
/ATourOfCPP11/Classes_16/MoreOnAliasesInsideClass_2_1.cpp
788dd18c5f4593e282fba3775fe8c391c7ad9f30
[]
no_license
Masoudas/SampleCPlusPlusCodes
2e7f4b3019cbfe5438f9a2490306ec4752515467
3945e0703f5d49fb4e86fffd3133d5076605c10e
refs/heads/master
2021-07-08T13:09:35.512300
2020-10-07T15:34:23
2020-10-07T15:34:23
196,350,870
0
0
null
null
null
null
UTF-8
C++
false
false
2,391
cpp
/** * So when aliasing, sometimes we have a situation like this, where UsingAliases * is defined before the classes it aliases. This happens for example when we try to define iterator * of a class on top of the class it iterates. In such situations, because the compiler still has * no access to what's happening, we need to define it for him. Say for example B is a class (class B), * it has a scope template (hence typename B::Type) and so forth. * * Note that if we didn't define using Templated_Other = class B; // We must use class, * then we wouldn't be able to say: * using Templated_Other_Template = typename B::Type; // We must use typename * * which is odd. Also, pay attenention to the fact that once we said class B, we didn't need to define * B again, because B and it's alias can be used interchangeably (Templated_Other == class B, so it * doesn't matter which one you use)! However, we could have said: * * using Templated_Other_Template = typename Templated_Other::Type; // We must use typename * */ template <typename T> class UsingAliases{ using Template = T; // This is fine, we don't use typeName using Template_WithTypeName = typename T; // This is fine, we can use typeName using Other = class A; // We must use class. We can't use typename using _INT = int; // Again, fine using Templated_Other = class B; // We must use class using Templated_Other_Template = typename B::Type; // We must use typename using Templated_Other_Template_1 = typename Templated_Other::Type; // We must use typename using Templated_With_class_Declare = class C; // We must use class using Templated_With_class = class C::Type; Other o{}; }; class A{ }; template <typename T> class B{ public: using Type = T; }; template <class T> class C{ public: using Type = T; }; template<typename C> class D{ }; template <typename T> class UsingAliases_1{ using Template = T; // This is fine, we don't use typeName using Template_WithTypeName = T; // This is fine, we can use typeName using Other = A; // We must use class. We can't use typename using _INT = int; // Again, fine using Templated_Other = B; // We must use class using Templated_Other_Template = B::Type; // We must use typename using Templated_With_class = C::Type; Other o{}; };
[ "Masoudas@hotmail.com" ]
Masoudas@hotmail.com
15ff1e484c8b1fb7f2cdb0d6da00f73618ddc196
5140f8c4dc26106646caa86ede14c44d3da5990f
/serveur/Karim/karim_scene.h
63a436cfd22d74bbf636b3123379653383a0e474
[ "Apache-2.0" ]
permissive
FranKie-Ming/car-dashboard
3dc62e067b58c902a7395e50b3ba3f4456f43dfb
ba3a6658887710a91d2d7095c9f2bb8e5f35b314
refs/heads/master
2022-04-24T02:51:28.854076
2019-12-10T11:54:52
2019-12-10T11:54:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
296
h
#ifndef KARIM_SCENE_H #define KARIM_SCENE_H #include <Karim/CadranVitesse.h> #include <Karim/cadrantourparmin.h> #include <Karim/cadranEss.h> #include <Karim/clignot.h> #include "scene_globale.h" class karim_scene : public scene_globale { public: karim_scene(); }; #endif // KARIM_SCENE_H
[ "karimjamal88@gmail.com" ]
karimjamal88@gmail.com
0d732e3226ec56498c4cfa8db85e95f48fa27218
2691dd38c8ba78133dac763adae38478fb330749
/drone_system/flight_dynamics_controller/pid.cpp
78a8acd845a92bb73317b75048b854821e16fff8
[]
no_license
NinjaWazzzabi/project-griffon
06a81bc923cecfc85be844045556aeaa931fe300
35dc676dd40dd4c6114fd2731a75200868250ce0
refs/heads/master
2021-07-22T04:02:29.500267
2018-07-02T09:33:33
2018-07-02T09:33:33
105,430,541
5
0
null
null
null
null
UTF-8
C++
false
false
806
cpp
// // // #include "pid.h" PidClass Pid; PidClass::PidClass() { pConstant = 0; iConstant = 0; dConstant = 0; pValue = 0; iValue = 0; dValue = 0; } PidClass::~PidClass() { } void PidClass::setConstants(float p, float i, float d) { pConstant = p; iConstant = i; dConstant = d; } void PidClass::update(float error, long time) { //Caclulate new P pValue = pConstant * error; //Calculate new I iValue += iConstant * error; //Calculate new D float deltaError = error - lastErrorValue; dValue = dConstant * deltaError; } void PidClass::reset() { pValue= 0; iValue = 0; dValue = 0; } float PidClass::getP() { return pValue; } float PidClass::getI() { return iValue; } float PidClass::getD() { return dValue; } float PidClass::getValue() { return pValue + iValue + dValue; }
[ "amk1997@hotmail.se" ]
amk1997@hotmail.se
f7c9356ff49f645833818fe4608be6f75b74efc7
3332db789e76776e085d5aba23e6ebf81f57b4f6
/Lab7/Lab7/Source.cpp
47073891d0f84905e43a795128c3ffb1b67fef66
[]
no_license
Steven-Efthimiadis/HighPerformanceComputing
78a6aa18d8b3cb3f9b6de05b3c1fb8f3bb28d5e2
17843a0b4e8eba7bc2396e3ba274625d91365035
refs/heads/master
2021-07-12T07:03:48.871671
2017-10-12T13:27:59
2017-10-12T13:27:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,533
cpp
#include <GL/glut.h> class wcPt2D { public: GLfloat x, y; }; void init(void) { /* Set color of display window to white. */ glClearColor(1.0, 1.0, 1.0, 0.0); /* Set parameters for world-coordinate clipping window. */ glMatrixMode(GL_PROJECTION); gluOrtho2D(-100.0, 100.0, -100.0, 100.0); /* Set mode for constructing geometric transformation matrix. */ glMatrixMode(GL_MODELVIEW); } void triangle(wcPt2D *verts) { GLint k; glBegin(GL_TRIANGLES); for (k = 0; k < 3; k++) glVertex2f(verts[k].x, verts[k].y); glEnd(); } void displayFcn(void) { /* Define initial position for triangle. */ wcPt2D verts[3] = { { -50.0, -25.0 },{ 50.0, -25.0 },{ 0.0, 50.0 } }; glClear(GL_COLOR_BUFFER_BIT); // Clear display window. glColor3f(0.0, 0.0, 1.0); // Set fill color to blue. glViewport(0, 0, 300, 300); // Set left viewport. triangle(verts); // Display triangle. /* Rotate triangle and display in right half of display window. */ glColor3f(1.0, 0.0, 0.0); // Set fill color to red. glViewport(300, 0, 300, 300); // Set right viewport. glRotatef(90.0, 0.0, 0.0, 1.0); // Rotate about z axis. triangle(verts); // Display red rotated triangle. glFlush(); } int main(int argc, char ** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowPosition(50, 50); glutInitWindowSize(600, 300); glutCreateWindow("Split-Screen Example"); init(); glutDisplayFunc(displayFcn); glutMainLoop(); }
[ "steven.efthimiadis@gmail.com" ]
steven.efthimiadis@gmail.com
df23c3ad9dc8b363020699bdab3f95d5238dada4
d6d43d0fbe14f03e45ad0310da37d15bbd968884
/Projects/ComplexProj/ComplexTesting/test5/testMain1.cpp
50c98e5c0ad25f4e30c1f81f8685c9d95bc21605
[]
no_license
EmmaSteinman/cs-173
97df6208c55a717650efca955750ea07bf6deb66
ed2274c6b16b21d1afa00e1d953550fb34b66699
refs/heads/master
2020-03-11T23:05:52.417706
2018-09-18T13:29:52
2018-09-18T13:29:52
130,311,942
0
0
null
null
null
null
UTF-8
C++
false
false
10,684
cpp
//=========================================================== // Noah Anderson // March 20, 2017 // testMain1.cpp // This program has non-terminal unit tests for Complex class. //=========================================================== #include <iostream> #include <sstream> #include <string> #include <assert.h> #include "Complex.h" using namespace std; //=========================================================== // test default constructor //=========================================================== void test1 ( void ) { cout << "test1\n"; Complex c1; assert(c1.getReal() == 0 && c1.getImag() == 0); } //=========================================================== // test complex constructor //=========================================================== void test2 ( void ) { cout << "test2\n"; Complex c1(-5,-3); assert(c1.getReal() == -5 && c1.getImag() == -3); } //=========================================================== // test complex constructor //=========================================================== void test3 ( void ) { cout << "test3\n"; Complex c1(5,10); assert(c1.getReal() == 5 && c1.getImag() == 10); } //=========================================================== // test copy constructor //=========================================================== void test4 ( void ) { cout << "test4\n"; Complex c2(5,3); Complex c1(c2); assert(c1.getReal() == 5 && c1.getImag() == 3); } //=========================================================== // test addition operator #1 //=========================================================== void test5 ( void ) { cout << "test5\n"; Complex c1(1,0); Complex c2(0,1); Complex c3 = c1 + c2; assert(c3.getReal() == 1 && c3.getImag() == 1); } //=========================================================== // test addition operator #2 //=========================================================== void test6 ( void ) { cout << "test6\n"; Complex c1(6,8); Complex c2(3,12); Complex c3 = c1 + c2; assert(c3.getReal() == 9 && c3.getImag() == 20); } //=========================================================== // test addition operator #3 // integers //=========================================================== void test7 ( void ) { cout << "test7\n"; Complex c1(4,8); int c2 = (3); Complex c3 = c1 + c2; assert(c3.getReal() == 7 && c3.getImag() == 8); } //=========================================================== // test addition operator #4 // floats //=========================================================== void test8 ( void ) { cout << "test8\n"; Complex c1(8,23); float c2 = (3); Complex c3 = c1 + c2; cout << c3.getReal() << endl; assert(c3.getReal() == 11 && c3.getImag() == 23); } //=========================================================== // test subtraction operator #1 //=========================================================== void test9 ( void ) { cout << "test9\n"; Complex c1(10,10); Complex c2(2,3); Complex c3 = c1 - c2; assert(c3.getReal() == 8 && c3.getImag() == 7); } //=========================================================== // test subtraction operator #2 //=========================================================== void test10 ( void ) { cout << "test10\n"; Complex c1(10,10); Complex c2(10,10); Complex c3 = c1 - c2; assert(c3.getReal() == 0 && c3.getImag() == 0); } //=========================================================== // test subtraction operator #3 //=========================================================== void test11 ( void ) { cout << "test11\n"; Complex c1(3,5); Complex c2(11,13); Complex c3 = c1 - c2; assert(c3.getReal() == -8 && c3.getImag() == -8); } //=========================================================== // test subtraction operator #4 //=========================================================== void test12 ( void ) { cout << "test12\n"; Complex c1(4,7); int c2 = (3); Complex c3 = c1 - c2; assert(c3.getReal() == 1 && c3.getImag() == 7); } //=========================================================== // test subtraction operator #5 //=========================================================== void test13 ( void ) { cout << "test13\n"; Complex c1(3,5); float c2 = (11.0); Complex c3 = c1 - c2; assert(c3.getReal() == (float) -8 && c3.getImag() == 5); } //=========================================================== // test multiplication operator //=========================================================== void test14 ( void ) { cout << "test14\n"; Complex c1(8,2); Complex c2(5,4); Complex c3 = c1 * c2; assert(c3.getReal() == 32 && c3.getImag() == 42); } //=========================================================== // test multiplication operator #2 //=========================================================== void test15 ( void ) { cout << "test15\n"; Complex c1(8,2); Complex c2(0,0); Complex c3 = c1 * c2; assert(c3.getReal() == 0 && c3.getImag() == 0); } //=========================================================== // test multiplication operator #3 // integers //=========================================================== void test16 ( void ) { cout << "test16\n"; Complex c1(6,7); int c2 = (4); Complex c3 = c1 * c2; assert(c3.getReal() == 24 && c3.getImag() == 28); } //=========================================================== // test multiplication operator #4 // floats //=========================================================== void test17 ( void ) { cout << "test17\n"; Complex c1(4,9); float c2 = (1.32); Complex c3 = c1 * c2; cout << c3.getReal() << " " << c3.getImag() << endl; assert(c3.getReal() == 5.28f && c3.getImag() == 11.88f); } //=========================================================== // test division operator #1 //=========================================================== void test18 ( void ) { cout << "test18\n"; Complex c1(4,4); Complex c2(4,4); Complex c3 = c1 / c2; assert(c3.getReal() == 1 && c3.getImag() == 0); } //=========================================================== // test division operator #2 //=========================================================== void test19 ( void ) { cout << "test19\n"; Complex c1(10,10); Complex c2(5,5); Complex c3 = c1 / c2; assert(c3.getReal() == 2 && c3.getImag() == 0); } //=========================================================== // test division operator #3 //=========================================================== void test20 ( void ) { cout << "test20\n"; Complex c1(4,10); int c2 = (2); Complex c3 = c1 / c2; assert(c3.getReal() == 2 && c3.getImag() == 5); } //=========================================================== // test division operator #4 //=========================================================== void test21 ( void ) { cout << "test21\n"; Complex c1(100,100); float c2 = (.25); Complex c3 = c1 / c2; assert(c3.getReal() == 400 && c3.getImag() == 400); } //=========================================================== // exponentiation test //=========================================================== void test22 ( void ) { cout << "test22\n"; Complex c1(2,2); Complex c2 = c1 ^ 2; assert(c2.getReal() == 0 && c2.getImag() == 8); } //=========================================================== // negation test #1 //=========================================================== void test23 ( void ) { cout << "test23\n"; Complex c1(12,12); Complex c2 = -c1; assert(c2.getReal() == -12 && c2.getImag() == -12); } //=========================================================== // negation test #2 //=========================================================== void test24 ( void ) { cout << "test24\n"; Complex c1(-12,-12); Complex c2 = -c1; assert(c2.getReal() == 12 && c2.getImag() == 12); } //=========================================================== // conjugate test #1 //=========================================================== void test25 ( void ) { cout << "test25\n"; Complex c1(2, 4); Complex c2 = ~c1; assert(c2.getReal() == 2 && c2.getImag() == -4); } //=========================================================== // conjugate test #2 //=========================================================== void test26 ( void ) { cout << "test26\n"; Complex c1(-4, -8); Complex c2 = ~c1; assert(c2.getReal() == -4 && c2.getImag() == 8); } //=========================================================== // assignment operator test //=========================================================== void test27 ( void ) { cout << "test27\n"; Complex c1(5, 7); Complex c2 = c1; assert(c2.getReal() == 5 && c2.getImag() == 7); } //=========================================================== // get imaginary test //=========================================================== void test28 ( void ) { cout << "test28\n"; Complex c1(2, 6); assert(c1.getImag() == 6); } //=========================================================== // get real test //=========================================================== void test29 ( void ) { cout << "test29\n"; Complex c1(2, 6); assert(c1.getReal() == 2); } //=========================================================== // set imaginary test //=========================================================== void test30 ( void ) { cout << "test30\n"; Complex c1(0, 3); c1.setImag(5); assert(c1.getImag() == 5); } //=========================================================== // set real test //=========================================================== void test31 ( void ) { cout << "test31\n"; Complex c1(0, 0); c1.setReal(2); assert(c1.getReal() == 2); } //=========================================================== // test == //=========================================================== void test32 ( void ) { cout << "test32\n"; Complex c1(6, 6); Complex c2(6, 6); assert(c1 == c2); } //=========================================================== // test != //=========================================================== void test33 ( void ) { cout << "test33\n"; Complex c1(2, 6); Complex c2(8, 8); assert(c1 != c2); } //=========================================================== // main //=========================================================== int main ( void ) { test1(); test2(); test3(); test4(); test5(); test6(); test7(); test8(); test9(); test10(); test11(); test12(); test13(); test14(); test15(); test16(); test17(); test18(); test19(); test20(); test21(); test22(); test23(); test24(); test25(); test26(); test27(); test28(); test29(); test30(); test31(); test32(); test33(); return 0; } //=========================================================== //===========================================================
[ "steinm_e1@red1.mathsci.denison.edu" ]
steinm_e1@red1.mathsci.denison.edu
0bb9cfa91db097add6c211e88d7f7b7a868cc36f
9102703aba869548fe26414c0757e40ded4e8629
/soj3540.cpp
bf40a806cbbff72fed5e1f6505181aae0967733b
[]
no_license
twocoldz/sojcode
e04e4b92ea4b6bce3bcaeb935efbdc62216d48ca
4ea12c7126e5297d823d620b35dd90585b825c41
refs/heads/master
2021-01-10T19:09:24.909558
2013-04-02T12:00:55
2013-04-02T12:00:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,962
cpp
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #define inf 0x3f3f3f3f using namespace std; int dp[2005][2005]; int bp[2005],sp[2005],bl[2005],sl[2005]; int q[2005],val[2005]; int main() { int n,Lim,W; memset(dp,-inf,sizeof(dp)); while(scanf("%d", &n)==1) { scanf("%d%d",&Lim,&W); int ans = 0; int ap,bp,as,bs; for (int i = 1; i < n + 1; ++i) { scanf("%d%d%d%d", &ap, &bp, &as, &bs); for (int j = 0; j < as + 1; ++j) dp[i][j] = -ap * j; for( int j=as+1;j<= Lim;j++) dp[i][j] = -inf; for (int j = 0; j < Lim + 1; ++j) dp[i][j] = max(dp[i][j], dp[i - 1][j]); int t = i - W - 1; if (t >= 0) { int head=0; int rear=0; for (int j = 0; j < Lim + 1; ++j) { while (head < rear && q[head] < j - as) ++head; while (head < rear && dp[t][j] + j * ap >= val[rear - 1]) --rear; val[rear] = dp[t][j] + j * ap; q[rear++] = j; if (head < rear) dp[i][j] = max(dp[i][j], val[head] - j * ap); } head=rear=0; for (int j = Lim; j > -1; --j) { while (head < rear && q[head] > j + bs) ++head; while (head < rear && dp[t][j] + j * bp >= val[rear - 1]) --rear; val[rear] = dp[t][j] + j * bp; q[rear++] = j; if (head < rear) dp[i][j] = max(dp[i][j], val[head] - j * bp); } } ans = max(dp[i][0], ans); } printf("%d\n", ans); } return 0; }
[ "twocoldz007@gmail.com" ]
twocoldz007@gmail.com
6062cf2a127efff840ec2cdaabdba9f0dd8bd489
adfad536bb190561013448590ddadaf312094039
/plugins/MacSignedAU/VoiceOfTheStarship/VoiceOfTheStarship.cpp
b067c2c550234e23771e0d3247026c0ab759046c
[ "MIT" ]
permissive
themucha/airwindows
ae7c1d5061f6e6b565c7be1b09cae21e5f601915
13bace268f2356e2a037e935c0845d91bfcb79a6
refs/heads/master
2022-02-21T08:46:53.021402
2022-01-30T18:30:35
2022-01-30T18:30:35
204,864,549
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
13,920
cpp
/* * File: VoiceOfTheStarship.cpp * * Version: 1.0 * * Created: 10/12/10 * * Copyright: Copyright © 2010 Airwindows, All Rights Reserved * * Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in * consideration of your agreement to the following terms, and your use, installation, modification * or redistribution of this Apple software constitutes acceptance of these terms. If you do * not agree with these terms, please do not use, install, modify or redistribute this Apple * software. * * In consideration of your agreement to abide by the following terms, and subject to these terms, * Apple grants you a personal, non-exclusive license, under Apple's copyrights in this * original Apple software (the "Apple Software"), to use, reproduce, modify and redistribute the * Apple Software, with or without modifications, in source and/or binary forms; provided that if you * redistribute the Apple Software in its entirety and without modifications, you must retain this * notice and the following text and disclaimers in all such redistributions of the Apple Software. * Neither the name, trademarks, service marks or logos of Apple Computer, Inc. may be used to * endorse or promote products derived from the Apple Software without specific prior written * permission from Apple. Except as expressly stated in this notice, no other rights or * licenses, express or implied, are granted by Apple herein, including but not limited to any * patent rights that may be infringed by your derivative works or by other works in which the * Apple Software may be incorporated. * * The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR * IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE * OR IN COMBINATION WITH YOUR PRODUCTS. * * IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, * REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER * UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN * IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /*============================================================================= VoiceOfTheStarship.h =============================================================================*/ #include "VoiceOfTheStarship.h" //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ AUDIOCOMPONENT_ENTRY(AUBaseFactory, VoiceOfTheStarship) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // VoiceOfTheStarship::VoiceOfTheStarship //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ VoiceOfTheStarship::VoiceOfTheStarship(AudioUnit component) : AUEffectBase(component) { CreateElements(); Globals()->UseIndexedParameters(kNumberOfParameters); SetParameter(kParam_One, kDefaultValue_ParamOne ); SetParameter(kParam_Two, kDefaultValue_ParamTwo ); #if AU_DEBUG_DISPATCHER mDebugDispatcher = new AUDebugDispatcher (this); #endif } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // VoiceOfTheStarship::GetParameterValueStrings //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ComponentResult VoiceOfTheStarship::GetParameterValueStrings(AudioUnitScope inScope, AudioUnitParameterID inParameterID, CFArrayRef * outStrings) { return kAudioUnitErr_InvalidProperty; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // VoiceOfTheStarship::GetParameterInfo //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ComponentResult VoiceOfTheStarship::GetParameterInfo(AudioUnitScope inScope, AudioUnitParameterID inParameterID, AudioUnitParameterInfo &outParameterInfo ) { ComponentResult result = noErr; outParameterInfo.flags = kAudioUnitParameterFlag_IsWritable | kAudioUnitParameterFlag_IsReadable; if (inScope == kAudioUnitScope_Global) { switch(inParameterID) { case kParam_One: AUBase::FillInParameterName (outParameterInfo, kParameterOneName, false); outParameterInfo.unit = kAudioUnitParameterUnit_Generic; outParameterInfo.minValue = 0.0; outParameterInfo.maxValue = 1.0; outParameterInfo.defaultValue = kDefaultValue_ParamOne; break; case kParam_Two: AUBase::FillInParameterName (outParameterInfo, kParameterTwoName, false); outParameterInfo.unit = kAudioUnitParameterUnit_Indexed; outParameterInfo.minValue = 0; outParameterInfo.maxValue = 16; outParameterInfo.defaultValue = kDefaultValue_ParamTwo; break; default: result = kAudioUnitErr_InvalidParameter; break; } } else { result = kAudioUnitErr_InvalidParameter; } return result; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // VoiceOfTheStarship::GetPropertyInfo //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ComponentResult VoiceOfTheStarship::GetPropertyInfo (AudioUnitPropertyID inID, AudioUnitScope inScope, AudioUnitElement inElement, UInt32 & outDataSize, Boolean & outWritable) { return AUEffectBase::GetPropertyInfo (inID, inScope, inElement, outDataSize, outWritable); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // VoiceOfTheStarship::GetProperty //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ComponentResult VoiceOfTheStarship::GetProperty( AudioUnitPropertyID inID, AudioUnitScope inScope, AudioUnitElement inElement, void * outData ) { return AUEffectBase::GetProperty (inID, inScope, inElement, outData); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // VoiceOfTheStarship::Initialize //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ComponentResult VoiceOfTheStarship::Initialize() { ComponentResult result = AUEffectBase::Initialize(); if (result == noErr) Reset(kAudioUnitScope_Global, 0); return result; } #pragma mark ____VoiceOfTheStarshipEffectKernel //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // VoiceOfTheStarship::VoiceOfTheStarshipKernel::Reset() //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ void VoiceOfTheStarship::VoiceOfTheStarshipKernel::Reset() { position = 99999999; quadratic = 0; noiseA = 0.0; noiseB = 0.0; noiseC = 0.0; flip = false; filterflip = false; for(int count = 0; count < 11; count++) {b[count] = 0.0; f[count] = 0.0;} lastAlgorithm = 0; fpNShape = 0.0; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // VoiceOfTheStarship::VoiceOfTheStarshipKernel::Process //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ void VoiceOfTheStarship::VoiceOfTheStarshipKernel::Process( const Float32 *inSourceP, Float32 *inDestP, UInt32 inFramesToProcess, UInt32 inNumChannels, bool &ioSilence ) { //This code will pass-thru the audio data. //This is where you want to process data to produce an effect. UInt32 nSampleFrames = inFramesToProcess; const Float32 *sourceP = inSourceP; Float32 *destP = inDestP; Float64 cutoff = pow((GetParameter( kParam_One )*0.89)+0.1,3); if (cutoff > 1.0) cutoff = 1.0; Float64 invcutoff = 1.0 - cutoff; //this is the lowpass Float64 overallscale = ((1.0-GetParameter( kParam_One ))*9.0)+1.0; Float64 gain = overallscale; if (gain > 1.0) {f[0] = 1.0; gain -= 1.0;} else {f[0] = gain; gain = 0.0;} if (gain > 1.0) {f[1] = 1.0; gain -= 1.0;} else {f[1] = gain; gain = 0.0;} if (gain > 1.0) {f[2] = 1.0; gain -= 1.0;} else {f[2] = gain; gain = 0.0;} if (gain > 1.0) {f[3] = 1.0; gain -= 1.0;} else {f[3] = gain; gain = 0.0;} if (gain > 1.0) {f[4] = 1.0; gain -= 1.0;} else {f[4] = gain; gain = 0.0;} if (gain > 1.0) {f[5] = 1.0; gain -= 1.0;} else {f[5] = gain; gain = 0.0;} if (gain > 1.0) {f[6] = 1.0; gain -= 1.0;} else {f[6] = gain; gain = 0.0;} if (gain > 1.0) {f[7] = 1.0; gain -= 1.0;} else {f[7] = gain; gain = 0.0;} if (gain > 1.0) {f[8] = 1.0; gain -= 1.0;} else {f[8] = gain; gain = 0.0;} if (gain > 1.0) {f[9] = 1.0; gain -= 1.0;} else {f[9] = gain; gain = 0.0;} //this is the moving average with remainders if (overallscale < 1.0) overallscale = 1.0; f[0] /= overallscale; f[1] /= overallscale; f[2] /= overallscale; f[3] /= overallscale; f[4] /= overallscale; f[5] /= overallscale; f[6] /= overallscale; f[7] /= overallscale; f[8] /= overallscale; f[9] /= overallscale; //and now it's neatly scaled, too int lowcut = GetParameter( kParam_Two ); if (lastAlgorithm != lowcut) { noiseA = 0.0; noiseB = 0.0; noiseC = 0.0; for(int count = 0; count < 11; count++) {b[count] = 0.0;} lastAlgorithm = lowcut; } //cuts the noise back to 0 if we are changing algorithms, //because that also changes gains and can make loud pops. //We still get pops, but they'd be even worse int dcut; if (lowcut > 15) {lowcut = 1151; dcut= 11517;} if (lowcut == 15) {lowcut = 113; dcut= 1151;} if (lowcut == 14) {lowcut = 71; dcut= 719;} if (lowcut == 13) {lowcut = 53; dcut= 541;} if (lowcut == 12) {lowcut = 31; dcut= 311;} if (lowcut == 11) {lowcut = 23; dcut= 233;} if (lowcut == 10) {lowcut = 19; dcut= 191;} if (lowcut == 9) {lowcut = 17; dcut= 173;} if (lowcut == 8) {lowcut = 13; dcut= 131;} if (lowcut == 7) {lowcut = 11; dcut= 113;} if (lowcut == 6) {lowcut = 7; dcut= 79;} if (lowcut == 5) {lowcut = 6; dcut= 67;} if (lowcut == 4) {lowcut = 5; dcut= 59;} if (lowcut == 3) {lowcut = 4; dcut= 43;} if (lowcut == 2) {lowcut = 3; dcut= 37;} if (lowcut == 1) {lowcut = 2; dcut= 23;} if (lowcut < 1) {lowcut = 1; dcut= 11;} //this is the mechanism for cutting back subs without filtering Float64 rumbletrim = sqrt(lowcut); //this among other things is just to give volume compensation Float64 inputSample; while (nSampleFrames-- > 0) { inputSample = *sourceP; //we then ignore this! quadratic -= 1; if (quadratic < 0) { position += 1; quadratic = position * position; quadratic = quadratic % 170003; //% is C++ mod operator quadratic *= quadratic; quadratic = quadratic % 17011; //% is C++ mod operator quadratic *= quadratic; quadratic = quadratic % 1709; //% is C++ mod operator quadratic *= quadratic; quadratic = quadratic % dcut; //% is C++ mod operator quadratic *= quadratic; quadratic = quadratic % lowcut; //sets density of the centering force if (noiseA < 0) {flip = true;} else {flip = false;} //every time we come here, we force the random walk to be //toward the center of the waveform. Without this, //it's a pure random walk that will generate DC. } if (flip) noiseA += (rand()/(double)RAND_MAX); else noiseA -= (rand()/(double)RAND_MAX); //here's the guts of the random walk if (filterflip) {noiseB *= invcutoff; noiseB += (noiseA*cutoff); inputSample = noiseB;} else {noiseC *= invcutoff; noiseC += (noiseA*cutoff); inputSample = noiseC;} //now we have the output of the filter as inputSample. //this filter is shallower than a straight IIR: it's interleaved b[9] = b[8]; b[8] = b[7]; b[7] = b[6]; b[6] = b[5]; b[5] = b[4]; b[4] = b[3]; b[3] = b[2]; b[2] = b[1]; b[1] = b[0]; b[0] = inputSample; inputSample *= f[0]; inputSample += (b[1] * f[1]); inputSample += (b[2] * f[2]); inputSample += (b[3] * f[3]); inputSample += (b[4] * f[4]); inputSample += (b[5] * f[5]); inputSample += (b[6] * f[6]); inputSample += (b[7] * f[7]); inputSample += (b[8] * f[8]); inputSample += (b[9] * f[9]); inputSample *= 0.1; inputSample *= invcutoff; inputSample /= rumbletrim; flip = !flip; filterflip = !filterflip; //32 bit dither, made small and tidy. int expon; frexpf((Float32)inputSample, &expon); long double dither = (rand()/(RAND_MAX*7.737125245533627e+25))*pow(2,expon+62); inputSample += (dither-fpNShape); fpNShape = dither; //end 32 bit dither *destP = inputSample; sourceP += inNumChannels; destP += inNumChannels; } }
[ "christopherjohnson@Christophers-MacBook-Pro.local" ]
christopherjohnson@Christophers-MacBook-Pro.local
ccd692a50cd845d9e58841e1923080563eff32d4
36c31b485a5906ab514c964491b8f001a70a67f5
/Codeforces/CF 1300 - 1399/CF1384/CF1384B/CF1384B/CF1384B2.cpp
7cb9f6c7e78ec7b74698ad17938f69afdb6bea29
[]
no_license
SMiles02/CompetitiveProgramming
77926918d5512824900384639955b31b0d0a5841
035040538c7e2102a88a2e3587e1ca984a2d9568
refs/heads/master
2023-08-18T22:14:09.997704
2023-08-13T20:30:42
2023-08-13T20:30:42
277,504,801
25
5
null
2022-11-01T01:34:30
2020-07-06T09:54:44
C++
UTF-8
C++
false
false
1,223
cpp
#include <bits/stdc++.h> #define ll long long #define sz(x) (int)(x).size() using namespace std; void solve() { int n,k,l,c; cin>>n>>k>>l; int a[n+1]; for (int i=0;i<n;++i) cin>>a[i]; for (int i=0;i<n;++i) if (a[i]>l) { cout<<"No\n"; return; } int b[n+1][2]; for (int i=0;i<n;++i) { if (a[i]+k<=l) { b[i][0]=-k; b[i][1]=k; } else { b[i][0]=a[i]-l; b[i][1]=l-a[i]; } } a[n]=l-k; b[n][0]=-k; b[n][1]=k; c=b[0][0]; for (int i=0;i<n;++i) { //cout<< if (a[i+1]+k<=l) c=-k; else if (c+1<=b[i+1][1]) { if (b[i+1][0]<=c+1) ++c; else if (b[i+1][0]<=b[i][1]+1) c=b[i+1][0]; else { cout<<"No\n"; return; } } else { cout<<"No\n"; return; } } cout<<"Yes\n"; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); int n; cin>>n; while (n--) solve(); return 0; }
[ "mahajan.suneet2002@gmail.com" ]
mahajan.suneet2002@gmail.com
6a2257191b58d07993c1b9012bbd0d6885a2da47
84eca9e02b1c9ec983677d99ded0b406126b5668
/C++/1.cpp
ad9e4a8412eca1f29ba6eb905cdc1ed544607dda
[]
no_license
khusrav2000/StudyProgramming
29d9aef5d90be8ec99a0ad2daf497d13ee28d381
ee5357331a9d7fadb15eeb2413cb465bc113758d
refs/heads/master
2023-01-28T12:31:59.249108
2023-01-14T16:34:55
2023-01-14T16:34:55
162,327,571
0
0
null
2022-05-20T21:09:25
2018-12-18T18:05:15
Jupyter Notebook
UTF-8
C++
false
false
53
cpp
#include<iosream> int main(){ std::cout << "1"; }
[ "khusrav2000@mail.ru" ]
khusrav2000@mail.ru
4963a49134d32378f6e1bf09d07749cd946ba547
6efdb26e67706d97da1ae884a88ff95d305bd5cf
/Plugins/AdvancedSessions/AdvancedSessions/Intermediate/Build/Win64/UE4Editor/Development/AdvancedSessions/Module.AdvancedSessions.cpp
b46b4fec060614801de8a2ebf20b67e86fbf35d7
[]
no_license
handwriter/TestForCheckAss
480f59e02aff2cb64389ad6dd0a8fb7c5f8ecbdc
214febd08ec37c06b89cb63180b984d3977445a4
refs/heads/main
2023-07-05T20:00:50.668431
2021-08-17T15:34:12
2021-08-17T15:34:12
397,286,299
0
0
null
null
null
null
UTF-8
C++
false
false
3,190
cpp
// This file is automatically generated at compile-time to include some subset of the user-created cpp files. #include "C:/Users/user/Desktop/TestForCheckAss/Plugins/AdvancedSessions/AdvancedSessions/Source/AdvancedSessions/Private/AdvancedExternalUILibrary.cpp" #include "C:/Users/user/Desktop/TestForCheckAss/Plugins/AdvancedSessions/AdvancedSessions/Source/AdvancedSessions/Private/AdvancedFriendsGameInstance.cpp" #include "C:/Users/user/Desktop/TestForCheckAss/Plugins/AdvancedSessions/AdvancedSessions/Source/AdvancedSessions/Private/AdvancedFriendsInterface.cpp" #include "C:/Users/user/Desktop/TestForCheckAss/Plugins/AdvancedSessions/AdvancedSessions/Source/AdvancedSessions/Private/AdvancedFriendsLibrary.cpp" #include "C:/Users/user/Desktop/TestForCheckAss/Plugins/AdvancedSessions/AdvancedSessions/Source/AdvancedSessions/Private/AdvancedIdentityLibrary.cpp" #include "C:/Users/user/Desktop/TestForCheckAss/Plugins/AdvancedSessions/AdvancedSessions/Source/AdvancedSessions/Private/AdvancedSessions.cpp" #include "C:/Users/user/Desktop/TestForCheckAss/Plugins/AdvancedSessions/AdvancedSessions/Source/AdvancedSessions/Private/AdvancedSessionsLibrary.cpp" #include "C:/Users/user/Desktop/TestForCheckAss/Plugins/AdvancedSessions/AdvancedSessions/Source/AdvancedSessions/Private/AdvancedVoiceLibrary.cpp" #include "C:/Users/user/Desktop/TestForCheckAss/Plugins/AdvancedSessions/AdvancedSessions/Source/AdvancedSessions/Private/CancelFindSessionsCallbackProxy.cpp" #include "C:/Users/user/Desktop/TestForCheckAss/Plugins/AdvancedSessions/AdvancedSessions/Source/AdvancedSessions/Private/CreateSessionCallbackProxyAdvanced.cpp" #include "C:/Users/user/Desktop/TestForCheckAss/Plugins/AdvancedSessions/AdvancedSessions/Source/AdvancedSessions/Private/EndSessionCallbackProxy.cpp" #include "C:/Users/user/Desktop/TestForCheckAss/Plugins/AdvancedSessions/AdvancedSessions/Source/AdvancedSessions/Private/FindFriendSessionCallbackProxy.cpp" #include "C:/Users/user/Desktop/TestForCheckAss/Plugins/AdvancedSessions/AdvancedSessions/Source/AdvancedSessions/Private/FindSessionsCallbackProxyAdvanced.cpp" #include "C:/Users/user/Desktop/TestForCheckAss/Plugins/AdvancedSessions/AdvancedSessions/Source/AdvancedSessions/Private/GetFriendsCallbackProxy.cpp" #include "C:/Users/user/Desktop/TestForCheckAss/Plugins/AdvancedSessions/AdvancedSessions/Source/AdvancedSessions/Private/GetRecentPlayersCallbackProxy.cpp" #include "C:/Users/user/Desktop/TestForCheckAss/Plugins/AdvancedSessions/AdvancedSessions/Source/AdvancedSessions/Private/GetUserPrivilegeCallbackProxy.cpp" #include "C:/Users/user/Desktop/TestForCheckAss/Plugins/AdvancedSessions/AdvancedSessions/Source/AdvancedSessions/Private/LoginUserCallbackProxy.cpp" #include "C:/Users/user/Desktop/TestForCheckAss/Plugins/AdvancedSessions/AdvancedSessions/Source/AdvancedSessions/Private/LogoutUserCallbackProxy.cpp" #include "C:/Users/user/Desktop/TestForCheckAss/Plugins/AdvancedSessions/AdvancedSessions/Source/AdvancedSessions/Private/SendFriendInviteCallbackProxy.cpp" #include "C:/Users/user/Desktop/TestForCheckAss/Plugins/AdvancedSessions/AdvancedSessions/Source/AdvancedSessions/Private/UpdateSessionCallbackProxyAdvanced.cpp"
[ "holtes10@mail.ru" ]
holtes10@mail.ru
f445c0987801fdec4201a6c67e856c75689ba33e
2b7114766edc38fc2dc9de0f1683777a9f0bf2a3
/adept/Stack.cpp
5f053a3bf6b3beaf3a486e6ad7a6b89939cda53e
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
vishalbelsare/Adept-2
72500e3540cd50a1cce583e24488ee4975336f35
f30c77a56ebdc06ded003c80a0ce25a58f1b5135
refs/heads/master
2023-08-04T11:32:21.717586
2023-07-23T10:23:02
2023-07-23T10:23:02
153,926,866
0
0
Apache-2.0
2023-07-23T13:10:00
2018-10-20T16:45:41
C++
UTF-8
C++
false
false
17,862
cpp
/* Stack.cpp -- Stack for storing automatic differentiation information Copyright (C) 2012-2014 University of Reading Copyright (C) 2015 European Centre for Medium-Range Weather Forecasts Author: Robin Hogan <r.j.hogan@ecmwf.int> This file is part of the Adept library. */ #include <iostream> #include <cstring> // For memcpy #ifdef _OPENMP #include <omp.h> #endif #include <adept/Stack.h> namespace adept { using namespace internal; // Global pointers to the current thread, the second of which is // thread safe. The first is only used if ADEPT_STACK_THREAD_UNSAFE // is defined. ADEPT_THREAD_LOCAL Stack* _stack_current_thread = 0; Stack* _stack_current_thread_unsafe = 0; // MEMBER FUNCTIONS OF THE STACK CLASS // Destructor: frees dynamically allocated memory (if any) Stack::~Stack() { // If this is the currently active stack then set to NULL as // "this" is shortly to become invalid if (is_thread_unsafe_) { if (_stack_current_thread_unsafe == this) { _stack_current_thread_unsafe = 0; } } else if (_stack_current_thread == this) { _stack_current_thread = 0; } #ifndef ADEPT_STACK_STORAGE_STL if (gradient_) { delete[] gradient_; } #endif } // Make this stack "active" by copying its "this" pointer to a // global variable; this makes it the stack that aReal objects // subsequently interact with when being created and participating // in mathematical expressions void Stack::activate() { // Check that we don't already have an active stack in this thread if ((is_thread_unsafe_ && _stack_current_thread_unsafe && _stack_current_thread_unsafe != this) || ((!is_thread_unsafe_) && _stack_current_thread && _stack_current_thread != this)) { throw(stack_already_active()); } else { if (!is_thread_unsafe_) { _stack_current_thread = this; } else { _stack_current_thread_unsafe = this; } } } // Set the maximum number of threads to be used in Jacobian // calculations, if possible. A value of 1 indicates that OpenMP // will not be used, while a value of 0 indicates that the number // will match the number of available processors. Returns the // maximum that will be used, which will be 1 if the Adept library // was compiled without OpenMP support. Note that a value of 1 will // disable the use of OpenMP with Adept, so Adept will then use no // OpenMP directives or function calls. Note that if in your program // you use OpenMP with each thread performing automatic // differentiaion with its own independent Adept stack, then // typically only one OpenMP thread is available for each Jacobian // calculation, regardless of whether you call this function. int Stack::set_max_jacobian_threads(int n) { #ifdef _OPENMP if (have_openmp_) { if (n == 1) { openmp_manually_disabled_ = true; return 1; } else if (n < 1) { openmp_manually_disabled_ = false; omp_set_num_threads(omp_get_num_procs()); return omp_get_max_threads(); } else { openmp_manually_disabled_ = false; omp_set_num_threads(n); return omp_get_max_threads(); } } #endif return 1; } // Return maximum number of OpenMP threads to be used in Jacobian // calculation int Stack::max_jacobian_threads() const { #ifdef _OPENMP if (have_openmp_) { if (openmp_manually_disabled_) { return 1; } else { return omp_get_max_threads(); } } #endif return 1; } // Perform to adjoint computation (reverse mode). It is assumed that // some gradients have been assigned already, otherwise the function // returns with an error. void Stack::compute_adjoint() { if (gradients_are_initialized()) { // Loop backwards through the derivative statements for (uIndex ist = n_statements_-1; ist > 0; ist--) { const Statement& statement = statement_[ist]; // We copy the RHS gradient (LHS in the original derivative // statement but swapped in the adjoint equivalent) to "a" in // case it appears on the LHS in any of the following statements Real a = gradient_[statement.index]; gradient_[statement.index] = 0.0; // By only looping if a is non-zero we gain a significant speed-up if (a != 0.0) { // Loop over operations for (uIndex i = statement_[ist-1].end_plus_one; i < statement.end_plus_one; i++) { gradient_[index_[i]] += multiplier_[i]*a; } } } } else { throw(gradients_not_initialized()); } } // Perform tangent linear computation (forward mode). It is assumed // that some gradients have been assigned already, otherwise the // function returns with an error. void Stack::compute_tangent_linear() { if (gradients_are_initialized()) { // Loop forward through the statements for (uIndex ist = 1; ist < n_statements_; ist++) { const Statement& statement = statement_[ist]; // We copy the LHS to "a" in case it appears on the RHS in any // of the following statements Real a = 0.0; for (uIndex i = statement_[ist-1].end_plus_one; i < statement.end_plus_one; i++) { a += multiplier_[i]*gradient_[index_[i]]; } gradient_[statement.index] = a; } } else { throw(gradients_not_initialized()); } } // Register n gradients uIndex Stack::do_register_gradients(const uIndex& n) { n_gradients_registered_ += n; if (!gap_list_.empty()) { uIndex return_val; // Insert in a gap, if there is one big enough for (GapListIterator it = gap_list_.begin(); it != gap_list_.end(); it++) { uIndex len = it->end + 1 - it->start; if (len > n) { // Gap a bit larger than needed: reduce its size return_val = it->start; it->start += n; return return_val; } else if (len == n) { // Gap exactly the size needed: fill it and remove from list return_val = it->start; if (most_recent_gap_ == it) { gap_list_.erase(it); most_recent_gap_ = gap_list_.end(); } else { gap_list_.erase(it); } return return_val; } } } // No suitable gap found; instead add to end of gradient vector i_gradient_ += n; if (i_gradient_ > max_gradient_) { max_gradient_ = i_gradient_; } return i_gradient_ - n; } // If an aReal object is deleted, its gradient_index is // unregistered from the stack. If this is at the top of the stack // then this is easy and is done inline; this is the usual case // since C++ trys to deallocate automatic objects in the reverse // order to that in which they were allocated. If it is not at the // top of the stack then a non-inline function is called to ensure // that the gap list is adjusted correctly. void Stack::unregister_gradient_not_top(const uIndex& gradient_index) { enum { ADDED_AT_BASE, ADDED_AT_TOP, NEW_GAP, NOT_FOUND } status = NOT_FOUND; // First try to find if the unregistered element is at the // start or end of an existing gap if (!gap_list_.empty() && most_recent_gap_ != gap_list_.end()) { // We have a "most recent" gap - check whether the gradient // to be unregistered is here Gap& current_gap = *most_recent_gap_; if (gradient_index == current_gap.start - 1) { current_gap.start--; status = ADDED_AT_BASE; } else if (gradient_index == current_gap.end + 1) { current_gap.end++; status = ADDED_AT_TOP; } // Should we check for erroneous removal from middle of gap? } if (status == NOT_FOUND) { // Search other gaps for (GapListIterator it = gap_list_.begin(); it != gap_list_.end(); it++) { if (gradient_index <= it->end + 1) { // Gradient to unregister is either within the gap // referenced by iterator "it", or it is between "it" // and the previous gap in the list if (gradient_index == it->start - 1) { status = ADDED_AT_BASE; it->start--; most_recent_gap_ = it; } else if (gradient_index == it->end + 1) { status = ADDED_AT_TOP; it->end++; most_recent_gap_ = it; } else { // Insert a new gap of width 1; note that list::insert // inserts *before* the specified location most_recent_gap_ = gap_list_.insert(it, Gap(gradient_index)); status = NEW_GAP; } break; } } if (status == NOT_FOUND) { gap_list_.push_back(Gap(gradient_index)); most_recent_gap_ = gap_list_.end(); most_recent_gap_--; } } // Finally check if gaps have merged if (status == ADDED_AT_BASE && most_recent_gap_ != gap_list_.begin()) { // Check whether the gap has merged with the next one GapListIterator it = most_recent_gap_; it--; if (it->end == most_recent_gap_->start - 1) { // Merge two gaps most_recent_gap_->start = it->start; gap_list_.erase(it); } } else if (status == ADDED_AT_TOP) { GapListIterator it = most_recent_gap_; it++; if (it != gap_list_.end() && it->start == most_recent_gap_->end + 1) { // Merge two gaps most_recent_gap_->end = it->end; gap_list_.erase(it); } } } // Unregister n gradients starting at gradient_index void Stack::unregister_gradients(const uIndex& gradient_index, const uIndex& n) { n_gradients_registered_ -= n; if (gradient_index+n == i_gradient_) { // Gradient to be unregistered is at the top of the stack i_gradient_ -= n; if (!gap_list_.empty()) { Gap& last_gap = gap_list_.back(); if (i_gradient_ == last_gap.end+1) { // We have unregistered the elements between the "gap" of // unregistered element and the top of the stack, so can set // the variables indicating the presence of the gap to zero i_gradient_ = last_gap.start; GapListIterator it = gap_list_.end(); it--; if (most_recent_gap_ == it) { most_recent_gap_ = gap_list_.end(); } gap_list_.pop_back(); } } } else { // Gradients to be unregistered not at top of stack. enum { ADDED_AT_BASE, ADDED_AT_TOP, NEW_GAP, NOT_FOUND } status = NOT_FOUND; // First try to find if the unregistered element is at the start // or end of an existing gap if (!gap_list_.empty() && most_recent_gap_ != gap_list_.end()) { // We have a "most recent" gap - check whether the gradient // to be unregistered is here Gap& current_gap = *most_recent_gap_; if (gradient_index == current_gap.start - n) { current_gap.start -= n; status = ADDED_AT_BASE; } else if (gradient_index == current_gap.end + 1) { current_gap.end += n; status = ADDED_AT_TOP; } /* else if (gradient_index > current_gap.start - n && gradient_index < current_gap.end + 1) { std::cout << "** Attempt to find " << gradient_index << " in gaps "; print_gaps(); std::cout << "\n"; throw invalid_operation("Gap list corruption"); } */ // Should we check for erroneous removal from middle of gap? } if (status == NOT_FOUND) { // Search other gaps for (GapListIterator it = gap_list_.begin(); it != gap_list_.end(); it++) { if (gradient_index <= it->end + 1) { // Gradient to unregister is either within the gap // referenced by iterator "it", or it is between "it" and // the previous gap in the list if (gradient_index == it->start - n) { status = ADDED_AT_BASE; it->start -= n; most_recent_gap_ = it; } else if (gradient_index == it->end + 1) { status = ADDED_AT_TOP; it->end += n; most_recent_gap_ = it; } /* else if (gradient_index > it->start - n) { std::cout << "*** Attempt to find " << gradient_index << " in gaps "; print_gaps(); std::cout << "\n"; throw invalid_operation("Gap list corruption"); } */ else { // Insert a new gap; note that list::insert inserts // *before* the specified location most_recent_gap_ = gap_list_.insert(it, Gap(gradient_index, gradient_index+n-1)); status = NEW_GAP; } break; } } if (status == NOT_FOUND) { gap_list_.push_back(Gap(gradient_index, gradient_index+n-1)); most_recent_gap_ = gap_list_.end(); most_recent_gap_--; } } // Finally check if gaps have merged if (status == ADDED_AT_BASE && most_recent_gap_ != gap_list_.begin()) { // Check whether the gap has merged with the next one GapListIterator it = most_recent_gap_; it--; if (it->end == most_recent_gap_->start - 1) { // Merge two gaps most_recent_gap_->start = it->start; gap_list_.erase(it); } } else if (status == ADDED_AT_TOP) { GapListIterator it = most_recent_gap_; it++; if (it != gap_list_.end() && it->start == most_recent_gap_->end + 1) { // Merge two gaps most_recent_gap_->end = it->end; gap_list_.erase(it); } } } } // Print each derivative statement to the specified stream (standard // output if omitted) void Stack::print_statements(std::ostream& os) const { for (uIndex ist = 1; ist < n_statements_; ist++) { const Statement& statement = statement_[ist]; os << ist << ": d[" << statement.index << "] = "; if (statement_[ist-1].end_plus_one == statement_[ist].end_plus_one) { os << "0\n"; } else { for (uIndex i = statement_[ist-1].end_plus_one; i < statement.end_plus_one; i++) { os << " + " << multiplier_[i] << "*d[" << index_[i] << "]"; } os << "\n"; } } } // Print the current gradient list to the specified stream (standard // output if omitted) bool Stack::print_gradients(std::ostream& os) const { if (gradients_are_initialized()) { for (uIndex i = 0; i < max_gradient_; i++) { if (i%10 == 0) { if (i != 0) { os << "\n"; } os << i << ":"; } os << " " << gradient_[i]; } os << "\n"; return true; } else { os << "No gradients initialized\n"; return false; } } // Print the list of gaps in the gradient list to the specified // stream (standard output if omitted) void Stack::print_gaps(std::ostream& os) const { for (std::list<Gap>::const_iterator it = gap_list_.begin(); it != gap_list_.end(); it++) { os << it->start << "-" << it->end << " "; } } #ifndef ADEPT_STACK_STORAGE_STL // Initialize the vector of gradients ready for the adjoint // calculation void Stack::initialize_gradients() { if (max_gradient_ > 0) { if (n_allocated_gradients_ < max_gradient_) { if (gradient_) { delete[] gradient_; } gradient_ = new Real[max_gradient_]; n_allocated_gradients_ = max_gradient_; } for (uIndex i = 0; i < max_gradient_; i++) { gradient_[i] = 0.0; } } gradients_initialized_ = true; } #else void Stack::initialize_gradients() { gradient_.resize(max_gradient_+10, 0.0); gradients_initialized_ = true; } #endif // Report information about the stack to the specified stream, or // standard output if omitted; note that this is synonymous with // sending the Stack object to a stream using the "<<" operator. void Stack::print_status(std::ostream& os) const { os << "Automatic Differentiation Stack (address " << this << "):\n"; if ((!is_thread_unsafe_) && _stack_current_thread == this) { os << " Currently attached - thread safe\n"; } else if (is_thread_unsafe_ && _stack_current_thread_unsafe == this) { os << " Currently attached - thread unsafe\n"; } else { os << " Currently detached\n"; } os << " Recording status:\n"; if (is_recording_) { os << " Recording is ON\n"; } else { os << " Recording is PAUSED\n"; } // Account for the null statement at the start by subtracting one os << " " << n_statements()-1 << " statements (" << n_allocated_statements() << " allocated)"; os << " and " << n_operations() << " operations (" << n_allocated_operations() << " allocated)\n"; os << " " << n_gradients_registered() << " gradients currently registered "; os << "and a total of " << max_gradients() << " needed (current index " << i_gradient() << ")\n"; if (gap_list_.empty()) { os << " Gradient list has no gaps\n"; } else { os << " Gradient list has " << gap_list_.size() << " gaps ("; print_gaps(os); os << ")\n"; } os << " Computation status:\n"; if (gradients_are_initialized()) { os << " " << max_gradients() << " gradients assigned (" << n_allocated_gradients() << " allocated)\n"; } else { os << " 0 gradients assigned (" << n_allocated_gradients() << " allocated)\n"; } os << " Jacobian size: " << n_dependents() << "x" << n_independents() << "\n"; if (n_dependents() <= 10 && n_independents() <= 10) { os << " Independent indices:"; for (std::size_t i = 0; i < independent_index_.size(); ++i) { os << " " << independent_index_[i]; } os << "\n Dependent indices: "; for (std::size_t i = 0; i < dependent_index_.size(); ++i) { os << " " << dependent_index_[i]; } os << "\n"; } #ifdef _OPENMP if (have_openmp_) { if (openmp_manually_disabled_) { os << " Parallel Jacobian calculation manually disabled\n"; } else { os << " Parallel Jacobian calculation can use up to " << omp_get_max_threads() << " threads\n"; os << " Each thread treats " << ADEPT_MULTIPASS_SIZE << " (in)dependent variables\n"; } } else { #endif os << " Parallel Jacobian calculation not available\n"; #ifdef _OPENMP } #endif } } // End namespace adept
[ "r.j.hogan@ecmwf.int" ]
r.j.hogan@ecmwf.int
d9ea615adc7f2a017a740e3d20ebf11fb05cea4e
35ef3359cb99fa0246e58623cd537484ac38c104
/mainWin.h
c7235a253ad51ec529409ad8732f33bafb690115
[]
no_license
yml210/MolInt_Cpp
775b92436b9fc94f95a732bb9c51682ad5797978
d5f798871d47efe3c5f5533afbbc5db6eaa76468
refs/heads/master
2021-01-13T09:51:24.432270
2011-10-17T03:37:15
2011-10-17T03:37:15
2,589,437
0
0
null
null
null
null
UTF-8
C++
false
false
775
h
//mainWin.h #define QT3_SUPPORT #include <Qt/qapplication.h> #include <QtGui/qpushbutton.h> //#include <QtGui/qpopupmenu.h> #include <QtGui/qmenu.h> #include <QtGui/qlayout.h> #include <QtGui/qfiledialog.h> #include <QtGui/qmessagebox.h> #include <QtGui/qwidget.h> #include <QtGui/qmenubar.h> #include "canvas.h" #include "dialog1.h" #include "dialog2.h" #include "dialog3.h" class MainWin: public QWidget { Q_OBJECT public: MainWin(QWidget* parent=0,char* name=0); public slots: void newCluster(); void openCluster(); void moveAtom(); void changeBondLength(); void changeAngle1(); private: void addEditMenu(); void addViewMenu(); Canvas* canvas; Dialog1* dialog; Dialog2* dialog2; Dialog3* dialog3; QMenuBar* mBar; };
[ "yml@berkeley.edu" ]
yml@berkeley.edu
d29f1c3c335f9441fe0ee4e7fc7e4886c3d4a6b0
a4870586b21bed55eabaadc73c3207397e5792e3
/FakeEngine/src/Engine/Core/DataTypes/FakeArray.h
940dcd7318225f52c37e4b77d9d83a6e28455438
[ "Apache-2.0" ]
permissive
FlareCoding/FakeEngineV2
09ed1992a58772de0d5854fc5a497cc1177d4798
34d9cbcae4786400d102303ae4b2ec5248b9b39a
refs/heads/master
2022-11-29T22:08:15.102267
2020-08-05T17:41:08
2020-08-05T17:41:08
285,105,174
0
0
null
2020-08-04T21:33:56
2020-08-04T21:33:56
null
UTF-8
C++
false
false
800
h
#pragma once #include "FakePch.h" template<typename T, size_t T_Size> class FakeArray { private: T Data[T_Size]; public: FakeArray() { } void ZeroInitialize() { FAKE_ASSERT(Data, "No Data set!"); memset(Data, 0, T_Size * sizeof(T)); } void Print() { for (size_t i = 0; i < T_Size; ++i) std::cout << data[i] << std::endl; } constexpr int Size() const { return T_Size; } T *GetData() { return Data; } const T *GetData() const { return Data; } T &operator[](uint32_t i) { FAKE_ASSERT(i < T_Size, "Array index out of bounds!"); return Data[i]; } const T &operator[](uint32_t i) const { FAKE_ASSERT(i < T_Size, "Array index out of bounds!"); return Data[i]; } };
[ "Can.Karka@Web.de" ]
Can.Karka@Web.de
3bcdb83c1ed4907a2e5d1617b7a2e5b91bd2a211
1eb894c9842bbae917f5a8c35784e34abfa35331
/Assignment-5(Trees)/serializeDeserialize.cpp
f9011efe298e8204e610c5ca8778e975ee8f04e2
[]
no_license
witcher-shailesh/CP_CipherSchools
b4dc6b6dd2d1e93d3bddd64779af09dc93ae86bb
96242b60b90d642fff306dedbc5d69b5ec739c14
refs/heads/main
2023-03-08T12:15:29.549532
2021-02-22T15:01:44
2021-02-22T15:01:44
338,615,327
0
0
null
null
null
null
UTF-8
C++
false
false
938
cpp
#include<bits/stdc++.h> using namespace std; class TreeNode{ public: int data; TreeNode *left; TreeNode *right; TreeNode(){ data = 0; left = NULL; right = NULL; } TreeNode(int data){ this.data = data; this.left = NULL; this.right = NULL; } }; string serialize(TreeNode* root) { if (!root) return "#"; return to_string(root->val) + " " + serialize(root->left) + " " + serialize(root->right); } TreeNode* deserialize(string data) { istringstream iss (data); return deserialized(iss); } TreeNode* deserialized(istringstream& iss) { string token; getline(iss, token, ' '); if(token == "#") return NULL; TreeNode* newNode = new TreeNode(std::stoi(token)); newNode->left = deserialized(iss); newNode->right = deserialized(iss); return newNode; }
[ "shailesh.techcourse@gmail.com" ]
shailesh.techcourse@gmail.com
ee047c723aaa4ba4db30996f8dd0be5b0d79ac76
e7473a998bb761b8e653abb94ae593bb0c0086e5
/android/android_9/frameworks/ml/nn/runtime/test/generated/models/space_to_depth_float_3_relaxed.model.cpp
0e37f1e3ac09cb06df76ae8945390208a9f2fca6
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
yakuizhao/intel-vaapi-driver
27353904d4483d80d961b90e0cd9864168dd245f
b2bb0383352694941826543a171b557efac2219b
refs/heads/master
2021-01-22T02:44:19.263890
2020-12-01T02:25:48
2020-12-01T02:26:50
81,062,952
0
0
NOASSERTION
2019-02-22T03:28:11
2017-02-06T08:05:28
C
UTF-8
C++
false
false
962
cpp
// Generated file (from: space_to_depth_float_3_relaxed.mod.py). Do not edit void CreateModel(Model *model) { OperandType type1(Type::INT32, {}); OperandType type2(Type::TENSOR_FLOAT32, {1, 2, 2, 8}); OperandType type0(Type::TENSOR_FLOAT32, {1, 4, 4, 2}); // Phase 1, operands auto input = model->addOperand(&type0); auto block_size = model->addOperand(&type1); auto output = model->addOperand(&type2); // Phase 2, operations static int32_t block_size_init[] = {2}; model->setOperandValue(block_size, block_size_init, sizeof(int32_t) * 1); model->addOperation(ANEURALNETWORKS_SPACE_TO_DEPTH, {input, block_size}, {output}); // Phase 3, inputs and outputs model->identifyInputsAndOutputs( {input}, {output}); // Phase 4: set relaxed execution model->relaxComputationFloat32toFloat16(true); assert(model->isValid()); } bool is_ignored(int i) { static std::set<int> ignore = {}; return ignore.find(i) != ignore.end(); }
[ "yakuizhao@tencent.com" ]
yakuizhao@tencent.com
6662db97a16ad9cc1ce9a79398912f5760f567b8
8130c4b1893d4a23260a5898b415b111868c0c2c
/STL Examples/CalcTest/CalcTest/main.cpp
d3b34f519cad94ce53a27b63fbd5d8620cf4e210
[]
no_license
TRBlount/SheevanPhitars
2eb08b968a523e1c5e193b2c3fc8d5380796a01c
057fb30bb6c7354a722aea020ac0b0a04605f34e
refs/heads/master
2021-05-30T11:29:21.914037
2016-01-31T07:14:51
2016-01-31T07:15:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,201
cpp
#include <iostream> #include <map> #include <string> #include <cmath> #include <algorithm> #include <cstdarg> #include <cstring> #include <limits.h> #include "CalcTest.h" inline bool ch_is_sign(char ch) { return ((ch == '-') || (ch == '+')); } inline bool ch_is_numeral(char ch) { return ((ch >= '0') && (ch <= '9')); } inline bool ch_is_decimal(char ch) { return (ch == '.'); } std::map<int,ExpTerm> FuncExpDiff(std::map<int,ExpTerm> nthTerms) { std::map<int,ExpTerm> diffTerms; for (auto it = nthTerms.begin(); it != nthTerms.end(); it++) { int Key = it->first; ExpTerm currTerm = it->second; currTerm.coefficient *= currTerm.exponent; currTerm.exponent -= 1.0f; if (currTerm.exponent < 0.0f) { currTerm.exponent = 0.0f; } diffTerms[Key] = currTerm; } return diffTerms; } void main() { int nTerms; std::map<int, ExpTerm> inTerms; std::cout << "Note: If a term has no exponent, enter 1 if it has an 'x' or enter 0 if it is a constant." << std::endl; std::cout << "For example: x + 1 has two terms, the first term has a coefficient of 1 and an exponent of 1, the second term has a coefficient of 1 and exponent of 0." << std::endl; std::cout << "Please enter the number of terms your function contains: " << std::endl; std::cin >> nTerms; for (int i = 1; i <= nTerms; i++) { std::cout << "Please enter the coefficient of term " << i << " of your function: " << std::endl; std::cin >> inTerms[i].coefficient; std::cout << std::endl; std::cout << "Please enter the exponent of term " << i << " of your function: " << std::endl; std::cin >> inTerms[i].exponent; std::cout << std::endl; } std::map<int, ExpTerm> outTerms = FuncExpDiff(inTerms); std::cout << "The derivative of your function is: " << std::endl; for (int i = 1; i <= nTerms; i++) { if (outTerms[i].coefficient != 0.0f) { if (i != 1) { std::cout << " + "; } if (outTerms[i].exponent == 0.0f) { std::cout << outTerms[i].coefficient; } else if (outTerms[i].exponent == 1.0f) { std::cout << outTerms[i].coefficient << "x"; } else { std::cout << outTerms[i].coefficient << "x^" << outTerms[i].exponent; } } else { std::cout << std::endl; } } }
[ "tylerrblount@gmail.com" ]
tylerrblount@gmail.com
0153578639b082c3fec0650897df9ca12e4369b9
ea8aa77c861afdbf2c9b3268ba1ae3f9bfd152fe
/hihoch29D.cpp
754d86eff4c3c4caf47564e754add72bd6aa7b7b
[]
no_license
lonelam/SolveSet
987a01e72d92f975703f715e6a7588d097f7f2e5
66a9a984d7270ff03b9c2dfa229d99b922907d57
refs/heads/master
2021-04-03T02:02:03.108669
2018-07-21T14:25:53
2018-07-21T14:25:53
62,948,874
9
3
null
null
null
null
UTF-8
C++
false
false
545
cpp
#include <cstdio> #include <set> using namespace std; const int maxn = 5e5 + 10; int a[maxn]; typedef long long ll; multiset<int> mul; int main() { int n; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf ("%d", a + i); } ll ans = 0; for (int i = 0; i < n; i++) { if (mul.empty() || *mul.begin() >= a[i]) { mul.insert(a[i]); } else { ans += a[i] - *mul.begin(); mul.erase(mul.begin()); mul.insert(a[i]); mul.insert(a[i]); } } printf("%lld\n", ans); return 0; }
[ "laizenan@gmail.com" ]
laizenan@gmail.com
6962be7678df814d7ef1f1ae8e42903c73c8d2c1
3acb9d586aea3eeae077a6951f9090fe19979f63
/engine/ui/src/shiroi/ui/rect.cpp
ba58f580982dc7b3a47faf6ff06a6e4577031c5f
[]
no_license
BrunoSilvaFreire/ShiroiEngine
75f9ad4381140a40ea12e0a873e47db25fc65cca
42df88d56772de7e8afca291025b2b7bea731899
refs/heads/master
2020-03-29T06:59:33.783210
2019-02-01T20:30:36
2019-02-01T20:30:36
149,648,838
0
0
null
null
null
null
UTF-8
C++
false
false
55
cpp
// // Created by Bruno Silva Freire on 13/01/2019. //
[ "brunorbsf@gmail.com" ]
brunorbsf@gmail.com
26c4a75520ee35e3cf6a266fcd5196caf8faa145
246b30bbf366cdc56fafcb1023dccfbf7deb27a9
/node.cpp
6269a26b7b49a4f4eb9b2d0c519201e92727d625
[]
no_license
kevinho6/Data-Communications-Lab-3
72edc5feaa332fbc3c18aea13bcfd6c1dcd50174
1dff079908fe5e8dc8c73fe9f2efb9fbbccdb186
refs/heads/master
2020-04-05T18:36:05.641829
2018-11-12T05:20:06
2018-11-12T05:20:06
157,105,338
0
0
null
null
null
null
UTF-8
C++
false
false
16,206
cpp
#include <stdio.h> #include <string.h> #include <sys/socket.h> #include <sys/types.h> #include <arpa/inet.h> #include <netinet/ip.h> #include <unistd.h> #include <stdlib.h> #include <stdint.h> #include <fcntl.h> #include <time.h> #include <fstream> #include <limits> #include "ipsum.h" using namespace std; #define MAX_NUM_ROUTING_ENTRIES 64 #define LOCALHOST "127.0.0.1" #define IP_ADDR_LEN 16 #define MAX_TTL 16 #define MAX_MTU_SIZE 1400 #define MAX_RECV_SIZE (1024 * 64) // 64 KB #define TEST_PROTOCOL_VAL 0 #define RIP_PROTOCOL_VAL 200 struct iphdr { #if __BYTE_ORDER == __LITTLE_ENDIAN unsigned int ihl : 4; unsigned int version : 4; #elif __BYTE_ORDER == __BIG_ENDIAN unsigned int version : 4; unsigned int ihl : 4; #else #error "Please fix <bits/endian.h>" #endif u_int8_t tos; u_int16_t tot_len; u_int16_t id; u_int16_t frag_off; u_int8_t ttl; u_int8_t protocol; u_int16_t check; u_int32_t saddr; u_int32_t daddr; }; typedef struct interface { int interface_id; char my_ip[IP_ADDR_LEN]; uint16_t my_port; char my_vip[IP_ADDR_LEN]; char other_vip[IP_ADDR_LEN]; int mtu_size; bool is_up; int send_socket; } interface_t; typedef struct forwarding_entry { char entry_src_addr[IP_ADDR_LEN]; char dest_addr[IP_ADDR_LEN]; int interface_id; int cost; time_t last_updated; } forwarding_entry_t; typedef struct forwarding_table { int num_entries; forwarding_entry_t forwarding_entries[MAX_NUM_ROUTING_ENTRIES]; } forwarding_table_t; typedef struct ifconfig_table { int num_entries; interface_t ifconfig_entries[MAX_NUM_ROUTING_ENTRIES]; } ifconfig_table_t; typedef struct rip_packet { uint16_t command; uint16_t num_entries; struct { uint32_t cost; uint32_t address; } entries[MAX_NUM_ROUTING_ENTRIES]; } rip_packet_t; typedef struct metadata { uint32_t port; char my_ip[IP_ADDR_LEN]; } metadata_t; forwarding_table_t FORWARDING_TABLE; ifconfig_table_t IFCONFIG_TABLE; metadata_t SELF; void initialize_interface(interface_t *interface) { if ((interface->send_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) { perror("Failed to start send socket"); exit(1); } } // Debugging utility void print_mem(char const *vp, size_t n) { char const *p = vp; for (size_t i = 0; i < n; i++) printf("%02x\n", p[i]); putchar('\n'); }; void send_packet_with_interface(interface_t *interface, char *data, int data_size, struct iphdr *ip_header) { // TODO --- 1 // contruct the socket and send it through socket // sendto function // https://linux.die.net/man/2/sendto if (!interface->is_up) return; struct sockaddr_in dest_addr; dest_addr.sin_addr.s_addr = inet_addr(interface->my_ip); dest_addr.sin_family = AF_INET; dest_addr.sin_port = htons(interface->my_port); ip_header->tot_len = ip_header->ihl * 4 + data_size; ip_header->check = ip_sum((char *)ip_header, ip_header->ihl * 4); char full_packet[ip_header->tot_len]; memcpy(full_packet, ip_header, ip_header->ihl * 4); memcpy(full_packet + ip_header->ihl * 4, data, data_size); if (sendto(interface->send_socket, full_packet, ip_header->tot_len, 0, (struct sockaddr *)&dest_addr, sizeof(dest_addr)) < 0) { perror("Failed to send packet"); } } interface_t *get_interface_by_id(int id) { interface_t *temp = IFCONFIG_TABLE.ifconfig_entries; int i; for (i = 0; i < IFCONFIG_TABLE.num_entries; i++) { if (IFCONFIG_TABLE.ifconfig_entries[i].interface_id == id) { return (temp + i); } } return NULL; } interface_t *get_interface_by_dest_addr(char *dest_addr) { interface_t *temp = IFCONFIG_TABLE.ifconfig_entries; int i; for (i = 0; i < IFCONFIG_TABLE.num_entries; i++) { if (strcmp(IFCONFIG_TABLE.ifconfig_entries[i].other_vip, dest_addr) == 0) { return (temp + i); } } return NULL; } forwarding_entry_t *get_forwarding_entry_by_dest_addr(char *dest_addr) { // TODO --- 2 // Search the forwarding table to find the next hop / best route for (int i = 0; i < FORWARDING_TABLE.num_entries; i++) { if (strcmp(FORWARDING_TABLE.forwarding_entries[i].dest_addr, dest_addr) == 0) { forwarding_entry_t *f_entry = &FORWARDING_TABLE.forwarding_entries[i]; return f_entry; } } return NULL; } /** * Creates an ifconfig entry and puts it into the ifconfig table **/ void create_ifconfig_entry(int ID, uint16_t port, char *myIP, char *myVIP, char *otherVIP) { interface_t entry; entry.interface_id = ID; entry.my_port = port; strcpy(entry.my_ip, myIP); strcpy(entry.my_vip, myVIP); strcpy(entry.other_vip, otherVIP); entry.is_up = true; entry.mtu_size = MAX_MTU_SIZE; initialize_interface(&entry); IFCONFIG_TABLE.ifconfig_entries[ID] = entry; IFCONFIG_TABLE.num_entries++; } void update_forwarding_entry(char *src_addr, char *next_addr, char *dest_addr, int cost) { // TODO --- 3 // Whenever needed (received an update from other nodes or link break), update the forwarding table // find the forwarding entry that matches the destination address and update the cost for (int i = 0; i < FORWARDING_TABLE.num_entries; i++) { if (strcmp(FORWARDING_TABLE.forwarding_entries[i].entry_src_addr, src_addr) == 0 && strcmp(FORWARDING_TABLE.forwarding_entries[i].dest_addr, dest_addr) == 0) { FORWARDING_TABLE.forwarding_entries[i].cost = cost; break; } } } void build_tables(FILE *fp) { // TODO --- 4 // Build the forwarding table char line1[256]; char line2[256]; fgets(line1, sizeof(line1), fp); fgets(line2, sizeof(line2), fp); char *thisNodeSocket = strtok(line1, "\n"); char *remoteNodeSocket = strtok(line2, " "); char *thisInterfaceVIP = strtok(NULL, " "); char *remoteInterfaceVIP = strtok(NULL, " "); int cost = atoi(strtok(NULL, " ")); char *myIP = strtok(thisNodeSocket, ":"); uint16_t myPort = atoi(strtok(NULL, "")); char *remoteIP = strtok(remoteNodeSocket, ":"); uint16_t remotePort = atoi(strtok(NULL, "")); char localhost[10] = "127.0.0.1"; if (strcmp(myIP, "localhost") == 0) { myIP = localhost; } if (strcmp(remoteIP, "localhost") == 0) { remoteIP = localhost; } forwarding_entry_t newForwardingEntry; // strcpy(newForwardingEntry.entry_src_addr, myIP); strcpy(newForwardingEntry.entry_src_addr, thisInterfaceVIP); // strcpy(newForwardingEntry.dest_addr, remoteIP); strcpy(newForwardingEntry.dest_addr, remoteInterfaceVIP); newForwardingEntry.interface_id = IFCONFIG_TABLE.num_entries; newForwardingEntry.cost = cost; newForwardingEntry.last_updated = time(NULL); FORWARDING_TABLE.forwarding_entries[FORWARDING_TABLE.num_entries] = newForwardingEntry; FORWARDING_TABLE.num_entries++; // Build the interface table create_ifconfig_entry(IFCONFIG_TABLE.num_entries, myPort, myIP, thisInterfaceVIP, remoteInterfaceVIP); } // Modified the function header void load_from_file(int numFiles, char **files) { // TODO --- 5 // Load the configuration files // Call build_tables(FILE *fp) for (int i = 1; i < numFiles; i++) { FILE *fp = fopen(files[i], "r"); build_tables(fp); fclose(fp); } } bool is_dest_equal_to_me(char *dest_addr) { interface_t *temp = IFCONFIG_TABLE.ifconfig_entries; int i; for (i = 0; i < IFCONFIG_TABLE.num_entries; i++) { if (strcmp(IFCONFIG_TABLE.ifconfig_entries[i].my_vip, dest_addr) == 0) { return true; } } return false; } void send_packet(char *dest_addr, char *msg, int msg_size, int TTL, int protocol) { // TODO --- 6 // Call the function to get the next check_for_expired_routes // Call the function to get the interface ID // Contruct the IP header (listed below) // Send the packet through a corresponding interface interface_t *interface = get_interface_by_dest_addr(dest_addr); struct iphdr ip_header; struct iphdr *ip_header_ptr = &ip_header; ip_header.id = rand(); ip_header.saddr = inet_addr(interface->my_vip); forwarding_entry_t *f_entry = get_forwarding_entry_by_dest_addr(dest_addr); ip_header.daddr = inet_addr(f_entry->dest_addr); ip_header.version = 4; ip_header.ttl = TTL; ip_header.protocol = protocol; ip_header.ihl = 5; // ??? ip_header.check = 0; ip_header.tot_len = 0; ip_header.frag_off = 0; send_packet_with_interface(interface, msg, msg_size, ip_header_ptr); } void set_as_up(int ID) { interface_t *interface = get_interface_by_id(ID); if (interface == NULL) { printf("\nInterface %d is not found.\n\n", ID); return; } interface->is_up = true; forwarding_entry_t *entry = get_forwarding_entry_by_dest_addr(IFCONFIG_TABLE.ifconfig_entries[ID].my_vip); entry->cost = 0; printf("\nInterface %d is up.\n\n", ID); return; } void set_as_down(int ID) { interface_t *interface = get_interface_by_id(ID); if (interface == NULL) { printf("\nInterface %d is not found.\n\n", ID); return; } interface->is_up = false; forwarding_entry_t *entry = get_forwarding_entry_by_dest_addr(IFCONFIG_TABLE.ifconfig_entries[ID].my_vip); entry->cost = MAX_TTL; printf("\nInterface %d is down.\n\n", ID); return; } void print_routes() { printf("\nStart finding routes....\n"); int i; for (i = 0; i < FORWARDING_TABLE.num_entries; ++i) { forwarding_entry_t entry = FORWARDING_TABLE.forwarding_entries[i]; printf("%s %d %d\n", entry.dest_addr, entry.interface_id, entry.cost); } printf("....end finding routes.\n\n"); } void print_ifconfig() { printf("\nStart ifconfig....\n"); int i; for (i = 0; i < IFCONFIG_TABLE.num_entries; ++i) { interface_t entry = IFCONFIG_TABLE.ifconfig_entries[i]; printf("%d %s %s\n", entry.interface_id, entry.my_vip, entry.is_up ? "up" : "down"); } printf("....end ifconfig.\n\n"); } void send_forwarding_update(char *dest_addr) { // TODO --- 7 // Sends an RIP update to a specified destination // Call a corresponding function // send_packet(); for (int i = 0; i < FORWARDING_TABLE.num_entries; i++) { if (strcmp(FORWARDING_TABLE.forwarding_entries[i].dest_addr, dest_addr) == 0) { rip_packet_t *RIP_packet = (rip_packet_t *)malloc(sizeof(rip_packet_t *)); RIP_packet->command = 1; RIP_packet->num_entries = 0; send_packet(dest_addr, (char *)RIP_packet, sizeof(rip_packet_t), MAX_TTL, RIP_PROTOCOL_VAL); } } } void activate_RIP_update() { int i; for (i = 0; i < IFCONFIG_TABLE.num_entries; i++) { if (IFCONFIG_TABLE.ifconfig_entries[i].is_up) { send_forwarding_update(IFCONFIG_TABLE.ifconfig_entries[i].other_vip); } } } void request_routes() { int i; for (i = 0; i < IFCONFIG_TABLE.num_entries; i++) { rip_packet_t *RIP_packet = (rip_packet_t *)malloc(sizeof(rip_packet_t *)); RIP_packet->command = 1; RIP_packet->num_entries = 0; send_packet(IFCONFIG_TABLE.ifconfig_entries[i].other_vip, (char *)RIP_packet, sizeof(rip_packet_t), MAX_TTL, RIP_PROTOCOL_VAL); } } void check_for_expired_routes() { // TODO --- 8 // Periodically check the routes // You should do something to mark it invalid for (int i = 0; i < FORWARDING_TABLE.num_entries; i++) { if ((FORWARDING_TABLE.forwarding_entries[i].interface_id != -1) && ((int)time(NULL) - (int)FORWARDING_TABLE.forwarding_entries[i].last_updated > 12)) { FORWARDING_TABLE.forwarding_entries[i].cost = numeric_limits<int>::max(); } } } void choose_command(char *command) { // TODO --- 9 // Get the command from the user // Process the commands if (strncmp(command, "ifconfig", 8) == 0) { print_ifconfig(); } else if (strncmp(command, "routes", 6) == 0) { print_routes(); } else if (strncmp(command, "down", 4) == 0) { strtok(command, " "); int interfaceID = atoi(strtok(NULL, "")); set_as_down(interfaceID); } else if (strncmp(command, "up", 2) == 0) { strtok(command, " "); int interfaceID = atoi(strtok(NULL, "")); set_as_up(interfaceID); activate_RIP_update(); } else if (strncmp(command, "send", 4) == 0) { strtok(command, " "); char *dest_addr = strtok(NULL, " "); char *msg = strtok(NULL, ""); int msg_size = strlen(msg); int TTL = MAX_TTL; int protocol = TEST_PROTOCOL_VAL; send_packet(dest_addr, msg, msg_size, TTL, protocol); } } int init_listen_socket(int port, fd_set *running_fd_set) { int listen_socket; struct sockaddr_in server_addr; bzero((char *)&server_addr, sizeof(server_addr)); server_addr.sin_addr.s_addr = INADDR_ANY; server_addr.sin_family = AF_INET; server_addr.sin_port = htons(port); if ((listen_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { //UDP socket listening for anything perror("Create socket error: "); exit(1); } if ((bind(listen_socket, (const struct sockaddr *)&server_addr, (socklen_t)sizeof(server_addr))) < 0) { perror("Bind error: "); exit(1); } FD_SET(listen_socket, running_fd_set); fcntl(listen_socket, F_SETFL, O_NONBLOCK, 1); // non-blocking interactions return listen_socket; } void handle_packet(int listen_socket) { // TODO --- 10 // The most important and comprehensive // Think carefully and completely // You should call multiple functions listed above // inet_ntop(AF_INET, &(recv_header->saddr), src_addr, INET_ADDRSTRLEN) // if(received_ip_checksum != calculated_ip_checksum){ // printf("Broken checksum, dropping packet\n"); // return; // } // if(recv_header->ttl <= 0) { // printf("TTL surpassed, dropping packet\n"); // return; // } } int main(int argc, char **argv) { // Initialize based on input file FORWARDING_TABLE.num_entries = 0; IFCONFIG_TABLE.num_entries = 0; // passed in number of arguments and the array of file names load_from_file(argc, argv); // initialize routing information int listen_socket; fd_set full_fd_set; fd_set *running_ptr; struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 1000; time_t last_updated; time(&last_updated); running_ptr = &full_fd_set; listen_socket = init_listen_socket(SELF.port, running_ptr); char command_line[1500]; request_routes(); while (1) { FD_ZERO(running_ptr); FD_SET(STDIN_FILENO, running_ptr); FD_SET(listen_socket, running_ptr); // check for user input // handle // check for received packet // handle if (select(FD_SETSIZE, running_ptr, NULL, NULL, &timeout) < 0) { perror("Select error: "); exit(EXIT_FAILURE); } if (FD_ISSET(listen_socket, running_ptr)) { // data ready on the read socket // TODO: receive data and pass directly to ALL interfaces // Only an up and directly attached interface (by source port) should act on this and call handle_packet handle_packet(listen_socket); } if (FD_ISSET(STDIN_FILENO, running_ptr)) { scanf("%s", command_line); choose_command(command_line); fflush(STDIN_FILENO); } if (((int)time(NULL) - (int)last_updated) >= 5) { request_routes(); time(&last_updated); } check_for_expired_routes(); } }
[ "bornarkun@gmail.com" ]
bornarkun@gmail.com
d6b9f316d316dc78e23f11329471ad40b19917ff
5a3af48f1993f7505167c91ce331ee8d410b6e28
/Engine/Physics/PhysicsSystem.cpp
3752f696551ed4c72a66c3ea18d61541f38bf017
[]
no_license
LuciusEverest/Gat150
46040597a8dbecbc1d5c7b115b0ba81306653600
bfff0d95d8e38dd91ba63180145298d0982d81e4
refs/heads/master
2022-12-16T19:25:24.621066
2020-09-01T22:56:06
2020-09-01T22:56:06
284,792,372
0
0
null
null
null
null
UTF-8
C++
false
false
1,580
cpp
#include "pch.h" #include "PhysicsSystem.h" #include "ContactListener.h" bool bleh::PhysicsSystem::Startup() { b2Vec2 gravity{0.0f, 10.0f}; m_world = new b2World{ gravity }; m_contactListener = new ContactListener; m_world->SetContactListener(m_contactListener); return true; } void bleh::PhysicsSystem::Shutdown() { delete m_world; m_world = nullptr; delete m_contactListener; m_contactListener = nullptr; } void bleh::PhysicsSystem::Update() { float timeStep(1.0f / 60.0f); m_world->Step(timeStep, 8, 3); } b2Body* bleh::PhysicsSystem::CreateBody(const Vector2& position, float angle, const RigidBodyData& data, GameObject* gameObject) { b2BodyDef bodyDef; Vector2 worldPosition = ScreenToWorld(position); bodyDef.type = (data.isDynamic) ? b2_dynamicBody : b2_staticBody; bodyDef.position.Set(worldPosition.x, worldPosition.y); bodyDef.angle = bleh::DegreesToRadians(angle); bodyDef.fixedRotation = data.lockAngle; b2Body* body = m_world->CreateBody(&bodyDef); Vector2 worldSize = ScreenToWorld(data.size); b2PolygonShape shape; shape.SetAsBox(worldSize.x, worldSize.y); b2FixtureDef fixtureDef; fixtureDef.density = data.density; fixtureDef.friction = data.friction; fixtureDef.restitution = data.restitution; fixtureDef.userData = gameObject; fixtureDef.shape = &shape; fixtureDef.isSensor = data.isSensor; body->CreateFixture(&fixtureDef); return body; } void bleh::PhysicsSystem::DestroyBody(b2Body* body) { m_world->DestroyBody(body); }
[ "61430189+LuciusEverest@users.noreply.github.com" ]
61430189+LuciusEverest@users.noreply.github.com
0b9ac0522ab06c56112b0fcadc1d66eac2281e03
7abf928bfa7d0a178623b3411d60b24c9b285503
/lib/RE_Transceiver/RE_Transceiver.cpp
032b6686d17e1461e9f41f324a9067f321d701f3
[]
no_license
rugi252126/RE_Transmitter
86dca162c57f50f273d2b4fa6d17de873ab81c3c
5c63fa612051d09e8310e0cddb25eacae5ed2e5c
refs/heads/master
2021-11-22T22:48:42.884069
2021-11-03T09:07:31
2021-11-03T09:07:31
217,965,682
0
0
null
null
null
null
UTF-8
C++
false
false
4,881
cpp
/** @file RE_Transceiver.cpp @brief The implementation handles the transmission of data before being processed by nRF24L01 library. The data being transmitted is a set of collected data from different modules. It will take care of the received data as well. This module has direct interface to the nRF24L01 library. Setting-up of nRF24L01 will be done here. @author Alfonso, Rudy Manalo @version */ #include "RE_Transceiver.h" #include <SPI.h> #include "RF24.h" /* Formula: Freq(selected) = 2400 + CH(selected) Channel is from 0 to 125. Recommended is from channel 25 and above as lower channel is used for wifi. */ // #define TRANSCEIVER_CHANNEL_FREQUENCY_K 108 // just set the number(e.g. 25) since the library only need this information /* Hardware configuration: Set up nRF24L01 radio on SPI bus plus pins 7 & 8 Create an instance from class RF24 */ RF24 RE_radio(TRANSCEIVER_CE_K,TRANSCEIVER_CSN_K); const uint8_t TXRX_ADDRESS[6] = "2RE5t"; // CLASS CONSTRUCTOR // --------------------------------------------------------------------------- Transceiver::Transceiver() { } // PUBLIC METHODS // --------------------------------------------------------------------------- // Module initialization void Transceiver::transceiverF_Init(void) { // start radio RE_radio.begin(); // Set PA(Power Amplifier) RE_radio.setPALevel(RF24_PA_MAX); // RF24_PA_MAX = 0dBm // Set channel frequency // RE_radio.setChannel(TRANSCEIVER_CHANNEL_FREQUENCY_K); // while( (RE_radio.setDataRate(RF24_1MBPS)) != true ){/* wait until it sets successfully. */} // sentivity of -94dBm. lowest sensitivity is better. // Open a writing and reading pipe on each radio, with opposite addresses RE_radio.openWritingPipe(TXRX_ADDRESS); // Stop receiving anything RE_radio.stopListening(); // set the connection status to NOK by default txrx_status_b_ = false; } // --------------------------------------------------------------------------- // Cyclic function void Transceiver::transceiverF_Cyclic(void) { // First, collect the data to be transmitted. transceiverLF_collectData(); // Send the data transceiverLF_Send(); // Check any received data // transceiverLF_Receive(); } // PRIVATE METHODS // --------------------------------------------------------------------------- // Collection of data from other modules via Rte void Transceiver::transceiverLF_collectData(void) { tx_data_s.joystick_throttle_fwd_bckwd_ = rte_ivar.Rte_Read_JoyStick_ThrottleFwdBckwrd(); tx_data_s.joystick_throttle_left_right_ = rte_ivar.Rte_Read_JoyStick_ThrottleLeftRight(); tx_data_s.joystick_ctrl_fwd_bckwd_ = (uint8_t)rte_ivar.Rte_Read_JoyStick_ControlFwdBckwrd(); tx_data_s.joystick_ctrl_left_right_ = (uint8_t)rte_ivar.Rte_Read_JoyStick_ControlLeftRight(); tx_data_s.potentiometer1_ = rte_ivar.Rte_Read_Potentiometer_Poti1Data(); tx_data_s.switch1_ = rte_ivar.Rte_Read_Hal_DI_Switch1(); tx_data_s.switch2_ = rte_ivar.Rte_Read_Hal_DI_Switch2(); tx_data_s.switch3_ = rte_ivar.Rte_Read_Hal_DI_Switch3(); tx_data_s.switch4_ = rte_ivar.Rte_Read_Hal_DI_Switch4(); } // --------------------------------------------------------------------------- // Increments radio timeout counter void Transceiver::transceiverLF_incrementTimeoutCounter(void) { if(timeout_ctr_ >= TRANSCEIVER_TIMEOUT_K) { // radio connection is not okay. txrx_status_b_ = false; rte_ivar.Rte_Write_Transceiver_Status(txrx_status_b_); } else { timeout_ctr_++; } } // --------------------------------------------------------------------------- // Decrements radio timeout counter void Transceiver::transceiverLF_decrementTimeoutCounter(void) { if(0u == timeout_ctr_) { // radio connection is okay. txrx_status_b_ = true; rte_ivar.Rte_Write_Transceiver_Status(txrx_status_b_); } else { timeout_ctr_--; } } // --------------------------------------------------------------------------- // Sending of collected data to nRF24L01 library void Transceiver::transceiverLF_Send(void) { // First, stop listening so we can talk. RE_radio.stopListening(); // Send the data if (RE_radio.write( &tx_data_s, sizeof(tx_data_s)) ) { //! Data is transmitted successfully. // start decrementing the timeout counter transceiverLF_decrementTimeoutCounter(); } else { //! Data is not transmitted successfully. // start incrementing the timeout counter transceiverLF_incrementTimeoutCounter(); } } // --------------------------------------------------------------------------- // Reading of data from nRF24L01 library //void RE_Transceiver_cls::transceiverLF_Receive(void) //{ //}
[ "alfonso_rudy@yahoo.com" ]
alfonso_rudy@yahoo.com
a54e15d97c0bbf7fc03ce563a60870f6beeae296
91a882547e393d4c4946a6c2c99186b5f72122dd
/Source/XPSP1/NT/multimedia/danim/src/appel/server/eventq.cpp
5ce8447f02a7cf1920cf8993fcf4f36a7de896d2
[]
no_license
IAmAnubhavSaini/cryptoAlgorithm-nt5src
94f9b46f101b983954ac6e453d0cf8d02aa76fc7
d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2
refs/heads/master
2023-09-02T10:14:14.795579
2021-11-20T13:47:06
2021-11-20T13:47:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,832
cpp
/******************************************************************************* Copyright (c) 1995-96 Microsoft Corporation Abstract: Event Queue management *******************************************************************************/ #include "headers.h" #include "context.h" #include "eventq.h" #include "view.h" #include "privinc/vec2i.h" #include "privinc/vec3i.h" #include "privinc/probe.h" #include "privinc/xformi.h" #include "privinc/xform2i.h" #include "appelles/image.h" #include "privinc/mutex.h" #include "privinc/resource.h" #include "privinc/registry.h" #include "privinc/debug.h" EventQ::EventQ () { ClearStates () ; } EventQ::~EventQ() { } // Offset to distinguish win event of same time static const Time DIFFERENTIAL_OFFSET = 0.0000001; // Ensures events are enqueued sorted by time and no times are the // same void EventQ::Add (AXAWindEvent & ev) { if (!_msgq.empty()) { AXAWindEvent & lastEvent = _msgq.back(); if (ev.when <= lastEvent.when) { ev.when = lastEvent.when + DIFFERENTIAL_OFFSET; } if (ev.id == AXAE_MOUSE_MOVE) { _mouseLeft = false; } } _msgq.push_back(ev); } void EventQ::ClearStates () { _mousex = _mousey = 1000000000 ; _keysDown.erase(_keysDown.begin(), _keysDown.end()); _buttonsDown.erase(_buttonsDown.begin(), _buttonsDown.end()); _resized = FALSE ; _mouseLeft = false; _mouseLeftTime = 0.0; } void EventQ::Reset () { _msgq.erase(_msgq.begin(), _msgq.end()); ClearStates () ; } // Keep events for DELTA time static const Time DELTA = 0.5; void EventQ::Prune(Time curTime) { Time cutOff = curTime - DELTA; while (!_msgq.empty()) { AXAWindEvent & ev = _msgq.front(); if (ev.when > cutOff) break; switch (ev.id) { case AXAE_MOUSE_BUTTON: if (ev.bState) _buttonsDown.push_front((BYTE) ev.data) ; else _buttonsDown.remove((BYTE) ev.data) ; break; case AXAE_KEY: if (ev.bState) _keysDown.push_front(ev.data) ; else _keysDown.remove(ev.data) ; break; case AXAE_MOUSE_MOVE: _mousex = ev.x ; _mousey = ev.y ; break ; case AXAE_APP_TRIGGER: GCRemoveFromRoots((Bvr) ev.x, GetCurrentGCRoots()); break; case AXAE_FOCUS: if (!ev.bState) { // When we lose focus clear all the key states _keysDown.erase(_keysDown.begin(), _keysDown.end()); } break ; default: break; } _msgq.pop_front(); } } // Search for event with event time > t0 AXAWindEvent * EventQ::OccurredAfter(Time when, AXAEventId id, DWORD data, BOOL bState, BYTE modReq, BYTE modOpt) { for (list<AXAWindEvent>::iterator i = _msgq.begin(); i != _msgq.end(); i++) { if ((*i).id == id && (*i).data == data && (*i).bState == bState && ((*i).modifiers & modReq) == modReq && ((*i).modifiers & (~modOpt)) == 0 && (*i).when > when) { return &(*i); } } return NULL; } BOOL EventQ::GetState(Time when, AXAEventId id, DWORD data, BYTE mod) { // Look through the list to see if we have any messages // Start looking from the end and if we find one return it for (list<AXAWindEvent>::reverse_iterator i = _msgq.rbegin(); i != _msgq.rend(); i++) { AXAWindEvent & ev = *i; if (ev.when > when) continue; // If we are looking for a key press and we have a lost focus // event then the key cannot be pressed if (ev.id == AXAE_FOCUS && id == AXAE_KEY && !ev.bState) { return FALSE ; } // Found the latest state - return it if (ev.id == id && ev.data == data && ev.modifiers == mod) return ev.bState ; } // Lookup the last known state switch (id) { case AXAE_MOUSE_BUTTON: { for (list<BYTE>::iterator i = _buttonsDown.begin(); i != _buttonsDown.end(); i++) { if (*i == data) return TRUE ; } break ; } case AXAE_KEY: { for (list<DWORD>::iterator i = _keysDown.begin(); i != _keysDown.end(); i++) { if (*i == data) return TRUE ; } break ; } default: RaiseException_InternalError ("EventGetState: Invalid event type") ; } // The data was out of range - return FALSE return FALSE ; } void EventQ::GetMousePos(Time when, DWORD & x, DWORD & y) { // Look through the list to see if we have any messages // Start looking from the end and if we find one return it for (list<AXAWindEvent>::reverse_iterator i = _msgq.rbegin(); i != _msgq.rend(); i++) { AXAWindEvent & ev = *i; if (ev.when > when) continue; if (ev.id == AXAE_MOUSE_MOVE || ev.id == AXAE_MOUSE_BUTTON) { x = ev.x ; y = ev.y ; return; } } // No queued events - return last known position x = _mousex ; y = _mousey ; } void EventQ::MouseLeave(Time when) { _mouseLeft = true; _mouseLeftTime = when; } bool EventQ::IsMouseInWindow(Time when) { if (_mouseLeft && (when > _mouseLeftTime)) { return false; } return true; } // ====================================================== // C Functions // ====================================================== AXAWindEvent* AXAEventOccurredAfter(Time when, AXAEventId id, DWORD data, BOOL bState, BYTE modReq, BYTE modOpt) { return GetCurrentEventQ().OccurredAfter(when, id, data, bState, modReq, modOpt) ; } BOOL AXAEventGetState(Time when, AXAEventId id, DWORD data, BYTE mod) { return GetCurrentEventQ().GetState(when, id, data, mod) ; } void AXAGetMousePos(Time when, DWORD & x, DWORD & y) { GetCurrentEventQ().GetMousePos (when, x, y) ; } BOOL AXAWindowSizeChanged() { return GetCurrentEventQ().IsResized() ; }
[ "support@cryptoalgo.cf" ]
support@cryptoalgo.cf
e023f9ac68b192c6fa46f0e13236dc3d47b7b6c4
a06a9ae73af6690fabb1f7ec99298018dd549bb7
/_Library/_Include/boost/spirit/include/classic_swap_actor.hpp
b63c1add2c3011b1e6aa7a686eaf95ddec0770dc
[]
no_license
longstl/mus12
f76de65cca55e675392eac162dcc961531980f9f
9e1be111f505ac23695f7675fb9cefbd6fa876e9
refs/heads/master
2021-05-18T08:20:40.821655
2020-03-29T17:38:13
2020-03-29T17:38:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
879
hpp
//////////////////////////////////////////////////////////////////////////////// // classic_swap_actor.hpp /*============================================================================= Copyright (c) 2001-2008 Joel de Guzman Copyright (c) 2001-2008 Hartmut Kaiser http://spirit.sourceforge.net/ Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef BOOST_SPIRIT_INCLUDE_CLASSIC_SWAP_ACTOR #define BOOST_SPIRIT_INCLUDE_CLASSIC_SWAP_ACTOR #include <boost/spirit/home/classic/actor/swap_actor.hpp> #endif ///////////////////////////////////////////////// // vnDev.Games - Trong.LIVE - DAO VAN TRONG // ////////////////////////////////////////////////////////////////////////////////
[ "adm.fael.hs@gmail.com" ]
adm.fael.hs@gmail.com
99e4088f2bb4d28b4ae326a970e8b68390ba2a35
bd953c12dec3f39ad490284c1d5e025d68a7f39b
/expression/Plus.h
6379e8b2891a7409325988dd4661ba5da25732db
[ "MIT" ]
permissive
benazoulaydev/Flight-Simulator-Cpp
b851d9e40027e9f27e8d393e2ac2fc6e3c2ef135
aa96de70de78d483636f558648238442ab4c306c
refs/heads/master
2020-10-01T13:17:06.511283
2020-01-05T13:43:20
2020-01-05T13:43:20
227,545,106
0
2
null
2020-01-05T13:43:21
2019-12-12T07:21:35
C++
UTF-8
C++
false
false
378
h
// // Created by kfir on 11/3/19. // #ifndef EX1_PLUS_H #define EX1_PLUS_H #include "BinaryOperator.h" class Plus: public BinaryOperator { public: Plus(Expression *l, Expression *r){ this->left = l; this->right = r; } double calculate() override { return this->left->calculate() + this->right->calculate(); } }; #endif //EX1_PLUS_H
[ "kfir.yehuda50@gmail.com" ]
kfir.yehuda50@gmail.com
8efab90c4af8f7b5464e21967d377fbc4c12484c
67fc9e51437e351579fe9d2d349040c25936472a
/wrappers/7.0.0/vtkAngleRepresentation3DWrap.cc
4f5aebb17ac079e9408969fbe7c1159d6240f1f7
[]
permissive
axkibe/node-vtk
51b3207c7a7d3b59a4dd46a51e754984c3302dec
900ad7b5500f672519da5aa24c99aa5a96466ef3
refs/heads/master
2023-03-05T07:45:45.577220
2020-03-30T09:31:07
2020-03-30T09:31:07
48,490,707
6
0
BSD-3-Clause
2022-12-07T20:41:45
2015-12-23T12:58:43
C++
UTF-8
C++
false
false
33,808
cc
/* this file has been autogenerated by vtkNodeJsWrap */ /* editing this might proof futile */ #define VTK_WRAPPING_CXX #define VTK_STREAMS_FWD_ONLY #include <nan.h> #include "vtkAngleRepresentationWrap.h" #include "vtkAngleRepresentation3DWrap.h" #include "vtkObjectWrap.h" #include "vtkActorWrap.h" #include "vtkFollowerWrap.h" #include "vtkWindowWrap.h" #include "vtkViewportWrap.h" #include "../../plus/plus.h" using namespace v8; extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap; Nan::Persistent<v8::FunctionTemplate> VtkAngleRepresentation3DWrap::ptpl; VtkAngleRepresentation3DWrap::VtkAngleRepresentation3DWrap() { } VtkAngleRepresentation3DWrap::VtkAngleRepresentation3DWrap(vtkSmartPointer<vtkAngleRepresentation3D> _native) { native = _native; } VtkAngleRepresentation3DWrap::~VtkAngleRepresentation3DWrap() { } void VtkAngleRepresentation3DWrap::Init(v8::Local<v8::Object> exports) { Nan::SetAccessor(exports, Nan::New("vtkAngleRepresentation3D").ToLocalChecked(), ConstructorGetter); Nan::SetAccessor(exports, Nan::New("AngleRepresentation3D").ToLocalChecked(), ConstructorGetter); } void VtkAngleRepresentation3DWrap::ConstructorGetter( v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { InitPtpl(); info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction()); } void VtkAngleRepresentation3DWrap::InitPtpl() { if (!ptpl.IsEmpty()) return; v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); VtkAngleRepresentationWrap::InitPtpl( ); tpl->Inherit(Nan::New<FunctionTemplate>(VtkAngleRepresentationWrap::ptpl)); tpl->SetClassName(Nan::New("VtkAngleRepresentation3DWrap").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "BuildRepresentation", BuildRepresentation); Nan::SetPrototypeMethod(tpl, "buildRepresentation", BuildRepresentation); Nan::SetPrototypeMethod(tpl, "GetAngle", GetAngle); Nan::SetPrototypeMethod(tpl, "getAngle", GetAngle); Nan::SetPrototypeMethod(tpl, "GetArc", GetArc); Nan::SetPrototypeMethod(tpl, "getArc", GetArc); Nan::SetPrototypeMethod(tpl, "GetCenterDisplayPosition", GetCenterDisplayPosition); Nan::SetPrototypeMethod(tpl, "getCenterDisplayPosition", GetCenterDisplayPosition); Nan::SetPrototypeMethod(tpl, "GetCenterWorldPosition", GetCenterWorldPosition); Nan::SetPrototypeMethod(tpl, "getCenterWorldPosition", GetCenterWorldPosition); Nan::SetPrototypeMethod(tpl, "GetClassName", GetClassName); Nan::SetPrototypeMethod(tpl, "getClassName", GetClassName); Nan::SetPrototypeMethod(tpl, "GetPoint1DisplayPosition", GetPoint1DisplayPosition); Nan::SetPrototypeMethod(tpl, "getPoint1DisplayPosition", GetPoint1DisplayPosition); Nan::SetPrototypeMethod(tpl, "GetPoint1WorldPosition", GetPoint1WorldPosition); Nan::SetPrototypeMethod(tpl, "getPoint1WorldPosition", GetPoint1WorldPosition); Nan::SetPrototypeMethod(tpl, "GetPoint2DisplayPosition", GetPoint2DisplayPosition); Nan::SetPrototypeMethod(tpl, "getPoint2DisplayPosition", GetPoint2DisplayPosition); Nan::SetPrototypeMethod(tpl, "GetPoint2WorldPosition", GetPoint2WorldPosition); Nan::SetPrototypeMethod(tpl, "getPoint2WorldPosition", GetPoint2WorldPosition); Nan::SetPrototypeMethod(tpl, "GetRay1", GetRay1); Nan::SetPrototypeMethod(tpl, "getRay1", GetRay1); Nan::SetPrototypeMethod(tpl, "GetRay2", GetRay2); Nan::SetPrototypeMethod(tpl, "getRay2", GetRay2); Nan::SetPrototypeMethod(tpl, "GetTextActor", GetTextActor); Nan::SetPrototypeMethod(tpl, "getTextActor", GetTextActor); Nan::SetPrototypeMethod(tpl, "HasTranslucentPolygonalGeometry", HasTranslucentPolygonalGeometry); Nan::SetPrototypeMethod(tpl, "hasTranslucentPolygonalGeometry", HasTranslucentPolygonalGeometry); Nan::SetPrototypeMethod(tpl, "IsA", IsA); Nan::SetPrototypeMethod(tpl, "isA", IsA); Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "ReleaseGraphicsResources", ReleaseGraphicsResources); Nan::SetPrototypeMethod(tpl, "releaseGraphicsResources", ReleaseGraphicsResources); Nan::SetPrototypeMethod(tpl, "RenderOpaqueGeometry", RenderOpaqueGeometry); Nan::SetPrototypeMethod(tpl, "renderOpaqueGeometry", RenderOpaqueGeometry); Nan::SetPrototypeMethod(tpl, "RenderTranslucentPolygonalGeometry", RenderTranslucentPolygonalGeometry); Nan::SetPrototypeMethod(tpl, "renderTranslucentPolygonalGeometry", RenderTranslucentPolygonalGeometry); Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "SetCenterDisplayPosition", SetCenterDisplayPosition); Nan::SetPrototypeMethod(tpl, "setCenterDisplayPosition", SetCenterDisplayPosition); Nan::SetPrototypeMethod(tpl, "SetCenterWorldPosition", SetCenterWorldPosition); Nan::SetPrototypeMethod(tpl, "setCenterWorldPosition", SetCenterWorldPosition); Nan::SetPrototypeMethod(tpl, "SetPoint1DisplayPosition", SetPoint1DisplayPosition); Nan::SetPrototypeMethod(tpl, "setPoint1DisplayPosition", SetPoint1DisplayPosition); Nan::SetPrototypeMethod(tpl, "SetPoint1WorldPosition", SetPoint1WorldPosition); Nan::SetPrototypeMethod(tpl, "setPoint1WorldPosition", SetPoint1WorldPosition); Nan::SetPrototypeMethod(tpl, "SetPoint2DisplayPosition", SetPoint2DisplayPosition); Nan::SetPrototypeMethod(tpl, "setPoint2DisplayPosition", SetPoint2DisplayPosition); Nan::SetPrototypeMethod(tpl, "SetPoint2WorldPosition", SetPoint2WorldPosition); Nan::SetPrototypeMethod(tpl, "setPoint2WorldPosition", SetPoint2WorldPosition); Nan::SetPrototypeMethod(tpl, "SetTextActorScale", SetTextActorScale); Nan::SetPrototypeMethod(tpl, "setTextActorScale", SetTextActorScale); #ifdef VTK_NODE_PLUS_VTKANGLEREPRESENTATION3DWRAP_INITPTPL VTK_NODE_PLUS_VTKANGLEREPRESENTATION3DWRAP_INITPTPL #endif ptpl.Reset( tpl ); } void VtkAngleRepresentation3DWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info) { if(!info.IsConstructCall()) { Nan::ThrowError("Constructor not called in a construct call."); return; } if(info.Length() == 0) { vtkSmartPointer<vtkAngleRepresentation3D> native = vtkSmartPointer<vtkAngleRepresentation3D>::New(); VtkAngleRepresentation3DWrap* obj = new VtkAngleRepresentation3DWrap(native); obj->Wrap(info.This()); } else { if(info[0]->ToObject() != vtkNodeJsNoWrap ) { Nan::ThrowError("Parameter Error"); return; } } info.GetReturnValue().Set(info.This()); } void VtkAngleRepresentation3DWrap::BuildRepresentation(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAngleRepresentation3DWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentation3DWrap>(info.Holder()); vtkAngleRepresentation3D *native = (vtkAngleRepresentation3D *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->BuildRepresentation(); } void VtkAngleRepresentation3DWrap::GetAngle(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAngleRepresentation3DWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentation3DWrap>(info.Holder()); vtkAngleRepresentation3D *native = (vtkAngleRepresentation3D *)wrapper->native.GetPointer(); double r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetAngle(); info.GetReturnValue().Set(Nan::New(r)); } void VtkAngleRepresentation3DWrap::GetArc(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAngleRepresentation3DWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentation3DWrap>(info.Holder()); vtkAngleRepresentation3D *native = (vtkAngleRepresentation3D *)wrapper->native.GetPointer(); vtkActor * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetArc(); VtkActorWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkActorWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkActorWrap *w = new VtkActorWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkAngleRepresentation3DWrap::GetCenterDisplayPosition(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAngleRepresentation3DWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentation3DWrap>(info.Holder()); vtkAngleRepresentation3D *native = (vtkAngleRepresentation3D *)wrapper->native.GetPointer(); size_t i; if(info.Length() > 0 && info[0]->IsFloat64Array()) { v8::Local<v8::Float64Array>a0(v8::Local<v8::Float64Array>::Cast(info[0]->ToObject())); if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->GetCenterDisplayPosition( (double *)(a0->Buffer()->GetContents().Data()) ); return; } else if(info.Length() > 0 && info[0]->IsArray()) { v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject())); double b0[3]; if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } for( i = 0; i < 3; i++ ) { if( !a0->Get(i)->IsNumber() ) { Nan::ThrowError("Array contents invalid."); return; } b0[i] = a0->Get(i)->NumberValue(); } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->GetCenterDisplayPosition( b0 ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkAngleRepresentation3DWrap::GetCenterWorldPosition(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAngleRepresentation3DWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentation3DWrap>(info.Holder()); vtkAngleRepresentation3D *native = (vtkAngleRepresentation3D *)wrapper->native.GetPointer(); size_t i; if(info.Length() > 0 && info[0]->IsFloat64Array()) { v8::Local<v8::Float64Array>a0(v8::Local<v8::Float64Array>::Cast(info[0]->ToObject())); if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->GetCenterWorldPosition( (double *)(a0->Buffer()->GetContents().Data()) ); return; } else if(info.Length() > 0 && info[0]->IsArray()) { v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject())); double b0[3]; if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } for( i = 0; i < 3; i++ ) { if( !a0->Get(i)->IsNumber() ) { Nan::ThrowError("Array contents invalid."); return; } b0[i] = a0->Get(i)->NumberValue(); } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->GetCenterWorldPosition( b0 ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkAngleRepresentation3DWrap::GetClassName(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAngleRepresentation3DWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentation3DWrap>(info.Holder()); vtkAngleRepresentation3D *native = (vtkAngleRepresentation3D *)wrapper->native.GetPointer(); char const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetClassName(); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); } void VtkAngleRepresentation3DWrap::GetPoint1DisplayPosition(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAngleRepresentation3DWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentation3DWrap>(info.Holder()); vtkAngleRepresentation3D *native = (vtkAngleRepresentation3D *)wrapper->native.GetPointer(); size_t i; if(info.Length() > 0 && info[0]->IsFloat64Array()) { v8::Local<v8::Float64Array>a0(v8::Local<v8::Float64Array>::Cast(info[0]->ToObject())); if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->GetPoint1DisplayPosition( (double *)(a0->Buffer()->GetContents().Data()) ); return; } else if(info.Length() > 0 && info[0]->IsArray()) { v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject())); double b0[3]; if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } for( i = 0; i < 3; i++ ) { if( !a0->Get(i)->IsNumber() ) { Nan::ThrowError("Array contents invalid."); return; } b0[i] = a0->Get(i)->NumberValue(); } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->GetPoint1DisplayPosition( b0 ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkAngleRepresentation3DWrap::GetPoint1WorldPosition(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAngleRepresentation3DWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentation3DWrap>(info.Holder()); vtkAngleRepresentation3D *native = (vtkAngleRepresentation3D *)wrapper->native.GetPointer(); size_t i; if(info.Length() > 0 && info[0]->IsFloat64Array()) { v8::Local<v8::Float64Array>a0(v8::Local<v8::Float64Array>::Cast(info[0]->ToObject())); if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->GetPoint1WorldPosition( (double *)(a0->Buffer()->GetContents().Data()) ); return; } else if(info.Length() > 0 && info[0]->IsArray()) { v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject())); double b0[3]; if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } for( i = 0; i < 3; i++ ) { if( !a0->Get(i)->IsNumber() ) { Nan::ThrowError("Array contents invalid."); return; } b0[i] = a0->Get(i)->NumberValue(); } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->GetPoint1WorldPosition( b0 ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkAngleRepresentation3DWrap::GetPoint2DisplayPosition(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAngleRepresentation3DWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentation3DWrap>(info.Holder()); vtkAngleRepresentation3D *native = (vtkAngleRepresentation3D *)wrapper->native.GetPointer(); size_t i; if(info.Length() > 0 && info[0]->IsFloat64Array()) { v8::Local<v8::Float64Array>a0(v8::Local<v8::Float64Array>::Cast(info[0]->ToObject())); if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->GetPoint2DisplayPosition( (double *)(a0->Buffer()->GetContents().Data()) ); return; } else if(info.Length() > 0 && info[0]->IsArray()) { v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject())); double b0[3]; if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } for( i = 0; i < 3; i++ ) { if( !a0->Get(i)->IsNumber() ) { Nan::ThrowError("Array contents invalid."); return; } b0[i] = a0->Get(i)->NumberValue(); } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->GetPoint2DisplayPosition( b0 ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkAngleRepresentation3DWrap::GetPoint2WorldPosition(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAngleRepresentation3DWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentation3DWrap>(info.Holder()); vtkAngleRepresentation3D *native = (vtkAngleRepresentation3D *)wrapper->native.GetPointer(); size_t i; if(info.Length() > 0 && info[0]->IsFloat64Array()) { v8::Local<v8::Float64Array>a0(v8::Local<v8::Float64Array>::Cast(info[0]->ToObject())); if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->GetPoint2WorldPosition( (double *)(a0->Buffer()->GetContents().Data()) ); return; } else if(info.Length() > 0 && info[0]->IsArray()) { v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject())); double b0[3]; if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } for( i = 0; i < 3; i++ ) { if( !a0->Get(i)->IsNumber() ) { Nan::ThrowError("Array contents invalid."); return; } b0[i] = a0->Get(i)->NumberValue(); } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->GetPoint2WorldPosition( b0 ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkAngleRepresentation3DWrap::GetRay1(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAngleRepresentation3DWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentation3DWrap>(info.Holder()); vtkAngleRepresentation3D *native = (vtkAngleRepresentation3D *)wrapper->native.GetPointer(); vtkActor * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetRay1(); VtkActorWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkActorWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkActorWrap *w = new VtkActorWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkAngleRepresentation3DWrap::GetRay2(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAngleRepresentation3DWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentation3DWrap>(info.Holder()); vtkAngleRepresentation3D *native = (vtkAngleRepresentation3D *)wrapper->native.GetPointer(); vtkActor * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetRay2(); VtkActorWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkActorWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkActorWrap *w = new VtkActorWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkAngleRepresentation3DWrap::GetTextActor(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAngleRepresentation3DWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentation3DWrap>(info.Holder()); vtkAngleRepresentation3D *native = (vtkAngleRepresentation3D *)wrapper->native.GetPointer(); vtkFollower * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetTextActor(); VtkFollowerWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkFollowerWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkFollowerWrap *w = new VtkFollowerWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkAngleRepresentation3DWrap::HasTranslucentPolygonalGeometry(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAngleRepresentation3DWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentation3DWrap>(info.Holder()); vtkAngleRepresentation3D *native = (vtkAngleRepresentation3D *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->HasTranslucentPolygonalGeometry(); info.GetReturnValue().Set(Nan::New(r)); } void VtkAngleRepresentation3DWrap::IsA(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAngleRepresentation3DWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentation3DWrap>(info.Holder()); vtkAngleRepresentation3D *native = (vtkAngleRepresentation3D *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsString()) { Nan::Utf8String a0(info[0]); int r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->IsA( *a0 ); info.GetReturnValue().Set(Nan::New(r)); return; } Nan::ThrowError("Parameter mismatch"); } void VtkAngleRepresentation3DWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAngleRepresentation3DWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentation3DWrap>(info.Holder()); vtkAngleRepresentation3D *native = (vtkAngleRepresentation3D *)wrapper->native.GetPointer(); vtkAngleRepresentation3D * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->NewInstance(); VtkAngleRepresentation3DWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkAngleRepresentation3DWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkAngleRepresentation3DWrap *w = new VtkAngleRepresentation3DWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkAngleRepresentation3DWrap::ReleaseGraphicsResources(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAngleRepresentation3DWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentation3DWrap>(info.Holder()); vtkAngleRepresentation3D *native = (vtkAngleRepresentation3D *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkWindowWrap::ptpl))->HasInstance(info[0])) { VtkWindowWrap *a0 = ObjectWrap::Unwrap<VtkWindowWrap>(info[0]->ToObject()); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->ReleaseGraphicsResources( (vtkWindow *) a0->native.GetPointer() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkAngleRepresentation3DWrap::RenderOpaqueGeometry(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAngleRepresentation3DWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentation3DWrap>(info.Holder()); vtkAngleRepresentation3D *native = (vtkAngleRepresentation3D *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkViewportWrap::ptpl))->HasInstance(info[0])) { VtkViewportWrap *a0 = ObjectWrap::Unwrap<VtkViewportWrap>(info[0]->ToObject()); int r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->RenderOpaqueGeometry( (vtkViewport *) a0->native.GetPointer() ); info.GetReturnValue().Set(Nan::New(r)); return; } Nan::ThrowError("Parameter mismatch"); } void VtkAngleRepresentation3DWrap::RenderTranslucentPolygonalGeometry(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAngleRepresentation3DWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentation3DWrap>(info.Holder()); vtkAngleRepresentation3D *native = (vtkAngleRepresentation3D *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkViewportWrap::ptpl))->HasInstance(info[0])) { VtkViewportWrap *a0 = ObjectWrap::Unwrap<VtkViewportWrap>(info[0]->ToObject()); int r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->RenderTranslucentPolygonalGeometry( (vtkViewport *) a0->native.GetPointer() ); info.GetReturnValue().Set(Nan::New(r)); return; } Nan::ThrowError("Parameter mismatch"); } void VtkAngleRepresentation3DWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAngleRepresentation3DWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentation3DWrap>(info.Holder()); vtkAngleRepresentation3D *native = (vtkAngleRepresentation3D *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectWrap::ptpl))->HasInstance(info[0])) { VtkObjectWrap *a0 = ObjectWrap::Unwrap<VtkObjectWrap>(info[0]->ToObject()); vtkAngleRepresentation3D * r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->SafeDownCast( (vtkObject *) a0->native.GetPointer() ); VtkAngleRepresentation3DWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkAngleRepresentation3DWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkAngleRepresentation3DWrap *w = new VtkAngleRepresentation3DWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); return; } Nan::ThrowError("Parameter mismatch"); } void VtkAngleRepresentation3DWrap::SetCenterDisplayPosition(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAngleRepresentation3DWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentation3DWrap>(info.Holder()); vtkAngleRepresentation3D *native = (vtkAngleRepresentation3D *)wrapper->native.GetPointer(); size_t i; if(info.Length() > 0 && info[0]->IsFloat64Array()) { v8::Local<v8::Float64Array>a0(v8::Local<v8::Float64Array>::Cast(info[0]->ToObject())); if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetCenterDisplayPosition( (double *)(a0->Buffer()->GetContents().Data()) ); return; } else if(info.Length() > 0 && info[0]->IsArray()) { v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject())); double b0[3]; if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } for( i = 0; i < 3; i++ ) { if( !a0->Get(i)->IsNumber() ) { Nan::ThrowError("Array contents invalid."); return; } b0[i] = a0->Get(i)->NumberValue(); } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetCenterDisplayPosition( b0 ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkAngleRepresentation3DWrap::SetCenterWorldPosition(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAngleRepresentation3DWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentation3DWrap>(info.Holder()); vtkAngleRepresentation3D *native = (vtkAngleRepresentation3D *)wrapper->native.GetPointer(); size_t i; if(info.Length() > 0 && info[0]->IsFloat64Array()) { v8::Local<v8::Float64Array>a0(v8::Local<v8::Float64Array>::Cast(info[0]->ToObject())); if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetCenterWorldPosition( (double *)(a0->Buffer()->GetContents().Data()) ); return; } else if(info.Length() > 0 && info[0]->IsArray()) { v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject())); double b0[3]; if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } for( i = 0; i < 3; i++ ) { if( !a0->Get(i)->IsNumber() ) { Nan::ThrowError("Array contents invalid."); return; } b0[i] = a0->Get(i)->NumberValue(); } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetCenterWorldPosition( b0 ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkAngleRepresentation3DWrap::SetPoint1DisplayPosition(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAngleRepresentation3DWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentation3DWrap>(info.Holder()); vtkAngleRepresentation3D *native = (vtkAngleRepresentation3D *)wrapper->native.GetPointer(); size_t i; if(info.Length() > 0 && info[0]->IsFloat64Array()) { v8::Local<v8::Float64Array>a0(v8::Local<v8::Float64Array>::Cast(info[0]->ToObject())); if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetPoint1DisplayPosition( (double *)(a0->Buffer()->GetContents().Data()) ); return; } else if(info.Length() > 0 && info[0]->IsArray()) { v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject())); double b0[3]; if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } for( i = 0; i < 3; i++ ) { if( !a0->Get(i)->IsNumber() ) { Nan::ThrowError("Array contents invalid."); return; } b0[i] = a0->Get(i)->NumberValue(); } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetPoint1DisplayPosition( b0 ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkAngleRepresentation3DWrap::SetPoint1WorldPosition(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAngleRepresentation3DWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentation3DWrap>(info.Holder()); vtkAngleRepresentation3D *native = (vtkAngleRepresentation3D *)wrapper->native.GetPointer(); size_t i; if(info.Length() > 0 && info[0]->IsFloat64Array()) { v8::Local<v8::Float64Array>a0(v8::Local<v8::Float64Array>::Cast(info[0]->ToObject())); if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetPoint1WorldPosition( (double *)(a0->Buffer()->GetContents().Data()) ); return; } else if(info.Length() > 0 && info[0]->IsArray()) { v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject())); double b0[3]; if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } for( i = 0; i < 3; i++ ) { if( !a0->Get(i)->IsNumber() ) { Nan::ThrowError("Array contents invalid."); return; } b0[i] = a0->Get(i)->NumberValue(); } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetPoint1WorldPosition( b0 ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkAngleRepresentation3DWrap::SetPoint2DisplayPosition(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAngleRepresentation3DWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentation3DWrap>(info.Holder()); vtkAngleRepresentation3D *native = (vtkAngleRepresentation3D *)wrapper->native.GetPointer(); size_t i; if(info.Length() > 0 && info[0]->IsFloat64Array()) { v8::Local<v8::Float64Array>a0(v8::Local<v8::Float64Array>::Cast(info[0]->ToObject())); if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetPoint2DisplayPosition( (double *)(a0->Buffer()->GetContents().Data()) ); return; } else if(info.Length() > 0 && info[0]->IsArray()) { v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject())); double b0[3]; if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } for( i = 0; i < 3; i++ ) { if( !a0->Get(i)->IsNumber() ) { Nan::ThrowError("Array contents invalid."); return; } b0[i] = a0->Get(i)->NumberValue(); } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetPoint2DisplayPosition( b0 ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkAngleRepresentation3DWrap::SetPoint2WorldPosition(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAngleRepresentation3DWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentation3DWrap>(info.Holder()); vtkAngleRepresentation3D *native = (vtkAngleRepresentation3D *)wrapper->native.GetPointer(); size_t i; if(info.Length() > 0 && info[0]->IsFloat64Array()) { v8::Local<v8::Float64Array>a0(v8::Local<v8::Float64Array>::Cast(info[0]->ToObject())); if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetPoint2WorldPosition( (double *)(a0->Buffer()->GetContents().Data()) ); return; } else if(info.Length() > 0 && info[0]->IsArray()) { v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject())); double b0[3]; if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } for( i = 0; i < 3; i++ ) { if( !a0->Get(i)->IsNumber() ) { Nan::ThrowError("Array contents invalid."); return; } b0[i] = a0->Get(i)->NumberValue(); } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetPoint2WorldPosition( b0 ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkAngleRepresentation3DWrap::SetTextActorScale(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkAngleRepresentation3DWrap *wrapper = ObjectWrap::Unwrap<VtkAngleRepresentation3DWrap>(info.Holder()); vtkAngleRepresentation3D *native = (vtkAngleRepresentation3D *)wrapper->native.GetPointer(); size_t i; if(info.Length() > 0 && info[0]->IsFloat64Array()) { v8::Local<v8::Float64Array>a0(v8::Local<v8::Float64Array>::Cast(info[0]->ToObject())); if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetTextActorScale( (double *)(a0->Buffer()->GetContents().Data()) ); return; } else if(info.Length() > 0 && info[0]->IsArray()) { v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject())); double b0[3]; if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } for( i = 0; i < 3; i++ ) { if( !a0->Get(i)->IsNumber() ) { Nan::ThrowError("Array contents invalid."); return; } b0[i] = a0->Get(i)->NumberValue(); } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetTextActorScale( b0 ); return; } Nan::ThrowError("Parameter mismatch"); }
[ "axkibe@gmail.com" ]
axkibe@gmail.com
99e02260f10d7ce0d7558bd3bc4741b2f177a5c7
62d17c9ad5f76eeff61a806eded4147c2d994dbe
/GETPATH/Coarse-lock/main-10-90.cpp
75fef19b422dcfc7516afcb31f157757b5bc073c
[ "MIT" ]
permissive
chandra3000/ConcurrentGraphDS
89a54788a0c8fbb75dc1ca6677df7f16ab6d4c7e
129280de9866e186de628995542f74f3e167169d
refs/heads/master
2023-05-11T14:06:09.703420
2019-05-30T09:52:19
2019-05-30T09:52:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,535
cpp
/* * File:main-10-90.cpp * * * Author(s): * Bapi Chatterjee <bapchatt@in.ibm.com> * Sathya Peri <sathya_p@iith.ac.in> * Muktikanta Sa <cs15resch11012@iith.ac.in> * Nandini Singhal <cs15mtech01004@iith.ac.in> * * Description: * implementation of a Coarse Graph GetPath * Copyright (c) 2018. * last Updated: 31/07/2018 * */ #include"CoarseGraphGetPath.cpp" //ofstream couttt("graphinput.txt"); typedef struct { int secs; int usecs; }TIME_DIFF; TIME_DIFF * my_difftime (struct timeval * start, struct timeval * end) { TIME_DIFF * diff = (TIME_DIFF *) malloc ( sizeof (TIME_DIFF) ); if (start->tv_sec == end->tv_sec) { diff->secs = 0; diff->usecs = end->tv_usec - start->tv_usec; } else { diff->usecs = 1000000 - start->tv_usec; diff->secs = end->tv_sec - (start->tv_sec + 1); diff->usecs += end->tv_usec; if (diff->usecs >= 1000000) { diff->usecs -= 1000000; diff->secs += 1; } } return diff; } atomic<long> vertexID; double seconds; struct timeval tv1, tv2; TIME_DIFF * difference; int NTHREADS, ops; typedef struct infothread{ long tid; slist G; }tinfo; void* pthread_call(void* t) { tinfo *ti=(tinfo*)t; long Tid = ti->tid; slist G1=ti->G; int u, v;; while(true) { gettimeofday(&tv2,NULL); difference = my_difftime (&tv1, &tv2); if(difference->secs >= seconds) break; int op = rand()%1000; if(op >= 0 && op < 20 ) { l1: u = rand()% vertexID +1; v = rand()% vertexID +1; if(u == v || u == 0 || v == 0) goto l1; pthread_mutex_lock(&lock); G1.GetPath(u,v, Tid); ops++; pthread_mutex_unlock(&lock); } else if(op >= 20 && op < 245 ) { pthread_mutex_lock(&lock); vertexID++; l: v = rand() % (vertexID); if(v == 0) goto l; G1.AddV(v,NTHREADS); ops++; pthread_mutex_unlock(&lock); } else if(op >= 245 && op <470 ) { l2: v = rand() % (vertexID)+1; if(v == 0) goto l2; pthread_mutex_lock(&lock); G1.RemoveV(v); ops++; pthread_mutex_unlock(&lock); } else if(op >= 470 && op < 695 ) { l3: u = (rand() % (vertexID))+1; v = (rand() % (vertexID))+1; if(u == v || u == 0 || v == 0) goto l3; pthread_mutex_lock(&lock); G1.RemoveE(u,v); ops++; pthread_mutex_unlock(&lock); } else if(op >= 695 && op <920 ) { l4: u = (rand() % (vertexID))+1; v = (rand() % (vertexID))+1; if(u == v || u == 0 || v == 0) goto l4; pthread_mutex_lock(&lock); G1.AddE(u,v); ops++; pthread_mutex_unlock(&lock); } else if(op >= 920 && op < 960 ) { l5: u = (rand() % (vertexID))+1; v = (rand() % (vertexID))+1; if(u == v || u == 0 || v == 0) goto l5; pthread_mutex_lock(&lock); G1.ContainsE(u,v); ops++; pthread_mutex_unlock(&lock); } else if(op >= 960 && op < 1000 ) { l6: v = rand() % (vertexID); if(v == 0) goto l6; pthread_mutex_lock(&lock); G1.ContainsV(v); ops++; pthread_mutex_unlock(&lock); } } } int main(int argc, char*argv[]) { slist sg; vertexID.store(1); int i; if(argc < 3) { cout << "Enter 3 command line arguments - #threads, #vertices initially, #time in seconds" << endl; return 0; } NTHREADS = atoi(argv[1]); int initial_vertices = atoi(argv[2]); seconds = atoi(argv[3]); ops = 0; vertexID.store(initial_vertices + 1); sg.init(); sg.initGraph(initial_vertices, NTHREADS); cout << "Number of Threads: " << NTHREADS << endl; cout << "Initial graph with " << initial_vertices << " created." << endl; pthread_t *thr = new pthread_t[NTHREADS]; pthread_attr_t attr; pthread_attr_init (&attr); pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_JOINABLE); int dig,temp; double duration = 0.0; gettimeofday(&tv1,NULL); cout << "timer started . . ." << endl; for (i=0;i < NTHREADS;i++) { tinfo *t =(tinfo*) malloc(sizeof(tinfo)); t->tid = i; t->G = sg; pthread_create(&thr[i], &attr, pthread_call, (void*)t); } for (i = 0; i < NTHREADS; i++) { pthread_join(thr[i], NULL); } cout << seconds << " seconds elapsed" << endl; cout << "Total operations: " << ops <<endl; return 0; }
[ "cs15resch11012@iith.ac.in" ]
cs15resch11012@iith.ac.in
b3e175dd019d5281740d9eb82df7153d93f34e06
640a23b3d5270f64e42fee279da4d3c66dec1bf5
/cpp/online_judge/leetcode/editor/cn/平衡二叉树.cpp
39ba4a953ed943482bb7d865c2f02e510e57b95f
[]
no_license
f20500909/study_note
82bc7f3d80e5c0684e4659fa5d4ac08a903b3757
09181332565479016aa9067c68769d3bcd40a6ab
refs/heads/master
2022-07-31T22:28:28.897562
2020-05-11T10:41:41
2020-05-11T10:41:41
228,950,706
0
0
null
null
null
null
UTF-8
C++
false
false
1,456
cpp
//给定一个二叉树,判断它是否是高度平衡的二叉树。 // // 本题中,一棵高度平衡二叉树定义为: // // // 一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。 // // // 示例 1: // // 给定二叉树 [3,9,20,null,null,15,7] // // 3 // / \ // 9 20 // / \ // 15 7 // // 返回 true 。 // //示例 2: // // 给定二叉树 [1,2,2,3,3,null,null,4,4] // // 1 // / \ // 2 2 // / \ // 3 3 // / \ // 4 4 // // // 返回 false 。 // // // Related Topics 树 深度优先搜索 //leetcode submit region begin(Prohibit modification and deletion) /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int getHeight(TreeNode *root) { if (!root) return 0; int leftHeight = getHeight(root->left); int rightHeight = getHeight(root->right); return max(leftHeight, rightHeight) + 1; } bool isBalanced(TreeNode *root) { if (!root) return true; int leftHeight = getHeight(root->left); int rightHeight = getHeight(root->right); return (abs(leftHeight - rightHeight) <= 1) && isBalanced(root->left) && isBalanced(root->right); } }; //leetcode submit region end(Prohibit modification and deletion)
[ "3213377511@qq.com" ]
3213377511@qq.com
4d5cf995b60805d6ea2778619c1b28eb68460805
91e8b2d251505d4af333438faecbb8a1aaf4d325
/归并排序 递归实现.cpp
3c2801b843c405c8487b6f9bf7acf31228b7ac08
[]
no_license
buwanqf/Algorithm
97f45078a413bf04f02762aeb497d005a853ded4
f1b4faa30dcd5ea496037e2d4a85ff2fd334c9ce
refs/heads/master
2020-05-05T08:16:21.895305
2018-11-11T06:47:35
2018-11-11T06:47:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
710
cpp
#include <stdio.h> const int MAX=110; int A[MAX],temp[MAX]; void Merge(int L1,int R1,int L2,int R2); void MergeSort(int L,int R); int main(){ int n; scanf("%d",&n); for(int i=0;i<n;i++) scanf("%d",&A[i]); MergeSort(0,n-1); for(int i=0;i<n;i++) printf("%d ",A[i]); return 0; } void MergeSort(int L,int R){ if(L<R){ int mid=L+(R-L)/2; MergeSort(L,mid); MergeSort(mid+1,R); Merge(L,mid,mid+1,R); } } void Merge(int L1,int R1,int L2,int R2){ int index=0; int i=L1; int j=L2; while(i<=R1 && j<=R2){ if(A[i]<=A[j]) temp[index++]=A[i++]; else temp[index++]=A[j++]; } while(i<=R1) temp[index++]=A[i++]; while(j<=R2) temp[index++]=A[j++]; for(int i=0;i<index;i++) A[L1+i]=temp[i]; }
[ "18842556043@163.com" ]
18842556043@163.com
64e9821b74939bb2c58894af9ee75faa7caa2d50
43452fbcbe43bda467cd24e5f161c93535bc2bd5
/src/fretalon/framework/src/MGUIMainFretalon.cxx
2fbba4277b72fb074ac5eb4ff1344e7f02ee5872
[]
no_license
xtsinghua/megalib
cae2e256ad5ddf9d7b6cdb9d2b680a76dd902e4f
0bd5c161c606c32a642efb34a963b6e2c07b81a0
refs/heads/master
2021-01-11T05:46:51.442857
2015-04-15T17:56:22
2015-04-15T17:56:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,286
cxx
/* * MGUIMainFretalon.cxx * * * Copyright (C) by Andreas Zoglauer. * All rights reserved. * * * This code implementation is the intellectual property of * Andreas Zoglauer. * * By copying, distributing or modifying the Program (or any work * based on the Program) you indicate your acceptance of this statement, * and all its terms. * */ // Include the header: #include "MGUIMainFretalon.h" // Standard libs: // ROOT libs: #include <KeySymbols.h> #include <TApplication.h> #include <TGPicture.h> #include <TStyle.h> #include <TGButton.h> #include <TGLabel.h> #include <TGWindow.h> #include <TGFrame.h> #include <TGClient.h> #include <TGResourcePool.h> // MEGAlib libs: #include "MStreams.h" #include "MGUIDefaults.h" #include "MGUIAbout.h" #include "MGUIGeometry.h" #include "MGUIModuleSelector.h" #include "MGUIEFileSelector.h" // Nuclearizer libs: #include "MModule.h" //////////////////////////////////////////////////////////////////////////////// #ifdef ___CINT___ ClassImp(MGUIMainFretalon) #endif //////////////////////////////////////////////////////////////////////////////// MGUIMainFretalon::MGUIMainFretalon(MSupervisor* Supervisor) : TGMainFrame(gClient->GetRoot(), 350, 300, kVerticalFrame), m_Supervisor(Supervisor) { gStyle->SetPalette(1, 0); // use hierarchical cleaning SetCleanup(kDeepCleanup); BindKey(this, gVirtualX->KeysymToKeycode(kKey_L), kAnyModifier); BindKey(this, gVirtualX->KeysymToKeycode(kKey_S), kAnyModifier); BindKey(this, gVirtualX->KeysymToKeycode(kKey_E), kAnyModifier); BindKey(this, gVirtualX->KeysymToKeycode(kKey_Return), kAnyModifier); BindKey(this, gVirtualX->KeysymToKeycode(kKey_Enter), kAnyModifier); BindKey(this, gVirtualX->KeysymToKeycode(kKey_Escape), kAnyModifier); m_ProgramName = "Unnamed program"; m_PicturePath = ""; m_SubTitle = "No sub title set!"; m_LeadAuthor = "No lead author"; } //////////////////////////////////////////////////////////////////////////////// MGUIMainFretalon::~MGUIMainFretalon() { // Deep Cleanup automatically deletes all used GUI elements } //////////////////////////////////////////////////////////////////////////////// void MGUIMainFretalon::Create() { // Create the main window // We start with a name and an icon... SetWindowName(m_ProgramName); double FontScaler = MGUIDefaults::GetInstance()->GetFontScaler(); // In the beginning we build the menus and define their layout, ... TGLayoutHints* MenuBarItemLayoutLeft = new TGLayoutHints(kLHintsTop | kLHintsLeft, 0, 0, 0, 0); //TGLayoutHints* MenuBarItemLayoutRight = new TGLayoutHints(kLHintsTop | kLHintsRight, 0, 0, 0, 0); // We continue with the menu bar and its layout ... TGLayoutHints* MenuBarLayout = new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsExpandX, 0, 0, 0, 0); TGMenuBar* MenuBar = new TGMenuBar(this, 1, 1, kHorizontalFrame | kRaisedFrame); AddFrame(MenuBar, MenuBarLayout); TGPopupMenu* MenuOptions = new TGPopupMenu(gClient->GetRoot()); MenuOptions->AddLabel("Configuration file"); MenuOptions->AddEntry("Open", c_LoadConfig); MenuOptions->AddEntry("Save As", c_SaveConfig); MenuOptions->AddSeparator(); MString Geo = MString("Geometry file"); if (m_Supervisor->GetGeometry() != 0) { Geo += " (current: "; Geo += m_Supervisor->GetGeometry()->GetName(); Geo += ")"; } MenuOptions->AddLabel(Geo); MenuOptions->AddEntry("Open", c_Geometry); MenuOptions->AddSeparator(); MenuOptions->AddEntry("Exit", c_Exit); MenuOptions->Associate(this); MenuBar->AddPopup("Options", MenuOptions, MenuBarItemLayoutLeft); TGPopupMenu* MenuInfo = new TGPopupMenu(fClient->GetRoot()); MenuInfo->AddEntry("About", c_About); MenuInfo->Associate(this); MenuBar->AddPopup("Info", MenuInfo, MenuBarItemLayoutLeft); // Main label bool PictureFound = false; if (m_PicturePath != "") { MFile::ExpandFileName(m_PicturePath); TGLayoutHints* TitleIconLayout = new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsCenterX, 0, 0, 10*FontScaler, 0); if (MFile::Exists(m_PicturePath) == true) { const TGPicture* TitlePicture = fClient->GetPicture(m_PicturePath, FontScaler*300, FontScaler*300/5); if (TitlePicture == 0) { mout<<"Can't find picture \""<<m_PicturePath<<"\"! Aborting!"<<endl; } else { TGIcon* TitleIcon = new TGIcon(this, TitlePicture, TitlePicture->GetWidth()+2, TitlePicture->GetHeight()+2); AddFrame(TitleIcon, TitleIconLayout); PictureFound = true; } } } if (PictureFound == false) { //mout<<"Can't find picture "<<m_PicturePath<<"! Using text!"<<endl; const TGFont* lFont = gClient->GetFont("-*-helvetica-bold-r-*-*-48-*-*-*-*-*-iso8859-1"); if (!lFont) lFont = gClient->GetResourcePool()->GetDefaultFont(); FontStruct_t LargeFont = lFont->GetFontStruct(); TGLabel* MainLabel = new TGLabel(this, m_ProgramName); MainLabel->SetTextFont(LargeFont); TGLayoutHints* MainLabelLayout = new TGLayoutHints(kLHintsTop | kLHintsCenterX | kLHintsExpandX, 0, 0, 20*FontScaler, 0); AddFrame(MainLabel, MainLabelLayout); } // Sub-title FontStruct_t ItalicFont = MGUIDefaults::GetInstance()->GetItalicMediumFont()->GetFontStruct(); TGLabel* SubTitle = new TGLabel(this, m_SubTitle); SubTitle->SetTextFont(ItalicFont); TGLayoutHints* SubTitleLayout = new TGLayoutHints(kLHintsTop | kLHintsCenterX | kLHintsExpandX, 0, 0, 0, 12*FontScaler); AddFrame(SubTitle, SubTitleLayout); // Modules TGLabel* ChooseLabel = new TGLabel(this, "Choose the module sequence for your detector setup:"); TGLayoutHints* ChooseLayout = new TGLayoutHints(kLHintsTop | kLHintsLeft, 20*FontScaler, 20*FontScaler, 20*FontScaler, 5*FontScaler); AddFrame(ChooseLabel, ChooseLayout); m_ModuleFrame = new TGVerticalFrame(this); TGLayoutHints* SectionLayout = new TGLayoutHints(kLHintsTop | kLHintsCenterX | kLHintsExpandX, 40*FontScaler, 20*FontScaler, 0, 10*FontScaler); AddFrame(m_ModuleFrame, SectionLayout); m_ModuleLayout = new TGLayoutHints(kLHintsTop | kLHintsCenterX | kLHintsExpandX, 0, 0, 3*FontScaler, 3*FontScaler); UpdateModules(); // Start & Exit buttons // Frame around the buttons: TGHorizontalFrame* ButtonFrame = new TGHorizontalFrame(this, 150, 25); TGLayoutHints* ButtonFrameLayout = new TGLayoutHints(kLHintsBottom | kLHintsExpandX | kLHintsCenterX, 20*FontScaler, 20*FontScaler, 20*FontScaler, 10*FontScaler); AddFrame(ButtonFrame, ButtonFrameLayout); // The buttons itself TGTextButton* StartButton = new TGTextButton(ButtonFrame, "Start", c_Start); StartButton->Associate(this); TGLayoutHints* StartButtonLayout = new TGLayoutHints(kLHintsTop | kLHintsRight | kLHintsExpandX, 40*FontScaler, 0, 0, 0); ButtonFrame->AddFrame(StartButton, StartButtonLayout); TGTextButton* ViewButton = new TGTextButton(ButtonFrame, " View ", c_View); ViewButton->Associate(this); TGLayoutHints* ViewButtonLayout = new TGLayoutHints(kLHintsTop | kLHintsLeft, 0, 0, 0, 0); ButtonFrame->AddFrame(ViewButton, ViewButtonLayout); TGTextButton* StopButton = new TGTextButton(ButtonFrame, " Stop ", c_Stop); StopButton->Associate(this); TGLayoutHints* StopButtonLayout = new TGLayoutHints(kLHintsTop | kLHintsLeft, 20*FontScaler, 0, 0, 0); ButtonFrame->AddFrame(StopButton, StopButtonLayout); // Give this element the default size of its content: Resize(GetDefaultWidth(), GetDefaultHeight()); MapSubwindows(); MapWindow(); Layout(); return; } //////////////////////////////////////////////////////////////////////////////// void MGUIMainFretalon::UpdateModules() { // Remove all existing modules: m_ModuleFrame->RemoveAll(); m_ModuleFrame->Resize(); for (unsigned int m = m_Modules.size()-1; m < m_Modules.size(); --m) { //m_ModuleFrame->RemoveFrame(m_Modules[m]); //m_Modules[m]->UnmapWindow(); delete m_Modules[m]; } m_Modules.clear(); for (unsigned int m = 0; m < m_Supervisor->GetNModules(); ++m) { MGUIEModule* GuiModule = new MGUIEModule(m_ModuleFrame, m, m_Supervisor->GetModule(m)); GuiModule->Associate(this); m_ModuleFrame->AddFrame(GuiModule, m_ModuleLayout); m_Modules.push_back(GuiModule); } if (m_Supervisor->GetNModules() == 0 || m_Supervisor->GetModule(m_Supervisor->GetNModules()-1)->GetNSucceedingModuleTypes() > 0) { MGUIEModule* GuiModule = new MGUIEModule(m_ModuleFrame, m_Supervisor->GetNModules()); GuiModule->Associate(this); m_ModuleFrame->AddFrame(GuiModule, m_ModuleLayout); m_Modules.push_back(GuiModule); } //Resize(GetDefaultWidth(), GetDefaultHeight()); m_ModuleFrame->Resize(); Resize(); MapSubwindows(); MapWindow(); Layout(); } //////////////////////////////////////////////////////////////////////////////// bool MGUIMainFretalon::HandleKey(Event_t* Event) { // Here we handle all keys... char tmp[10]; unsigned int keysym; // Test if we have a key release: if (Event->fType != kKeyRelease) return false; // First we get the key... gVirtualX->LookupString(Event, tmp, sizeof(tmp), keysym); // ... and than we do what we need to do... // The following keys need an initialized hardware switch ((EKeySym) keysym) { case kKey_Escape: OnExit(); break; case kKey_Return: case kKey_Enter: OnStart(); break; case kKey_l: case kKey_L: OnLoadConfiguration(); break; case kKey_s: case kKey_S: OnSaveConfiguration(); break; default: break; } return true; } //////////////////////////////////////////////////////////////////////////////// bool MGUIMainFretalon::ProcessMessage(long Message, long Parameter1, long Parameter2) { // Process the messages for this application bool Status = true; switch (GET_MSG(Message)) { case kC_COMMAND: switch (GET_SUBMSG(Message)) { case kCM_BUTTON: if (Parameter1 >= c_Change && Parameter1 <= c_Change+99) { OnChange(Parameter1-c_Change); } else if (Parameter1 >= c_Remove && Parameter1 <= c_Remove+99) { OnRemove(Parameter1-c_Remove); } else if (Parameter1 >= c_Options && Parameter1 <= c_Options+99) { OnOptions(Parameter1-c_Options); } switch (Parameter1) { case c_Exit: Status = OnExit(); break; case c_Start: Status = OnStart(); break; case c_Stop: Status = OnStop(); break; case c_View: Status = OnView(); break; default: break; } case kCM_MENU: switch (Parameter1) { case c_LoadConfig: Status = OnLoadConfiguration(); break; case c_SaveConfig: Status = OnSaveConfiguration(); break; case c_Geometry: Status = OnGeometry(); break; case c_Exit: Status = OnExit(); break; case c_About: Status = OnAbout(); break; default: break; } default: break; } default: break; } return Status; } //////////////////////////////////////////////////////////////////////////////// void MGUIMainFretalon::CloseWindow() { // Call exit for controlled good-bye OnExit(); } //////////////////////////////////////////////////////////////////////////////// bool MGUIMainFretalon::OnChange(unsigned int ModuleID) { MGUIModuleSelector* S = new MGUIModuleSelector(m_Supervisor, ModuleID); gClient->WaitForUnmap(S); delete S; UpdateModules(); return true; } //////////////////////////////////////////////////////////////////////////////// bool MGUIMainFretalon::OnRemove(unsigned int ModuleID) { m_Supervisor->RemoveModule(ModuleID); UpdateModules(); return true; } //////////////////////////////////////////////////////////////////////////////// bool MGUIMainFretalon::OnOptions(unsigned int ModuleID) { if (m_Supervisor->GetModule(ModuleID) != 0) { m_Supervisor->GetModule(ModuleID)->ShowOptionsGUI(); return true; } cout<<"Warning: No module with ID: "<<ModuleID<<endl; return false; } //////////////////////////////////////////////////////////////////////////////// bool MGUIMainFretalon::OnExit() { OnApply(); m_Supervisor->Exit(); return true; } //////////////////////////////////////////////////////////////////////////////// bool MGUIMainFretalon::OnStart() { if (OnApply() == false) return false; m_Supervisor->Analyze(); return true; } //////////////////////////////////////////////////////////////////////////////// bool MGUIMainFretalon::OnStop() { if (OnApply() == false) return false; m_Supervisor->SetInterrupt(); return true; } //////////////////////////////////////////////////////////////////////////////// bool MGUIMainFretalon::OnView() { m_Supervisor->View(); return true; } //////////////////////////////////////////////////////////////////////////////// bool MGUIMainFretalon::OnApply() { /* if (MFile::Exists(m_FileSelectorLoad->GetFileName()) == false) { mgui<<"The data file \""<<m_FileSelectorLoad->GetFileName()<<"\" does not exist."<<show; return false; } */ /* if (MFile::Exists(m_FileSelectorGeometry->GetFileName()) == false) { mgui<<"The geometry file \""<<m_FileSelectorGeometry->GetFileName()<<"\" does not exist."<<show; return false; } */ /* m_Supervisor->SetLoadFileName(m_FileSelectorLoad->GetFileName()); m_Supervisor->SetSaveFileName(m_FileSelectorSave->GetFileName()); m_Supervisor->SetGeometryFileName(m_FileSelectorGeometry->GetFileName()); */ return true; } //////////////////////////////////////////////////////////////////////////////// bool MGUIMainFretalon::OnLoadConfiguration() { const char** Types = new const char*[4]; Types[0] = "Configuration file"; Types[1] = "*.cfg"; Types[2] = 0; Types[3] = 0; TGFileInfo Info; Info.fFileTypes = (const char **) Types; new TGFileDialog(gClient->GetRoot(), this, kFDOpen, &Info); // Get the filename ... if ((char *) Info.fFilename != 0) { m_Supervisor->Load(MString(Info.fFilename)); UpdateModules(); } return true; } //////////////////////////////////////////////////////////////////////////////// bool MGUIMainFretalon::OnSaveConfiguration() { // Save a configuration file... if (OnApply() == false) return false; const char** Types = new const char*[4]; Types[0] = "Configuration file"; Types[1] = "*.cfg"; Types[2] = 0; Types[3] = 0; TGFileInfo Info; Info.fFileTypes = (const char **) Types; //Info.fIniDir = StrDup(gSystem->DirName(m_Supervisor->GetCurrentFile())); new TGFileDialog(gClient->GetRoot(), this, kFDSave, &Info); // Get the filename ... if ((char *) Info.fFilename != 0) { m_Supervisor->Save(MString(Info.fFilename)); } return true; } //////////////////////////////////////////////////////////////////////////////// bool MGUIMainFretalon::OnGeometry() { // Show the geometry dialog // Returns the geometry file name MString Name = m_Supervisor->GetGeometryFileName(); MGUIGeometry* Geo = new MGUIGeometry(gClient->GetRoot(), gClient->GetRoot(), Name); gClient->WaitForUnmap(Geo); if (Geo->OkPressed() == true) { Name = Geo->GetGeometryFileName(); delete Geo; for (unsigned int i = 0; i < 100; ++i) { gSystem->ProcessEvents(); } m_Supervisor->SetGeometryFileName(Name); } return true; } //////////////////////////////////////////////////////////////////////////////// bool MGUIMainFretalon::OnAbout() { // Launch the about dialog MGUIAbout* About = new MGUIAbout(gClient->GetRoot(), this); About->SetProgramName(m_ProgramName); About->SetIconPath(m_PicturePath); About->SetLeadProgrammer(m_LeadAuthor); About->SetUpdates(""); if (m_CoAuthors != "") { About->SetProgrammers(m_CoAuthors); } About->SetCopyright("All rights reserved"); About->ShowReferencesTab(false); About->ShowPeopleTab(false); About->ShowBugsTab(false); About->ShowDisclaimerTab(false); About->Create(); return true; } // MGUIMainFretalon: the end... ////////////////////////////////////////////////////////////////////////////////
[ "andreas@megalibtoolkit.com" ]
andreas@megalibtoolkit.com
84dd452e644615db4490e3e67efb3d28444d9372
8f5220cab6e5b924d412d3d501dce8d0a9a02073
/AFactory/AFactory/FlyMovement.hpp
ec96b6dc92dca429cba4d1f5ca29cade9947b3c8
[]
no_license
Denis2613/kursach
f707285840265e43633c23336c63e3a88e3d6a51
b78bf3c9cfbbcb5adc19654ed457e2a0b4f5529e
refs/heads/master
2020-05-04T03:24:33.062537
2019-04-01T21:16:09
2019-04-01T21:16:09
178,940,907
0
0
null
null
null
null
UTF-8
C++
false
false
179
hpp
#pragma once #include "Movement.hpp" #include <string> //класс передвижения class FlyMovement: public Movement{ public: const char *Name(){return "Fly"; } };
[ "uvade98@mail.ru" ]
uvade98@mail.ru
1ba149307cab5069a36f379ec86b06fa69853c1d
df3f0c768464eded073c1d32fb835a86112beafa
/llvm/include/llvm/Analysis/TargetTransformInfoImpl.h
506c7f24c1ddc4f750da10e13dc85059e99e06a9
[ "BSD-2-Clause", "NCSA" ]
permissive
mitchty/ellcc-mirror
6d9e6fd45b8087f641ba556e659f9dad3fcd8066
b03a4afac74d50cf0987554b8c0cd8209bcb92a2
refs/heads/master
2021-01-10T06:47:27.028119
2015-10-19T11:36:17
2015-10-19T11:36:17
44,582,115
1
2
NOASSERTION
2020-03-07T21:40:07
2015-10-20T04:27:47
C
UTF-8
C++
false
false
17,743
h
//===- TargetTransformInfoImpl.h --------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// \file /// This file provides helpers for the implementation of /// a TargetTransformInfo-conforming class. /// //===----------------------------------------------------------------------===// #ifndef LLVM_ANALYSIS_TARGETTRANSFORMINFOIMPL_H #define LLVM_ANALYSIS_TARGETTRANSFORMINFOIMPL_H #include "llvm/Analysis/TargetTransformInfo.h" #include "llvm/IR/CallSite.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/Function.h" #include "llvm/IR/GetElementPtrTypeIterator.h" #include "llvm/IR/Operator.h" #include "llvm/IR/Type.h" namespace llvm { /// \brief Base class for use as a mix-in that aids implementing /// a TargetTransformInfo-compatible class. class TargetTransformInfoImplBase { protected: typedef TargetTransformInfo TTI; const DataLayout &DL; explicit TargetTransformInfoImplBase(const DataLayout &DL) : DL(DL) {} public: // Provide value semantics. MSVC requires that we spell all of these out. TargetTransformInfoImplBase(const TargetTransformInfoImplBase &Arg) : DL(Arg.DL) {} TargetTransformInfoImplBase(TargetTransformInfoImplBase &&Arg) : DL(Arg.DL) {} const DataLayout &getDataLayout() const { return DL; } unsigned getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy) { switch (Opcode) { default: // By default, just classify everything as 'basic'. return TTI::TCC_Basic; case Instruction::GetElementPtr: llvm_unreachable("Use getGEPCost for GEP operations!"); case Instruction::BitCast: assert(OpTy && "Cast instructions must provide the operand type"); if (Ty == OpTy || (Ty->isPointerTy() && OpTy->isPointerTy())) // Identity and pointer-to-pointer casts are free. return TTI::TCC_Free; // Otherwise, the default basic cost is used. return TTI::TCC_Basic; case Instruction::FDiv: case Instruction::FRem: case Instruction::SDiv: case Instruction::SRem: case Instruction::UDiv: case Instruction::URem: return TTI::TCC_Expensive; case Instruction::IntToPtr: { // An inttoptr cast is free so long as the input is a legal integer type // which doesn't contain values outside the range of a pointer. unsigned OpSize = OpTy->getScalarSizeInBits(); if (DL.isLegalInteger(OpSize) && OpSize <= DL.getPointerTypeSizeInBits(Ty)) return TTI::TCC_Free; // Otherwise it's not a no-op. return TTI::TCC_Basic; } case Instruction::PtrToInt: { // A ptrtoint cast is free so long as the result is large enough to store // the pointer, and a legal integer type. unsigned DestSize = Ty->getScalarSizeInBits(); if (DL.isLegalInteger(DestSize) && DestSize >= DL.getPointerTypeSizeInBits(OpTy)) return TTI::TCC_Free; // Otherwise it's not a no-op. return TTI::TCC_Basic; } case Instruction::Trunc: // trunc to a native type is free (assuming the target has compare and // shift-right of the same width). if (DL.isLegalInteger(DL.getTypeSizeInBits(Ty))) return TTI::TCC_Free; return TTI::TCC_Basic; } } unsigned getGEPCost(Type *PointeeType, const Value *Ptr, ArrayRef<const Value *> Operands) { // In the basic model, we just assume that all-constant GEPs will be folded // into their uses via addressing modes. for (unsigned Idx = 0, Size = Operands.size(); Idx != Size; ++Idx) if (!isa<Constant>(Operands[Idx])) return TTI::TCC_Basic; return TTI::TCC_Free; } unsigned getCallCost(FunctionType *FTy, int NumArgs) { assert(FTy && "FunctionType must be provided to this routine."); // The target-independent implementation just measures the size of the // function by approximating that each argument will take on average one // instruction to prepare. if (NumArgs < 0) // Set the argument number to the number of explicit arguments in the // function. NumArgs = FTy->getNumParams(); return TTI::TCC_Basic * (NumArgs + 1); } unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy, ArrayRef<Type *> ParamTys) { switch (IID) { default: // Intrinsics rarely (if ever) have normal argument setup constraints. // Model them as having a basic instruction cost. // FIXME: This is wrong for libc intrinsics. return TTI::TCC_Basic; case Intrinsic::annotation: case Intrinsic::assume: case Intrinsic::dbg_declare: case Intrinsic::dbg_value: case Intrinsic::invariant_start: case Intrinsic::invariant_end: case Intrinsic::lifetime_start: case Intrinsic::lifetime_end: case Intrinsic::objectsize: case Intrinsic::ptr_annotation: case Intrinsic::var_annotation: case Intrinsic::experimental_gc_result_int: case Intrinsic::experimental_gc_result_float: case Intrinsic::experimental_gc_result_ptr: case Intrinsic::experimental_gc_result: case Intrinsic::experimental_gc_relocate: // These intrinsics don't actually represent code after lowering. return TTI::TCC_Free; } } bool hasBranchDivergence() { return false; } bool isSourceOfDivergence(const Value *V) { return false; } bool isLoweredToCall(const Function *F) { // FIXME: These should almost certainly not be handled here, and instead // handled with the help of TLI or the target itself. This was largely // ported from existing analysis heuristics here so that such refactorings // can take place in the future. if (F->isIntrinsic()) return false; if (F->hasLocalLinkage() || !F->hasName()) return true; StringRef Name = F->getName(); // These will all likely lower to a single selection DAG node. if (Name == "copysign" || Name == "copysignf" || Name == "copysignl" || Name == "fabs" || Name == "fabsf" || Name == "fabsl" || Name == "sin" || Name == "fmin" || Name == "fminf" || Name == "fminl" || Name == "fmax" || Name == "fmaxf" || Name == "fmaxl" || Name == "sinf" || Name == "sinl" || Name == "cos" || Name == "cosf" || Name == "cosl" || Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl") return false; // These are all likely to be optimized into something smaller. if (Name == "pow" || Name == "powf" || Name == "powl" || Name == "exp2" || Name == "exp2l" || Name == "exp2f" || Name == "floor" || Name == "floorf" || Name == "ceil" || Name == "round" || Name == "ffs" || Name == "ffsl" || Name == "abs" || Name == "labs" || Name == "llabs") return false; return true; } void getUnrollingPreferences(Loop *, TTI::UnrollingPreferences &) {} bool isLegalAddImmediate(int64_t Imm) { return false; } bool isLegalICmpImmediate(int64_t Imm) { return false; } bool isLegalAddressingMode(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset, bool HasBaseReg, int64_t Scale, unsigned AddrSpace) { // Guess that only reg and reg+reg addressing is allowed. This heuristic is // taken from the implementation of LSR. return !BaseGV && BaseOffset == 0 && (Scale == 0 || Scale == 1); } bool isLegalMaskedStore(Type *DataType, int Consecutive) { return false; } bool isLegalMaskedLoad(Type *DataType, int Consecutive) { return false; } int getScalingFactorCost(Type *Ty, GlobalValue *BaseGV, int64_t BaseOffset, bool HasBaseReg, int64_t Scale, unsigned AddrSpace) { // Guess that all legal addressing mode are free. if (isLegalAddressingMode(Ty, BaseGV, BaseOffset, HasBaseReg, Scale, AddrSpace)) return 0; return -1; } bool isTruncateFree(Type *Ty1, Type *Ty2) { return false; } bool isZExtFree(Type *Ty1, Type *Ty2) { return false; } bool isProfitableToHoist(Instruction *I) { return true; } bool isTypeLegal(Type *Ty) { return false; } unsigned getJumpBufAlignment() { return 0; } unsigned getJumpBufSize() { return 0; } bool shouldBuildLookupTables() { return true; } bool enableAggressiveInterleaving(bool LoopHasReductions) { return false; } bool enableInterleavedAccessVectorization() { return false; } TTI::PopcntSupportKind getPopcntSupport(unsigned IntTyWidthInBit) { return TTI::PSK_Software; } bool haveFastSqrt(Type *Ty) { return false; } unsigned getFPOpCost(Type *Ty) { return TargetTransformInfo::TCC_Basic; } unsigned getIntImmCost(const APInt &Imm, Type *Ty) { return TTI::TCC_Basic; } unsigned getIntImmCost(unsigned Opcode, unsigned Idx, const APInt &Imm, Type *Ty) { return TTI::TCC_Free; } unsigned getIntImmCost(Intrinsic::ID IID, unsigned Idx, const APInt &Imm, Type *Ty) { return TTI::TCC_Free; } unsigned getNumberOfRegisters(bool Vector) { return 8; } unsigned getRegisterBitWidth(bool Vector) { return 32; } unsigned getMaxInterleaveFactor(unsigned VF) { return 1; } unsigned getArithmeticInstrCost(unsigned Opcode, Type *Ty, TTI::OperandValueKind Opd1Info, TTI::OperandValueKind Opd2Info, TTI::OperandValueProperties Opd1PropInfo, TTI::OperandValueProperties Opd2PropInfo) { return 1; } unsigned getShuffleCost(TTI::ShuffleKind Kind, Type *Ty, int Index, Type *SubTp) { return 1; } unsigned getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src) { return 1; } unsigned getCFInstrCost(unsigned Opcode) { return 1; } unsigned getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy) { return 1; } unsigned getVectorInstrCost(unsigned Opcode, Type *Val, unsigned Index) { return 1; } unsigned getMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment, unsigned AddressSpace) { return 1; } unsigned getMaskedMemoryOpCost(unsigned Opcode, Type *Src, unsigned Alignment, unsigned AddressSpace) { return 1; } unsigned getInterleavedMemoryOpCost(unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices, unsigned Alignment, unsigned AddressSpace) { return 1; } unsigned getIntrinsicInstrCost(Intrinsic::ID ID, Type *RetTy, ArrayRef<Type *> Tys) { return 1; } unsigned getCallInstrCost(Function *F, Type *RetTy, ArrayRef<Type *> Tys) { return 1; } unsigned getNumberOfParts(Type *Tp) { return 0; } unsigned getAddressComputationCost(Type *Tp, bool) { return 0; } unsigned getReductionCost(unsigned, Type *, bool) { return 1; } unsigned getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) { return 0; } bool getTgtMemIntrinsic(IntrinsicInst *Inst, MemIntrinsicInfo &Info) { return false; } Value *getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst, Type *ExpectedType) { return nullptr; } bool areInlineCompatible(const Function *Caller, const Function *Callee) const { return (Caller->getFnAttribute("target-cpu") == Callee->getFnAttribute("target-cpu")) && (Caller->getFnAttribute("target-features") == Callee->getFnAttribute("target-features")); } }; /// \brief CRTP base class for use as a mix-in that aids implementing /// a TargetTransformInfo-compatible class. template <typename T> class TargetTransformInfoImplCRTPBase : public TargetTransformInfoImplBase { private: typedef TargetTransformInfoImplBase BaseT; protected: explicit TargetTransformInfoImplCRTPBase(const DataLayout &DL) : BaseT(DL) {} public: // Provide value semantics. MSVC requires that we spell all of these out. TargetTransformInfoImplCRTPBase(const TargetTransformInfoImplCRTPBase &Arg) : BaseT(static_cast<const BaseT &>(Arg)) {} TargetTransformInfoImplCRTPBase(TargetTransformInfoImplCRTPBase &&Arg) : BaseT(std::move(static_cast<BaseT &>(Arg))) {} using BaseT::getCallCost; unsigned getCallCost(const Function *F, int NumArgs) { assert(F && "A concrete function must be provided to this routine."); if (NumArgs < 0) // Set the argument number to the number of explicit arguments in the // function. NumArgs = F->arg_size(); if (Intrinsic::ID IID = F->getIntrinsicID()) { FunctionType *FTy = F->getFunctionType(); SmallVector<Type *, 8> ParamTys(FTy->param_begin(), FTy->param_end()); return static_cast<T *>(this) ->getIntrinsicCost(IID, FTy->getReturnType(), ParamTys); } if (!static_cast<T *>(this)->isLoweredToCall(F)) return TTI::TCC_Basic; // Give a basic cost if it will be lowered // directly. return static_cast<T *>(this)->getCallCost(F->getFunctionType(), NumArgs); } unsigned getCallCost(const Function *F, ArrayRef<const Value *> Arguments) { // Simply delegate to generic handling of the call. // FIXME: We should use instsimplify or something else to catch calls which // will constant fold with these arguments. return static_cast<T *>(this)->getCallCost(F, Arguments.size()); } using BaseT::getGEPCost; unsigned getGEPCost(Type *PointeeType, const Value *Ptr, ArrayRef<const Value *> Operands) { const GlobalValue *BaseGV = nullptr; if (Ptr != nullptr) { // TODO: will remove this when pointers have an opaque type. assert(Ptr->getType()->getScalarType()->getPointerElementType() == PointeeType && "explicit pointee type doesn't match operand's pointee type"); BaseGV = dyn_cast<GlobalValue>(Ptr->stripPointerCasts()); } bool HasBaseReg = (BaseGV == nullptr); int64_t BaseOffset = 0; int64_t Scale = 0; // Assumes the address space is 0 when Ptr is nullptr. unsigned AS = (Ptr == nullptr ? 0 : Ptr->getType()->getPointerAddressSpace()); auto GTI = gep_type_begin(PointerType::get(PointeeType, AS), Operands); for (auto I = Operands.begin(); I != Operands.end(); ++I, ++GTI) { if (isa<SequentialType>(*GTI)) { int64_t ElementSize = DL.getTypeAllocSize(GTI.getIndexedType()); if (const ConstantInt *ConstIdx = dyn_cast<ConstantInt>(*I)) { BaseOffset += ConstIdx->getSExtValue() * ElementSize; } else { // Needs scale register. if (Scale != 0) { // No addressing mode takes two scale registers. return TTI::TCC_Basic; } Scale = ElementSize; } } else { StructType *STy = cast<StructType>(*GTI); uint64_t Field = cast<ConstantInt>(*I)->getZExtValue(); BaseOffset += DL.getStructLayout(STy)->getElementOffset(Field); } } if (static_cast<T *>(this)->isLegalAddressingMode( PointerType::get(*GTI, AS), const_cast<GlobalValue *>(BaseGV), BaseOffset, HasBaseReg, Scale, AS)) { return TTI::TCC_Free; } return TTI::TCC_Basic; } using BaseT::getIntrinsicCost; unsigned getIntrinsicCost(Intrinsic::ID IID, Type *RetTy, ArrayRef<const Value *> Arguments) { // Delegate to the generic intrinsic handling code. This mostly provides an // opportunity for targets to (for example) special case the cost of // certain intrinsics based on constants used as arguments. SmallVector<Type *, 8> ParamTys; ParamTys.reserve(Arguments.size()); for (unsigned Idx = 0, Size = Arguments.size(); Idx != Size; ++Idx) ParamTys.push_back(Arguments[Idx]->getType()); return static_cast<T *>(this)->getIntrinsicCost(IID, RetTy, ParamTys); } unsigned getUserCost(const User *U) { if (isa<PHINode>(U)) return TTI::TCC_Free; // Model all PHI nodes as free. if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) { SmallVector<Value *, 4> Indices(GEP->idx_begin(), GEP->idx_end()); return static_cast<T *>(this)->getGEPCost( GEP->getSourceElementType(), GEP->getPointerOperand(), Indices); } if (auto CS = ImmutableCallSite(U)) { const Function *F = CS.getCalledFunction(); if (!F) { // Just use the called value type. Type *FTy = CS.getCalledValue()->getType()->getPointerElementType(); return static_cast<T *>(this) ->getCallCost(cast<FunctionType>(FTy), CS.arg_size()); } SmallVector<const Value *, 8> Arguments(CS.arg_begin(), CS.arg_end()); return static_cast<T *>(this)->getCallCost(F, Arguments); } if (const CastInst *CI = dyn_cast<CastInst>(U)) { // Result of a cmp instruction is often extended (to be used by other // cmp instructions, logical or return instructions). These are usually // nop on most sane targets. if (isa<CmpInst>(CI->getOperand(0))) return TTI::TCC_Free; } return static_cast<T *>(this)->getOperationCost( Operator::getOpcode(U), U->getType(), U->getNumOperands() == 1 ? U->getOperand(0)->getType() : nullptr); } }; } #endif
[ "rich@82857169-6e38-49d7-aaa8-07fb558f12fc" ]
rich@82857169-6e38-49d7-aaa8-07fb558f12fc
cf6bf0fad4a8aa7c328bee016f38bb41bad6a574
e45adb4daabea0d0a2b96d5eccae52a236f0d265
/src/scripts/RaidsScripts/Raid_TheEye.cpp
a19d883343aa4af40d80447d718776c48a6366c2
[]
no_license
Refuge89/WoW-1
790a72d7a27b4fd19783bc032309ef7d02437521
d18b293f5548dae7b09ac5b56398a23c604a728d
refs/heads/master
2020-04-12T22:37:26.167417
2018-12-21T23:49:25
2018-12-21T23:49:25
162,793,929
1
0
null
2018-12-22T08:15:07
2018-12-22T08:15:06
null
UTF-8
C++
false
false
105,473
cpp
/* * ArcScripts for ArcEmu MMORPG Server * Copyright (C) 2009 ArcEmu Team <http://www.arcemu.org/> * Copyright (C) 2008-2009 Sun++ Team <http://www.sunscripting.com/> * Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/> * Copyright (C) 2007-2008 Moon++ Team <http://www.moonplusplus.info/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * 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, see <http://www.gnu.org/licenses/>. */ #include "Setup.h" /************************************************************************/ /* Raid_TheEye.cpp Script */ /************************************************************************/ /****************/ /* Trashes */ /****************/ // APPRENTICE STAR SCRYER #define CN_A_STAR_SCRYER 20043 #define ARCANE_VOLLEY 40424 #define A_STAR_ARCANE_EXPLOSION 27082 class AStarScryerAI : public CreatureAIScript { public: ADD_CREATURE_FACTORY_FUNCTION(AStarScryerAI); SP_AI_Spell spells[2]; bool m_spellcheck[2]; AStarScryerAI(Creature* pCreature) : CreatureAIScript(pCreature) { nrspells = 2; for(int i = 0; i < nrspells; i++) { m_spellcheck[i] = false; } spells[0].info = dbcSpell.LookupEntry(ARCANE_VOLLEY); spells[0].targettype = TARGET_VARIOUS; spells[0].instant = true; spells[0].cooldown = 15; spells[0].perctrigger = 50.0f; spells[0].attackstoptimer = 1000; spells[1].info = dbcSpell.LookupEntry(A_STAR_ARCANE_EXPLOSION); spells[1].targettype = TARGET_VARIOUS; spells[1].instant = true; spells[1].cooldown = 5; spells[1].perctrigger = 50.0f; spells[1].attackstoptimer = 1000; } void OnCombatStart(Unit* mTarget) { CastTime(); RegisterAIUpdateEvent(_unit->GetBaseAttackTime(MELEE)); } void CastTime() { for(int i = 0; i < nrspells; i++) spells[i].casttime = spells[i].cooldown; } void OnTargetDied(Unit* mTarget) { } void OnCombatStop(Unit* mTarget) { CastTime(); _unit->GetAIInterface()->setCurrentAgent(AGENT_NULL); _unit->GetAIInterface()->SetAIState(STATE_IDLE); RemoveAIUpdateEvent(); } void OnDied(Unit* mKiller) { CastTime(); RemoveAIUpdateEvent(); } void AIUpdate() { float val = RandomFloat(100.0f); SpellCast(val); } void SpellCast(float val) { if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->getNextTarget()) { float comulativeperc = 0; Unit* target = NULL; for(int i = 0; i < nrspells; i++) { if(!spells[i].perctrigger) continue; if(m_spellcheck[i]) { target = _unit->GetAIInterface()->getNextTarget(); switch(spells[i].targettype) { case TARGET_SELF: case TARGET_VARIOUS: _unit->CastSpell(_unit, spells[i].info, spells[i].instant); break; case TARGET_ATTACKING: _unit->CastSpell(target, spells[i].info, spells[i].instant); break; case TARGET_DESTINATION: _unit->CastSpellAoF(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), spells[i].info, spells[i].instant); break; case TARGET_RANDOM_FRIEND: case TARGET_RANDOM_SINGLE: case TARGET_RANDOM_DESTINATION: CastSpellOnRandomTarget(i, spells[i].mindist2cast, spells[i].maxdist2cast, spells[i].minhp2cast, spells[i].maxhp2cast); break; } m_spellcheck[i] = false; return; } uint32 t = (uint32)time(NULL); if(val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger) && t > spells[i].casttime) { _unit->setAttackTimer(spells[i].attackstoptimer, false); spells[i].casttime = t + spells[i].cooldown; m_spellcheck[i] = true; } comulativeperc += spells[i].perctrigger; } } } void CastSpellOnRandomTarget(uint32 i, float mindist2cast, float maxdist2cast, int minhp2cast, int maxhp2cast) { if(!maxdist2cast) maxdist2cast = 100.0f; if(!maxhp2cast) maxhp2cast = 100; if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->getNextTarget()) { std::vector<Unit*> TargetTable; /* From M4ksiu - Big THX to Capt who helped me with std stuff to make it simple and fully working <3 */ /* If anyone wants to use this function, then leave this note! */ for(set<Object*>::iterator itr = _unit->GetInRangeSetBegin(); itr != _unit->GetInRangeSetEnd(); ++itr) { if(((spells[i].targettype == TARGET_RANDOM_FRIEND && isFriendly(_unit, (*itr))) || (spells[i].targettype != TARGET_RANDOM_FRIEND && isHostile(_unit, (*itr)) && (*itr) != _unit)) && (*itr)->IsUnit()) // isAttackable(_unit, (*itr)) && { Unit* RandomTarget = NULL; RandomTarget = TO_UNIT(*itr); if(RandomTarget->isAlive() && _unit->GetDistance2dSq(RandomTarget) >= mindist2cast * mindist2cast && _unit->GetDistance2dSq(RandomTarget) <= maxdist2cast * maxdist2cast && ((RandomTarget->GetHealthPct() >= minhp2cast && RandomTarget->GetHealthPct() <= maxhp2cast && spells[i].targettype == TARGET_RANDOM_FRIEND) || (_unit->GetAIInterface()->getThreatByPtr(RandomTarget) > 0 && isHostile(_unit, RandomTarget)))) { TargetTable.push_back(RandomTarget); } } } if(_unit->GetHealthPct() >= minhp2cast && _unit->GetHealthPct() <= maxhp2cast && spells[i].targettype == TARGET_RANDOM_FRIEND) TargetTable.push_back(_unit); if(!TargetTable.size()) return; size_t RandTarget = rand() % TargetTable.size(); Unit* RTarget = TargetTable[RandTarget]; if(!RTarget) return; switch(spells[i].targettype) { case TARGET_RANDOM_FRIEND: case TARGET_RANDOM_SINGLE: _unit->CastSpell(RTarget, spells[i].info, spells[i].instant); break; case TARGET_RANDOM_DESTINATION: _unit->CastSpellAoF(RTarget->GetPositionX(), RTarget->GetPositionY(), RTarget->GetPositionZ(), spells[i].info, spells[i].instant); break; } TargetTable.clear(); } } protected: int nrspells; }; // STAR SCRYER #define CN_STAR_SCRYER 20034 #define STARFALL 37124 class StarScryerAI : public CreatureAIScript { public: ADD_CREATURE_FACTORY_FUNCTION(StarScryerAI); SP_AI_Spell spells[1]; bool m_spellcheck[1]; StarScryerAI(Creature* pCreature) : CreatureAIScript(pCreature) { nrspells = 1; for(int i = 0; i < nrspells; i++) { m_spellcheck[i] = false; } spells[0].info = dbcSpell.LookupEntry(STARFALL); spells[0].targettype = TARGET_RANDOM_SINGLE; spells[0].instant = true; spells[0].cooldown = 12; spells[0].perctrigger = 50.0f; spells[0].attackstoptimer = 1000; } void OnCombatStart(Unit* mTarget) { CastTime(); RegisterAIUpdateEvent(_unit->GetBaseAttackTime(MELEE)); } void CastTime() { for(int i = 0; i < nrspells; i++) spells[i].casttime = spells[i].cooldown; } void OnTargetDied(Unit* mTarget) { } void OnCombatStop(Unit* mTarget) { CastTime(); _unit->GetAIInterface()->setCurrentAgent(AGENT_NULL); _unit->GetAIInterface()->SetAIState(STATE_IDLE); RemoveAIUpdateEvent(); } void OnDied(Unit* mKiller) { CastTime(); RemoveAIUpdateEvent(); } void AIUpdate() { float val = RandomFloat(100.0f); SpellCast(val); } void SpellCast(float val) { if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->getNextTarget()) { float comulativeperc = 0; Unit* target = NULL; for(int i = 0; i < nrspells; i++) { if(!spells[i].perctrigger) continue; if(m_spellcheck[i]) { target = _unit->GetAIInterface()->getNextTarget(); switch(spells[i].targettype) { case TARGET_SELF: case TARGET_VARIOUS: _unit->CastSpell(_unit, spells[i].info, spells[i].instant); break; case TARGET_ATTACKING: _unit->CastSpell(target, spells[i].info, spells[i].instant); break; case TARGET_DESTINATION: _unit->CastSpellAoF(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), spells[i].info, spells[i].instant); break; case TARGET_RANDOM_FRIEND: case TARGET_RANDOM_SINGLE: case TARGET_RANDOM_DESTINATION: CastSpellOnRandomTarget(i, spells[i].mindist2cast, spells[i].maxdist2cast, spells[i].minhp2cast, spells[i].maxhp2cast); break; } m_spellcheck[i] = false; return; } uint32 t = (uint32)time(NULL); if(val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger) && t > spells[i].casttime) { _unit->setAttackTimer(spells[i].attackstoptimer, false); spells[i].casttime = t + spells[i].cooldown; m_spellcheck[i] = true; } comulativeperc += spells[i].perctrigger; } } } void CastSpellOnRandomTarget(uint32 i, float mindist2cast, float maxdist2cast, int minhp2cast, int maxhp2cast) { if(!maxdist2cast) maxdist2cast = 100.0f; if(!maxhp2cast) maxhp2cast = 100; if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->getNextTarget()) { std::vector<Unit*> TargetTable; /* From M4ksiu - Big THX to Capt who helped me with std stuff to make it simple and fully working <3 */ /* If anyone wants to use this function, then leave this note! */ for(set<Object*>::iterator itr = _unit->GetInRangeSetBegin(); itr != _unit->GetInRangeSetEnd(); ++itr) { if(((spells[i].targettype == TARGET_RANDOM_FRIEND && isFriendly(_unit, (*itr))) || (spells[i].targettype != TARGET_RANDOM_FRIEND && isHostile(_unit, (*itr)) && (*itr) != _unit)) && (*itr)->IsUnit()) // isAttackable(_unit, (*itr)) && { Unit* RandomTarget = NULL; RandomTarget = TO_UNIT(*itr); if(RandomTarget->isAlive() && _unit->GetDistance2dSq(RandomTarget) >= mindist2cast * mindist2cast && _unit->GetDistance2dSq(RandomTarget) <= maxdist2cast * maxdist2cast && ((RandomTarget->GetHealthPct() >= minhp2cast && RandomTarget->GetHealthPct() <= maxhp2cast && spells[i].targettype == TARGET_RANDOM_FRIEND) || (_unit->GetAIInterface()->getThreatByPtr(RandomTarget) > 0 && isHostile(_unit, RandomTarget)))) { TargetTable.push_back(RandomTarget); } } } if(_unit->GetHealthPct() >= minhp2cast && _unit->GetHealthPct() <= maxhp2cast && spells[i].targettype == TARGET_RANDOM_FRIEND) TargetTable.push_back(_unit); if(!TargetTable.size()) return; size_t RandTarget = rand() % TargetTable.size(); Unit* RTarget = TargetTable[RandTarget]; if(!RTarget) return; switch(spells[i].targettype) { case TARGET_RANDOM_FRIEND: case TARGET_RANDOM_SINGLE: _unit->CastSpell(RTarget, spells[i].info, spells[i].instant); break; case TARGET_RANDOM_DESTINATION: _unit->CastSpellAoF(RTarget->GetPositionX(), RTarget->GetPositionY(), RTarget->GetPositionZ(), spells[i].info, spells[i].instant); break; } TargetTable.clear(); } } protected: int nrspells; }; // ASTROMANCER #define CN_ASTROMANCER 20033 #define ASTROMANCER_FIREBALL 36971 #define ASTROMANCER_CONFLAGRATION 37018 #define ASTROMANCER_ARCANE_BURST 36970 class AstromancerAI : public MoonScriptCreatureAI { MOONSCRIPT_FACTORY_FUNCTION(AstromancerAI, MoonScriptCreatureAI); AstromancerAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature) { //spells mArcaneBurst = AddSpell(ASTROMANCER_ARCANE_BURST, Target_Self, 0, 0, 0, 0, 10); AddSpell(ASTROMANCER_FIREBALL, Target_Current, 75, 2, 0, 0, 35); AddSpell(ASTROMANCER_CONFLAGRATION, Target_RandomUnit, 25, 0, 0, 0, 30); mArcaneBurstTimer = -1; SetAIUpdateFreq(250); } void AIUpdate() { if(!IsCasting()) { if(mArcaneBurstTimer == -1 || IsTimerFinished(mArcaneBurstTimer)) { Unit* unit = GetBestUnitTarget(TargetFilter_Closest); if(unit && GetRangeToUnit(unit) <= 10.0f) { CastSpellNowNoScheduling(mArcaneBurst); if(mArcaneBurstTimer == -1) mArcaneBurstTimer = AddTimer(6000); else ResetTimer(mArcaneBurstTimer, 6000); ParentClass::AIUpdate(); return; } } } ParentClass::AIUpdate(); } SpellDesc* mArcaneBurst; int32 mArcaneBurstTimer; }; // ASTROMANCER LORD #define CN_ASTROMANCER_LORD 20046 #define A_LORD_FIREBALL_VOLLEY 29922 #define BLAST_WEAVE 33933 #define DRAGONS_BREATH 33043 class AstromancerLordAI : public CreatureAIScript { public: ADD_CREATURE_FACTORY_FUNCTION(AstromancerLordAI); SP_AI_Spell spells[3]; bool m_spellcheck[3]; AstromancerLordAI(Creature* pCreature) : CreatureAIScript(pCreature) { nrspells = 3; for(int i = 0; i < nrspells; i++) { m_spellcheck[i] = false; } spells[0].info = dbcSpell.LookupEntry(A_LORD_FIREBALL_VOLLEY); spells[0].targettype = TARGET_VARIOUS; spells[0].instant = false; spells[0].cooldown = 15; spells[0].perctrigger = 50.0f; spells[0].attackstoptimer = 1000; spells[1].info = dbcSpell.LookupEntry(BLAST_WEAVE); spells[1].targettype = TARGET_VARIOUS; spells[1].instant = true; spells[1].cooldown = 7; spells[1].perctrigger = 50.0f; spells[1].attackstoptimer = 1000; spells[2].info = dbcSpell.LookupEntry(DRAGONS_BREATH); spells[2].targettype = TARGET_ATTACKING; spells[2].instant = true; spells[2].cooldown = 10; spells[2].perctrigger = 50.0f; spells[2].attackstoptimer = 1000; } void OnCombatStart(Unit* mTarget) { CastTime(); RegisterAIUpdateEvent(_unit->GetBaseAttackTime(MELEE)); } void CastTime() { for(int i = 0; i < nrspells; i++) spells[i].casttime = spells[i].cooldown; } void OnTargetDied(Unit* mTarget) { } void OnCombatStop(Unit* mTarget) { CastTime(); _unit->GetAIInterface()->setCurrentAgent(AGENT_NULL); _unit->GetAIInterface()->SetAIState(STATE_IDLE); RemoveAIUpdateEvent(); } void OnDied(Unit* mKiller) { CastTime(); RemoveAIUpdateEvent(); } void AIUpdate() { float val = RandomFloat(100.0f); SpellCast(val); } void SpellCast(float val) { if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->getNextTarget()) { float comulativeperc = 0; Unit* target = NULL; for(int i = 0; i < nrspells; i++) { if(!spells[i].perctrigger) continue; if(m_spellcheck[i]) { target = _unit->GetAIInterface()->getNextTarget(); switch(spells[i].targettype) { case TARGET_SELF: case TARGET_VARIOUS: _unit->CastSpell(_unit, spells[i].info, spells[i].instant); break; case TARGET_ATTACKING: _unit->CastSpell(target, spells[i].info, spells[i].instant); break; case TARGET_DESTINATION: _unit->CastSpellAoF(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), spells[i].info, spells[i].instant); break; case TARGET_RANDOM_FRIEND: case TARGET_RANDOM_SINGLE: case TARGET_RANDOM_DESTINATION: CastSpellOnRandomTarget(i, spells[i].mindist2cast, spells[i].maxdist2cast, spells[i].minhp2cast, spells[i].maxhp2cast); break; } m_spellcheck[i] = false; return; } uint32 t = (uint32)time(NULL); if(val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger) && t > spells[i].casttime) { _unit->setAttackTimer(spells[i].attackstoptimer, false); spells[i].casttime = t + spells[i].cooldown; m_spellcheck[i] = true; } comulativeperc += spells[i].perctrigger; } } } void CastSpellOnRandomTarget(uint32 i, float mindist2cast, float maxdist2cast, int minhp2cast, int maxhp2cast) { if(!maxdist2cast) maxdist2cast = 100.0f; if(!maxhp2cast) maxhp2cast = 100; if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->getNextTarget()) { std::vector<Unit*> TargetTable; /* From M4ksiu - Big THX to Capt who helped me with std stuff to make it simple and fully working <3 */ /* If anyone wants to use this function, then leave this note! */ for(set<Object*>::iterator itr = _unit->GetInRangeSetBegin(); itr != _unit->GetInRangeSetEnd(); ++itr) { if(((spells[i].targettype == TARGET_RANDOM_FRIEND && isFriendly(_unit, (*itr))) || (spells[i].targettype != TARGET_RANDOM_FRIEND && isHostile(_unit, (*itr)) && (*itr) != _unit)) && (*itr)->IsUnit()) // isAttackable(_unit, (*itr)) && { Unit* RandomTarget = NULL; RandomTarget = TO_UNIT(*itr); if(RandomTarget->isAlive() && _unit->GetDistance2dSq(RandomTarget) >= mindist2cast * mindist2cast && _unit->GetDistance2dSq(RandomTarget) <= maxdist2cast * maxdist2cast && ((RandomTarget->GetHealthPct() >= minhp2cast && RandomTarget->GetHealthPct() <= maxhp2cast && spells[i].targettype == TARGET_RANDOM_FRIEND) || (_unit->GetAIInterface()->getThreatByPtr(RandomTarget) > 0 && isHostile(_unit, RandomTarget)))) { TargetTable.push_back(RandomTarget); } } } if(_unit->GetHealthPct() >= minhp2cast && _unit->GetHealthPct() <= maxhp2cast && spells[i].targettype == TARGET_RANDOM_FRIEND) TargetTable.push_back(_unit); if(!TargetTable.size()) return; size_t RandTarget = rand() % TargetTable.size(); Unit* RTarget = TargetTable[RandTarget]; if(!RTarget) return; switch(spells[i].targettype) { case TARGET_RANDOM_FRIEND: case TARGET_RANDOM_SINGLE: _unit->CastSpell(RTarget, spells[i].info, spells[i].instant); break; case TARGET_RANDOM_DESTINATION: _unit->CastSpellAoF(RTarget->GetPositionX(), RTarget->GetPositionY(), RTarget->GetPositionZ(), spells[i].info, spells[i].instant); break; } TargetTable.clear(); } } protected: int nrspells; }; // BLOODWARDER VINDICATOR #define CN_BLOOD_VINDICATOR 20032 #define HAMMER_OF_JUSTICE 32416 #define FLASH_HEAL 38588 class BloodVindicatorAI : public CreatureAIScript { public: ADD_CREATURE_FACTORY_FUNCTION(BloodVindicatorAI); SP_AI_Spell spells[2]; bool m_spellcheck[2]; BloodVindicatorAI(Creature* pCreature) : CreatureAIScript(pCreature) { nrspells = 2; for(int i = 0; i < nrspells; i++) { m_spellcheck[i] = false; } spells[0].info = dbcSpell.LookupEntry(HAMMER_OF_JUSTICE); spells[0].targettype = TARGET_ATTACKING; spells[0].instant = true; spells[0].cooldown = 10; spells[0].perctrigger = 50.0f; spells[0].attackstoptimer = 1000; spells[1].info = dbcSpell.LookupEntry(FLASH_HEAL); spells[1].targettype = TARGET_SELF; spells[1].instant = false; spells[1].cooldown = 15; spells[1].perctrigger = 50.0f; spells[1].attackstoptimer = 1000; } void OnCombatStart(Unit* mTarget) { CastTime(); RegisterAIUpdateEvent(_unit->GetBaseAttackTime(MELEE)); } void CastTime() { for(int i = 0; i < nrspells; i++) spells[i].casttime = spells[i].cooldown; } void OnTargetDied(Unit* mTarget) { } void OnCombatStop(Unit* mTarget) { CastTime(); _unit->GetAIInterface()->setCurrentAgent(AGENT_NULL); _unit->GetAIInterface()->SetAIState(STATE_IDLE); RemoveAIUpdateEvent(); } void OnDied(Unit* mKiller) { CastTime(); RemoveAIUpdateEvent(); } void AIUpdate() { float val = RandomFloat(100.0f); SpellCast(val); } void SpellCast(float val) { if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->getNextTarget()) { float comulativeperc = 0; Unit* target = NULL; for(int i = 0; i < nrspells; i++) { if(!spells[i].perctrigger) continue; if(m_spellcheck[i]) { target = _unit->GetAIInterface()->getNextTarget(); switch(spells[i].targettype) { case TARGET_SELF: case TARGET_VARIOUS: _unit->CastSpell(_unit, spells[i].info, spells[i].instant); break; case TARGET_ATTACKING: _unit->CastSpell(target, spells[i].info, spells[i].instant); break; case TARGET_DESTINATION: _unit->CastSpellAoF(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), spells[i].info, spells[i].instant); break; case TARGET_RANDOM_FRIEND: case TARGET_RANDOM_SINGLE: case TARGET_RANDOM_DESTINATION: CastSpellOnRandomTarget(i, spells[i].mindist2cast, spells[i].maxdist2cast, spells[i].minhp2cast, spells[i].maxhp2cast); break; } m_spellcheck[i] = false; return; } uint32 t = (uint32)time(NULL); if(val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger) && t > spells[i].casttime) { _unit->setAttackTimer(spells[i].attackstoptimer, false); spells[i].casttime = t + spells[i].cooldown; m_spellcheck[i] = true; } comulativeperc += spells[i].perctrigger; } } } void CastSpellOnRandomTarget(uint32 i, float mindist2cast, float maxdist2cast, int minhp2cast, int maxhp2cast) { if(!maxdist2cast) maxdist2cast = 100.0f; if(!maxhp2cast) maxhp2cast = 100; if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->getNextTarget()) { std::vector<Unit*> TargetTable; /* From M4ksiu - Big THX to Capt who helped me with std stuff to make it simple and fully working <3 */ /* If anyone wants to use this function, then leave this note! */ for(set<Object*>::iterator itr = _unit->GetInRangeSetBegin(); itr != _unit->GetInRangeSetEnd(); ++itr) { if(((spells[i].targettype == TARGET_RANDOM_FRIEND && isFriendly(_unit, (*itr))) || (spells[i].targettype != TARGET_RANDOM_FRIEND && isHostile(_unit, (*itr)) && (*itr) != _unit)) && (*itr)->IsUnit()) // isAttackable(_unit, (*itr)) && { Unit* RandomTarget = NULL; RandomTarget = TO_UNIT(*itr); if(RandomTarget->isAlive() && _unit->GetDistance2dSq(RandomTarget) >= mindist2cast * mindist2cast && _unit->GetDistance2dSq(RandomTarget) <= maxdist2cast * maxdist2cast && ((RandomTarget->GetHealthPct() >= minhp2cast && RandomTarget->GetHealthPct() <= maxhp2cast && spells[i].targettype == TARGET_RANDOM_FRIEND) || (_unit->GetAIInterface()->getThreatByPtr(RandomTarget) > 0 && isHostile(_unit, RandomTarget)))) { TargetTable.push_back(RandomTarget); } } } if(_unit->GetHealthPct() >= minhp2cast && _unit->GetHealthPct() <= maxhp2cast && spells[i].targettype == TARGET_RANDOM_FRIEND) TargetTable.push_back(_unit); if(!TargetTable.size()) return; size_t RandTarget = rand() % TargetTable.size(); Unit* RTarget = TargetTable[RandTarget]; if(!RTarget) return; switch(spells[i].targettype) { case TARGET_RANDOM_FRIEND: case TARGET_RANDOM_SINGLE: _unit->CastSpell(RTarget, spells[i].info, spells[i].instant); break; case TARGET_RANDOM_DESTINATION: _unit->CastSpellAoF(RTarget->GetPositionX(), RTarget->GetPositionY(), RTarget->GetPositionZ(), spells[i].info, spells[i].instant); break; } TargetTable.clear(); } } protected: int nrspells; }; // BLOODWARDER LEGIONNARE #define CN_BLOOD_LEGIONNARE 20031 #define LEGION_WHIRLWIND 36981 #define CLEAVE 26350 class BloodLegionnareAI : public CreatureAIScript { public: ADD_CREATURE_FACTORY_FUNCTION(BloodLegionnareAI); SP_AI_Spell spells[2]; bool m_spellcheck[2]; BloodLegionnareAI(Creature* pCreature) : CreatureAIScript(pCreature) { nrspells = 2; for(int i = 0; i < nrspells; i++) { m_spellcheck[i] = false; } spells[0].info = dbcSpell.LookupEntry(LEGION_WHIRLWIND); spells[0].targettype = TARGET_ATTACKING; spells[0].instant = true; spells[0].cooldown = 15; spells[0].perctrigger = 50.0f; spells[0].attackstoptimer = 1000; spells[1].info = dbcSpell.LookupEntry(CLEAVE); spells[1].targettype = TARGET_ATTACKING; spells[1].instant = true; spells[1].cooldown = 10; spells[1].perctrigger = 40.0f; spells[1].attackstoptimer = 1000; } void OnCombatStart(Unit* mTarget) { CastTime(); RegisterAIUpdateEvent(_unit->GetBaseAttackTime(MELEE)); } void CastTime() { for(int i = 0; i < nrspells; i++) spells[i].casttime = spells[i].cooldown; } void OnTargetDied(Unit* mTarget) { } void OnCombatStop(Unit* mTarget) { CastTime(); _unit->GetAIInterface()->setCurrentAgent(AGENT_NULL); _unit->GetAIInterface()->SetAIState(STATE_IDLE); RemoveAIUpdateEvent(); } void OnDied(Unit* mKiller) { CastTime(); RemoveAIUpdateEvent(); } void AIUpdate() { float val = RandomFloat(100.0f); SpellCast(val); } void SpellCast(float val) { if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->getNextTarget()) { float comulativeperc = 0; Unit* target = NULL; for(int i = 0; i < nrspells; i++) { if(!spells[i].perctrigger) continue; if(m_spellcheck[i]) { target = _unit->GetAIInterface()->getNextTarget(); switch(spells[i].targettype) { case TARGET_SELF: case TARGET_VARIOUS: _unit->CastSpell(_unit, spells[i].info, spells[i].instant); break; case TARGET_ATTACKING: _unit->CastSpell(target, spells[i].info, spells[i].instant); break; case TARGET_DESTINATION: _unit->CastSpellAoF(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), spells[i].info, spells[i].instant); break; case TARGET_RANDOM_FRIEND: case TARGET_RANDOM_SINGLE: case TARGET_RANDOM_DESTINATION: CastSpellOnRandomTarget(i, spells[i].mindist2cast, spells[i].maxdist2cast, spells[i].minhp2cast, spells[i].maxhp2cast); break; } m_spellcheck[i] = false; return; } uint32 t = (uint32)time(NULL); if(val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger) && t > spells[i].casttime) { _unit->setAttackTimer(spells[i].attackstoptimer, false); spells[i].casttime = t + spells[i].cooldown; m_spellcheck[i] = true; } comulativeperc += spells[i].perctrigger; } } } void CastSpellOnRandomTarget(uint32 i, float mindist2cast, float maxdist2cast, int minhp2cast, int maxhp2cast) { if(!maxdist2cast) maxdist2cast = 100.0f; if(!maxhp2cast) maxhp2cast = 100; if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->getNextTarget()) { std::vector<Unit*> TargetTable; /* From M4ksiu - Big THX to Capt who helped me with std stuff to make it simple and fully working <3 */ /* If anyone wants to use this function, then leave this note! */ for(set<Object*>::iterator itr = _unit->GetInRangeSetBegin(); itr != _unit->GetInRangeSetEnd(); ++itr) { if(((spells[i].targettype == TARGET_RANDOM_FRIEND && isFriendly(_unit, (*itr))) || (spells[i].targettype != TARGET_RANDOM_FRIEND && isHostile(_unit, (*itr)) && (*itr) != _unit)) && (*itr)->IsUnit()) // isAttackable(_unit, (*itr)) && { Unit* RandomTarget = NULL; RandomTarget = TO_UNIT(*itr); if(RandomTarget->isAlive() && _unit->GetDistance2dSq(RandomTarget) >= mindist2cast * mindist2cast && _unit->GetDistance2dSq(RandomTarget) <= maxdist2cast * maxdist2cast && ((RandomTarget->GetHealthPct() >= minhp2cast && RandomTarget->GetHealthPct() <= maxhp2cast && spells[i].targettype == TARGET_RANDOM_FRIEND) || (_unit->GetAIInterface()->getThreatByPtr(RandomTarget) > 0 && isHostile(_unit, RandomTarget)))) { TargetTable.push_back(RandomTarget); } } } if(_unit->GetHealthPct() >= minhp2cast && _unit->GetHealthPct() <= maxhp2cast && spells[i].targettype == TARGET_RANDOM_FRIEND) TargetTable.push_back(_unit); if(!TargetTable.size()) return; size_t RandTarget = rand() % TargetTable.size(); Unit* RTarget = TargetTable[RandTarget]; if(!RTarget) return; switch(spells[i].targettype) { case TARGET_RANDOM_FRIEND: case TARGET_RANDOM_SINGLE: _unit->CastSpell(RTarget, spells[i].info, spells[i].instant); break; case TARGET_RANDOM_DESTINATION: _unit->CastSpellAoF(RTarget->GetPositionX(), RTarget->GetPositionY(), RTarget->GetPositionZ(), spells[i].info, spells[i].instant); break; } TargetTable.clear(); } } protected: int nrspells; }; // BLOODWARDER MARSHAL #define CN_BLOOD_MARSHAL 20035 #define WHIRLWIND 36981 #define UPPERCUT 26007 class BloodMarshalAI : public CreatureAIScript { public: ADD_CREATURE_FACTORY_FUNCTION(BloodMarshalAI); SP_AI_Spell spells[2]; bool m_spellcheck[2]; BloodMarshalAI(Creature* pCreature) : CreatureAIScript(pCreature) { nrspells = 2; for(int i = 0; i < nrspells; i++) { m_spellcheck[i] = false; } spells[0].info = dbcSpell.LookupEntry(WHIRLWIND); spells[0].targettype = TARGET_ATTACKING; spells[0].instant = true; spells[0].cooldown = 15; spells[0].perctrigger = 50.0f; spells[0].attackstoptimer = 1000; spells[1].info = dbcSpell.LookupEntry(UPPERCUT); spells[1].targettype = TARGET_ATTACKING; spells[1].instant = true; spells[1].cooldown = 20; spells[1].perctrigger = 50.0f; spells[1].attackstoptimer = 1000; } void OnCombatStart(Unit* mTarget) { CastTime(); RegisterAIUpdateEvent(_unit->GetBaseAttackTime(MELEE)); } void CastTime() { for(int i = 0; i < nrspells; i++) spells[i].casttime = spells[i].cooldown; } void OnTargetDied(Unit* mTarget) { } void OnCombatStop(Unit* mTarget) { CastTime(); _unit->GetAIInterface()->setCurrentAgent(AGENT_NULL); _unit->GetAIInterface()->SetAIState(STATE_IDLE); RemoveAIUpdateEvent(); } void OnDied(Unit* mKiller) { CastTime(); RemoveAIUpdateEvent(); } void AIUpdate() { float val = RandomFloat(100.0f); SpellCast(val); } void SpellCast(float val) { if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->getNextTarget()) { float comulativeperc = 0; Unit* target = NULL; for(int i = 0; i < nrspells; i++) { if(!spells[i].perctrigger) continue; if(m_spellcheck[i]) { target = _unit->GetAIInterface()->getNextTarget(); switch(spells[i].targettype) { case TARGET_SELF: case TARGET_VARIOUS: _unit->CastSpell(_unit, spells[i].info, spells[i].instant); break; case TARGET_ATTACKING: _unit->CastSpell(target, spells[i].info, spells[i].instant); break; case TARGET_DESTINATION: _unit->CastSpellAoF(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), spells[i].info, spells[i].instant); break; case TARGET_RANDOM_FRIEND: case TARGET_RANDOM_SINGLE: case TARGET_RANDOM_DESTINATION: CastSpellOnRandomTarget(i, spells[i].mindist2cast, spells[i].maxdist2cast, spells[i].minhp2cast, spells[i].maxhp2cast); break; } m_spellcheck[i] = false; return; } uint32 t = (uint32)time(NULL); if(val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger) && t > spells[i].casttime) { _unit->setAttackTimer(spells[i].attackstoptimer, false); spells[i].casttime = t + spells[i].cooldown; m_spellcheck[i] = true; } comulativeperc += spells[i].perctrigger; } } } void CastSpellOnRandomTarget(uint32 i, float mindist2cast, float maxdist2cast, int minhp2cast, int maxhp2cast) { if(!maxdist2cast) maxdist2cast = 100.0f; if(!maxhp2cast) maxhp2cast = 100; if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->getNextTarget()) { std::vector<Unit*> TargetTable; /* From M4ksiu - Big THX to Capt who helped me with std stuff to make it simple and fully working <3 */ /* If anyone wants to use this function, then leave this note! */ for(set<Object*>::iterator itr = _unit->GetInRangeSetBegin(); itr != _unit->GetInRangeSetEnd(); ++itr) { if(((spells[i].targettype == TARGET_RANDOM_FRIEND && isFriendly(_unit, (*itr))) || (spells[i].targettype != TARGET_RANDOM_FRIEND && isHostile(_unit, (*itr)) && (*itr) != _unit)) && (*itr)->IsUnit()) // isAttackable(_unit, (*itr)) && { Unit* RandomTarget = NULL; RandomTarget = TO_UNIT(*itr); if(RandomTarget->isAlive() && _unit->GetDistance2dSq(RandomTarget) >= mindist2cast * mindist2cast && _unit->GetDistance2dSq(RandomTarget) <= maxdist2cast * maxdist2cast && ((RandomTarget->GetHealthPct() >= minhp2cast && RandomTarget->GetHealthPct() <= maxhp2cast && spells[i].targettype == TARGET_RANDOM_FRIEND) || (_unit->GetAIInterface()->getThreatByPtr(RandomTarget) > 0 && isHostile(_unit, RandomTarget)))) { TargetTable.push_back(RandomTarget); } } } if(_unit->GetHealthPct() >= minhp2cast && _unit->GetHealthPct() <= maxhp2cast && spells[i].targettype == TARGET_RANDOM_FRIEND) TargetTable.push_back(_unit); if(!TargetTable.size()) return; size_t RandTarget = rand() % TargetTable.size(); Unit* RTarget = TargetTable[RandTarget]; if(!RTarget) return; switch(spells[i].targettype) { case TARGET_RANDOM_FRIEND: case TARGET_RANDOM_SINGLE: _unit->CastSpell(RTarget, spells[i].info, spells[i].instant); break; case TARGET_RANDOM_DESTINATION: _unit->CastSpellAoF(RTarget->GetPositionX(), RTarget->GetPositionY(), RTarget->GetPositionZ(), spells[i].info, spells[i].instant); break; } TargetTable.clear(); } } protected: int nrspells; }; // PHOENIX HAWK #define CN_PHOENIX_HAWK 20039 #define MANA_BURN 25380 #define HAWK_CHARGE 16636 class PhoenixHawkAI : public CreatureAIScript { public: ADD_CREATURE_FACTORY_FUNCTION(PhoenixHawkAI); SP_AI_Spell spells[2]; bool m_spellcheck[2]; PhoenixHawkAI(Creature* pCreature) : CreatureAIScript(pCreature) { nrspells = 2; for(int i = 0; i < nrspells; i++) { m_spellcheck[i] = false; } spells[0].info = dbcSpell.LookupEntry(MANA_BURN); spells[0].targettype = TARGET_RANDOM_SINGLE; spells[0].instant = true; spells[0].cooldown = 15; spells[0].perctrigger = 50.0f; spells[0].attackstoptimer = 1000; spells[1].info = dbcSpell.LookupEntry(HAWK_CHARGE); spells[1].targettype = TARGET_RANDOM_SINGLE; spells[1].instant = true; spells[1].cooldown = 12; spells[1].perctrigger = 50.0f; spells[1].attackstoptimer = 1000; spells[1].mindist2cast = 15; spells[1].maxdist2cast = 45; } void OnCombatStart(Unit* mTarget) { CastTime(); RegisterAIUpdateEvent(_unit->GetBaseAttackTime(MELEE)); } void CastTime() { for(int i = 0; i < nrspells; i++) spells[i].casttime = spells[i].cooldown; } void OnTargetDied(Unit* mTarget) { } void OnCombatStop(Unit* mTarget) { CastTime(); _unit->GetAIInterface()->setCurrentAgent(AGENT_NULL); _unit->GetAIInterface()->SetAIState(STATE_IDLE); RemoveAIUpdateEvent(); } void OnDied(Unit* mKiller) { CastTime(); RemoveAIUpdateEvent(); } void AIUpdate() { float val = RandomFloat(100.0f); SpellCast(val); } void SpellCast(float val) { if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->getNextTarget()) { float comulativeperc = 0; Unit* target = NULL; for(int i = 0; i < nrspells; i++) { if(!spells[i].perctrigger) continue; if(m_spellcheck[i]) { target = _unit->GetAIInterface()->getNextTarget(); switch(spells[i].targettype) { case TARGET_SELF: case TARGET_VARIOUS: _unit->CastSpell(_unit, spells[i].info, spells[i].instant); break; case TARGET_ATTACKING: _unit->CastSpell(target, spells[i].info, spells[i].instant); break; case TARGET_DESTINATION: _unit->CastSpellAoF(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), spells[i].info, spells[i].instant); break; case TARGET_RANDOM_FRIEND: case TARGET_RANDOM_SINGLE: case TARGET_RANDOM_DESTINATION: CastSpellOnRandomTarget(i, spells[i].mindist2cast, spells[i].maxdist2cast, spells[i].minhp2cast, spells[i].maxhp2cast); break; } m_spellcheck[i] = false; return; } uint32 t = (uint32)time(NULL); if(val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger) && t > spells[i].casttime) { _unit->setAttackTimer(spells[i].attackstoptimer, false); spells[i].casttime = t + spells[i].cooldown; m_spellcheck[i] = true; } comulativeperc += spells[i].perctrigger; } } } void CastSpellOnRandomTarget(uint32 i, float mindist2cast, float maxdist2cast, int minhp2cast, int maxhp2cast) { if(!maxdist2cast) maxdist2cast = 100.0f; if(!maxhp2cast) maxhp2cast = 100; if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->getNextTarget()) { std::vector<Unit*> TargetTable; /* From M4ksiu - Big THX to Capt who helped me with std stuff to make it simple and fully working <3 */ /* If anyone wants to use this function, then leave this note! */ for(set<Object*>::iterator itr = _unit->GetInRangeSetBegin(); itr != _unit->GetInRangeSetEnd(); ++itr) { if(((spells[i].targettype == TARGET_RANDOM_FRIEND && isFriendly(_unit, (*itr))) || (spells[i].targettype != TARGET_RANDOM_FRIEND && isHostile(_unit, (*itr)) && (*itr) != _unit)) && (*itr)->IsUnit()) // isAttackable(_unit, (*itr)) && { Unit* RandomTarget = NULL; RandomTarget = TO_UNIT(*itr); if(RandomTarget->isAlive() && _unit->GetDistance2dSq(RandomTarget) >= mindist2cast * mindist2cast && _unit->GetDistance2dSq(RandomTarget) <= maxdist2cast * maxdist2cast && ((RandomTarget->GetHealthPct() >= minhp2cast && RandomTarget->GetHealthPct() <= maxhp2cast && spells[i].targettype == TARGET_RANDOM_FRIEND) || (_unit->GetAIInterface()->getThreatByPtr(RandomTarget) > 0 && isHostile(_unit, RandomTarget)))) { TargetTable.push_back(RandomTarget); } } } if(_unit->GetHealthPct() >= minhp2cast && _unit->GetHealthPct() <= maxhp2cast && spells[i].targettype == TARGET_RANDOM_FRIEND) TargetTable.push_back(_unit); if(!TargetTable.size()) return; size_t RandTarget = rand() % TargetTable.size(); Unit* RTarget = TargetTable[RandTarget]; if(!RTarget) return; switch(spells[i].targettype) { case TARGET_RANDOM_FRIEND: case TARGET_RANDOM_SINGLE: _unit->CastSpell(RTarget, spells[i].info, spells[i].instant); break; case TARGET_RANDOM_DESTINATION: _unit->CastSpellAoF(RTarget->GetPositionX(), RTarget->GetPositionY(), RTarget->GetPositionZ(), spells[i].info, spells[i].instant); break; } TargetTable.clear(); } } protected: int nrspells; }; // CRYSTALCORE SENTINEL #define CN_CRYSTAL_SENTINEL 20041 #define TRAMPLE 40340 #define CHARGET_ARCANE_EXPLOSION 37106 class CrystalSentinelAI : public CreatureAIScript { public: ADD_CREATURE_FACTORY_FUNCTION(CrystalSentinelAI); SP_AI_Spell spells[2]; bool m_spellcheck[2]; CrystalSentinelAI(Creature* pCreature) : CreatureAIScript(pCreature) { nrspells = 2; for(int i = 0; i < nrspells; i++) { m_spellcheck[i] = false; } spells[0].info = dbcSpell.LookupEntry(TRAMPLE); spells[0].targettype = TARGET_VARIOUS; spells[0].instant = true; spells[0].cooldown = 15; spells[0].perctrigger = 50.0f; spells[0].attackstoptimer = 1000; spells[1].info = dbcSpell.LookupEntry(CHARGET_ARCANE_EXPLOSION); spells[1].targettype = TARGET_VARIOUS; spells[1].instant = false; spells[1].cooldown = 20; spells[1].perctrigger = 50.0f; spells[1].attackstoptimer = 1000; } void OnCombatStart(Unit* mTarget) { CastTime(); RegisterAIUpdateEvent(_unit->GetBaseAttackTime(MELEE)); } void CastTime() { for(int i = 0; i < nrspells; i++) spells[i].casttime = spells[i].cooldown; } void OnTargetDied(Unit* mTarget) { } void OnCombatStop(Unit* mTarget) { CastTime(); _unit->GetAIInterface()->setCurrentAgent(AGENT_NULL); _unit->GetAIInterface()->SetAIState(STATE_IDLE); RemoveAIUpdateEvent(); } void OnDied(Unit* mKiller) { CastTime(); RemoveAIUpdateEvent(); } void AIUpdate() { float val = RandomFloat(100.0f); SpellCast(val); } void SpellCast(float val) { if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->getNextTarget()) { float comulativeperc = 0; Unit* target = NULL; for(int i = 0; i < nrspells; i++) { if(!spells[i].perctrigger) continue; if(m_spellcheck[i]) { target = _unit->GetAIInterface()->getNextTarget(); switch(spells[i].targettype) { case TARGET_SELF: case TARGET_VARIOUS: _unit->CastSpell(_unit, spells[i].info, spells[i].instant); break; case TARGET_ATTACKING: _unit->CastSpell(target, spells[i].info, spells[i].instant); break; case TARGET_DESTINATION: _unit->CastSpellAoF(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), spells[i].info, spells[i].instant); break; case TARGET_RANDOM_FRIEND: case TARGET_RANDOM_SINGLE: case TARGET_RANDOM_DESTINATION: CastSpellOnRandomTarget(i, spells[i].mindist2cast, spells[i].maxdist2cast, spells[i].minhp2cast, spells[i].maxhp2cast); break; } m_spellcheck[i] = false; return; } uint32 t = (uint32)time(NULL); if(val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger) && t > spells[i].casttime) { _unit->setAttackTimer(spells[i].attackstoptimer, false); spells[i].casttime = t + spells[i].cooldown; m_spellcheck[i] = true; } comulativeperc += spells[i].perctrigger; } } } void CastSpellOnRandomTarget(uint32 i, float mindist2cast, float maxdist2cast, int minhp2cast, int maxhp2cast) { if(!maxdist2cast) maxdist2cast = 100.0f; if(!maxhp2cast) maxhp2cast = 100; if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->getNextTarget()) { std::vector<Unit*> TargetTable; /* From M4ksiu - Big THX to Capt who helped me with std stuff to make it simple and fully working <3 */ /* If anyone wants to use this function, then leave this note! */ for(set<Object*>::iterator itr = _unit->GetInRangeSetBegin(); itr != _unit->GetInRangeSetEnd(); ++itr) { if(((spells[i].targettype == TARGET_RANDOM_FRIEND && isFriendly(_unit, (*itr))) || (spells[i].targettype != TARGET_RANDOM_FRIEND && isHostile(_unit, (*itr)) && (*itr) != _unit)) && (*itr)->IsUnit()) // isAttackable(_unit, (*itr)) && { Unit* RandomTarget = NULL; RandomTarget = TO_UNIT(*itr); if(RandomTarget->isAlive() && _unit->GetDistance2dSq(RandomTarget) >= mindist2cast * mindist2cast && _unit->GetDistance2dSq(RandomTarget) <= maxdist2cast * maxdist2cast && ((RandomTarget->GetHealthPct() >= minhp2cast && RandomTarget->GetHealthPct() <= maxhp2cast && spells[i].targettype == TARGET_RANDOM_FRIEND) || (_unit->GetAIInterface()->getThreatByPtr(RandomTarget) > 0 && isHostile(_unit, RandomTarget)))) { TargetTable.push_back(RandomTarget); } } } if(_unit->GetHealthPct() >= minhp2cast && _unit->GetHealthPct() <= maxhp2cast && spells[i].targettype == TARGET_RANDOM_FRIEND) TargetTable.push_back(_unit); if(!TargetTable.size()) return; size_t RandTarget = rand() % TargetTable.size(); Unit* RTarget = TargetTable[RandTarget]; if(!RTarget) return; switch(spells[i].targettype) { case TARGET_RANDOM_FRIEND: case TARGET_RANDOM_SINGLE: _unit->CastSpell(RTarget, spells[i].info, spells[i].instant); break; case TARGET_RANDOM_DESTINATION: _unit->CastSpellAoF(RTarget->GetPositionX(), RTarget->GetPositionY(), RTarget->GetPositionZ(), spells[i].info, spells[i].instant); break; } TargetTable.clear(); } } protected: int nrspells; }; // CRYSTALCORE MECHANIC #define CN_CRYSTAL_MECHANIC 20052 #define SAW_BLADE 37123 class CrystalMechanicAI : public CreatureAIScript { public: ADD_CREATURE_FACTORY_FUNCTION(CrystalMechanicAI); SP_AI_Spell spells[1]; bool m_spellcheck[1]; CrystalMechanicAI(Creature* pCreature) : CreatureAIScript(pCreature) { nrspells = 1; for(int i = 0; i < nrspells; i++) { m_spellcheck[i] = false; } spells[0].info = dbcSpell.LookupEntry(SAW_BLADE); spells[0].targettype = TARGET_RANDOM_SINGLE; spells[0].instant = true; spells[0].cooldown = 6; spells[0].perctrigger = 100.0f; spells[0].attackstoptimer = 1000; spells[0].mindist2cast = 0.0f; spells[0].maxdist2cast = 40.0f; } void OnCombatStart(Unit* mTarget) { CastTime(); RegisterAIUpdateEvent(_unit->GetBaseAttackTime(MELEE)); } void CastTime() { for(int i = 0; i < nrspells; i++) spells[i].casttime = spells[i].cooldown; } void OnTargetDied(Unit* mTarget) { } void OnCombatStop(Unit* mTarget) { CastTime(); _unit->GetAIInterface()->setCurrentAgent(AGENT_NULL); _unit->GetAIInterface()->SetAIState(STATE_IDLE); RemoveAIUpdateEvent(); } void OnDied(Unit* mKiller) { CastTime(); RemoveAIUpdateEvent(); } void AIUpdate() { float val = RandomFloat(100.0f); SpellCast(val); } void SpellCast(float val) { if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->getNextTarget()) { float comulativeperc = 0; Unit* target = NULL; for(int i = 0; i < nrspells; i++) { if(!spells[i].perctrigger) continue; if(m_spellcheck[i]) { target = _unit->GetAIInterface()->getNextTarget(); switch(spells[i].targettype) { case TARGET_SELF: case TARGET_VARIOUS: _unit->CastSpell(_unit, spells[i].info, spells[i].instant); break; case TARGET_ATTACKING: _unit->CastSpell(target, spells[i].info, spells[i].instant); break; case TARGET_DESTINATION: _unit->CastSpellAoF(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), spells[i].info, spells[i].instant); break; case TARGET_RANDOM_FRIEND: case TARGET_RANDOM_SINGLE: case TARGET_RANDOM_DESTINATION: CastSpellOnRandomTarget(i, spells[i].mindist2cast, spells[i].maxdist2cast, spells[i].minhp2cast, spells[i].maxhp2cast); break; } m_spellcheck[i] = false; return; } uint32 t = (uint32)time(NULL); if(val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger) && t > spells[i].casttime) { _unit->setAttackTimer(spells[i].attackstoptimer, false); spells[i].casttime = t + spells[i].cooldown; m_spellcheck[i] = true; } comulativeperc += spells[i].perctrigger; } } } void CastSpellOnRandomTarget(uint32 i, float mindist2cast, float maxdist2cast, int minhp2cast, int maxhp2cast) { if(!maxdist2cast) maxdist2cast = 100.0f; if(!maxhp2cast) maxhp2cast = 100; if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->getNextTarget()) { std::vector<Unit*> TargetTable; /* From M4ksiu - Big THX to Capt who helped me with std stuff to make it simple and fully working <3 */ /* If anyone wants to use this function, then leave this note! */ for(set<Object*>::iterator itr = _unit->GetInRangeSetBegin(); itr != _unit->GetInRangeSetEnd(); ++itr) { if(((spells[i].targettype == TARGET_RANDOM_FRIEND && isFriendly(_unit, (*itr))) || (spells[i].targettype != TARGET_RANDOM_FRIEND && isHostile(_unit, (*itr)) && (*itr) != _unit)) && (*itr)->IsUnit()) // isAttackable(_unit, (*itr)) && { Unit* RandomTarget = NULL; RandomTarget = TO_UNIT(*itr); if(RandomTarget->isAlive() && _unit->GetDistance2dSq(RandomTarget) >= mindist2cast * mindist2cast && _unit->GetDistance2dSq(RandomTarget) <= maxdist2cast * maxdist2cast && ((RandomTarget->GetHealthPct() >= minhp2cast && RandomTarget->GetHealthPct() <= maxhp2cast && spells[i].targettype == TARGET_RANDOM_FRIEND) || (_unit->GetAIInterface()->getThreatByPtr(RandomTarget) > 0 && isHostile(_unit, RandomTarget)))) { TargetTable.push_back(RandomTarget); } } } if(_unit->GetHealthPct() >= minhp2cast && _unit->GetHealthPct() <= maxhp2cast && spells[i].targettype == TARGET_RANDOM_FRIEND) TargetTable.push_back(_unit); if(!TargetTable.size()) return; size_t RandTarget = rand() % TargetTable.size(); Unit* RTarget = TargetTable[RandTarget]; if(!RTarget) return; switch(spells[i].targettype) { case TARGET_RANDOM_FRIEND: case TARGET_RANDOM_SINGLE: _unit->CastSpell(RTarget, spells[i].info, spells[i].instant); break; case TARGET_RANDOM_DESTINATION: _unit->CastSpellAoF(RTarget->GetPositionX(), RTarget->GetPositionY(), RTarget->GetPositionZ(), spells[i].info, spells[i].instant); break; } TargetTable.clear(); } } protected: int nrspells; }; /****************/ /* Bosses */ /****************/ //------------------------------------ // -= Void Reaver =- //------------------------------------ #define CN_VOID_REAVER 19516 #define VOID_REAVER_POUNDING 34164 #define VOID_REAVER_ARCANE_ORB 34190 #define VOID_REAVER_ARCANE_ORB_TRIGGER 34172 #define VOID_REAVER_KNOCK_AWAY 25778 #define VOID_REAVER_ENRAGE 27680 // Needs checking (as it can be wrong [or maybe IS wrong]) class VoidReaverAI : public MoonScriptBossAI { public: MOONSCRIPT_FACTORY_FUNCTION(VoidReaverAI, MoonScriptBossAI); VoidReaverAI(Creature* pCreature) : MoonScriptBossAI(pCreature) { SpellDesc* pPounding = AddSpell(VOID_REAVER_POUNDING, Target_Self, 100, 0, 12); if(pPounding != NULL) { pPounding->AddEmote("Alternative measure commencing...", Text_Yell, 11218); pPounding->AddEmote("Calculating force parameters...", Text_Yell, 11219); } mArcaneOrb = AddSpell(VOID_REAVER_ARCANE_ORB_TRIGGER, Target_RandomPlayerDestination, 100, 0, 3); AddSpell(VOID_REAVER_KNOCK_AWAY, Target_Current, 100, 0, 20, 0, 12); // 12 is experimental value SetEnrageInfo(AddSpell(VOID_REAVER_ENRAGE, Target_Self, 0, 0, 0), 600000); AddEmote(Event_OnCombatStart, "Alert, you are marked for extermination!", Text_Yell, 11213); AddEmote(Event_OnTargetDied, "Extermination, successful.", Text_Yell, 11215); AddEmote(Event_OnTargetDied, "Imbecile life form, no longer functional.", Text_Yell, 11216); AddEmote(Event_OnTargetDied, "Threat neutralized.", Text_Yell, 11217); AddEmote(Event_OnDied, "Systems... shutting... down...", Text_Yell, 11214); mArcaneOrbTimer = INVALIDATE_TIMER; } void OnCombatStart(Unit* mTarget) { ParentClass::OnCombatStart(mTarget); if(mArcaneOrb != NULL) { mArcaneOrbTimer = AddTimer(10000); mArcaneOrb->mEnabled = false; } } void AIUpdate() { if(mArcaneOrb != NULL && !mArcaneOrb->mEnabled && IsTimerFinished(mArcaneOrbTimer)) { RemoveTimer(mArcaneOrbTimer); mArcaneOrb->mEnabled = true; } ParentClass::AIUpdate(); } int32 mArcaneOrbTimer; SpellDesc* mArcaneOrb; }; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //High Astromancer Solarian AI Script // // Phase timers based on boss mods: // - Split every 90sec (except first split happens 50sec after engage) // - 3x4 Solarium Agents spawns 6sec after split // - Solarian comes back with two Solarium Priest 22sec after split (end of phase 2) // - Once phase 2 is finished, phase 1 starts again // - At 20% health, Solarian enter phase 3 until she dies // #define CN_SOLARIAN 18805 #define CN_SOLARIUMAGENT 18925 #define CN_SOLARIUMPRIEST 18806 #define CN_SOLARIUM_SPOT_LIGHT 15631 #define SOLARIAN_WRATH_OF_THE_ASTROMANCER 42783 //Infuses an enemy with Arcane power, causing them to harm nearby allies for 5400 to 6600. Arcane damage after 6 sec. #define SOLARIAN_WRATH_OF_THE_ASTROMANCER_BOMB 42787 //The actual spell that triggers the explosion with arcane damage and slow fall #define SOLARIAN_ARCANE_MISSILES 33031 //Launches magical missiles at an enemy, inflicting Arcane damage each second for 3 sec. Trigger spell (3000 arcane damage) #define SOLARIAN_BLINDING_LIGHT 33009 //Hits everyone in the raid for 2280 to 2520 arcane damage. 20sec cooldown. #define SOLARIAN_SOLARIANS_TRANSFORM 39117 //Transforms into void walker. #define SOLARIAN_VOID_BOLT 39329 //The Void Walker casts this every 10 seconds. It deals 4394 to 5106 shadow damage to the target with the highest aggro. #define SOLARIAN_PSYCHIC_SCREAM 34322 //Fears up to 5 targets in melee range. #define SOLARIUMPRIEST_GREATER_HEAL 38580 //Heals 23125 to 26875 any friendly target #define SOLARIUMPRIEST_HOLY_SMITE 31740 //Deals 553 to 747 holy damage bool Dummy_Solarian_WrathOfTheAstromancer(uint32 pEffectIndex, Spell* pSpell); void SpellFunc_Solarian_Disappear(SpellDesc* pThis, MoonScriptCreatureAI* pCreatureAI, Unit* pTarget, TargetType pType); void SpellFunc_Solarian_Reappear(SpellDesc* pThis, MoonScriptCreatureAI* pCreatureAI, Unit* pTarget, TargetType pType); class HighAstromancerSolarianAI : public MoonScriptBossAI { MOONSCRIPT_FACTORY_FUNCTION(HighAstromancerSolarianAI, MoonScriptBossAI); HighAstromancerSolarianAI(Creature* pCreature) : MoonScriptBossAI(pCreature) { //Initialize timers mSplitTimer = mAgentsTimer = mSolarianTimer = INVALIDATE_TIMER; //Phase 1 spells AddPhaseSpell(1, AddSpell(SOLARIAN_ARCANE_MISSILES, Target_RandomUnit, 60, 3, 0, 0, 45)); AddPhaseSpell(1, AddSpell(SOLARIAN_WRATH_OF_THE_ASTROMANCER, Target_RandomPlayerNotCurrent, 20, 0, 6, 0, 50000)); AddPhaseSpell(1, AddSpell(SOLARIAN_BLINDING_LIGHT, Target_Self, 20, 0, 20, 0, 50)); mDisappear = AddSpellFunc(&SpellFunc_Solarian_Disappear, Target_Self, 0, 22, 0); mDisappear->AddEmote("You are hopelessly outmatched!", Text_Yell, 11139); mDisappear->AddEmote("I will crush your delusions of grandeur!", Text_Yell, 11140); //Phase 2 spells mReappear = AddSpellFunc(&SpellFunc_Solarian_Reappear, Target_Self, 0, 0, 0); //Phase 3 spells AddPhaseSpell(3, AddSpell(SOLARIAN_VOID_BOLT, Target_Current, 100, 3, 10, 0, 100)); AddPhaseSpell(3, AddSpell(SOLARIAN_PSYCHIC_SCREAM, Target_Self, 10, 0, 0)); mVoidForm = AddSpell(SOLARIAN_SOLARIANS_TRANSFORM, Target_Self, 0, 0, 0); mVoidForm->AddEmote("Enough of this! Now I call upon the fury of the cosmos itself.", Text_Yell); mVoidForm->AddEmote("I become ONE... with the VOID!", Text_Yell); //Emotes AddEmote(Event_OnCombatStart, "Tal anu'men no sin'dorei!", Text_Yell, 11134); AddEmote(Event_OnDied, "The warmth of the sun... awaits.", Text_Yell, 11135); AddEmote(Event_OnTargetDied, "Your soul belongs to the Abyss!", Text_Yell, 11136); AddEmote(Event_OnTargetDied, "By the blood of the Highborne!", Text_Yell, 11137); AddEmote(Event_OnTargetDied, "For the Sunwell!", Text_Yell, 11138); } void OnCombatStart(Unit* pTarget) { mSplitTimer = AddTimer(50000); //First split after 50sec ParentClass::OnCombatStart(pTarget); } void AIUpdate() { if(GetPhase() == 1) { if(GetHealthPercent() <= 20 && !IsCasting()) { SetPhase(3, mVoidForm); CancelAllTimers(); } else if(IsTimerFinished(mSplitTimer) && !IsCasting()) { SetPhase(2, mDisappear); ResetTimer(mSplitTimer, 90000); //Next split in 90sec mAgentsTimer = AddTimer(6000); //Agents spawns 6sec after the split mSolarianTimer = AddTimer(22000); //Solarian with 2 priests spawns 22sec after split } } else if(GetPhase() == 2) { if(IsTimerFinished(mSolarianTimer) && !IsCasting()) { SetPhase(1, mReappear); RemoveTimer(mSolarianTimer); } else if(IsTimerFinished(mAgentsTimer) && !IsCasting()) { for(int SpawnIter = 0; SpawnIter < 4; SpawnIter++) { SpawnCreature(CN_SOLARIUMAGENT, mSpawnPositions[0][0], mSpawnPositions[0][1], 17, 0, true); SpawnCreature(CN_SOLARIUMAGENT, mSpawnPositions[1][0], mSpawnPositions[1][1], 17, 0, true); SpawnCreature(CN_SOLARIUMAGENT, mSpawnPositions[2][0], mSpawnPositions[2][1], 17, 0, true); } RemoveTimer(mAgentsTimer); } } ParentClass::AIUpdate(); } SpellDesc* mVoidForm; SpellDesc* mDisappear; SpellDesc* mReappear; int32 mSplitTimer, mAgentsTimer, mSolarianTimer; float mSpawnPositions[3][2]; }; bool Dummy_Solarian_WrathOfTheAstromancer(uint32 pEffectIndex, Spell* pSpell) { Unit* Caster = pSpell->u_caster; if(!Caster) return true; Unit* Target = Caster->GetAIInterface()->getNextTarget(); if(!Target) return true; SpellEntry* SpellInfo = dbcSpell.LookupEntry(SOLARIAN_WRATH_OF_THE_ASTROMANCER_BOMB); if(!SpellInfo) return true; //Explode bomb after 6sec sEventMgr.AddEvent(Target, &Unit::EventCastSpell, Target, SpellInfo, EVENT_UNK, 6000, 1, EVENT_FLAG_DO_NOT_EXECUTE_IN_WORLD_CONTEXT); return true; } void SpellFunc_Solarian_Disappear(SpellDesc* pThis, MoonScriptCreatureAI* pCreatureAI, Unit* pTarget, TargetType pType) { HighAstromancerSolarianAI* Solarian = (pCreatureAI) ? TO< HighAstromancerSolarianAI* >(pCreatureAI) : NULL; if(Solarian) { SpellFunc_Disappear(pThis, pCreatureAI, pTarget, pType); //Spawn spot lights, and despawn them after 26sec X(400,460) Y(-340,-400) Solarian->mSpawnPositions[0][0] = 400 + RandomFloat(60); Solarian->mSpawnPositions[0][1] = -400 + RandomFloat(60); Solarian->SpawnCreature(CN_SOLARIUM_SPOT_LIGHT, Solarian->mSpawnPositions[0][0], Solarian->mSpawnPositions[0][1], 17)->Despawn(26000); Solarian->mSpawnPositions[1][0] = 400 + RandomFloat(60); Solarian->mSpawnPositions[1][1] = -400 + RandomFloat(60); Solarian->SpawnCreature(CN_SOLARIUM_SPOT_LIGHT, Solarian->mSpawnPositions[1][0], Solarian->mSpawnPositions[1][1], 17)->Despawn(26000); Solarian->mSpawnPositions[2][0] = 400 + RandomFloat(60); Solarian->mSpawnPositions[2][1] = -400 + RandomFloat(60); Solarian->SpawnCreature(CN_SOLARIUM_SPOT_LIGHT, Solarian->mSpawnPositions[2][0], Solarian->mSpawnPositions[2][1], 17)->Despawn(26000); } } void SpellFunc_Solarian_Reappear(SpellDesc* pThis, MoonScriptCreatureAI* pCreatureAI, Unit* pTarget, TargetType pType) { HighAstromancerSolarianAI* Solarian = (pCreatureAI) ? TO< HighAstromancerSolarianAI* >(pCreatureAI) : NULL; if(Solarian) { //Spawn two priest friend to help Solarian Solarian->SpawnCreature(CN_SOLARIUMPRIEST, Solarian->mSpawnPositions[0][0], Solarian->mSpawnPositions[0][1], 17); Solarian->SpawnCreature(CN_SOLARIUMPRIEST, Solarian->mSpawnPositions[1][0], Solarian->mSpawnPositions[1][1], 17); //Solarian->MoveTo(Solarian->mSpawnPositions[2][0], Solarian->mSpawnPositions[2][1], 17); //Doesn't work quite right yet SpellFunc_Reappear(pThis, pCreatureAI, pTarget, pType); } } class SolariumAgentAI : public MoonScriptCreatureAI { MOONSCRIPT_FACTORY_FUNCTION(SolariumAgentAI, MoonScriptCreatureAI); SolariumAgentAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature) { SetDespawnWhenInactive(true); //despawn creature if it gets out of combat or dead } void OnLoad() { AggroNearestUnit(); //Aggro on spawn } }; class SolariumPriestAI : public MoonScriptCreatureAI { MOONSCRIPT_FACTORY_FUNCTION(SolariumPriestAI, MoonScriptCreatureAI); SolariumPriestAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature) { AddSpell(SOLARIUMPRIEST_GREATER_HEAL, Target_WoundedFriendly, 20, 2, 0, 0, 40); AddSpell(SOLARIUMPRIEST_HOLY_SMITE, Target_Current, 80, 2.5f, 0, 0, 40); SetDespawnWhenInactive(true); //despawn creature if it gets out of combat or dead } void OnLoad() { AggroNearestUnit(); //Aggro on spawn } }; class SolariumSpotLight : public MoonScriptCreatureAI { MOONSCRIPT_FACTORY_FUNCTION(SolariumSpotLight, MoonScriptCreatureAI); SolariumSpotLight(Creature* pCreature) : MoonScriptCreatureAI(pCreature) { SetCanEnterCombat(false); } }; // Al'ar AI class AlarAuxClass: public Object { public: AlarAuxClass(CreatureAIScript*); ~AlarAuxClass(); void Rebirth(); protected: CreatureAIScript* alar; }; #define WALK 0 #define RUN 256 #define FLY 768 #define CN_ALAR 19514 // Phase1 spells #define FLAME_BUFFET 34121 // casted only when there is no player in melee range! #define FLAME_QUILLS 34316 // it flies to a high point in a center of room and use this on players located on platform // also can be many others (Idk even if this spell works =S) #define SUMMON_PHOENIX_ADDS 18814 // Summons 3 phoenixs // Phase2 spells #define FLAME_PATCH 35383 // 35383, 35380; #define METEOR 35181 // but shouldn't be instant imho --Dive Bomb 35367 //#define EMBER_BLAST 34133 // used when one of adds has low health #define MELT_ARMOR 35410 // maybe they are used, but not sure //#define RANDOM_CHARGE // Other spells #define REBIRTH 34342 static Location fly[] = { { }, { 337.864868f, 65.702301f, 33.171944f, 1.329919f }, // fly 1 to ... { 391.245148f, 35.472462f, 36.886353f, 0.822089f }, { 392.959869f, -34.031734f, 33.630096f, 3.342431f }, { 321.277008f, -70.101540f, 43.650482f, 3.844443f }, { 256.202911f, -1.549352f, 44.718426f, 0.069512f }, // ... fly 5 { 342.090088f, 55.661064f, 27.638260f, 0.739368f }, // attack/tank positions from phase 1 from here to ... { 392.815369f, 31.636963f, 25.414761f, 0.551340f }, { 388.397308f, -38.834595f, 22.335297f, 5.702067f }, { 333.922229f, -60.645069f, 24.484278f, 1.454599f }, // ... to here { 328.103455f, -0.192393f, 50.216309f, 4.188326f }, // fire quills cast position // EMOTE_STATE_WHIRLWIND = 382, { 326.225647f, 2.381837f, -2.389485f, 4.877070f } // center of the room which is used in phase 2 }; class AlarAI : public CreatureAIScript { public: ADD_CREATURE_FACTORY_FUNCTION(AlarAI); SP_AI_Spell spells[7]; bool m_spellcheck[7]; AlarAI(Creature* pCreature) : CreatureAIScript(pCreature) { /************************ Waypoint Place ************************/ for(int i = 1; i < 12; i++) { _unit->GetAIInterface()->addWayPoint(CreateWaypoint(i, 0, RUN)); // FLY stucks my client } /************************** Spells ******************************/ nrspells = 7; for(int i = 0; i < nrspells; i++) { m_spellcheck[i] = false; } spells[0].info = dbcSpell.LookupEntry(FLAME_BUFFET); spells[0].targettype = TARGET_VARIOUS; spells[0].instant = false; spells[0].cooldown = 4; spells[0].perctrigger = 0.0f; spells[0].attackstoptimer = 1000; spells[1].info = dbcSpell.LookupEntry(FLAME_QUILLS); spells[1].targettype = TARGET_VARIOUS; spells[1].instant = true; spells[1].cooldown = 3; spells[1].perctrigger = 0.0f; spells[1].attackstoptimer = 1000; spells[2].info = dbcSpell.LookupEntry(SUMMON_PHOENIX_ADDS); spells[2].targettype = TARGET_VARIOUS; spells[2].instant = true; spells[2].cooldown = 5; spells[2].perctrigger = 0.0f; spells[2].attackstoptimer = 1000; spells[3].info = dbcSpell.LookupEntry(FLAME_PATCH); spells[3].targettype = TARGET_VARIOUS; spells[3].instant = true; spells[3].cooldown = 10; spells[3].perctrigger = 0.0f; spells[3].attackstoptimer = 1000; spells[4].info = dbcSpell.LookupEntry(METEOR); spells[4].targettype = TARGET_ATTACKING; spells[4].instant = true; // =( spells[4].cooldown = 30; spells[4].perctrigger = 0.0f; spells[4].attackstoptimer = 1000; spells[5].info = dbcSpell.LookupEntry(MELT_ARMOR); spells[5].targettype = TARGET_ATTACKING; spells[5].instant = true; spells[5].cooldown = 60; spells[5].perctrigger = 0.0f; spells[5].attackstoptimer = 1000; spells[6].info = dbcSpell.LookupEntry(REBIRTH); spells[6].targettype = TARGET_SELF; spells[6].instant = false; spells[6].cooldown = -1; spells[6].perctrigger = 0.0f; spells[6].attackstoptimer = 1000; /******************* Additional Settings *******************/ _unit->GetAIInterface()->setMoveType(MOVEMENTTYPE_FORWARDTHANSTOP); _unit->GetAIInterface()->SetFly(); FlameQuills = false; Meteor = false; SetPhase(0); nDeath = 0; timer = lasttime = 0; _unit->GetAIInterface()->setOutOfCombatRange(200000); //RegisterAIUpdateEvent(_unit->GetBaseAttackTime(MELEE)); _unit->GetAIInterface()->SetFly(); _unit->GetAIInterface()->StopMovement(0); _unit->GetAIInterface()->SetAIState(STATE_SCRIPTMOVE); _unit->GetAIInterface()->setMoveType(MOVEMENTTYPE_WANTEDWP); _unit->GetAIInterface()->setWaypointToMove(1); Flying = true; CastTime(); } void OnDamageTaken(Unit* mAttacker, uint32 fAmount) { if(!_unit->event_HasEvents()) { RegisterAIUpdateEvent(_unit->GetBaseAttackTime(MELEE)); ModifyAIUpdateEvent(1000); NextWP = 6; } } void OnCombatStart(Unit* mTarget) { FlameQuills = false; Meteor = false; NextWP = 6; RegisterAIUpdateEvent(_unit->GetBaseAttackTime(MELEE)); ModifyAIUpdateEvent(1000); } void CastTime() { for(int i = 0; i < nrspells; i++) spells[i].casttime = spells[i].cooldown; } void SetPhase(uint32 ph) { Phase = ph; _unit->SetBaseMana(Phase); } void OnCombatStop(Unit* mTarget) { CastTime(); FlameQuills = false; Meteor = false; SetPhase(0); RemoveAIUpdateEvent(); } void Rebirth() { //_unit->SetPosition( fly[11].x, fly[11].y, fly[11].z, fly[11].o); SetPhase(2); _unit->CastSpell(_unit, spells[6].info, spells[6].instant); _unit->SetUInt64Value(UNIT_FIELD_HEALTH, _unit->GetUInt32Value(UNIT_FIELD_MAXHEALTH)); _unit->setDeathState(ALIVE); _unit->RemoveFlag(UNIT_DYNAMIC_FLAGS, U_DYN_FLAG_TAGGED_BY_OTHER); _unit->SetFlag(UNIT_DYNAMIC_FLAGS, U_DYN_FLAG_LOOTABLE); // no idea what this tag means, smth loot/party related //_unit->ClearTag(); _unit->GetAIInterface()->StopMovement(0); // after respawn monster can move _unit->GetAIInterface()->WipeTargetList(); _unit->GetAIInterface()->WipeHateList(); _unit->GetAIInterface()->setMoveType(MOVEMENTTYPE_DONTMOVEWP); _unit->GetAIInterface()->m_canMove = true; Flying = false; lasttime = timer; } void OnDied(Unit* mKiller) { nDeath++; //azolex: commenting this "tag" code, no idea what is it for, nothing like this in arcemu /*if (nDeath==1) { if (mKiller->IsPlayer()) { _unit->Tag(TO_PLAYER(mKiller)); } else if (mKiller->IsPet() && TO_PET(mKiller)->GetPetOwner()) { _unit->Tag(TO_PET(mKiller)->GetPetOwner()); } AlarAuxClass *cAux=new AlarAuxClass(this); return; }*/ SetPhase(0); nDeath = 0; FlameQuills = false; Meteor = false; CastTime(); RemoveAIUpdateEvent(); } bool HostileInMeleeRange() { for(Object::InRangeSet::iterator i = _unit->GetInRangeSetBegin(); i != _unit->GetInRangeSetEnd(); ++i) { if(isHostile(_unit, (*i)) && _unit->GetDistance2dSq((*i)) < 225) { return true; } } return false; } void UPCastTime() { for(int i = 0; i < nrspells; i++) if(spells[i].casttime > 0) spells[i].casttime--; } void AIUpdate() { UPCastTime(); if(!HostileInMeleeRange() && spells[0].casttime == 0 && !FlameQuills && !Flying) { _unit->CastSpell(_unit, spells[0].info, spells[0].instant); spells[0].casttime = spells[0].cooldown; } if(!Flying) timer++; switch(Phase) { case 0: return; case 1: { PhaseOne(); } break; case 2: { PhaseTwo(); } break; default: { SetPhase(0); }; } } void PhaseOne() { if(FlameQuills == true) { //_unit->CastSpell(_unit, dbcSpell.LookupEntry(34229), true); if(lasttime + 11 == timer) { _unit->CastSpellAoF(fly[1].x, fly[1].y, fly[1].z, spells[1].info, spells[1].instant); _unit->CastSpellAoF(fly[2].x, fly[2].y, fly[2].z, spells[1].info, spells[1].instant); _unit->CastSpellAoF(fly[3].x, fly[3].y, fly[3].z, spells[1].info, spells[1].instant); _unit->CastSpellAoF(fly[4].x, fly[4].y, fly[4].z, spells[1].info, spells[1].instant); _unit->GetAIInterface()->m_canMove = true; _unit->GetAIInterface()->setMoveType(MOVEMENTTYPE_WANTEDWP); _unit->GetAIInterface()->setWaypointToMove(NextWP); FlameQuills = false; Flying = true; lasttime = timer; } } else if(lasttime + 35 == timer) { _unit->GetMapMgr()->GetInterface()->SpawnCreature(19551, _unit->GetPositionX(), _unit->GetPositionY(), _unit->GetPositionZ(), 0, true, false, 0, 0); //_unit->CastSpell(_unit, spells[2].info, spells[2].instant); lasttime = timer + rand() % 10; _unit->GetAIInterface()->SetAllowedToEnterCombat(false); _unit->GetAIInterface()->setCurrentAgent(AGENT_NULL); _unit->GetAIInterface()->StopMovement(0); _unit->GetAIInterface()->m_canMove = true; _unit->GetAIInterface()->SetAIState(STATE_SCRIPTMOVE); _unit->GetAIInterface()->setMoveType(MOVEMENTTYPE_WANTEDWP); _unit->GetAIInterface()->setWaypointToMove(NextWP); // ugly code, trows compile error if left just null, this should do it ~ azolex // uint32 nullfix = 0; _unit->GetAIInterface()->resetNextTarget(); Flying = true; } } void PhaseTwo() { CastSpell(5); CastSpell(4); if((rand() % 100) < 2) { Unit* target = GetRandomTarget(); Creature* patch; if(target != NULL) { patch = _unit->GetMapMgr()->GetInterface()->SpawnCreature(20602, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), 0, true, false, _unit->GetFaction(), 0); if(patch != NULL) { patch->SetDisplayId(16946); patch->SetNativeDisplayId(16946); } } } if(Meteor == true) { } if(lasttime + 35 == timer) { _unit->GetMapMgr()->GetInterface()->SpawnCreature(19551, _unit->GetPositionX(), _unit->GetPositionY(), _unit->GetPositionZ(), 0, true, false, 0, 0); _unit->GetMapMgr()->GetInterface()->SpawnCreature(19551, _unit->GetPositionX(), _unit->GetPositionY(), _unit->GetPositionZ(), 0, true, false, 0, 0); lasttime = timer; } } Unit* GetRandomTarget() { for(Object::InRangeSet::iterator i = _unit->GetInRangeSetBegin(); i != _unit->GetInRangeSetEnd(); ++i) { if(isHostile(_unit, (*i)) && (*i)->GetInstanceID() == _unit->GetInstanceID()) { Unit* RandomTarget = TO_UNIT(*i); if(RandomTarget->isAlive()) return RandomTarget; } } return NULL; } void CastSpell(int id) { if(spells[id].casttime > 0) return; if(_unit->GetCurrentSpell() != NULL) return; Unit* target = NULL; target = _unit->GetAIInterface()->getNextTarget(); switch(spells[id].targettype) { case TARGET_SELF: case TARGET_VARIOUS: _unit->CastSpell(_unit, spells[id].info, spells[id].instant); break; case TARGET_ATTACKING: _unit->CastSpell(target, spells[id].info, spells[id].instant); break; case TARGET_DESTINATION: _unit->CastSpellAoF(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), spells[id].info, spells[id].instant); break; case TARGET_RANDOM_SINGLE: { target = GetRandomTarget(); if(target != NULL) _unit->CastSpell(target, spells[id].info, spells[id].instant); } break; } spells[id].casttime = spells[id].cooldown; } void SetNextWP(uint32 wp) { _unit->GetAIInterface()->SetAIState(STATE_ATTACKING);//STATE_IDLE NextWP = wp; Flying = false; _unit->GetAIInterface()->setMoveType(MOVEMENTTYPE_DONTMOVEWP); _unit->GetAIInterface()->m_canMove = false; lasttime = timer; } void OnReachWP(uint32 iWaypointId, bool bForwards) { if(Phase == 0) { if(NextWP == 6) Phase = 1; else NextWP = iWaypointId % 5 + 1; _unit->GetAIInterface()->SetAIState(STATE_SCRIPTMOVE); _unit->GetAIInterface()->setMoveType(MOVEMENTTYPE_WANTEDWP); _unit->GetAIInterface()->setWaypointToMove(NextWP); } switch(iWaypointId) { case 6: { SetNextWP(7); } break; case 7: { SetNextWP(8); } break; case 8: { SetNextWP(9); } break; case 9: { SetNextWP(10); } break; case 10: { if(Phase == 1) { FlameQuills = true; QuillsCount = 0; Flying = false; _unit->GetAIInterface()->setMoveType(MOVEMENTTYPE_DONTMOVEWP); _unit->GetAIInterface()->m_canMove = false; NextWP = 6; lasttime = timer; //_unit->Emote(EMOTE_STATE_WHIRLWIND); _unit->CastSpell(_unit, dbcSpell.LookupEntry(34229), true); } if(Phase == 2) { Meteor = true; } } break; default: { } } } inline WayPoint* CreateWaypoint(int id, uint32 waittime, uint32 flags) { WayPoint* wp = _unit->CreateWaypointStruct(); wp->id = id; wp->x = fly[id].x; wp->y = fly[id].y; wp->z = fly[id].z; wp->o = fly[id].o; wp->waittime = waittime; wp->flags = flags; wp->forwardemoteoneshot = false; wp->forwardemoteid = 0; wp->backwardemoteoneshot = false; wp->backwardemoteid = 0; wp->forwardskinid = 0; wp->backwardskinid = 0; return wp; } protected: bool FlameQuills; uint32 QuillsCount; bool Meteor; uint32 NextWP; uint32 m_entry; uint32 FlyWay; uint32 Phase; uint32 nDeath; int nrspells; uint32 timer, lasttime; bool Flying; }; #define CN_EMBEROFALAR 19551 class EmberAlarAI : public CreatureAIScript { public: ADD_CREATURE_FACTORY_FUNCTION(EmberAlarAI); SP_AI_Spell spells[1]; bool m_spellcheck[1]; EmberAlarAI(Creature* pCreature) : CreatureAIScript(pCreature) { nrspells = 1; for(int i = 0; i < nrspells; i++) { m_spellcheck[i] = false; } spells[0].info = dbcSpell.LookupEntry(34341); spells[0].targettype = TARGET_VARIOUS; spells[0].instant = true; spells[0].cooldown = 15; spells[0].perctrigger = 50.0f; spells[0].attackstoptimer = 1000; } void OnCombatStart(Unit* mTarget) { CastTime(); RegisterAIUpdateEvent(_unit->GetBaseAttackTime(MELEE)); } void CastTime() { for(int i = 0; i < nrspells; i++) spells[i].casttime = spells[i].cooldown; } void OnTargetDied(Unit* mTarget) { } void OnCombatStop(Unit* mTarget) { CastTime(); _unit->GetAIInterface()->setCurrentAgent(AGENT_NULL); _unit->GetAIInterface()->SetAIState(STATE_IDLE); RemoveAIUpdateEvent(); } Unit* GetAlar() { for(Object::InRangeSet::iterator i = _unit->GetInRangeSetBegin(); i != _unit->GetInRangeSetEnd(); ++i) { if((*i)->IsCreature() && _unit->GetDistance2dSq((*i)) < 400000) { Creature* creature = TO_CREATURE((*i)); if(creature->GetEntry() == 19514 && (*i)->GetInstanceID() == _unit->GetInstanceID()) { return creature; } } } return NULL; } void OnDied(Unit* mKiller) { _unit->CastSpell(_unit, spells[0].info, spells[0].instant); CastTime(); Unit* Alar = NULL; //Alar=_unit->GetMapMgr()->GetInterface()->GetCreatureNearestCoords(_unit->GetPositionX(), _unit->GetPositionY(), _unit->GetPositionZ(), 19514); Alar = GetAlar(); if(Alar == NULL) { return; } uint32 Phase = Alar->GetBaseMana(); if(Phase == 2/*&& Alar->isAlive()*/) { uint32 maxhp = Alar->GetUInt32Value(UNIT_FIELD_MAXHEALTH); Alar->DealDamage(Alar, (maxhp * 3) / 100, 0, 0, 0); } } protected: int nrspells; }; #define CN_PATCHALAR 20602 class PatchAlarAI : public CreatureAIScript { public: ADD_CREATURE_FACTORY_FUNCTION(PatchAlarAI); SP_AI_Spell spells[1]; bool m_spellcheck[1]; PatchAlarAI(Creature* pCreature) : CreatureAIScript(pCreature) { nrspells = 1; for(int i = 0; i < nrspells; i++) { m_spellcheck[i] = false; } spells[0].info = dbcSpell.LookupEntry(35380); spells[0].targettype = TARGET_VARIOUS; spells[0].instant = true; spells[0].cooldown = 15; spells[0].perctrigger = 50.0f; spells[0].attackstoptimer = 1000; //_unit->GetAIInterface()->SetAllowedToEnterCombat(false); //_unit->GetAIInterface()->SetAIState(STATE_IDLE); //_unit->SetUInt64Value(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); _unit->SetUInt64Value(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_ATTACKABLE_2); _unit->GetAIInterface()->m_canMove = false; _unit->Despawn(120000, 0); } void OnCombatStart(Unit* mTarget) { CastTime(); RegisterAIUpdateEvent(_unit->GetBaseAttackTime(MELEE)); _unit->CastSpell(_unit, spells[0].info, true); } void CastTime() { for(int i = 0; i < nrspells; i++) spells[i].casttime = spells[i].cooldown; } void OnTargetDied(Unit* mTarget) { } void OnCombatStop(Unit* mTarget) { CastTime(); _unit->GetAIInterface()->setCurrentAgent(AGENT_NULL); _unit->GetAIInterface()->SetAIState(STATE_IDLE); RemoveAIUpdateEvent(); } void OnDied(Unit* mKiller) { CastTime(); } protected: int nrspells; }; /* AlarAuxClass::AlarAuxClass (CreatureAIScript *al) { alar=al; sEventMgr.AddEvent( al, &AlarAI::Rebirth, EVENT_CORPSE_DESPAWN, 3000, 1,0); } AlarAuxClass::~AlarAuxClass () { sEventMgr.RemoveEvents(alar); } void AlarAuxClass::Rebirth() { //((AlarAI *)alar)->Rebirth(); //delete this; } */ //-----------------------------------------------------------// //---------------Kael'thas Encounter Script------------------// //--------------Rewritten/optimized by M4ksiu----------------// //-------------------Scripted by Plexor----------------------// //-----------------------------------------------------------// // Thaladred the Darkener AI(1st advisor) #define CN_DARKENER 20064 #define DARKENER_PSYCHIC_BLOW 36966 #define DARKENER_SILENCE 29943 class DarkenerAI : public MoonScriptCreatureAI { public: MOONSCRIPT_FACTORY_FUNCTION(DarkenerAI, MoonScriptCreatureAI) DarkenerAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature) { AddSpell(DARKENER_PSYCHIC_BLOW, Target_Current, 10, 0, 20); AddSpell(DARKENER_SILENCE, Target_Current, 10, 0, 15); AddEmote(Event_OnCombatStart, "Prepare yourselves!", Text_Yell, 11203); AddEmote(Event_OnDied, "Forgive me, my prince! I have... failed.", Text_Yell, 11204); SetCanEnterCombat(false); mCurrentTarget = NULL; mGazeSwitchTimer = 0; } void OnCombatStart(Unit* mTarget) { ParentClass::OnCombatStart(mTarget); SetCanEnterCombat(true); SwitchTarget(); mGazeSwitchTimer = AddTimer((RandomUInt(4) + 8) * 1000); } void OnCombatStop(Unit* mTarget) { ParentClass::OnCombatStop(mTarget); mCurrentTarget = NULL; if(IsAlive()) { SetCanEnterCombat(false); } } void OnTargetDied(Unit* mTarget) { SwitchTarget(); } void AIUpdate() { if(IsTimerFinished(mGazeSwitchTimer)) { ResetTimer(mGazeSwitchTimer, (RandomUInt(4) + 8) * 1000); if(!SwitchTarget()) return; } ParentClass::AIUpdate(); } bool SwitchTarget() { mCurrentTarget = GetBestPlayerTarget(); if(mCurrentTarget == _unit->GetAIInterface()->getNextTarget()) return true; if(mCurrentTarget != NULL) { _unit->GetAIInterface()->modThreatByPtr(mCurrentTarget, 1000000); Player* pPlayer = TO_PLAYER(mCurrentTarget); char msg[256]; snprintf((char*)msg, 256, "%s sets eyes on %s", _unit->GetCreatureInfo()->Name, pPlayer->GetName()); _unit->SendChatMessageAlternateEntry(CN_DARKENER, CHAT_MSG_MONSTER_EMOTE, LANG_UNIVERSAL, msg); return true; } WipeHateList(); return false; } int32 mGazeSwitchTimer; Unit* mCurrentTarget; }; // Lord Sanguinar AI (2nd advisor) #define CN_SANGUINAR 20060 #define SANGUINAR_BELLOWING 36922 class SanguinarAI : public MoonScriptCreatureAI { public: MOONSCRIPT_FACTORY_FUNCTION(SanguinarAI, MoonScriptCreatureAI) SanguinarAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature) { AddSpell(SANGUINAR_BELLOWING, Target_Self, 100, 0, 30); AddEmote(Event_OnCombatStart, "Blood for blood!", Text_Yell, 11152); AddEmote(Event_OnDied, "NO! I will... not.", Text_Yell, 11153); SetCanEnterCombat(false); } void OnCombatStart(Unit* mTarget) { ParentClass::OnCombatStart(mTarget); SetCanEnterCombat(true); } void OnCombatStop(Unit* mTarget) { ParentClass::OnCombatStop(mTarget); if(IsAlive()) { SetCanEnterCombat(false); } } }; // Grand Astromancer Capernian AI (3rd advisor) #define CN_CAPERNIAN 20062 #define CAPERNIAN_CONFLAGRATION 37018 #define CAPERNIAN_FIREBALL 36971 #define CAPERNIAN_ARCANE_BURST 36970 class CapernianAI : public MoonScriptCreatureAI { public: MOONSCRIPT_FACTORY_FUNCTION(CapernianAI, MoonScriptCreatureAI); CapernianAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature) { AddSpell(CAPERNIAN_CONFLAGRATION, Target_RandomPlayer, 7, 0, 10, 0, 30, true); AddSpell(CAPERNIAN_FIREBALL, Target_Current, 73, 2, 0); mArcaneBurst = AddSpell(CAPERNIAN_ARCANE_BURST, Target_Self, 0, 1, 15); AddEmote(Event_OnCombatStart, "The sin'dorei reign supreme!", Text_Yell, 11117); AddEmote(Event_OnDied, "This is not over!", Text_Yell, 11118); SetCanEnterCombat(false); } void OnCombatStart(Unit* mTarget) { ParentClass::OnCombatStart(mTarget); SetCanEnterCombat(true); if(GetRangeToUnit(mTarget) <= 30.0f) { SetBehavior(Behavior_Spell); SetCanMove(false); } } void OnCombatStop(Unit* mTarget) { ParentClass::OnCombatStop(mTarget); if(IsAlive()) { SetCanEnterCombat(false); } } void AIUpdate() { SetBehavior(Behavior_Default); SetCanMove(true); Unit* pClosestTarget = GetBestPlayerTarget(TargetFilter_Closest); if(pClosestTarget != NULL && GetRangeToUnit(pClosestTarget) <= 6.0f) { CastSpellNowNoScheduling(mArcaneBurst); } Unit* pTarget = _unit->GetAIInterface()->getNextTarget(); if(pTarget != NULL && GetRangeToUnit(pTarget) <= 30.0f) { ParentClass::AIUpdate(); if(GetBehavior() != Behavior_Spell) { SetBehavior(Behavior_Spell); SetCanMove(false); } } } SpellDesc* mArcaneBurst; }; // Master Engineer Telonicus AI (4th advisor) #define CN_TELONICUS 20063 #define TELONICUS_BOMB 37036 #define TELONICUS_REMOTE_TOY 37027 // doesn't seems to work like it should class TelonicusAI : public MoonScriptCreatureAI { public: MOONSCRIPT_FACTORY_FUNCTION(TelonicusAI, MoonScriptCreatureAI); TelonicusAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature) { AddSpell(TELONICUS_BOMB, Target_RandomPlayerDestination, 10, 1.5f, 15, 0, 30); AddSpell(TELONICUS_REMOTE_TOY, Target_RandomPlayer, 10, 0, 15, 0, 30); AddEmote(Event_OnCombatStart, "Anar'alah belore!", Text_Yell, 11157); AddEmote(Event_OnDied, "More perlis... await.", Text_Yell, 11158); // not sure SetCanEnterCombat(false); } void OnCombatStart(Unit* mTarget) { ParentClass::OnCombatStart(mTarget); SetCanEnterCombat(true); } void OnCombatStop(Unit* mTarget) { ParentClass::OnCombatStop(mTarget); if(IsAlive()) { SetCanEnterCombat(false); } } }; // Flame Strike AI #define CN_FLAME_STRIKE_TRIGGER 21369 #define FLAME_STRIKE_TRIGGER_FLAME_STRIKE 36731 #define FLAME_STRIKE_TRIGGER_FLAME_STRIKE_EFFECT 36730 class FlameStrikeAI : public MoonScriptCreatureAI { public: MOONSCRIPT_FACTORY_FUNCTION(FlameStrikeAI, MoonScriptCreatureAI); FlameStrikeAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature) { ApplyAura(FLAME_STRIKE_TRIGGER_FLAME_STRIKE_EFFECT); RegisterAIUpdateEvent(5000); SetCanEnterCombat(false); SetAllowMelee(false); SetCanMove(false); _unit->SetUInt64Value(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); } void OnDied(Unit* mKiller) { ParentClass::OnDied(mKiller); RemoveAura(FLAME_STRIKE_TRIGGER_FLAME_STRIKE_EFFECT); Despawn(500); } void AIUpdate() { _unit->SetUInt64Value(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_ATTACKABLE_2); ApplyAura(FLAME_STRIKE_TRIGGER_FLAME_STRIKE); RemoveAIUpdateEvent(); Despawn(8500); } int32 mDespawnTimer; }; // Phoenix AI #define CN_PHOENIX 21362 #define PHOENIX_BURN 36721 #define PHOENIX_REBIRTH 35369 // used as instant cast - but it does not show animation now (maybe it would be good to move it to trigger?) class PhoenixAI : public MoonScriptCreatureAI { public: MOONSCRIPT_FACTORY_FUNCTION(PhoenixAI, MoonScriptCreatureAI); PhoenixAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature) { RegisterAIUpdateEvent(1000); Unit* pTarget = GetBestPlayerTarget(); if(pTarget != NULL) { _unit->GetAIInterface()->AttackReaction(pTarget, 500, 0); } mBurnTimer = AddTimer(3000); } void OnCombatStart(Unit* mTarget) {} void OnCombatStop(Unit* pTarget) {} void OnTargetDied(Unit* mTarget) { ParentClass::OnTargetDied(mTarget); Unit* pTarget = GetBestPlayerTarget(TargetFilter_Closest); if(pTarget != NULL) { _unit->GetAIInterface()->AttackReaction(pTarget, 500); ParentClass::OnCombatStart(pTarget); } else { Despawn(1, 0); } } void OnDied(Unit* mKiller) { ParentClass::OnDied(mKiller); ApplyAura(PHOENIX_REBIRTH); SpawnCreature(21364); Despawn(500); } void AIUpdate() { double CurrentHP = (double)_unit->GetUInt32Value(UNIT_FIELD_HEALTH); double PercMaxHP = (double)_unit->GetUInt32Value(UNIT_FIELD_MAXHEALTH) * 0.05; if(CurrentHP > PercMaxHP && IsTimerFinished(mBurnTimer)) { _unit->SetHealth((uint32)(CurrentHP - PercMaxHP)); ResetTimer(mBurnTimer, 3000); ApplyAura(PHOENIX_BURN); } else if(CurrentHP <= PercMaxHP) { SpawnCreature(21364); Despawn(500); return; } ParentClass::AIUpdate(); } int32 mBurnTimer; }; //Phoenix Egg AI #define CN_PHOENIX_EGG 21364 class PhoenixEggAI : public MoonScriptCreatureAI { public: MOONSCRIPT_FACTORY_FUNCTION(PhoenixEggAI, MoonScriptCreatureAI); PhoenixEggAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature) { RegisterAIUpdateEvent(15000); SetCanEnterCombat(false); SetAllowMelee(false); SetCanMove(false); } void OnDied(Unit* mKiller) { ParentClass::OnDied(mKiller); Despawn(500); } void AIUpdate() { SpawnCreature(CN_PHOENIX); Despawn(0); } }; //-------------------Kael'thas Weapons------------------// #define NETHERSTRAND_LONGBOW 21268 #define DEVASTATION 21269 #define COSMIC_INFUSER 21270 #define INFINITY_BLADE 21271 #define WARP_SLICER 21272 #define PHASESHIFT_BULWARK 21273 #define STAFF_OF_DISINTEGRATION 21274 class WeaponsAI : public MoonScriptCreatureAI { public: MOONSCRIPT_FACTORY_FUNCTION(WeaponsAI, MoonScriptCreatureAI); WeaponsAI(Creature* pCreature) : MoonScriptCreatureAI(pCreature) { _unit->m_noRespawn = true; Unit* pTarget = GetBestPlayerTarget(); if(pTarget != NULL) { _unit->GetAIInterface()->AttackReaction(pTarget, 200, 0); } } void OnCombatStop(Unit* mTarget) { Unit* pTarget = GetBestPlayerTarget(); if(pTarget != NULL) { _unit->GetAIInterface()->AttackReaction(pTarget, 500); } else { Despawn(1); } } }; /* * TO DO: * - Add weapon summon effect * - Check why some features block (like melee, movement and so on) if there's only 1 target and spell req. NotCurrent one */ //Prince Kael'Thas #define CN_KAELTHAS 19622 // Common spells #define KAELTHAS_FIREBALL 36805 // prolly wrong id #define KAELTHAS_ARCANE_DISRUPTION 36834 #define KAELTHAS_SHOCK_BARRIER 36815 // timed // Phase 4 spells #define KAELTHAS_FLAME_STRIKE_SUMMON 36735 #define KAELTHAS_PHOENIX 36723 #define KAELTHAS_PYROBLAST 36819 // timed #define KAELTHAS_MIND_CONTROL 36797 // timed // Phase 5 spells #define KAELTHAS_GRAVITY_LAPSE 35966 // timed #define KAELTHAS_NETHER_VAPOR 35859 #define KAELTHAS_NETHER_BEAM 35873 // timed along with lapse //#define KAELTHAS_GRAVITY1 34480 // knockback + aura //#define KAELTHAS_GRAVITY2 35941 // explosion effect #define KAELTHAS_SUMMON_WEAPONS 36976 //casting effect #define REMOVE_INFUSER 39498 #define REMOVE_DEVASTATION 39499 #define REMOVE_INFINITY 39500 #define REMOVE_LONGBOW 39501 #define REMOVE_BULWARK 39502 #define REMOVE_STAFF 39503 #define REMOVE_SLICER 39504 const Location Triggers[] = { { 789.719543f, 24.627499f, 52.728550f }, { 791.931152f, -24.925735f, 52.728550f }, }; const LocationExtra Advisors[] = { { 785.807007f, 19.486200f, 48.911800f, 3.979350f, 20064 }, { 785.781982f, -20.399500f, 48.911800f, 2.303830f, 20060 }, { 792.408020f, -13.241500f, 48.911800f, 2.687810f, 20062 }, { 792.724976f, 12.775400f, 48.911800f, 3.595380f, 20063 } }; const LocationExtra Gates[] = { { 676.777283f, -44.468628f, 46.780785f, 0.932028f, 184325 }, { 676.812500f, 43.073757f, 46.781292f, 5.312979f, 184324 } }; const LocationExtra Waypoints[] = { { }, { 794.072998f, 0.214634f, 48.728500f, 0.0f, Flag_Run }, { 794.052998f, 0.214634f, 75.728500f, 0.0f, Flag_Fly }, { 794.032998f, 0.214634f, 48.728500f, 0.0f, Flag_Fly } }; const LocationExtra KaelthasWeapons[] = { { 794.38f, 15.00f, 48.72f, 2.9f, 21270 }, // [Cosmic Infuser] { 785.47f, 12.12f, 48.72f, 3.14f, 21269 }, // [Devastation] { 781.25f, 4.39f, 48.72f, 3.14f, 21271 }, // [Infinity Blade] { 777.38f, -0.81f, 48.72f, 3.06f, 21273 }, // [Phaseshift Bulwark] { 781.48f, -6.08f, 48.72f, 3.9f, 21274 }, // [Staff of Disintegration] { 785.42f, -13.59f, 48.72f, 3.4f, 21272 }, // [Warp Slicer] { 793.06f, -16.61f, 48.72f, 3.10f, 21268 } // [Netherstrand Longbow] }; enum AdvisorPhase { PHASE_SPEECH, PHASE_ATTACK_COMMAND, PHASE_ADV_FIGHT, }; void SpellFunc_KaelThasArcaneDisruption(SpellDesc* pThis, MoonScriptCreatureAI* pCreatureAI, Unit* pTarget, TargetType pType); void SpellFunc_KaelThasFlameStrike(SpellDesc* pThis, MoonScriptCreatureAI* pCreatureAI, Unit* pTarget, TargetType pType); class KaelThasAI : public MoonScriptBossAI { public: MOONSCRIPT_FACTORY_FUNCTION(KaelThasAI, MoonScriptBossAI); KaelThasAI(Creature* pCreature) : MoonScriptBossAI(pCreature) { for(int i = 1; i < 4; ++i) { AddWaypoint(CreateWaypoint(1, 0, Waypoints[i].addition, Waypoints[i])); } SetCanEnterCombat(true); SetMoveType(Move_DontMoveWP); SetCanMove(true); // Other spells mSummonWeapons = AddSpell(KAELTHAS_SUMMON_WEAPONS, Target_Self, 0, 3, 0); mSummonWeapons->AddEmote("As you see, I have many weapons in my arsenal...", Text_Yell, 11261); // Common spells mArcaneDisruption = AddSpell(KAELTHAS_ARCANE_DISRUPTION, Target_Self, 0, 0, 0); mArcaneDisruptionFunc = AddSpellFunc(&SpellFunc_KaelThasArcaneDisruption, Target_RandomPlayerNotCurrent, 0, 0, 0); mShockBarrier = AddSpell(KAELTHAS_SHOCK_BARRIER, Target_Self, 0, 0, 60); AddPhaseSpell(7, AddSpell(KAELTHAS_FIREBALL, Target_Current, 10, 2, 15)); AddPhaseSpell(8, AddSpell(KAELTHAS_FIREBALL, Target_Current, 10, 2, 15)); // 1st phase mPyroblast = AddSpell(KAELTHAS_PYROBLAST, Target_Current, 0, 4, 0); SpellDesc* mMindControl = AddPhaseSpell(7, AddSpell(KAELTHAS_MIND_CONTROL, Target_Self, 100, 0, 30)); mMindControl->AddEmote("Obey me.", Text_Yell, 11268); mMindControl->AddEmote("Bow to my will.", Text_Yell, 11269); mFlameStrike = AddSpell(KAELTHAS_FLAME_STRIKE_SUMMON, Target_RandomPlayerNotCurrent, 0, 0, 0); mFlameStrikeFunc = AddSpellFunc(&SpellFunc_KaelThasFlameStrike, Target_RandomPlayerNotCurrent, 0, 0, 0); mPhoenix = AddSpell(KAELTHAS_PHOENIX, Target_Self, 0, 0, 0); mPhoenix->AddEmote("Anara'nel belore!", Text_Yell, 11267); mPhoenix->AddEmote("By the power of the sun!", Text_Yell, 11266); // After powering up + Nether Vapor + Additional spells mNetherBeam = AddPhaseSpell(8, AddSpell(KAELTHAS_NETHER_BEAM, Target_RandomPlayer, 0, 0, 0)); AddEmote(Event_OnCombatStart, "Energy. Power. My people are addicted to it. Their dependence made manifest after the Sunwell was destroyed. Welcome to the future...a pity you're too late to stop it. No one can stop me now. Selama ashal'anore.", Text_Yell, 11256); AddEmote(Event_OnTargetDied, "You will not prevail.", Text_Yell, 11270); AddEmote(Event_OnTargetDied, "You gambled...and lost.", Text_Yell, 11271); AddEmote(Event_OnTargetDied, "This was child's play.", Text_Yell, 11272); AddEmote(Event_OnDied, "For...Quel...thalas!", Text_Yell, 11274); mAIUpdateFrequency = 30000; for(int i = 0; i < 4; ++i) { Creature* pCreature = TO_CREATURE(ForceCreatureFind(Advisors[i].addition, Advisors[i].x, Advisors[i].y, Advisors[i].z)); if(pCreature != NULL) { pCreature->Despawn(0, 0); } SpawnCreature(Advisors[i].addition, Advisors[i].x, Advisors[i].y, Advisors[i].z, Advisors[i].o); } } void OnCombatStart(Unit* mTarget) { _unit->SetUInt64Value(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_ATTACKABLE_9); SetAIUpdateFreq(24000); ParentClass::OnCombatStart(mTarget); SetBehavior(Behavior_Spell); SetCanMove(false); for(int i = 0; i < 2; ++i) { GameObject* pGameobject = _unit->GetMapMgr()->GetInterface()->GetGameObjectNearestCoords(Gates[i].x, Gates[i].y, Gates[i].z, Gates[i].addition); if(pGameobject != NULL && pGameobject->GetState() == 0) { pGameobject->SetState(1); } } mEventTimer = mArcaneDisruptionTimer = mShockBarrierTimer = mFlameStrikeTimer = mPhoenixTimer = -1; mAdvisorPhase = PHASE_SPEECH; mAdvCoords.clear(); } void OnCombatStop(Unit* mTarget) { SetCanMove(true); ParentClass::OnCombatStop(mTarget); _unit->SetUInt64Value(UNIT_FIELD_FLAGS, 0); if(IsAlive()) { for(int i = 0; i < 4; ++i) { Creature* pCreature = TO_CREATURE(ForceCreatureFind(Advisors[i].addition, Advisors[i].x, Advisors[i].y, Advisors[i].z)); if(pCreature != NULL) { pCreature->Despawn(0, 0); } SpawnCreature(Advisors[i].addition, Advisors[i].x, Advisors[i].y, Advisors[i].z, Advisors[i].o); } } for(int i = 0; i < 2; ++i) { GameObject* pGameobject = _unit->GetMapMgr()->GetInterface()->GetGameObjectNearestCoords(Gates[i].x, Gates[i].y, Gates[i].z, Gates[i].addition); if(pGameobject != NULL && pGameobject->GetState() == 1) { pGameobject->SetState(0); } } } void SendAdvisorEmote() { switch(GetPhase()) { case 1: Emote("Let us see how your nerves hold up against the Darkener, Thaladred.", Text_Yell, 11259); SetAIUpdateFreq(5000); break; case 2: Emote("You have persevered against some of my best advisors. But none can withstand the might of the Bloodhammer. Behold, Lord Sanguinar.", Text_Yell, 11260); SetAIUpdateFreq(12000); break; case 3: Emote("Capernian will see to it that your stay here is a short one.", Text_Yell, 11257); SetAIUpdateFreq(5000); break; case 4: Emote("Well done. You have proven worthy to test your skills against my Master Engineer, Telonicus.", Text_Yell, 11258); SetAIUpdateFreq(8000); break; } mAdvisorPhase = PHASE_ATTACK_COMMAND; } void SendAdvisorToFight(Creature* pCreature) { pCreature->GetAIInterface()->SetAllowedToEnterCombat(true); pCreature->SetUInt64Value(UNIT_FIELD_FLAGS, 0); Unit* pTarget = GetBestPlayerTarget(); if(pTarget != NULL) { pCreature->GetAIInterface()->AttackReaction(pTarget, 200, 0); } SetAIUpdateFreq(1000); mAdvisorPhase = PHASE_ADV_FIGHT; } void CheckAdvisorState(Creature* pCreature) { if(!pCreature->isAlive()) { LocationExtra pCoords; pCoords.x = pCreature->GetPositionX(); pCoords.y = pCreature->GetPositionY(); pCoords.z = pCreature->GetPositionZ(); pCoords.o = pCreature->GetOrientation(); pCoords.addition = pCreature->GetEntry(); SetAIUpdateFreq(5000); SetPhase(GetPhase() + 1); mAdvCoords.push_back(pCoords); mAdvisorPhase = PHASE_SPEECH; } } void AIUpdate() { if(GetPhase() < 5) { uint32 i = GetPhase() > 0 ? GetPhase() - 1 : 0; Creature* pCreature = TO_CREATURE(ForceCreatureFind(Advisors[i].addition, Advisors[i].x, Advisors[i].y, Advisors[i].z)); if(pCreature == NULL || (!pCreature->isAlive() && mAdvisorPhase != PHASE_ADV_FIGHT)) { LocationExtra pCoords; pCoords.x = Advisors[i].x; pCoords.y = Advisors[i].y; pCoords.z = Advisors[i].z; pCoords.o = Advisors[i].o; pCoords.addition = Advisors[i].addition; mAdvCoords.push_back(pCoords); SetPhase(GetPhase() + 1); mAdvisorPhase = PHASE_SPEECH; return; } switch(mAdvisorPhase) { case PHASE_SPEECH: SendAdvisorEmote(); break; case PHASE_ATTACK_COMMAND: SendAdvisorToFight(pCreature); break; case PHASE_ADV_FIGHT: CheckAdvisorState(pCreature); break; } } if(GetPhase() == 5) { if(mEventTimer == -1) { CastSpellNowNoScheduling(mSummonWeapons); SetAIUpdateFreq(3000); mEventTimer = -2; return; } else if(mEventTimer == -2) { for(int i = 0; i < 7; ++i) { SpawnCreature(KaelthasWeapons[i].addition, KaelthasWeapons[i].x, KaelthasWeapons[i].y, KaelthasWeapons[i].z, KaelthasWeapons[i].o); } SetAIUpdateFreq(1000); mEventTimer = AddTimer(125000); return; } else if(IsTimerFinished(mEventTimer)) { for(int i = 0; i < 4; ++i) { if(mAdvCoords.size() <= (size_t)i) break; Creature* pCreature = TO_CREATURE(ForceCreatureFind(mAdvCoords[i].addition, mAdvCoords[i].x, mAdvCoords[i].y, mAdvCoords[i].z)); if(pCreature != NULL && !pCreature->isAlive()) { pCreature->Despawn(0, 0); } MoonScriptCreatureAI* pAI = SpawnCreature(mAdvCoords[i].addition, mAdvCoords[i].x, mAdvCoords[i].y, mAdvCoords[i].z, false); if(pAI != NULL) { pCreature = pAI->GetUnit(); } else continue; if(pCreature != NULL) { pCreature->GetAIInterface()->SetAllowedToEnterCombat(true); pCreature->SetUInt64Value(UNIT_FIELD_FLAGS, 0); if(pCreature->GetScript() != NULL) { TO< MoonScriptCreatureAI* >(pCreature->GetScript())->AggroNearestUnit(200); } } } Emote("Perhaps I underestimated you. It would be unfair to make you fight all four Advisors at once, but...fair treatment was never shown to my people. I'm just returning the favor.", Text_Yell, 11262); ResetTimer(mEventTimer, 180000); SetPhase(6); mAdvCoords.clear(); } ParentClass::AIUpdate(); SetBehavior(Behavior_Spell); SetCanMove(false); } if(GetPhase() == 6) { ParentClass::AIUpdate(); if(IsTimerFinished(mEventTimer)) { mArcaneDisruptionTimer = AddTimer(20000); mShockBarrierTimer = AddTimer(60000); mFlameStrikeTimer = AddTimer(40000); SetCanEnterCombat(true); SetBehavior(Behavior_Default); SetCanMove(true); SetPhase(7); } else { SetBehavior(Behavior_Spell); SetCanMove(false); } return; } if(GetPhase() == 7) { if(!IsCasting()) { if(GetBehavior() == Behavior_Spell) { SetBehavior(Behavior_Default); SetCanMove(true); } if(IsTimerFinished(mShockBarrierTimer)) { CastSpellNowNoScheduling(mShockBarrier); ResetTimer(mShockBarrierTimer, 70000); } else if(IsTimerFinished(mArcaneDisruptionTimer)) { CastSpellNowNoScheduling(mArcaneDisruptionFunc); ResetTimer(mArcaneDisruptionTimer, 30000); } else if(IsTimerFinished(mFlameStrikeTimer)) { CastSpellNowNoScheduling(mFlameStrikeFunc); } } if(_unit->HasAura(KAELTHAS_SHOCK_BARRIER)) { CastSpellNowNoScheduling(mPyroblast); SetBehavior(Behavior_Spell); SetCanMove(false); } else if(IsTimerFinished(mPhoenixTimer)) // it spawns on caster's place, but should in 20y from him { // also it seems to not work (not always) CastSpell(mPhoenix); RemoveTimer(mPhoenixTimer); } ParentClass::AIUpdate(); } } Unit* GetRandomPlayer() { return GetBestPlayerTarget(TargetFilter_NotCurrent); } SpellDesc* mSummonWeapons; SpellDesc* mArcaneDisruption; SpellDesc* mArcaneDisruptionFunc; SpellDesc* mShockBarrier; SpellDesc* mPyroblast; SpellDesc* mFlameStrike; SpellDesc* mFlameStrikeFunc; SpellDesc* mPhoenix; SpellDesc* mNetherBeam; AdvisorPhase mAdvisorPhase; int32 mArcaneDisruptionTimer; int32 mShockBarrierTimer; int32 mFlameStrikeTimer; int32 mPhoenixTimer; int32 mEventTimer; std::vector<LocationExtra> mAdvCoords; }; void SpellFunc_KaelThasArcaneDisruption(SpellDesc* pThis, MoonScriptCreatureAI* pCreatureAI, Unit* pTarget, TargetType pType) { KaelThasAI* KaelThas = (pCreatureAI) ? TO< KaelThasAI* >(pCreatureAI) : NULL; if(KaelThas != NULL) { KaelThas->CastSpellNowNoScheduling(KaelThas->mArcaneDisruption); Unit* pMainTarget = KaelThas->GetUnit()->GetAIInterface()->getNextTarget(); if(pTarget != NULL && pMainTarget != NULL) { KaelThas->GetUnit()->GetAIInterface()->setNextTarget(pTarget); KaelThas->GetUnit()->GetAIInterface()->AttackReaction(pTarget, 1000); KaelThas->GetUnit()->GetAIInterface()->RemoveThreatByPtr(pMainTarget); } } } void SpellFunc_KaelThasFlameStrike(SpellDesc* pThis, MoonScriptCreatureAI* pCreatureAI, Unit* pTarget, TargetType pType) { KaelThasAI* KaelThas = (pCreatureAI) ? TO< KaelThasAI* >(pCreatureAI) : NULL; if(KaelThas != NULL) { if(pTarget != NULL) { KaelThas->GetUnit()->CastSpell(pTarget, KAELTHAS_FLAME_STRIKE_SUMMON, true); Creature* pFriendlyTrigger = TO_CREATURE(KaelThas->ForceCreatureFind(CN_FLAME_STRIKE_TRIGGER)); if(pFriendlyTrigger != NULL && pFriendlyTrigger->IsPet()) { pFriendlyTrigger->Despawn(0, 0); } KaelThas->SpawnCreature(CN_FLAME_STRIKE_TRIGGER, pTarget->GetPositionX(), pTarget->GetPositionY(), pTarget->GetPositionZ(), pTarget->GetOrientation()); uint32 TimerAdd = (3 + RandomUInt(5)) * 1000; KaelThas->mPhoenixTimer = KaelThas->AddTimer(TimerAdd); KaelThas->ResetTimer(KaelThas->mFlameStrikeTimer, TimerAdd + 40000); return; } KaelThas->ResetTimer(KaelThas->mFlameStrikeTimer, 40000); } } void SetupTheEye(ScriptMgr* mgr) { //Trash mobs /*mgr->register_creature_script(CN_A_STAR_SCRYER, &AStarScryerAI::Create); mgr->register_creature_script(CN_ASTROMANCER, &AstromancerAI::Create); mgr->register_creature_script(CN_STAR_SCRYER, &StarScryerAI::Create); mgr->register_creature_script(CN_ASTROMANCER_LORD, &AstromancerLordAI::Create); mgr->register_creature_script(CN_BLOOD_VINDICATOR, &BloodVindicatorAI::Create); mgr->register_creature_script(CN_BLOOD_LEGIONNARE, &BloodLegionnareAI::Create); mgr->register_creature_script(CN_BLOOD_MARSHAL, &BloodMarshalAI::Create); mgr->register_creature_script(CN_PHOENIX_HAWK, &PhoenixHawkAI::Create); mgr->register_creature_script(CN_CRYSTAL_SENTINEL, &CrystalSentinelAI::Create); mgr->register_creature_script(CN_CRYSTAL_MECHANIC, &CrystalMechanicAI::Create);*/ //Void Reaver event mgr->register_creature_script(CN_VOID_REAVER, &VoidReaverAI::Create); //High Astromancer Solarian mgr->register_creature_script(CN_SOLARIAN, &HighAstromancerSolarianAI::Create); mgr->register_creature_script(CN_SOLARIUMAGENT, &SolariumAgentAI::Create); mgr->register_creature_script(CN_SOLARIUMPRIEST, &SolariumPriestAI::Create); mgr->register_creature_script(CN_SOLARIUM_SPOT_LIGHT, &SolariumSpotLight::Create); //Al'ar event /*mgr->register_creature_script(CN_ALAR, &AlarAI::Create); mgr->register_creature_script(CN_EMBEROFALAR, &EmberAlarAI::Create); mgr->register_creature_script(CN_PATCHALAR, &PatchAlarAI::Create);*/ //Kael'Thas Encounter mgr->register_creature_script(CN_PHOENIX, &PhoenixAI::Create); mgr->register_creature_script(CN_PHOENIX_EGG, &PhoenixEggAI::Create); mgr->register_creature_script(CN_FLAME_STRIKE_TRIGGER, &FlameStrikeAI::Create); mgr->register_creature_script(CN_DARKENER, &DarkenerAI::Create); mgr->register_creature_script(CN_SANGUINAR, &SanguinarAI::Create); mgr->register_creature_script(CN_CAPERNIAN, &CapernianAI::Create); mgr->register_creature_script(CN_TELONICUS, &TelonicusAI::Create); mgr->register_creature_script(CN_KAELTHAS, &KaelThasAI::Create); // Kael'thas Weapons mgr->register_creature_script(NETHERSTRAND_LONGBOW, &WeaponsAI::Create); mgr->register_creature_script(DEVASTATION, &WeaponsAI::Create); mgr->register_creature_script(COSMIC_INFUSER, &WeaponsAI::Create); mgr->register_creature_script(INFINITY_BLADE, &WeaponsAI::Create); mgr->register_creature_script(WARP_SLICER, &WeaponsAI::Create); mgr->register_creature_script(PHASESHIFT_BULWARK, &WeaponsAI::Create); mgr->register_creature_script(STAFF_OF_DISINTEGRATION, &WeaponsAI::Create); }
[ "zbestofzbest@yahoo.com" ]
zbestofzbest@yahoo.com
512ca3c69b03c4d34a5c02a8f917c3a23ba957eb
20487d6bed34c8af7192064a234fe7db1461fdfc
/w8/Project4_Yucen_Cao/character_base.cpp
9fa81116a1197ce038e8c3a8f00f7e94a36b32e7
[]
no_license
caoyucen/OSU_CS162
0eaf911f8914e566df5b8b9e9f60ed0c3ad6340a
16b9a920f6426ce454917b2e90f31f90cfe5736f
refs/heads/master
2020-12-11T00:14:08.512837
2020-01-14T04:01:29
2020-01-14T04:01:29
233,749,692
0
0
null
null
null
null
UTF-8
C++
false
false
3,768
cpp
//********************************************************************* // Project3 // Program name: character_base.cpp // Author: YUCEN CAO - CS162 Spring 2019 // Date: May 6, 2019 // Description: In this project, we will develop a fantasy combat game. This is going to be part 1 of the game development in which we develop the characters and a menu to test the characters. // The game universe contains Vampire, Barbarian, Blue Men, Medusa, and Harry Potter. Each character has attributes of attack, defense, armor, and strength points. // ********************************************************************* #include "character_base.hpp" namespace cs_characterBase { //constructor CharacterBase::CharacterBase(const string name) { attack_sizeDie = 0; attack_die_side = 0; defense_sizeDie = 0; defense_die_side = 0; armor = 0; strength = 0; ctype = 0; //1 Vampire, 2 Barbarian, 3 Blue Men, 4 Medusa, 5 Harry Potter type_name = ""; character_name = name; } //get type name string CharacterBase::get_name(){ return (type_name); } string CharacterBase::get_character_name() { return character_name; } //get armor int CharacterBase::get_armor(){ return (armor); } //get strength int CharacterBase::get_strength(){ return (strength); } //get type int CharacterBase::get_ctype() { return (ctype); } /** * recovers pct % of max health */ void CharacterBase::recover(double pct) { strength = ((strength + pct * max_strength) > max_strength) ? (strength + pct * max_strength) : max_strength; //std::cout << "Recover: " << get_character_name() // << "recovered " << pct << " percent of max strength, current strength is: " // << get_strength() << std::endl; } void CharacterBase::decide_recover() { recover(double(rand() % 101) * 0.01); } //get the attack point int CharacterBase::attack() { //std::cout<< "---Attack---" << std::endl; int roll = 0; int point = 0; for ( int i = 0 ; i < attack_sizeDie; i++){ roll = rand() % attack_die_side + 1; point =point + roll; //std::cout << "The attack: " <<"NO." << i+1 << " dice rolls " << roll << " points." << std::endl; } //std::cout << type_name << " attacks " << point << " points." << std::endl; return (point); } //get the defense point int CharacterBase::defense() { int roll = 0; int point = 0; //std::cout<< "---Defense---" << std::endl; for (int i = 0; i < defense_sizeDie; i++){ roll = rand() % defense_die_side + 1; point = point + roll; //std::cout << "The defense: NO." << i+1 << " dice rolls " << roll << " points." << std::endl; } //std::cout << type_name << " defenses " << point << " points." << std::endl; return (point); } void CharacterBase::actual_damage(int attack_point, int defense_point) { int total_damage = 0; //std::cout<< "---Total inflicted damage---" << std::endl; if (attack_point == 2147483646) { //std::cout << "The total inflicted damage calculation is: " << strength << "." << std::endl << "Oops, someone die because of the Glare. " << std::endl; strength = 0; } else{ total_damage = attack_point - defense_point - armor; if (total_damage <= 0){ //std::cout << " The defense is really strong, no damage." << std::endl; } else{ strength = strength - total_damage; //std::cout << "The total inflicted damage calculation is:" << total_damage<< std::endl; } } //"The Defender's Updated Strength After Damage Subtracted:" if (strength <= 0){ //std::cout << type_name << " dies. No more strength" << std::endl; } else{ //std::cout << "After Damage Subtracted: " << type_name << "'s strength is: " << strength << std::endl; } } }
[ "caoyucen@gmail.com" ]
caoyucen@gmail.com
111925d63ba4fc1c8a45e2e306e78980ac6d3f75
0d666be1446398c359aa4a8ed5c2adaebc1da4a1
/OverlordProject/CourseObjects/Game/ExamGameMainMenuScene.cpp
db73027ba6b84385e3212e38aaab83ba0b21f803
[]
no_license
AliyevRufat/GhostOfFuji
76aa88f5b43b12c02ddc397da538f17d2c1a4f13
a445749b5b94baa9a82df6b2b2befc01457986e9
refs/heads/master
2023-08-19T09:10:32.904068
2021-10-08T15:24:43
2021-10-08T15:24:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,534
cpp
#include "stdafx.h" #include "ExamGameMainMenuScene.h" #include "Logger.h" #include "SpriteRenderer.h" #include "ContentManager.h" #include "SpriteFont.h" #include "TextRenderer.h" #include "OverlordGame.h" #include "SceneManager.h" #include "SpriteComponent.h" #include "GameObject.h" #include "../OverlordProject/AudioManager.h" ExamGameMainMenuScene::ExamGameMainMenuScene() : GameScene(L"ExamGameMainMenuScene") { } void ExamGameMainMenuScene::Initialize() { auto go = new GameObject(); go->AddComponent(new SpriteComponent(L"./Resources/Textures/MainMenu.png", DirectX::XMFLOAT2(0.f, 0.f), DirectX::XMFLOAT4(1, 1, 1, 1))); AddChild(go); m_pFont = ContentManager::Load<SpriteFont>(L"Resources/SpriteFonts/MyConsolas.fnt"); m_MenuOptions.push_back(L"Start"); m_MenuOptions.push_back(L"Exit"); GetGameContext().pInput->AddInputAction( InputAction((int)MenuControls::Up, InputTriggerState::Pressed, VK_UP)); GetGameContext().pInput->AddInputAction( InputAction((int)MenuControls::Down, InputTriggerState::Pressed, VK_DOWN)); GetGameContext().pInput->AddInputAction( InputAction((int)MenuControls::Select, InputTriggerState::Pressed, VK_RETURN)); } void ExamGameMainMenuScene::Update() { if (GetGameContext().pInput->IsActionTriggered((int)MenuControls::Up)) { if (m_SelectedMenuOption == 0) m_SelectedMenuOption = m_MenuOptions.size() - 1; else m_SelectedMenuOption--; } else if (GetGameContext().pInput->IsActionTriggered((int)MenuControls::Down)) { if (m_SelectedMenuOption == (int)m_MenuOptions.size() - 1) m_SelectedMenuOption = 0; else m_SelectedMenuOption++; } else if (GetGameContext().pInput->IsActionTriggered((int)MenuControls::Select)) { switch (m_SelectedMenuOption) { case 0: SceneManager::GetInstance()->SetActiveGameScene(L"ExamGameScene"); break; case 1: OverlordGame::EndGame(); break; } } } void ExamGameMainMenuScene::Draw() { if (m_pFont->GetFontName() != L"") { for (size_t i = 0; i < m_MenuOptions.size(); i++) { DirectX::XMFLOAT2 windowWH = TextRenderer::GetInstance()->GetWindowWidthHeight(); if ((int)i == m_SelectedMenuOption) TextRenderer::GetInstance()->DrawText(m_pFont, m_MenuOptions[i], DirectX::XMFLOAT2(windowWH.x / 2 - 45, windowWH.y / 2 + (i * 60)), static_cast<DirectX::XMFLOAT4>(DirectX::Colors::Black)); else TextRenderer::GetInstance()->DrawText(m_pFont, m_MenuOptions[i], DirectX::XMFLOAT2(windowWH.x / 2 - 45, windowWH.y / 2 + (i * 60)), static_cast<DirectX::XMFLOAT4>(DirectX::Colors::White)); } } }
[ "76409612+AliyevRufat@users.noreply.github.com" ]
76409612+AliyevRufat@users.noreply.github.com
df8481939f06d976613765a78c2227664a005ee0
022ab015bc7e0cc1ca43ea95b063373858129094
/icp/contest_7/A.cpp
2cadd847f23040bf4d0e0603ee7f62ee23a5dc4a
[]
no_license
italovinicius18/contests
ee1afdcafdd0b21801bd0537acbe0edc1cb73baf
c2a9919f30ffcff5fde0721dd654df0487a6c89f
refs/heads/master
2022-07-31T13:57:07.869149
2020-05-15T19:03:12
2020-05-15T19:03:12
261,821,345
0
0
null
null
null
null
UTF-8
C++
false
false
196
cpp
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n,k; cin >> n>> k; while(k--){ } return 0; }
[ "italovinicius18@yahoo.com" ]
italovinicius18@yahoo.com
30ac672a7941733c5c535a8524eafc4b482c63cf
8d2329ab697a2e963fd592e02a9b81e28964962e
/opencv/立体标定-校正-匹配-加标注.cpp
f0a686e9f27abf169f4f6b796b17c97341125bbc
[]
no_license
tsingjinyun/----------
c20bd6af9e6a4b9e0e770d90f2771be645ed906d
05efa7ef2b60fb95a077b3164299a0d38bd3e44d
refs/heads/master
2021-11-25T07:04:20.434528
2021-11-18T09:41:14
2021-11-18T09:41:14
14,815,374
1
1
null
null
null
null
GB18030
C++
false
false
16,340
cpp
/* This is sample from the OpenCV book. The copyright notice is below */ /* *************** License:************************** Oct. 3, 2008 Right to use this code in any way you want without warrenty, support or any guarentee of it working. BOOK: It would be nice if you cited it: Learning OpenCV: Computer Vision with the OpenCV Library by Gary Bradski and Adrian Kaehler Published by O'Reilly Media, October 3, 2008 AVAILABLE AT: http://www.amazon.com/Learning-OpenCV-Computer-Vision-Library/dp/0596516134 Or: http://oreilly.com/catalog/9780596516130/ ISBN-10: 0596516134 or: ISBN-13: 978-0596516130 OTHER OPENCV SITES: * The source code is on sourceforge at: http://sourceforge.net/projects/opencvlibrary/ * The OpenCV wiki page (As of Oct 1, 2008 this is down for changing over servers, but should come back): http://opencvlibrary.sourceforge.net/ * An active user group is at: http://tech.groups.yahoo.com/group/OpenCV/ * The minutes of weekly OpenCV development meetings are at: http://pr.willowgarage.com/wiki/OpenCV ************************************************** */ #include "StdAfx.h" #include "cv.h" #include "cxmisc.h" #include "highgui.h" #include <vector> #include <string> #include <algorithm> #include <stdio.h> #include <ctype.h> using namespace std; // // Given a list of chessboard images, the number of corners (nx, ny) // on the chessboards, and a flag: useCalibrated for calibrated (0) or // uncalibrated (1: use cvStereoCalibrate(), 2: compute fundamental // matrix separately) stereo. Calibrate the cameras and display the // rectified results along with the computed disparity images. // static void StereoCalib(const char* imageList, int useUncalibrated) { int nx = 0, ny = 0; // the number of corners (nx, ny) int displayCorners = 0; int showUndistorted = 1; bool isVerticalStereo = false; //OpenCV can handle left-right //or up-down camera arrangements const int maxScale = 1; // 缩放图像以寻找精确的棋盘角点坐标 const float squareSize = 1.f; // 设置为实际的方块大小 FILE* f = fopen(imageList, "rt"); // 打开含有左右视图图像列表的txt文档 int i, j, lr, nframes, n, N = 0; vector<string> imageNames[2]; // vector<type> 是C++的向量类,相当于 char* vector<CvPoint3D32f> objectPoints; // 存储棋盘角点的实际坐标 vector<CvPoint2D32f> points[2]; // 存储棋盘角点的图像坐标 vector<int> npoints; // 存储每幅图像的角点数目 vector<uchar> active[2]; // 记录成功检测角点的棋盘数目 vector<CvPoint2D32f> temp; // 缓存每幅图像检测到的棋盘角点坐标 CvSize imageSize = {0,0}; // ARRAY AND VECTOR STORAGE: double M1[3][3], M2[3][3], D1[5], D2[5]; double R[3][3], T[3], E[3][3], F[3][3]; CvMat _M1 = cvMat(3, 3, CV_64F, M1 ); CvMat _M2 = cvMat(3, 3, CV_64F, M2 ); CvMat _D1 = cvMat(1, 5, CV_64F, D1 ); CvMat _D2 = cvMat(1, 5, CV_64F, D2 ); CvMat _R = cvMat(3, 3, CV_64F, R ); CvMat _T = cvMat(3, 1, CV_64F, T ); CvMat _E = cvMat(3, 3, CV_64F, E ); CvMat _F = cvMat(3, 3, CV_64F, F ); char buf[1024]; if( displayCorners ) cvNamedWindow( "corners", 1 ); // 读入含有左右视图图像列表的txt文档: if( !f ) { fprintf(stderr, "can not open file %s\n", imageList ); return; } if( !fgets(buf, sizeof(buf)-3, f) || sscanf(buf, "%d%d", &nx, &ny) != 2 ) return; n = nx*ny; temp.resize(n); for(i=0;;i++) { int count = 0, result=0; // 用模2的方法在循环中区分左右图像,偶左奇右 lr = i % 2; vector<CvPoint2D32f>& pts = points[lr]; if( !fgets( buf, sizeof(buf)-3, f )) break; size_t len = strlen(buf); // 将最后一个字符替换为终止符'\0' while( len > 0 && isspace(buf[len-1])) buf[--len] = '\0'; // 首字符为'#'时则跳过,转入下一循环 if( buf[0] == '#') continue; // 读取本地图像 IplImage* img = cvLoadImage( buf, 0 ); if( !img ) break; imageSize = cvGetSize(img); imageNames[lr].push_back(buf); // (缩放图像)寻找棋盘及其角点: for( int s = 1; s <= maxScale; s++ ) { IplImage* timg = img; // 若 s>1,则放大图像 if( s > 1 ) { timg = cvCreateImage(cvSize(img->width*s,img->height*s), img->depth, img->nChannels ); cvResize( img, timg, CV_INTER_CUBIC ); } // 寻找棋盘中的角点 result = cvFindChessboardCorners( timg, cvSize(nx, ny), &temp[0], &count, CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_NORMALIZE_IMAGE); // 如果 timg 是放大后的图像,则释放其占用的内存 if( timg != img ) cvReleaseImage( &timg ); // 将检测到的角点坐标数据存入到 temp if( result || s == maxScale ) for( j = 0; j < count; j++ ) { temp[j].x /= s; temp[j].y /= s; } // 已检测到角点,转入下一步骤 if( result ) break; } // 显示检测到的角点 if( displayCorners ) { printf("%s\n", buf); IplImage* cimg = cvCreateImage( imageSize, 8, 3 ); cvCvtColor( img, cimg, CV_GRAY2BGR ); cvDrawChessboardCorners( cimg, cvSize(nx, ny), &temp[0], count, result ); cvShowImage( "corners", cimg ); cvReleaseImage( &cimg ); int c = cvWaitKey(1000); if( c == 27 || c == 'q' || c == 'Q' ) //Allow ESC to quit exit(-1); } else putchar('.'); // 向终端输出字符'.' // 将 pts 增加 n 个元素,每个元素初始值为 (0,0) // 注意操作对象是 points[lr] N = pts.size(); pts.resize(N + n, cvPoint2D32f(0,0)); // 将角点检测结果 result 存入向量 active active[lr].push_back((uchar)result); //assert( result != 0 ); // 将检测到的角点坐标精确化 if( result ) { //Calibration will suffer without subpixel interpolation cvFindCornerSubPix( img, &temp[0], count, cvSize(11, 11), cvSize(-1,-1), cvTermCriteria(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, 30, 0.01) ); // 将 temp 的角点坐标数据复制到 pts 中 copy( temp.begin(), temp.end(), pts.begin() + N ); } cvReleaseImage( &img ); } // 已读入并处理所有的图像 fclose(f); printf("\n"); // 生成棋盘角点的三维实际坐标: nframes = active[0].size(); //Number of good chessboads found objectPoints.resize(nframes*n); // 单幅图像对应的实际角点坐标; for( i = 0; i < ny; i++ ) for( j = 0; j < nx; j++ ) objectPoints[i*nx + j] = cvPoint3D32f(i*squareSize, j*squareSize, 0); // 将实际坐标复制 nframes 次 for( i = 1; i < nframes; i++ ) copy( objectPoints.begin(), objectPoints.begin() + n, objectPoints.begin() + i*n ); // 每幅图像的角点数均为 n npoints.resize(nframes,n); N = nframes*n; CvMat _objectPoints = cvMat(1, N, CV_32FC3, &objectPoints[0] ); CvMat _imagePoints1 = cvMat(1, N, CV_32FC2, &points[0][0] ); CvMat _imagePoints2 = cvMat(1, N, CV_32FC2, &points[1][0] ); CvMat _npoints = cvMat(1, npoints.size(), CV_32S, &npoints[0] ); cvSetIdentity(&_M1); cvSetIdentity(&_M2); cvZero(&_D1); cvZero(&_D2); // 进行双摄像头标定 printf("Running stereo calibration ..."); fflush(stdout); cvStereoCalibrate( &_objectPoints, &_imagePoints1, &_imagePoints2, &_npoints, &_M1, &_D1, &_M2, &_D2, imageSize, &_R, &_T, &_E, &_F, cvTermCriteria(CV_TERMCRIT_ITER+ CV_TERMCRIT_EPS, 100, 1e-5), CV_CALIB_FIX_ASPECT_RATIO + CV_CALIB_ZERO_TANGENT_DIST + CV_CALIB_SAME_FOCAL_LENGTH ); printf(" done\n"); // 利用极线几何约束检查标定效果 // because the output fundamental matrix implicitly // includes all the output information, // we can check the quality of calibration using the // epipolar geometry constraint: m2^t*F*m1=0 vector<CvPoint3D32f> lines[2]; points[0].resize(N); points[1].resize(N); _imagePoints1 = cvMat(1, N, CV_32FC2, &points[0][0] ); _imagePoints2 = cvMat(1, N, CV_32FC2, &points[1][0] ); lines[0].resize(N); lines[1].resize(N); CvMat _L1 = cvMat(1, N, CV_32FC3, &lines[0][0]); CvMat _L2 = cvMat(1, N, CV_32FC3, &lines[1][0]); //Always work in undistorted space cvUndistortPoints( &_imagePoints1, &_imagePoints1, &_M1, &_D1, 0, &_M1 ); cvUndistortPoints( &_imagePoints2, &_imagePoints2, &_M2, &_D2, 0, &_M2 ); cvComputeCorrespondEpilines( &_imagePoints1, 1, &_F, &_L1 ); cvComputeCorrespondEpilines( &_imagePoints2, 2, &_F, &_L2 ); double avgErr = 0; for( i = 0; i < N; i++ ) { double err = fabs(points[0][i].x*lines[1][i].x + points[0][i].y*lines[1][i].y + lines[1][i].z) + fabs(points[1][i].x*lines[0][i].x + points[1][i].y*lines[0][i].y + lines[0][i].z); avgErr += err; } printf( "avg err = %g\n", avgErr/(nframes*n) ); // 双目校正,并求取视差 if( showUndistorted ) { // 初始化 CvMat* mx1 = cvCreateMat( imageSize.height, imageSize.width, CV_32F ); CvMat* my1 = cvCreateMat( imageSize.height, imageSize.width, CV_32F ); CvMat* mx2 = cvCreateMat( imageSize.height, imageSize.width, CV_32F ); CvMat* my2 = cvCreateMat( imageSize.height, imageSize.width, CV_32F ); CvMat* img1r = cvCreateMat( imageSize.height, imageSize.width, CV_8U ); CvMat* img2r = cvCreateMat( imageSize.height, imageSize.width, CV_8U ); CvMat* disp = cvCreateMat( imageSize.height, imageSize.width, CV_16S ); CvMat* vdisp = cvCreateMat( imageSize.height, imageSize.width, CV_8U ); CvMat* pair; // 创建 pair 用来存放、显示校正后的左右视图数据 if( !isVerticalStereo ) pair = cvCreateMat( imageSize.height, imageSize.width*2, CV_8UC3 ); else pair = cvCreateMat( imageSize.height*2, imageSize.width, CV_8UC3 ); // 使用 Bouguet 或 Hartley 方法求取双目校正参数 // double R1[3][3], R2[3][3], P1[3][4], P2[3][4]; CvMat _R1 = cvMat(3, 3, CV_64F, R1); CvMat _R2 = cvMat(3, 3, CV_64F, R2); // IF BY CALIBRATED (BOUGUET'S METHOD) if( useUncalibrated == 0 ) { CvMat _P1 = cvMat(3, 4, CV_64F, P1); CvMat _P2 = cvMat(3, 4, CV_64F, P2); cvStereoRectify( &_M1, &_M2, &_D1, &_D2, imageSize, &_R, &_T, &_R1, &_R2, &_P1, &_P2, 0, 0/*CV_CALIB_ZERO_DISPARITY*/ ); isVerticalStereo = fabs(P2[1][3]) > fabs(P2[0][3]); //Precompute maps for cvRemap() cvInitUndistortRectifyMap(&_M1,&_D1,&_R1,&_P1,mx1,my1); cvInitUndistortRectifyMap(&_M2,&_D2,&_R2,&_P2,mx2,my2); } //OR ELSE HARTLEY'S METHOD else if( useUncalibrated == 1 || useUncalibrated == 2 ) // use intrinsic parameters of each camera, but // compute the rectification transformation directly // from the fundamental matrix { double H1[3][3], H2[3][3], iM[3][3]; CvMat _H1 = cvMat(3, 3, CV_64F, H1); CvMat _H2 = cvMat(3, 3, CV_64F, H2); CvMat _iM = cvMat(3, 3, CV_64F, iM); // 逆矩阵 //Just to show you could have independently used F if( useUncalibrated == 2 ) cvFindFundamentalMat( &_imagePoints1, &_imagePoints2, &_F); cvStereoRectifyUncalibrated( &_imagePoints1, &_imagePoints2, &_F, imageSize, &_H1, &_H2, 3); cvInvert(&_M1, &_iM); // iM=M1^(-1) cvMatMul(&_H1, &_M1, &_R1); // R1=H1*M1 cvMatMul(&_iM, &_R1, &_R1); // R1=iM*R1=iM*H1*M1 cvInvert(&_M2, &_iM); cvMatMul(&_H2, &_M2, &_R2); cvMatMul(&_iM, &_R2, &_R2); //Precompute map for cvRemap() cvInitUndistortRectifyMap(&_M1,&_D1,&_R1,&_M1,mx1,my1); cvInitUndistortRectifyMap(&_M2,&_D1,&_R2,&_M2,mx2,my2); } else assert(0); cvNamedWindow( "rectified", 1 ); // 创建 CvStereoBMState 类的一个实例 BMState,以求取视差 CvStereoBMState *BMState = cvCreateStereoBMState(); assert(BMState != 0); BMState->preFilterSize=33; BMState->preFilterCap=33; BMState->SADWindowSize=33; if( useUncalibrated ) { BMState->minDisparity=-64; BMState->numberOfDisparities=128; } else { BMState->minDisparity=-32; BMState->numberOfDisparities=192; } BMState->textureThreshold=10; BMState->uniquenessRatio=15; // 循环处理左右视图 // for( i = 0; i < nframes; i++ ) { IplImage* img1=cvLoadImage(imageNames[0][i].c_str(),0); IplImage* img2=cvLoadImage(imageNames[1][i].c_str(),0); if( img1 && img2 ) { CvMat part; cvRemap( img1, img1r, mx1, my1 ); cvRemap( img2, img2r, mx2, my2 ); // 求取视差 if( !isVerticalStereo || useUncalibrated != 0 ) { // When the stereo camera is oriented vertically, // useUncalibrated==0 does not transpose the // image, so the epipolar lines in the rectified // images are vertical. Stereo correspondence // function does not support such a case. cvFindStereoCorrespondenceBM( img1r, img2r, disp, BMState); cvNormalize( disp, vdisp, 0, 256, CV_MINMAX ); cvNamedWindow( "disparity" ); cvShowImage( "disparity", vdisp ); } // 显示双目校正后的图像 if( !isVerticalStereo ) { cvGetCols( pair, &part, 0, imageSize.width ); cvCvtColor( img1r, &part, CV_GRAY2BGR ); cvGetCols( pair, &part, imageSize.width, imageSize.width*2 ); cvCvtColor( img2r, &part, CV_GRAY2BGR ); for( j = 0; j < imageSize.height; j += 16 ) cvLine( pair, cvPoint(0,j), cvPoint(imageSize.width*2,j), CV_RGB(0,255,0)); } else { cvGetRows( pair, &part, 0, imageSize.height ); cvCvtColor( img1r, &part, CV_GRAY2BGR ); cvGetRows( pair, &part, imageSize.height, imageSize.height*2 ); cvCvtColor( img2r, &part, CV_GRAY2BGR ); for( j = 0; j < imageSize.width; j += 16 ) cvLine( pair, cvPoint(j,0), cvPoint(j,imageSize.height*2), CV_RGB(0,255,0)); } cvShowImage( "rectified", pair ); if( cvWaitKey() == 27 ) break; } cvReleaseImage( &img1 ); cvReleaseImage( &img2 ); } cvReleaseStereoBMState(&BMState); cvReleaseMat( &mx1 ); cvReleaseMat( &my1 ); cvReleaseMat( &mx2 ); cvReleaseMat( &my2 ); cvReleaseMat( &img1r ); cvReleaseMat( &img2r ); cvReleaseMat( &disp ); } } // 主程序 // int main(int argc, char** argv) { StereoCalib(argc > 1 ? argv[1] : "ch12_list.txt", 1); return 0; }
[ "dongyxin@126.com" ]
dongyxin@126.com
117378cdc355201afe679718cd6f3dbf4d2f74e6
b3f5ecfd3912c5695f00538542e9b072f8b237b0
/InputComponent.cpp
3eb80cf6f8df7b3594b685cbfb5c8b0e65d93b0e
[]
no_license
xsat/unit
0a7c2e4ad176a90da8af6f14aba899c6ae14448a
4190a048dc11632ada45a0bda299dbced931e3ce
refs/heads/master
2021-05-16T08:57:36.823225
2017-10-08T20:06:59
2017-10-08T20:06:59
104,258,899
0
0
null
null
null
null
UTF-8
C++
false
false
264
cpp
#include "InputComponent.h" namespace unit { /* virtual */ void InputComponent::update(sf::RenderWindow *window) { sf::Event event; while (window->pollEvent(event)) { if (event.type == sf::Event::Closed) { window->close(); } } } }; // namespace unit
[ "xsat.php@gmail.com" ]
xsat.php@gmail.com
8fda1f1777eb03f904276bf77cdf6f8e38cbcf08
185dc32ae942476709850d9b31db5d38935a1b4d
/examples/cpp/parantheses.inl
95a4dff1c4979653cebb26df10a9857ad480b514
[ "BSD-2-Clause" ]
permissive
PearCoding/ParMaLy
fc3c3a4c43a50e07da369ce7b009cde2a1e07b61
e71e9abd6dd3e0842e3230c4dba7a2c9c18bd452
refs/heads/master
2022-05-04T08:16:33.538874
2022-04-29T00:15:49
2022-04-29T00:15:49
53,277,112
1
0
null
null
null
null
UTF-8
C++
false
false
2,651
inl
struct ParseResult { bool Successful; void* Return; }; class Parser { protected: /* Tokens returned by the lexer */ enum BUToken { _BUT_EOF=0, BUT_0, // ( BUT_1, // ) }; virtual BUToken nextToken(void** param) = 0; public: ParseResult parse(); }; /* Utility functions */ typedef uint64_t table_entry_t; typedef uint64_t state_t; enum ActionType {AT_INVALID=0, AT_ACCEPT, AT_REDUCE, AT_SHIFT}; inline ActionType extractAction(table_entry_t entry) { return (ActionType)((0xC000000000000000 & entry) >> 0x3E); } inline state_t extractState(table_entry_t entry) { return (0x3FFFFFFFFFFFFFFF & entry); } /* Rule groups defined by the grammar */ enum BURuleGroup { BURG_0=0, // goal BURG_1=1, // list BURG_2=2, // pair }; /* Action Table */ constexpr int LookaheadCount = 1; constexpr int TokenCount = 3; constexpr int StateCount = 8; static uint64_t indirectTokenMap[3]={ 1,0,2 }; const static table_entry_t actionTable[]={ 0xC000000000000003, 0, 0, 0xC000000000000003, 0x4000000000000000, 0, 0x8000000000000002, 0x8000000000000002, 0, 0xC000000000000003, 0, 0xC000000000000006, 0x8000000000000001, 0x8000000000000001, 0, 0, 0, 0xC000000000000007, 0x8000000000000004, 0x8000000000000004, 0x8000000000000004, 0x8000000000000003, 0x8000000000000003, 0x8000000000000003, }; /* Goto Table */ constexpr int GroupCount = 3; const static uint64_t indirectGroupMap[3]={ 0,1,2 }; const static state_t gotoTable[]={ 0, 0x1, 0x2, 0, 0, 0x4, 0, 0, 0, 0, 0, 0x5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; /* Glue Tables */ const static BURuleGroup rule2GroupTable[]={ BURG_0,BURG_1,BURG_1,BURG_2,BURG_2 }; const static uint64_t ruleBetaTable[]={ 1,2,1,3,2 }; /* Parse Function */ ParseResult Parser::parse() { void* lexerParam = nullptr; std::stack<uint64_t> stack; stack.push(_BUT_EOF); stack.push(0); BUToken currentToken = nextToken(&lexerParam); while(true){ state_t state = stack.top(); table_entry_t entry = actionTable[state*TokenCount + indirectTokenMap[currentToken]]; ActionType action = extractAction(entry); uint64_t suffix = extractState(entry); switch(action){ case AT_INVALID: return ParseResult{false, nullptr}; case AT_ACCEPT: return ParseResult{true, nullptr}; case AT_REDUCE: { for(int i = 0; i < 2*ruleBetaTable[suffix]; ++i) stack.pop(); state = stack.top(); uint64_t grp = rule2GroupTable[suffix]; stack.push(grp); stack.push(gotoTable[state*GroupCount + indirectGroupMap[grp]]); } break; case AT_SHIFT: stack.push(currentToken); stack.push(suffix); currentToken = nextToken(&lexerParam); break; } } return ParseResult{true, nullptr}; };
[ "pearcoding@gmail.com" ]
pearcoding@gmail.com
cb1a726619f56af316b97fd176f68a26d8b6dfb1
7890e727f391539ae5f8bf0219bc06841d83443a
/gui/src/gui_focusframe_glues.cpp
9431ac0001d22879badd7a51b15317231e6dd1d8
[ "MIT" ]
permissive
dreamplayer-zhang/lxgui
9424d7e65a2208294d8157ff5a886e24961a667d
3128a25482ea189a5513c36f6261044d63f7bd4c
refs/heads/master
2022-11-01T06:51:34.974005
2020-06-17T19:19:39
2020-06-17T19:19:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,540
cpp
#include "lxgui/gui_focusframe.hpp" #include <lxgui/luapp_state.hpp> #include <lxgui/luapp_function.hpp> namespace lxgui { namespace gui { lua_focus_frame::lua_focus_frame(lua_State* pLua) : lua_frame(pLua) { if (pParent_) { pFocusFrameParent_ = pParent_->down_cast<focus_frame>(); if (!pFocusFrameParent_) throw exception("lua_focus_frame", "Dynamic cast failed !"); } } int lua_focus_frame::_clear_focus(lua_State* pLua) { if (!check_parent_()) return 0; lua::function mFunc("FocusFrame:clear_focus", pLua); pFocusFrameParent_->set_focus(false); return mFunc.on_return(); } int lua_focus_frame::_is_auto_focus(lua_State* pLua) { if (!check_parent_()) return 0; lua::function mFunc("FocusFrame:is_auto_focus", pLua); mFunc.push(pFocusFrameParent_->is_auto_focus_enabled()); return mFunc.on_return(); } int lua_focus_frame::_set_auto_focus(lua_State* pLua) { if (!check_parent_()) return 0; lua::function mFunc("FocusFrame:set_auto_focus", pLua); mFunc.add(0, "enabled", lua::type::BOOLEAN); if (mFunc.check()) pFocusFrameParent_->enable_auto_focus(mFunc.get(0)->get_bool()); return mFunc.on_return(); } int lua_focus_frame::_set_focus(lua_State* pLua) { if (!check_parent_()) return 0; lua::function mFunc("FocusFrame:set_focus", pLua); pFocusFrameParent_->set_focus(true); return mFunc.on_return(); } } }
[ "cschreib@orange.fr" ]
cschreib@orange.fr
57ae032c55fc7f6a7165bd3b33e74d436b34c28c
60ad2402566db36a0bc2584c41cdae2bcc322f6b
/Libraries/utils/MozillaParser-v-0-3-0/src/native/ProcessPool.h
91aeff8c40b039c7a76f14e39b8393cc42d8f084
[]
no_license
areeda/ldvw
95d3c2246ad0131c9942e970a82aba1e8564681b
c7a29c3eefecfe245ecb311e674bb825aa72e2c8
refs/heads/master
2020-12-25T15:28:43.195743
2016-12-07T02:08:17
2016-12-07T02:08:17
55,113,337
0
0
null
null
null
null
UTF-8
C++
false
false
1,730
h
#ifndef _PROCESS_POOL_H_ #define _PROCESS_POOL_H_ #if MOZILLAPARSER_USE_IPC #include <sys/types.h> #include <jni.h> #include <map> class Semaphore; class Lock; class ProcessDescriptor; /** * Implements a pool of ParserProcess processes with a specified minimum size. * An external semaphore is used to control the maximum allowable size of the * pool. */ class ProcessPool { public: /** * Create a new process pool. * * @param minSize The minimum number of children to keep around when * there is at least one idle child. * @param maxJobs The maximum number of jobs to assign to any given child * process before euthanizing it * @param semaphore The semaphore used to control the maximum size of the * process pool * @param lock The Lock object to use to protect critical sections. */ ProcessPool( size_t minSize, size_t maxJobs, Semaphore &semaphore, Lock &lock ); /** * Return a ProcessDescriptor for a worker process, creating a new process * if necessary. This method may block if the current number of child * processes is at least maxSize. */ const ProcessDescriptor *spawn( JNIEnv *env ); /** * Inform us that the specified worker is no longer in use. This method * must be called by the parent process when it has finished interacting * with the worker; otherwise the worker will always be considered busy! */ void release( JNIEnv *env, const ProcessDescriptor *pd ); private: typedef std::map<pid_t, ProcessDescriptor *> ProcessTable; size_t _minSize; size_t _maxJobs; Semaphore &_semaphore; Lock &_lock; ProcessTable _workers; }; #endif // MOZILLAPARSER_USE_IPC #endif // _PROCESS_POOL_H_
[ "joseph.areeda@ligo.org" ]
joseph.areeda@ligo.org
56ec5d9dabed2fdbf1b50f603e3246bce61b06a8
a0ca606eeab6f0614118c54d470dd41e4fa15723
/code/20.有效的括号.cpp
2c525c70a86ed4f4e7bd7750ad8091bc15ce2ae8
[]
no_license
MagicConchCpp/LeetCode
70f95bc045cc4f9452063965c0f8c963409da6c3
d35dd37174453d27d78173bc2d69e2ba41eddbdd
refs/heads/master
2022-10-28T03:01:06.568360
2020-06-15T13:40:24
2020-06-15T13:40:24
272,449,030
0
0
null
null
null
null
UTF-8
C++
false
false
557
cpp
/* * @lc app=leetcode.cn id=20 lang=cpp * * [20] 有效的括号 */ // @lc code=start #include<bits/stdc++.h> using namespace std; class Solution { public: bool isValid(string s) { stack<char> st; map<char, char> m = { {'(', ')'}, {'[', ']'}, {'{', '}'} }; for (auto c : s) { if (!st.empty() && m[st.top()] == c) { st.pop(); } else { st.push(c); } } return st.empty(); } }; // @lc code=end
[ "csuzhangyang@gmail.com" ]
csuzhangyang@gmail.com
a2811ee62e368d0d41b439060f2a59ccd483d6ff
3efc50ba20499cc9948473ee9ed2ccfce257d79a
/data/others/files/cfgtool.cpp
91b4eaa8484083c8331cbcf5f72d895f31943ec1
[ "Apache-2.0" ]
permissive
arthurherbout/crypto_code_detection
7e10ed03238278690d2d9acaa90fab73e52bab86
3c9ff8a4b2e4d341a069956a6259bf9f731adfc0
refs/heads/master
2020-07-29T15:34:31.380731
2019-12-20T13:52:39
2019-12-20T13:52:39
209,857,592
9
4
null
2019-12-20T13:52:42
2019-09-20T18:35:35
C
UTF-8
C++
false
false
8,989
cpp
/* Copyright 2018 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // This code is intended for security research purposes #include <stdio.h> #include "windows.h" struct location { size_t original_address; size_t original_value; location *ptrvalue; location *reverseptr; unsigned int hops; unsigned int offset; }; struct region { size_t base_address; size_t size; location *data; }; struct resultline { size_t address; unsigned offset; size_t address2; size_t dest; bool goal; }; region *regions; size_t numregions; size_t minaddress; size_t maxaddress; size_t start_min; size_t start_max; size_t goal_min; size_t goal_max; resultline *resultbuf; unsigned int maxhops; unsigned int maxoffset; region *findregion(size_t address) { if (address < minaddress) return NULL; if (address > maxaddress) return NULL; long long l = 0; long long r = numregions - 1; long long m; while (l <= r) { m = (l + r) / 2; if (address > (regions[m].base_address + regions[m].size - 1)) { l = m + 1; } else if (address < regions[m].base_address) { r = m - 1; } else { return &(regions[m]); } } return NULL; } location* findlocation(size_t address) { region *r = findregion(address); if (!r) return 0; return &(r->data[(address - r->base_address) / sizeof(void *)]); } void printresult(location *loc) { location *data; size_t index; location *offset0; location *withoffset; bool goal = true; int resultsize = 0; printf("\nGoal reached:\n"); withoffset = loc; while (1) { data = findregion(withoffset->original_address)->data; index = ((size_t)withoffset - (size_t)data) / sizeof(location); offset0 = &(data[index - data[index].offset / sizeof(void *)]); resultbuf[resultsize].address = offset0->original_address; resultbuf[resultsize].offset = withoffset->offset; resultbuf[resultsize].address2 = withoffset->original_address; resultbuf[resultsize].goal = goal; if (goal) { resultbuf[resultsize].dest = 0; goal = false; } else { resultbuf[resultsize].dest = withoffset->ptrvalue->original_address; } if (offset0->hops == 0) break; withoffset = offset0->reverseptr; resultsize++; } for (int i = resultsize; i >= 0; i--) { if (resultbuf[i].goal) { printf("%p + %x = %p (goal address)\n", (void *)resultbuf[i].address, resultbuf[i].offset, (void *)resultbuf[i].address2); } else { printf("%p + %x = %p -> %p\n", (void *)resultbuf[i].address, resultbuf[i].offset, (void *)resultbuf[i].address2, (void *)resultbuf[i].dest); } } } bool markaddressrange(size_t minaddress, size_t maxaddress, unsigned int hopsvalue, unsigned int offsetvalue) { bool ret = false; for (size_t address = minaddress; address < maxaddress; ) { region *r = findregion(address); if (!r) { address += sizeof(void *); continue; } size_t startindex = (address - r->base_address) / sizeof(void *); size_t endindex = r->size / sizeof(void *); location *data = r->data; for (size_t i = startindex; i < endindex; i++) { data[i].hops = hopsvalue; data[i].offset = offsetvalue; address += sizeof(void *); ret = true; if (address >= maxaddress) break; } } return ret; } void propagatepointers() { for (size_t i = 0; i < numregions; i++) { location *data = regions[i].data; size_t numlocs = regions[i].size / sizeof(void *); for (size_t j = 0; j < numlocs; j++) { if (!data[j].ptrvalue) continue; if (data[j].hops >= 0xfffffff0) continue; if (data[j].ptrvalue->hops > (data[j].hops + 1)) { bool goal = (data[j].ptrvalue->hops == 0xfffffffe); data[j].ptrvalue->hops = data[j].hops + 1; data[j].ptrvalue->offset = 0; data[j].ptrvalue->reverseptr = &data[j]; if (goal) { printresult(data[j].ptrvalue); data[j].ptrvalue->hops = 0xfffffffd; } } } } } void propagateoffsets() { for (size_t i = 0; i < numregions; i++) { location *data = regions[i].data; size_t numlocs = regions[i].size / sizeof(void *); for (size_t j = 0; j < numlocs - 1; j++) { if (data[j].hops >= 0xfffffff0) continue; if (data[j].offset + sizeof(void *) > maxoffset) continue; if (data[j + 1].hops > data[j].hops) { data[j + 1].offset = data[j].offset + sizeof(void *); data[j + 1].hops = data[j].hops; } } } } int main(int argc, char**argv) { if (argc < 6) { printf("Usage: %s <pid> <startaddress> <goal address range> <max hops> <max offset>\n", argv[0]); return 0; } int pid = atoi(argv[1]); char *dash; dash = strchr(argv[2], '-'); if (!dash) { start_min = strtoull(argv[2], NULL, 16); start_max = start_min + sizeof(void *); } else { start_min = strtoull(argv[2], NULL, 16); start_max = strtoull(dash + 1, NULL, 16); } dash = strchr(argv[3], '-'); if (!dash) { goal_min = strtoull(argv[3], NULL, 16); goal_max = goal_min + sizeof(void *); } else { goal_min = strtoull(argv[3], NULL, 16); goal_max = strtoull(dash + 1, NULL, 16); } maxhops = atoi(argv[4]); maxoffset = atoi(argv[5]); resultbuf = (resultline *)malloc(maxoffset * sizeof(resultline)); HANDLE proc = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, pid); if (!proc) { printf("Error opening process\n"); return 0; } MEMORY_BASIC_INFORMATION meminfobuf; size_t address = 0; numregions = 0; size_t regionbufsize = 1024; regions = (region *)malloc(regionbufsize * sizeof(region)); DWORD readflags = PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_READWRITE | PAGE_READONLY | PAGE_READWRITE | PAGE_WRITECOPY; printf("Reading memory layout from process..."); while (1) { size_t ret = VirtualQueryEx(proc, (LPCVOID)address, &meminfobuf, sizeof(MEMORY_BASIC_INFORMATION)); if (!ret) break; if ((meminfobuf.State & MEM_COMMIT) && (meminfobuf.Protect & readflags) && !(meminfobuf.Protect & PAGE_GUARD)) { if (numregions >= regionbufsize) { regionbufsize += 1024; regions = (region *)realloc(regions, regionbufsize * sizeof(region)); } regions[numregions].base_address = (size_t)meminfobuf.BaseAddress; regions[numregions].size = meminfobuf.RegionSize; numregions++; } address = (size_t)meminfobuf.BaseAddress + meminfobuf.RegionSize; } if (numregions == 0) { printf("Error reading memory layout\n"); return 0; } printf("done\n"); regions = (region *)realloc(regions, numregions * sizeof(region)); printf("Reading data from process..."); for (size_t i = 0; i < numregions; i++) { size_t *buf = (size_t *)malloc(regions[i].size); memset(buf, 0, regions[i].size); size_t numbytesread; if (!ReadProcessMemory(proc, (LPCVOID)regions[i].base_address, (LPVOID)buf, regions[i].size, &numbytesread)) { printf("Error reading process memory\n"); return 0; } size_t numlocations = regions[i].size / sizeof(size_t); location *locations = (location *)malloc(numlocations * sizeof(location)); for (size_t j = 0; j < numlocations; j++) { locations[j].original_value = buf[j]; locations[j].original_address = regions[i].base_address + j * sizeof(void *); } regions[i].data = locations; free(buf); } minaddress = regions[0].base_address; maxaddress = regions[numregions - 1].base_address + regions[numregions - 1].size - 1; printf("done\n"); printf("Preliminary analysis..."); size_t numlocations=0, numpointers=0; for (size_t i = 0; i < numregions; i++) { location *data = regions[i].data; for (size_t j = 0; j < (regions[i].size / sizeof(void *)); j++) { data[j].hops = 0xffffffff; data[j].offset = 0xffffffff; data[j].reverseptr = NULL; numlocations++; if (data[j].original_value < minaddress || data[j].original_value > maxaddress) { data[j].ptrvalue = NULL; continue; } region *r = findregion(data[j].original_value); if (!r) { data[j].ptrvalue = NULL; continue; } data[j].ptrvalue = &(r->data[(data[j].original_value - r->base_address) / sizeof(void *)]); numpointers++; } } printf("done\n"); printf("Scanned %lld memory locations, found %lld pointers\n", numlocations, numpointers); //mark start addresses if (!markaddressrange(start_min, start_max, 0, 0)) { printf("Error: Start address is not in readable memory\n"); return 0; } //mark goal addresses if (!markaddressrange(goal_min, goal_max, 0xfffffffe, 0xfffffffe)) { printf("Error: Goal address is not in readable memory\n"); return 0; } for (unsigned int i = 1; i < maxhops; i++) { printf("hop %d\n", i); propagateoffsets(); propagatepointers(); } return 0; }
[ "arthurherbout@gmail.com" ]
arthurherbout@gmail.com
00fd5780a71a5e858ad65aac8940287e62763ede
1e0051ba81f35565dac9d571403047723005742c
/Shaders/thrustflame-ALS.vert
dd39bc9d3f06dd49be3e72fb75a243c8870839f2
[]
no_license
FGMEMBERS/f-14b
981a2a6faf9a6d7dd41e176fde08041f398b6dde
685f1efa4a8bd35eb1e85ec7d2255ef03e85cfb4
refs/heads/master
2021-01-17T13:04:38.199475
2019-09-23T02:02:18
2019-09-23T02:02:18
31,022,321
2
0
null
2015-08-05T14:31:33
2015-02-19T15:43:36
null
UTF-8
C++
false
false
392
vert
// -*-C++-*- #version 120 varying vec3 vertex; varying vec3 viewDir; void main() { vec4 ep = gl_ModelViewMatrixInverse * vec4(0.0,0.0,0.0,1.0); vertex = gl_Vertex.xyz; viewDir = normalize(vertex - ep.xyz); gl_Position = ftransform(); gl_TexCoord[0] = gl_TextureMatrix[0] * gl_MultiTexCoord0; gl_FrontColor = vec4 (1.0,1.0,1.0,1.0); gl_BackColor = gl_FrontColor; }
[ "r-harrison@9eb9bc84-db9d-4e05-893b-26dd41ac94a6" ]
r-harrison@9eb9bc84-db9d-4e05-893b-26dd41ac94a6
5d87037ae6396243876abf2304f94117e943c37e
939e9f160955a5827874729c7e7b95bc6b5382be
/Chapter_17/c17_2.cpp
598dcc0391dd8b0b4a1e251eb6b2b5891e776973
[]
no_license
HelloSunyi/Elements-of-Programming-Interviews
3c3dea1214d82d5a4906827702cec679b6d0d1b9
1b53792ecae8e36fa5ac9a446add776dd7382c69
refs/heads/master
2020-04-09T02:42:28.946229
2014-08-03T14:26:12
2014-08-03T14:26:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
345
cpp
#include <iostream> #include <vector> int knapsack(int w, vector<int> v, vector<int> w) { vector<vector<int> > dp(v.size() + 1, w + 1); dp[0][0] = 0; for (int i = 1; i <= v.size(); i++) for (int j = 1; j <= w; j++) { dp[i][j] = max(dp[i-1][j], (j >= w[i-1]) ? dp[i-1][j-w[i-1]]+v[i-1] : 0); } return dp[v.size()][w]; }
[ "onthewinghgd@gmail.com" ]
onthewinghgd@gmail.com
469b0c019cb00880ee1ffa0acc165131c7184f77
4b1efac337ff12a32c986aefc20d6c12b037a2a0
/yahtzee1cpp.cpp
d4a6bbff640c181e67393ae66139def16b742393
[]
no_license
mfontanilla98/CS224_fontanilla
464fd18e4fbc4ef3eb7e95cb316d7909ebf9fc71
4e9d3341be497ddedbf858fbb5fe9be63ab65c5a
refs/heads/master
2020-04-18T08:56:25.131730
2019-05-07T16:50:17
2019-05-07T16:50:17
167,415,579
0
0
null
null
null
null
UTF-8
C++
false
false
5,018
cpp
//A program that plays and scores one hand of Yahtzee #include <iostream> #include <cstdlib> #include <ctime> #include <string> using namespace std; int rollDie(); int maxOfAKindFound(int[]); int maxStraightFound(int[]); bool fullHouseFound(int[]); int totalAllDice(int[]); void sortArray(int[], int); int main() { const int DICE_IN_PLAY = 5; int hand[DICE_IN_PLAY]; srand(time(0)); char playAgain = 'y'; while (playAgain == 'y') { string keep = "nnnnn"; //setup to roll all dice in the first roll int turn = 1; while (turn < 4 && keep != "yyyyy") { //roll dice not kept for (int dieNumber = 0; dieNumber < DICE_IN_PLAY; dieNumber++) { if (keep[dieNumber] != 'y') hand[dieNumber] = rollDie(); } //output roll cout << "Your roll was: "; for (int dieNumber = 0; dieNumber < DICE_IN_PLAY; dieNumber++) { cout << hand[dieNumber] << " "; } cout << endl; //if not the last roll of the hand prompt the user for dice to keep if (turn < 3) { cout << "enter dice to keep (y or n) "; cin >> keep; } turn++; } //start scoring //hand need to be sorted to check for straights sortArray(hand, DICE_IN_PLAY); cout << "Here is your sorted hand : "; for (int dieNumber = 0; dieNumber < DICE_IN_PLAY; dieNumber++) { cout << hand[dieNumber] << " "; } cout << endl; //upper scorecard for (int dieValue = 1; dieValue <= 6; dieValue++) { int currentCount = 0; for (int diePosition = 0; diePosition < 5; diePosition++) { if (hand[diePosition] == dieValue) currentCount++; } cout << "Score " << dieValue * currentCount << " on the "; cout << dieValue << " line" << endl; } //lower scorecard if (maxOfAKindFound(hand) >= 3) { cout << "Score " << totalAllDice(hand) << " on the "; cout << "3 of a Kind line" << endl; } else cout << "Score 0 on the 3 of a Kind line" << endl; if (maxOfAKindFound(hand) >= 4) { cout << "Score " << totalAllDice(hand) << " on the "; cout << "4 of a Kind line" << endl; } else cout << "Score 0 on the 4 of a Kind line" << endl; if (fullHouseFound(hand)) cout << "Score 25 on the Full House line" << endl; else cout << "Score 0 on the Full House line" << endl; if (maxStraightFound(hand) >= 4) cout << "Score 30 on the Small Straight line" << endl; else cout << "Score 0 on the Small Straight line" << endl; if (maxStraightFound(hand) >= 5) cout << "Score 40 on the Large Straight line" << endl; else cout << "Score 0 on the Large Straight line" << endl; if (maxOfAKindFound(hand) >= 5) cout << "Score 50 on the Yahtzee line" << endl; else cout << "Score 0 on the Yahtzee line" << endl; cout << "Score " << totalAllDice(hand) << " on the "; cout << "Chance line" << endl; cout << "\nEnter 'y' to play again "; cin >> playAgain; } return 0; } int rollDie() //this function simulates the rolling of a single die { int roll = rand() % 6 + 1; return roll; } int maxOfAKindFound(int hand[]) //this function returns the count of the die value occurring most in the hand //but not the value itself { int maxCount = 0; int currentCount; for (int dieValue = 1; dieValue <= 6; dieValue++) { currentCount = 0; for (int diePosition = 0; diePosition < 5; diePosition++) { if (hand[diePosition] == dieValue) currentCount++; } if (currentCount > maxCount) maxCount = currentCount; } return maxCount; } int totalAllDice(int hand[]) //this function returns the total value of all dice in a hand { int total = 0; for (int diePosition = 0; diePosition < 5; diePosition++) { total += hand[diePosition]; } return total; } void sortArray(int array[], int size) //bubble sort from Gaddis chapter 8 { bool swap; int temp; do { swap = false; for (int count = 0; count < (size - 1); count++) { if (array[count] > array[count + 1]) { temp = array[count]; array[count] = array[count + 1]; array[count + 1] = temp; swap = true; } } } while (swap); } int maxStraightFound(int hand[]) //this function returns the length of the longest //straight found in a hand { int maxLength = 1; int curLength = 1; for (int counter = 0; counter < 4; counter++) { if (hand[counter] + 1 == hand[counter + 1]) //jump of 1 curLength++; else if (hand[counter] + 1 < hand[counter + 1]) //jump of >= 2 curLength = 1; if (curLength > maxLength) maxLength = curLength; } return maxLength; } bool fullHouseFound(int hand[]) //this function returns true if the hand is a full house //or false if it does not { bool foundFH = false; bool found3K = false; bool found2K = false; int currentCount; for (int dieValue = 1; dieValue <= 6; dieValue++) { currentCount = 0; for (int diePosition = 0; diePosition < 5; diePosition++) { if (hand[diePosition] == dieValue) currentCount++; } if (currentCount == 2) found2K = true; if (currentCount == 3) found3K = true; } if (found2K && found3K) foundFH = true; return foundFH; }
[ "meafontanilla@outlook.com" ]
meafontanilla@outlook.com
eb30f915c3187c65cf5208cb0d745c666067d631
2f597b17f1db0760ef91ecdf2391a3816c63d642
/LED_PWM_Trail/LED_PWM_Trail.ino
44fb04666ce986e7851646861b698968e5abc040
[]
no_license
adicu/hardware_hacking_workshop
10d7f3ac2b2d299f44002503e6949eab5bcd1dbc
54748f4bc04c230a687d57955f40c75346051efc
refs/heads/master
2016-09-10T00:13:33.302905
2013-04-04T23:23:20
2013-04-04T23:23:20
9,230,205
1
0
null
null
null
null
UTF-8
C++
false
false
571
ino
int direction = -1; int LED = 8; #define NUMLEDS 4 int brightness[NUMLEDS]; void setup() { pinMode(8,OUTPUT); pinMode(9,OUTPUT); pinMode(10,OUTPUT); pinMode(11,OUTPUT); for (int i=0; i < NUMLEDS; i++) { brightness[i] = 0; } } void loop() { int i; if(LED == 11 || LED == 8) { direction = -direction; } delay(100); for (i = 0; i < NUMLEDS; i++) { brightness[i] >>= 1; // divide everything by two } brightness[LED-8] = 255; for (i = 0; i < NUMLEDS; i++) { analogWrite(i + 8, brightness[i]); } LED += direction; }
[ "zhehao.mao@gmail.com" ]
zhehao.mao@gmail.com