blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
1334fd2df48597c415810dd3f94c36d530ca6edf
24643916cd1515911b7837ce81ebd17b0890cc81
/platform/common/hardware/audio/aud_drv/AudioMTKStreamManager.cpp
79d2dcf46a3b47ca0105a2bb0c57f1979c191882
[ "Apache-2.0" ]
permissive
touxiong88/92_mediatek
3a0d61109deb2fa77f79ecb790d0d3fdd693e5fd
5e96a7bb778fd9d9b335825584664e0c8b5ff2c7
refs/heads/master
2020-05-02T10:20:49.365871
2019-04-25T09:12:56
2019-04-25T09:12:56
177,894,636
1
1
null
null
null
null
UTF-8
C++
false
false
14,666
cpp
AudioMTKStreamManager.cpp
#include <utils/String16.h> #include "AudioMTKStreamManager.h" #include "AudioUtility.h" #include "AudioMTKStreamOut.h" #include "AudioMTKStreamIn.h" #include "AudioMTKStreamInManager.h" #include "AudioCompFltCustParam.h" #define LOG_TAG "AudioMTKStreamManager" #ifndef ANDROID_DEFAULT_CODE #include <cutils/xlog.h> #ifdef ALOGE #undef ALOGE #endif #ifdef ALOGW #undef ALOGW #endif ALOGI #undef ALOGI #ifdef ALOGD #undef ALOGD #endif #ifdef ALOGV #undef ALOGV #endif #define ALOGE XLOGE #define ALOGW XLOGW #define ALOGI XLOGI #define ALOGD XLOGD #define ALOGV XLOGV #else #include <utils/Log.h> #endif namespace android { #ifdef USE_SPECIFIC_STREAM_MANAGER extern "C" AudioMTKStreamManager *createSpecificStreamManager(); #endif AudioMTKStreamManager *AudioMTKStreamManager::UniqueStreamManagerInstance = NULL; AudioMTKStreamManager *AudioMTKStreamManager::getInstance() { static Mutex gLock; AutoMutex lock(gLock); if (UniqueStreamManagerInstance == 0) { ALOGD("+UniqueAnalogInstance\n"); #ifndef USE_SPECIFIC_STREAM_MANAGER UniqueStreamManagerInstance = new AudioMTKStreamManager(); #else UniqueStreamManagerInstance = createSpecificStreamManager(); #endif ALOGD("-UniqueAnalogInstance\n"); } return UniqueStreamManagerInstance; } AudioMTKStreamManager::AudioMTKStreamManager() { ALOGD("AudioMTKStreamManager contructor \n"); mStreamInNumber = 1; mStreamOutNumber = 1; #ifdef MTK_BESLOUDNESS_SUPPORT unsigned int result = 0 ; AUDIO_AUDENH_CONTROL_OPTION_STRUCT audioParam; if (GetBesLoudnessControlOptionParamFromNV(&audioParam)) { result = audioParam.u32EnableFlg; } mBesLoudnessStatus = (result ? true : false); ALOGD("AudioMTKStreamManager mBesLoudnessStatus [%d] (From NvRam) \n", mBesLoudnessStatus); #else mBesLoudnessStatus = true; ALOGD("AudioMTKStreamManager mBesLoudnessStatus [%d] (Always) \n", mBesLoudnessStatus); #endif mBesLoudnessControlCallback = NULL; } status_t AudioMTKStreamManager::initCheck() { ALOGD("AudioMTKStreamManager initCheck \n"); return NO_ERROR; } bool AudioMTKStreamManager::StreamExist() { return InputStreamExist() || OutputStreamExist(); } bool AudioMTKStreamManager::InputStreamExist() { if (mStreamInVector.size()) { return true; } else { return false; } } bool AudioMTKStreamManager::OutputStreamExist() { if (mStreamOutVector.size()) { return true; } else { return false; } } status_t AudioMTKStreamManager::closeInputStream(android_audio_legacy::AudioStreamIn *in) { AudioMTKStreamIn *StreamIn = (AudioMTKStreamIn *)in; uint32_t Identity = StreamIn->GetIdentity(); ALOGD("closeInputStream in = %p Identity = %d", in, Identity); ssize_t index = mStreamInVector.indexOfKey(Identity); if (in) { delete mStreamInVector.valueAt(index); mStreamInVector.removeItem(Identity); ALOGD("index = %d mStreamInVector.size() = %d", index, mStreamInVector.size()); } return NO_ERROR; } android_audio_legacy::AudioStreamIn *AudioMTKStreamManager::openInputStream( uint32_t devices, int *format, uint32_t *channels, uint32_t *sampleRate, status_t *status, android_audio_legacy::AudioSystem::audio_in_acoustics acoustics) { ALOGD("openInputStream, devices = 0x%x format=0x%x ,channels=0x%x, rate=%d acoustics = 0x%x", devices, *format, *channels, *sampleRate, acoustics); if (SpeechVMRecorder::GetInstance()->GetVMRecordStatus() == true) { ALOGW("%s(), The following record data will be muted until VM/EPL is closed.", __FUNCTION__); } AudioMTKStreamIn *StreamIn = new AudioMTKStreamIn(); StreamIn->Set(devices, format, channels, sampleRate, status, acoustics); if (*status == NO_ERROR) { mStreamInNumber++; StreamIn->SetIdentity(mStreamInNumber); mStreamInVector.add(mStreamInNumber, StreamIn); ALOGD("openInputStream NO_ERROR mStreamInNumber = %d mStreamInVector.size() = %d" , mStreamInNumber, mStreamInVector.size()); return StreamIn; } else { ALOGD("openInputStream delete streamin"); delete StreamIn; return NULL; } } android_audio_legacy::AudioStreamOut *AudioMTKStreamManager::openOutputStream( uint32_t devices, int *format, uint32_t *channels, uint32_t *sampleRate, status_t *status, uint32_t output_flag) { unsigned int Address = 0; // Check the Attribute if (*format == 0) { *format = AUDIO_FORMAT_PCM_16_BIT; } if (*channels == 0) { *channels = AUDIO_CHANNEL_OUT_STEREO; } if (*sampleRate == 0) { *sampleRate = 44100; } ALOGD("openOutputStream, devices = 0x%x format=0x%x ,channels=0x%x, rate=%d", devices, *format, *channels, *sampleRate); AudioMTKStreamOut *out = new AudioMTKStreamOut(devices, format, channels, sampleRate, status); Address = (unsigned int)out; // use pointer address mStreamOutVector.add(Address, out); return out; } status_t AudioMTKStreamManager::closeOutputStream(android_audio_legacy::AudioStreamOut *out) { return NO_ERROR; } bool AudioMTKStreamManager::IsOutPutStreamActive() { for (int i = 0; i < mStreamOutVector.size() ; i++) { AudioMTKStreamOut *pTempOut = (AudioMTKStreamOut *)mStreamOutVector.valueAt(i); if (pTempOut->GetStreamRunning()) { return true; } } return false; } bool AudioMTKStreamManager::IsInPutStreamActive() { for (int i = 0; i < mStreamInVector.size() ; i++) { AudioMTKStreamIn *pTempIn = (AudioMTKStreamIn *)mStreamInVector.valueAt(i); if (pTempIn != NULL) // fpr input ,exist means active { return true; } } return false; } // set musicplus to streamout void AudioMTKStreamManager::SetMusicPlusStatus(bool bEnable) { if (mStreamOutVector.size()) { for (size_t i = 0; i < mStreamOutVector.size() ; i++) { AudioMTKStreamOut *pTempOut = (AudioMTKStreamOut *)mStreamOutVector.valueAt(i); pTempOut->SetMusicPlusStatus(bEnable ? true : false); } } } bool AudioMTKStreamManager::GetMusicPlusStatus() { if (mStreamOutVector.size()) { for (size_t i = 0; i < mStreamOutVector.size() ; i++) { AudioMTKStreamOut *pTempOut = (AudioMTKStreamOut *)mStreamOutVector.valueAt(i); bool musicplus_status = pTempOut->GetMusicPlusStatus(); if (musicplus_status) { return true; } } } return false; } void AudioMTKStreamManager::SetBesLoudnessStatus(bool bEnable) { #ifdef MTK_BESLOUDNESS_SUPPORT ALOGD("mBesLoudnessStatus() flag %d", bEnable); mBesLoudnessStatus = bEnable; AUDIO_AUDENH_CONTROL_OPTION_STRUCT audioParam; audioParam.u32EnableFlg = bEnable ? 1 : 0; SetBesLoudnessControlOptionParamToNV(&audioParam); if (mBesLoudnessControlCallback != NULL) { mBesLoudnessControlCallback((void *)mBesLoudnessStatus); } #else ALOGD("Unsupport set mBesLoudnessStatus()"); #endif } bool AudioMTKStreamManager::GetBesLoudnessStatus() { return mBesLoudnessStatus; } void AudioMTKStreamManager::SetBesLoudnessControlCallback(const BESLOUDNESS_CONTROL_CALLBACK_STRUCT *callback_data) { if (callback_data == NULL) { mBesLoudnessControlCallback = NULL; } else { mBesLoudnessControlCallback = callback_data->callback; ASSERT(mBesLoudnessControlCallback != NULL); mBesLoudnessControlCallback((void *)mBesLoudnessStatus); } } void AudioMTKStreamManager::SetHiFiDACStatus(bool bEnable) { #ifdef HIFIDAC_SWITCH //HP switch use AudEnh setting ALOGD("SetHiFiDACStatus mHiFiDACStatus %d", bEnable); mHiFiDACStatus = bEnable; AUDIO_AUDENH_CONTROL_OPTION_STRUCT audioParam; audioParam.u32EnableFlg = bEnable ? 1 : 0; SetHiFiDACControlOptionParamToNV(&audioParam); #else ALOGD("Unsupport SetHiFiDACStatus()"); #endif } bool AudioMTKStreamManager::GetHiFiDACStatus() { #ifdef HIFIDAC_SWITCH //HP switch use AudEnh setting ALOGD("GetHiFiDACStatus(+) "); AUDIO_AUDENH_CONTROL_OPTION_STRUCT audioParam; unsigned int result = 0 ; if (GetHiFiDACControlOptionParamFromNV(&audioParam)) { result = audioParam.u32EnableFlg; } mHiFiDACStatus = (result ? true : false); ALOGD("GetHiFiDACStatus mHiFiDACStatus %d", mHiFiDACStatus); return mHiFiDACStatus; #else ALOGD("Unsupport GetHiFiDACStatus()"); return false; #endif } size_t AudioMTKStreamManager::getInputBufferSize(int32_t sampleRate, int format, int channelCount) { ALOGD("AudioMTKHardware getInputBufferSize, sampleRate=%d, format=%d, channelCount=%d\n", sampleRate, format, channelCount); #if 1 size_t bufferSize = 0; bufferSize = (sampleRate * channelCount * 20 * sizeof(int16_t)) / 1000; ALOGD("getInputBufferSize bufferSize=%d\n", bufferSize); return bufferSize; #else if (mStreamInVector.size()) { // get input stream szie android_audio_legacy::AudioStreamIn *Input = mStreamInVector.valueAt(0); return Input->bufferSize(); } else { return AudioMTKStreamIn::GetfixBufferSize(sampleRate, format, channelCount); } #endif } status_t AudioMTKStreamManager::UpdateACFHCF(int value) { AUDIO_ACF_CUSTOM_PARAM_STRUCT sACFHCFParam; for (int i = 0; i < mStreamOutVector.size() ; i++) { AudioMTKStreamOut *pTempOut = (AudioMTKStreamOut *)mStreamOutVector.valueAt(i); if (value == 0) { ALOGD("setParameters Update ACF Parames"); GetAudioCompFltCustParamFromNV(AUDIO_COMP_FLT_AUDIO, &sACFHCFParam); pTempOut->StreamOutCompFltPreviewParameter(AUDIO_COMP_FLT_AUDIO, (void *)&sACFHCFParam, sizeof(AUDIO_ACF_CUSTOM_PARAM_STRUCT)); if ((pTempOut->GetStreamRunning()) && (pTempOut->GetStreamOutCompFltStatus(AUDIO_COMP_FLT_AUDIO))) { pTempOut->SetStreamOutCompFltStatus(AUDIO_COMP_FLT_AUDIO, false); pTempOut->SetStreamOutCompFltStatus(AUDIO_COMP_FLT_AUDIO, true); } } else if (value == 1) { ALOGD("setParameters Update HCF Parames"); GetAudioCompFltCustParamFromNV(AUDIO_COMP_FLT_HEADPHONE, &sACFHCFParam); pTempOut->StreamOutCompFltPreviewParameter(AUDIO_COMP_FLT_HEADPHONE, (void *)&sACFHCFParam, sizeof(AUDIO_ACF_CUSTOM_PARAM_STRUCT)); if ((pTempOut->GetStreamRunning()) && (pTempOut->GetStreamOutCompFltStatus(AUDIO_COMP_FLT_HEADPHONE))) { pTempOut->SetStreamOutCompFltStatus(AUDIO_COMP_FLT_HEADPHONE, false); pTempOut->SetStreamOutCompFltStatus(AUDIO_COMP_FLT_HEADPHONE, true); } } else if (value == 2) { ALOGD("setParameters Update ACFSub Parames"); GetAudioCompFltCustParamFromNV(AUDIO_COMP_FLT_AUDIO_SUB, &sACFHCFParam); pTempOut->StreamOutCompFltPreviewParameter(AUDIO_COMP_FLT_AUDIO_SUB, (void *)&sACFHCFParam, sizeof(AUDIO_ACF_CUSTOM_PARAM_STRUCT)); if ((pTempOut->GetStreamRunning()) && (pTempOut->GetStreamOutCompFltStatus(AUDIO_COMP_FLT_AUDIO))) { pTempOut->SetStreamOutCompFltStatus(AUDIO_COMP_FLT_AUDIO, false); pTempOut->SetStreamOutCompFltStatus(AUDIO_COMP_FLT_AUDIO, true); } } } return NO_ERROR; } // ACF Preview parameter status_t AudioMTKStreamManager::SetACFPreviewParameter(void *ptr , int len) { ALOGD("AudioMTKHardware SetACFPreviewParameter\n"); if (mStreamOutVector.size()) { for (size_t i = 0; i < mStreamOutVector.size() ; i++) { AudioMTKStreamOut *pTempOut = (AudioMTKStreamOut *)mStreamOutVector.valueAt(i); pTempOut->StreamOutCompFltPreviewParameter(AUDIO_COMP_FLT_AUDIO, ptr, len); } } return NO_ERROR; } status_t AudioMTKStreamManager::SetHCFPreviewParameter(void *ptr , int len) { ALOGD("AudioMTKHardware SetHCFPreviewParameter\n"); if (mStreamOutVector.size()) { for (size_t i = 0; i < mStreamOutVector.size() ; i++) { AudioMTKStreamOut *pTempOut = (AudioMTKStreamOut *)mStreamOutVector.valueAt(i); pTempOut->StreamOutCompFltPreviewParameter(AUDIO_COMP_FLT_HEADPHONE, ptr, len); } } return NO_ERROR; } //suspend input and output standby status_t AudioMTKStreamManager::SetOutputStreamSuspend(bool bEnable) { ALOGD("SetOutputStreamSuspend"); if (mStreamOutVector.size()) { for (size_t i = 0; i < mStreamOutVector.size() ; i++) { AudioMTKStreamOut *pTempOut = (AudioMTKStreamOut *)mStreamOutVector.valueAt(i); pTempOut->SetSuspend(bEnable); } } return NO_ERROR; } status_t AudioMTKStreamManager::SetInputStreamSuspend(bool bEnable) { ALOGD("SetOutputStreamSuspend"); if (mStreamInVector.size()) { for (size_t i = 0; i < mStreamInVector.size() ; i++) { AudioMTKStreamIn *pTempIn = (AudioMTKStreamIn *)mStreamInVector.valueAt(i); pTempIn->SetSuspend(bEnable); } } return NO_ERROR; } status_t AudioMTKStreamManager::ForceAllStandby() { // force all stream to standby ALOGD("ForceAllStandby"); if (mStreamInVector.size()) { for (size_t i = 0; i < mStreamInVector.size() ; i++) { AudioMTKStreamIn *pTempIn = (AudioMTKStreamIn *)mStreamInVector.valueAt(i); pTempIn->standby(); } } if (mStreamOutVector.size()) { for (size_t i = 0; i < mStreamOutVector.size() ; i++) { AudioMTKStreamOut *pTempOut = (AudioMTKStreamOut *)mStreamOutVector.valueAt(i); pTempOut->setForceStandby(true); pTempOut->standby(); pTempOut->setForceStandby(false); } } return NO_ERROR; } void AudioMTKStreamManager::SetInputMute(bool bEnable) { AudioMTKStreamInManager::getInstance()->SetInputMute(bEnable); } status_t AudioMTKStreamManager::setParametersToStreamOut(const String8 &keyValuePairs) { if (mStreamOutVector.size()) { for (size_t i = 0; i < mStreamOutVector.size() ; i++) { AudioMTKStreamOut *pTempOut = (AudioMTKStreamOut *)mStreamOutVector.valueAt(i); pTempOut->setParameters(keyValuePairs); } } return NO_ERROR; } }
ec327926965e484724ab3b334ba4ab54909db3db
28f0247bd82f29db8be698d03ea5cd36b50a28ac
/Программирование/Зачетные и Экзаменационные Классы/Слово/word.h
04f7fc55653560e0e2c833f14f32e4a5f7c647d9
[]
no_license
slntopp/Labs
b6bcd45489b9513fc6c7700675c800a74f23c680
d9bda8aa9832735c4034b05426dd716b7e183e8c
refs/heads/master
2021-08-23T19:50:20.852572
2017-12-06T08:55:02
2017-12-06T08:55:02
106,384,340
1
0
null
null
null
null
UTF-8
C++
false
false
4,801
h
word.h
class Word { private: int size; //Длина строки char* body; //СТрока public: Word(int _size = 0): size(_size) { //Создание пустого слова размера _size (по умолчанию = 0) body = new char[size + 1]; //Выделение памяти под нуль терминант body[0] = '\0'; //Запись нуль-терминанта в начало строки } Word(char* word): size(strlen(word)) { //Создание объекта на основе си-строки body = new char[size + 1]; //Выделение памяти под строку + нуль-терминант for(int i = 0; i < size; ++i) body[i] = word[i]; //Копирование строки в объект (циклом, тому що понаставят вижуалок - strcpy не работает) body[size] = '\0'; //Запись нуль-терминанта в конец строки } Word(const Word &obj): size(obj.size){ //Конструктор копирования body = new char[size]; //Выделение памяти под копию строки входящего объекта for(int i = 0; i < size; ++i) body[i] = obj.body[i]; //Копирование строки body[size] = '\0'; //Запись нуль-терминанта в конец } int length() const { return size; } //Получение длины строки-объекта const char* to_c() const { return body; } //Возврат константной строки в формате указателя на char (char*) char* pointer() { return body; } //Возврат указателя на внутреннее представление строки(например, для ее инициализации при вводе строки необычными методами) void re_init() { while(body[++size] != '\0'); } //Пересчет длины строки Word operator+ (const Word &obj){ //Конкатенация строк (склеивание крч) char* buff = new char[size]; //Создание буфферной строки for(int i = 0; i < size; ++i) buff[i] = body[i]; //Копирование в нее строки из основного объекта return Word(strcat(buff, obj.body)); //Склеивание этой строки со строкой из входящего объекта и создание анонимного объекта на основе это строки.\ возврат объекта в вызывающую функцию } void Push(char ch){ //Добавление символа в конец body = (char*) realloc(body, ++size * sizeof(char)); //Перевыделение памяти - на один символ больше body[size] = '\0'; //Запись в конец нуль-терминанта body[size - 1] = ch; //Запись в конец строки символа } void Push(char* str){ //Добавление строки в конец body = (char*) realloc(body, (size + strlen(str)) * sizeof(char)); //Перевыделение памяти for(int i = size; i < size + strlen(str); ++i) body[i] = str[i - size]; //Запись доп строки в объект size += strlen(str); //Увеличение размера строки объекта на длину входящей строки body[size] = '\0'; //Запись нуль-терминанта в конец } char operator[] (int index) { if(index >= size) return '\0'; return body[index]; } //Перегрузка оператора индексирования - если индекс превышает размер - возврат пустоты ~Word(){ delete[] body; } //Деструктор - очистка памяти от массива char }; ostream& operator<< (ostream& out, const Word &obj){ //Перегрузка вывода return out << obj.to_c(); //С-строки выводятся в потоки, если подключена библиотека <string> и если в них есть '\0' } istream& operator>> (istream& in, Word &obj){ //Перегрузка ввода in >> obj.pointer(); //Ввод из потока ввода в С-строку поддерживается библиотекой <string>, см. метод Word::pointer() obj.re_init(); //Переучет! return in; }
5943843ce7907ef801c2dad9fad9bbe29c4c974c
057a475216e9beed41983481aafcaf109bbf58da
/src/Server/TLSHandler.h
dd025e3e165e5fad365e9045935063b5267a1f68
[ "Apache-2.0" ]
permissive
ClickHouse/ClickHouse
fece5204263a5b4d693854b6039699265f1bb27f
6649328db809d51a694c358571539bc5820464be
refs/heads/master
2023-08-31T18:48:36.615225
2023-08-31T17:51:24
2023-08-31T17:51:24
60,246,359
23,878
5,449
Apache-2.0
2023-09-14T20:10:52
2016-06-02T08:28:18
C++
UTF-8
C++
false
false
1,696
h
TLSHandler.h
#pragma once #include <Poco/Net/TCPServerConnection.h> #include <Poco/SharedPtr.h> #include <Common/Exception.h> #include <Server/TCPProtocolStackData.h> #if USE_SSL # include <Poco/Net/Context.h> # include <Poco/Net/SecureStreamSocket.h> # include <Poco/Net/SSLManager.h> #endif namespace DB { namespace ErrorCodes { extern const int SUPPORT_IS_DISABLED; } class TLSHandler : public Poco::Net::TCPServerConnection { #if USE_SSL using SecureStreamSocket = Poco::Net::SecureStreamSocket; using SSLManager = Poco::Net::SSLManager; using Context = Poco::Net::Context; #endif using StreamSocket = Poco::Net::StreamSocket; public: explicit TLSHandler(const StreamSocket & socket, const std::string & key_, const std::string & certificate_, TCPProtocolStackData & stack_data_) : Poco::Net::TCPServerConnection(socket) , key(key_) , certificate(certificate_) , stack_data(stack_data_) {} void run() override { #if USE_SSL auto ctx = SSLManager::instance().defaultServerContext(); if (!key.empty() && !certificate.empty()) ctx = new Context(Context::Usage::SERVER_USE, key, certificate, ctx->getCAPaths().caLocation); socket() = SecureStreamSocket::attach(socket(), ctx); stack_data.socket = socket(); stack_data.certificate = certificate; #else throw Exception(ErrorCodes::SUPPORT_IS_DISABLED, "SSL support for TCP protocol is disabled because Poco library was built without NetSSL support."); #endif } private: std::string key [[maybe_unused]]; std::string certificate [[maybe_unused]]; TCPProtocolStackData & stack_data [[maybe_unused]]; }; }
d9b90dc4dd9516288db36fc37bdb1007a64262bd
9789c068f903cb35baf48a0a2ec6903bcb368897
/include/holo/types/tuple/tuple_prepend.h
6a40468a972a1909b3bd141f21f3eb24eeda2f0a
[]
no_license
netcan/holo
fcc7e2bdb380ad82921bbbfde4ed4b7cb6df6be5
35234df50391157700511e00cdbd870f1d8bbe91
refs/heads/master
2022-12-16T02:56:59.274512
2020-09-17T20:53:57
2020-09-17T20:53:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
914
h
tuple_prepend.h
// // Created by Darwin Yuan on 2020/8/29. // #ifndef HOLO_TUPLE_PREPEND_H #define HOLO_TUPLE_PREPEND_H #include <holo/types/tuple/tuple_t.h> HOLO_NS_BEGIN template<> struct prepend_algo<tuple_tag> { private: template<typename ... Xs, typename X, std::size_t ... Xn> constexpr static auto tuple_prepend(X const& x, tuple<Xs...> const& xs, std::index_sequence<Xn...>) { if constexpr (Is_Empty_Class<tuple<Xs...>>) { return holo::make_tuple(x, Xs{}...); } else { return holo::make_tuple(x, get<Xn>(xs)...); } } public: template<typename ... Xs, typename X> constexpr static auto apply(X const& x, tuple<Xs...> const& xs) { if constexpr (Is_Empty_Class<tuple<Xs...>, X>) { return tuple<X, Xs...>{}; } else { return tuple_prepend(x, xs, std::index_sequence_for<Xs...>{}); } } }; HOLO_NS_END #endif //HOLO_TUPLE_PREPEND_H
ab492cf1bd85d0a72b6b54f94e1c79d738f467ab
5885fd1418db54cc4b699c809cd44e625f7e23fc
/asc12-cf100215/g.cpp
204fb77583bd451c61e06c6602f5b9633c81fb73
[]
no_license
ehnryx/acm
c5f294a2e287a6d7003c61ee134696b2a11e9f3b
c706120236a3e55ba2aea10fb5c3daa5c1055118
refs/heads/master
2023-08-31T13:19:49.707328
2023-08-29T01:49:32
2023-08-29T01:49:32
131,941,068
2
0
null
null
null
null
UTF-8
C++
false
false
2,711
cpp
g.cpp
//#pragma GCC optimize("O3") //#pragma GCC target("sse4,avx2,abm,fma,tune=native") #include <bits/stdc++.h> using namespace std; #define _USE_MATH_DEFINES #define FILENAME "pipe" #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; template <typename T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; typedef long long ll; typedef long double ld; typedef complex<ld> pt; const char nl = '\n'; const ll INF = 0x3f3f3f3f; const ll INFLL = 0x3f3f3f3f3f3f3f3f; const ll MOD = 998244353; const ld EPS = 1e-9; mt19937 rng(chrono::high_resolution_clock::now().time_since_epoch().count()); ld cp(const pt& a, const pt& b) { return imag(conj(a) * b); } ld lp_dist(const pt& a, const pt& b, const pt& p) { return cp(b-a, p-a) / abs(b-a); } ld get_dist(int a, int b, int x, int y, int s, int t) { pt A(a, b), B(x, y), C(s, t); return abs(lp_dist(A, B, C)); } const int N = 200 + 1; ld cost[N][2]; ld dp[N][N]; pair<int,int> pre[N][N]; bool update(ld& x, const ld& v) { x = min(x, v); return x == v; } // double-check correctness // read limits carefully // characterize valid solutions int main() { ios::sync_with_stdio(0); cin.tie(0); cout << fixed << setprecision(10); ///* #ifdef ONLINE_JUDGE freopen(FILENAME ".in", "r", stdin); freopen(FILENAME ".out", "w", stdout); #endif //*/ int n, c; cin >> n >> c; vector<tuple<int,int,int,int>> lines; for(int t=0; t<2; t++) { int a, b, x, y; cin >> a >> b >> x >> y; lines.emplace_back(a, b, x, y); } for(int i=1; i<=n; i++) { int x, y, z; cin >> x >> y >> z; for(int t=0; t<2; t++) { cost[i][t] = z * apply(get_dist, tuple_cat(lines[t], tie(x, y))); } } fill(&dp[0][0], &dp[0][0]+N*N, INFLL); dp[0][0] = 0; for(int i=0; i<=n; i++) { for(int j=0; i+j<=n; j++) { if(i && update(dp[i][j], dp[i-1][j] + cost[i+j][0])) { pre[i][j] = make_pair(i-1, j); } if(j && update(dp[i][j], dp[i][j-1] + cost[i+j][1])) { pre[i][j] = make_pair(i, j-1); } } } ld best = INFLL; for(int i=0; i<=n; i++) { if(abs(n-i - i) <= c) { best = min(best, dp[i][n-i]); } } for(int i=0; i<=n; i++) { if(abs(n-i - i) <= c && dp[i][n-i] == best) { vector<int> ans; for(int a=i, b=n-i; a || b; ) { if(pre[a][b].first < a) { ans.push_back(1); a--; } else { ans.push_back(2); b--; } } reverse(ans.begin(), ans.end()); for(int it : ans) { cout << it << " "; } cout << nl; return 0; } } assert(false); return 0; }
1ca1f99ab893700fe1c3e732ec4403f663a75dea
e68dc707ce2c4a737d0638b85cd7bac06d59b380
/todo.cpp
a4b83108259efc6637b77b0e960c41a6a04cc5e7
[]
no_license
mk533/Codes
27f2de286bc9f87175bda84314b22f46303fa7a2
827db5c4df16b8c6750a55a212efd6dba319729c
refs/heads/master
2020-06-01T16:29:04.571345
2019-09-21T12:29:09
2019-09-21T12:29:09
190,850,249
1
1
null
null
null
null
UTF-8
C++
false
false
1,692
cpp
todo.cpp
-> Length of longest palindrome https://www.geeksforgeeks.org/rearrange-array-maximum-minimum-form-set-2-o1-extra-space/ https://www.geeksforgeeks.org/find-last-digit-of-ab-for-large-numbers/ https://www.geeksforgeeks.org/sum-minimum-maximum-elements-subarrays-size-k/ https://www.geeksforgeeks.org/minimum-sum-squares-characters-counts-given-string-removing-k-characters/ https://www.geeksforgeeks.org/design-a-stack-that-supports-getmin-in-o1-time-and-o1-extra-space/ https://www.geeksforgeeks.org/next-greater-frequency-element/ https://www.geeksforgeeks.org/largest-rectangle-under-histogram/ https://www.geeksforgeeks.org/avl-with-duplicate-keys/ https://www.geeksforgeeks.org/generating-numbers-that-are-divisor-of-their-right-rotations/ https://www.geeksforgeeks.org/find-the-two-numbers-with-odd-occurences-in-an-unsorted-array/ https://www.geeksforgeeks.org/print-maximum-shortest-distance/ https://www.geeksforgeeks.org/median-two-sorted-arrays-different-sizes-ologminn-m/ https://www.geeksforgeeks.org/count-frequencies-elements-array-o1-extra-space-time/ https://www.geeksforgeeks.org/hoares-vs-lomuto-partition-scheme-quicksort/ https://www.geeksforgeeks.org/reorder-a-array-according-to-given-indexes/ https://www.geeksforgeeks.org/shuffle-a-given-array-using-fisher-yates-shuffle-algorithm/ https://www.geeksforgeeks.org/counting-inversions/ https://www.geeksforgeeks.org/median-of-stream-of-integers-running-integers/ https://www.geeksforgeeks.org/find-number-pairs-xy-yx/ https://www.geeksforgeeks.org/minimum-swaps-to-make-two-array-identical/ 15 -> BFS n DFS , Basics and problems 16 -> Strings 17 ,18 -> Matrix and DP 19,20 ->maths,aptitude
d689bf489ec6b034b23b9a9de72dc0d3c8a3ea05
1b9bef9d2c1f7896c254a3d7d271ae9a968695a9
/ege/main/Config.h
835ac285a0a96efd4344da0dca3adf6346e5757e
[ "MIT" ]
permissive
sysfce2/SFML_Hexagon-Engine_ege
1ca194e19b7f6377846bc091c95756c306441479
a82ff6fccc8ac1bce5a50ed5a8f101b63f58b020
refs/heads/master
2023-07-17T04:08:36.077672
2021-08-28T16:24:22
2021-08-28T16:24:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,807
h
Config.h
/* * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * * ,---- ,---- ,---- * | | | * |---- | --, |---- * | | | | * '---- '---' '---- * * Framework Library for Hexagon * * Copyright (c) Sppmacd 2020 - 2021 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * */ #pragma once #include <iostream> #include <stdlib.h> #include <utility> namespace EGE { [[noreturn]] void assertionFailed(const char* expr, const char* message, const char* file, unsigned line); } #define ASSERT_WITH_MESSAGE(expr, message) \ if(!(expr)) EGE::assertionFailed(#expr, message, __FILE__, __LINE__) #define ASSERT(expr) ASSERT_WITH_MESSAGE(expr, "Check failed") #define CRASH_WITH_MESSAGE(message) \ ASSERT_WITH_MESSAGE(false, message) #define CRASH() CRASH_WITH_MESSAGE("Crash") #define NOT_IMPLEMENTED(message) CRASH_WITH_MESSAGE("Not implemented: " message) #define EGE_ENUM_YES_NO(X) \ enum class X : bool \ { \ Yes, \ No \ } #define EGE_SINGLETON_VA(clazz,...) \ static clazz& instance() \ { \ static clazz inst(__VA_ARGS__); \ return inst; \ } #define EGE_SINGLETON(clazz) \ static clazz& instance() \ { \ static clazz inst; \ return inst; \ } #define DBG(run,txt) \ if constexpr(run) \ { \ std::cerr << "DBG " << (txt) << std::endl; \ } #define DUMP(run,var) \ if constexpr(run) \ { \ std::cerr << "DUMP '" << #var << "' = [" << (var) << "]" << std::endl; \ } #define instanceof(pointer, clazz) \ (dynamic_cast<clazz*>(pointer) != nullptr)
21f50881c8448ed5f04ac2110739d9bdd115b16d
048432ca8462ad4f5ccc5cf801c35bcf4f559645
/src/vb/bn/MVInverseGammaModel.h
0ac0344db7065d238b9f5ab6fd1453fd0d5eadce
[]
no_license
manazhao/BayesianNetwork
5c0c09cf06d5fe1bb41c269c91767d84b159d8f0
1fc3598c85117862f054ac07cf5e56798ae3c159
refs/heads/master
2021-01-16T00:41:40.783334
2014-05-14T01:06:08
2014-05-14T01:06:08
18,185,015
0
0
null
null
null
null
UTF-8
C++
false
false
929
h
MVInverseGammaModel.h
/* * MVInverseGammaModel.h * * Created on: Mar 21, 2014 * Author: qzhao2 */ #ifndef MVINVERSEGAMMAMODEL_H_ #define MVINVERSEGAMMAMODEL_H_ #include "Model.h" namespace bn { class MVInverseGammaModel: public bn::ProbModel { public: typedef MVInverseGamma dist_type; typedef Variable<MVInverseGamma> var_type; typedef typename dist_type::value_type value_type; public: enum role_type{ COND_ALPHA, COND_BETA }; protected: virtual DistParamBundle _update_from_parent(); public: MVInverseGammaModel(string const& id, string const& name); MVInverseGammaModel(string const& id, string const& name, value_type const& value) : ProbModel(var_ptr_type(new var_type(id, name, dist_type::observation(value))),true) { } virtual DistParamBundle to_parent_message(string const& varId) { return DistParamBundle(); } virtual ~MVInverseGammaModel(); }; } /* namespace bn */ #endif /* MVINVERSEGAMMAMODEL_H_ */
468024569c90068b7b25c937a058e7a417203db6
263fb69275a75b646c6f99690d9abc44edad6f4e
/ladder/A. Young Physicist.cpp
4a4c13751978f80b6980150fee4dd864f1cf2b89
[]
no_license
mehmetaltuner/competitive
40d1dd3cc780e78e56571f367b32c1ce843fe544
37d847775010f87cea88bb7db7fc5d331b8dddd4
refs/heads/master
2020-04-23T12:17:20.102342
2019-03-26T21:01:32
2019-03-26T21:01:32
171,163,189
0
0
null
null
null
null
UTF-8
C++
false
false
574
cpp
A. Young Physicist.cpp
// https://codeforces.com/problemset/problem/69/A #include <bits/stdc++.h> #define ALL(e) e.begin(), e.end() #define mp(a, b) make_pair(a, b) #define pb push_back #define dbg(x) (cerr << #x << ":" << x) #define mid (l + r) / 2 #define fi first #define sc second #define N 1000000009 using namespace std; typedef long long int lli; int main(){ int n; cin >> n; int x = 0, y = 0, z=0; for(int i=0; i<n; i++){ int a, b, c; cin >> a >> b >> c; x += a; y += b; z += c; } if(x == 0 and y == 0 and z == 0) cout << "YES"; else cout << "NO"; return 0; }
715b42939f9ac21de3c1bd6a5eb8589662ca8b9c
4bb0bf583f8eef28dcdba4917218d4ff8c40d171
/src/PyZPK/gadgetlib1/gadgets/cpu_checkers/fooram/fooram_components.cpp
e56a24164209ed57cac6f768b5acc3d0a399d868
[ "Python-2.0", "Apache-2.0" ]
permissive
gargarchit/PyZPK
88390082033088e50d10b86162bd85bd69d68b35
9168b2c401e1af805e1b327cd94bdf5073e2113a
refs/heads/master
2021-04-10T04:32:07.725466
2020-09-14T07:46:56
2020-09-14T07:46:56
264,120,878
2
0
Apache-2.0
2020-06-04T17:32:48
2020-05-15T07:00:09
C++
UTF-8
C++
false
false
2,148
cpp
fooram_components.cpp
#include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <pybind11/stl_bind.h> #include <libff/algebra/curves/mnt/mnt6/mnt6_pp.hpp> #include <libsnark/gadgetlib1/gadgets/cpu_checkers/fooram/components/bar_gadget.hpp> #include <libsnark/gadgetlib1/gadgets/cpu_checkers/fooram/components/fooram_protoboard.hpp> namespace py = pybind11; using namespace libsnark; using namespace libff; // Interfaces for an auxiliary gadget for the FOORAM CPU. // The bar gadget checks linear combination Z = aX + bY (mod 2^w) // for a, b - const, X, Y - vectors of w bits, where w is implicitly inferred, // Z - a packed variable. This gadget is used four times in fooram: // PC' = PC + 1 // load_addr = 2 * x + PC' // store_addr = x + PC void declare_bar_gadget(py::module &m) { using FieldT = Fp_model<5l, libff::mnt46_modulus_B>; py::class_<bar_gadget<FieldT>, gadget<FieldT>>(m, "bar_gadget") .def(py::init<protoboard<FieldT> &, const pb_linear_combination_array<FieldT> &, const FieldT &, const pb_linear_combination_array<FieldT> &, const FieldT &, const pb_linear_combination<FieldT> &, const std::string &>()) .def("generate_r1cs_constraints", &bar_gadget<FieldT>::generate_r1cs_constraints) .def("generate_r1cs_witness", &bar_gadget<FieldT>::generate_r1cs_witness); } // Interfaces for a protoboard for the FOORAM CPU. void declare_fooram_protoboard(py::module &m) { using FieldT = Fp_model<5l, libff::mnt46_modulus_B>; py::class_<fooram_protoboard<FieldT>, protoboard<FieldT>>(m, "fooram_protoboard") .def(py::init<const fooram_architecture_params &>()); } void declare_fooram_gadget(py::module &m) { using FieldT = Fp_model<5l, libff::mnt46_modulus_B>; py::class_<fooram_gadget<FieldT>, gadget<FieldT>>(m, "fooram_gadget") .def(py::init<fooram_protoboard<FieldT> &, const std::string &>()); } void init_gadgetlib1_fooram_components(py::module &m) { declare_bar_gadget(m); declare_fooram_protoboard(m); declare_fooram_gadget(m); }
4a1883c9b47d93e4474b4fca458a142a33601fc7
e384f5467d8bcfd70845997bcbd68d950e874a61
/example/cpp/_render_util/source/OpenGL/OpenGLLine_1_0.cpp
5d3a01519ee6e869bfa3aa08a249fdd3312da6b9
[]
no_license
Rabbid76/graphics-snippets
ee642f1ed9ceafc6d320e467d3a084d2446d22c2
fa187afeabb9630bc1d988304fb5787e95a91385
refs/heads/master
2023-08-04T04:32:06.884318
2023-07-21T09:15:43
2023-07-21T09:15:43
109,126,544
177
12
null
2023-04-11T20:05:52
2017-11-01T12:05:56
C++
UTF-8
C++
false
false
15,675
cpp
OpenGLLine_1_0.cpp
/******************************************************************//** * \brief Implementation of OpenGL line renderer, * for OpenGL version 1.00 - "Software-OpenGL". * * \author gernot * \date 2018-08-01 * \version 1.0 **********************************************************************/ #include <stdafx.h> // includes #include "../../include/OpenGL/OpenGLLine_1_0.h" // OpenGL wrapper #include "../../include/OpenGL/OpenGL_include.h" #include "../../include/OpenGL/OpenGL_enumconst.h" // STL #include <cassert> // class definitions /******************************************************************//** * \brief General namespace for OpenGL implementation. * * \author gernot * \date 2018-09-07 * \version 1.0 **********************************************************************/ namespace OpenGL { /******************************************************************//** * \brief Namespace for drawing lines with the use of OpenGL. * * \author gernot * \date 2018-09-07 * \version 1.0 **********************************************************************/ namespace Line { /******************************************************************//** * \brief ctor * * \author gernot * \date 2018-09-07 * \version 1.0 **********************************************************************/ CLineOpenGL_1_00::CLineOpenGL_1_00( void ) {} /******************************************************************//** * \brief ctor * * \author gernot * \date 2018-09-07 * \version 1.0 **********************************************************************/ CLineOpenGL_1_00::~CLineOpenGL_1_00() {} /******************************************************************//** * \brief Initialize the line renderer. * * \author gernot * \date 2018-09-07 * \version 1.0 **********************************************************************/ bool CLineOpenGL_1_00::Init( void ) { return true; } /******************************************************************//** * \brief Change the current line color, for the pending line drawing * instructions * * \author gernot * \date 2018-09-07 * \version 1.0 **********************************************************************/ Render::Line::IRender & CLineOpenGL_1_00::SetColor( const Render::TColor & color ) //!< I - the new color { // change the vertex color glColor4fv( color.data() ); return *this; } /******************************************************************//** * \brief Change the current line color, for the pending line drawing * instructions * * \author gernot * \date 2018-09-07 * \version 1.0 **********************************************************************/ Render::Line::IRender & CLineOpenGL_1_00::SetColor( const Render::TColor8 & color ) //!< I - the new color { // change the vertex color glColor4ubv( color.data() ); return *this; } /******************************************************************//** * \brief Change the current line with and the current line pattern, * for the pending line drawing instructions. * * The line width and line pattern can't be changed within a drawing * sequence. * * \author gernot * \date 2018-09-09 * \version 1.0 **********************************************************************/ Render::Line::IRender & CLineOpenGL_1_00::SetStyle( const Render::Line::TStyle & style ) { //! This is impossible, while an drawing sequence is active. //! The only possible operations within a `glBegin`/`glEnd` sequence are those operations, //! which directly change fixed function attributes or specify a new vertex coordinate. //! See [`glBegin`](https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glBegin.xml) if ( _active_sequence ) { assert( false ); return *this; } // set line width glLineWidth( style._width ); // activate line stipple if ( style._stipple_type == 1 ) { glDisable( GL_LINE_STIPPLE ); return *this; } glEnable( GL_LINE_STIPPLE ); // set stipple pattern static const std::array<GLushort, 8> patterns { 0x0000, 0xFFFF, 0x5555, 0x3333, 0x0F0F, 0x00FF, 0x7D7D, 0x7FFD }; GLushort pattern = style._stipple_type >= 0 && style._stipple_type < patterns.size() ? patterns[style._stipple_type] : 0xFFFF; glLineStipple( (GLint)(style._width + 0.5f), pattern ); return *this; } /******************************************************************//** * \brief Draw a single line sequence. * * \author gernot * \date 2018-09-07 * \version 1.0 **********************************************************************/ bool CLineOpenGL_1_00::Draw( Render::TPrimitive primitive_type, //!< in: primitive type of the coordinates - lines, line strip, line loop, lines adjacency or line strip adjacency unsigned int tuple_size, //!< in: kind of the coordinates - 2: 2D (x, y), 3: 3D (x, y, z), 4: homogeneous (x, y, z, w) size_t coords_size, //!< in: number of elements (size) of the coordinate array - `coords_size` = `tuple_size` * "number of coordinates" const float *coords ) //!< in: pointer to an array of the vertex coordinates { // A new sequence can't be started within an active sequence if ( _active_sequence ) { ASSERT( false ); return false; } ASSERT( Render::BasePrimitive(primitive_type) == Render::TBasePrimitive::line ); ASSERT( tuple_size == 2 || tuple_size == 3 || tuple_size == 4 ); // start `glBegin` / `glEnd` sequence glBegin( OpenGL::Primitive(primitive_type) ); // draw the line sequence if ( tuple_size == 2 ) { for ( const float *ptr = coords, *end_ptr = coords + coords_size; ptr < end_ptr; ptr += 2 ) glVertex2fv( ptr ); } else if ( tuple_size == 3 ) { for ( const float *ptr = coords, *end_ptr = coords + coords_size; ptr < end_ptr; ptr += 3 ) glVertex3fv( ptr ); } else if ( tuple_size == 4 ) { for ( const float *ptr = coords, *end_ptr = coords + coords_size; ptr < end_ptr; ptr += 4 ) glVertex4fv( ptr ); } // complete sequence glEnd(); return true; } /******************************************************************//** * \brief Draw a single line sequence. * * \author gernot * \date 2018-09-07 * \version 1.0 **********************************************************************/ bool CLineOpenGL_1_00::Draw( Render::TPrimitive primitive_type, //!< in: primitive type of the coordinates - lines, line strip, line loop, lines adjacency or line strip adjacency unsigned int tuple_size, //!< in: kind of the coordinates - 2: 2D (x, y), 3: 3D (x, y, z), 4: homogeneous (x, y, z, w) size_t coords_size, //!< in: number of elements (size) of the coordinate array - `coords_size` = `tuple_size` * "number of coordinates" const double *coords ) //!< in: pointer to an array of the vertex coordinates { // A new sequence can't be started within an active sequence if ( _active_sequence ) { ASSERT( false ); return false; } ASSERT( Render::BasePrimitive(primitive_type) == Render::TBasePrimitive::line ); ASSERT( tuple_size == 2 || tuple_size == 3 || tuple_size == 4 ); // start `glBegin` / `glEnd` sequence glBegin( OpenGL::Primitive(primitive_type) ); // draw the line sequence if ( tuple_size == 2 ) { for ( const double *ptr = coords, *end_ptr = coords + coords_size; ptr < end_ptr; ptr += 2 ) glVertex2dv( ptr ); } else if ( tuple_size == 3 ) { for ( const double *ptr = coords, *end_ptr = coords + coords_size; ptr < end_ptr; ptr += 3 ) glVertex3dv( ptr ); } else if ( tuple_size == 4 ) { for ( const double *ptr = coords, *end_ptr = coords + coords_size; ptr < end_ptr; ptr += 4 ) glVertex4dv( ptr ); } // complete sequence glEnd(); return true; } /******************************************************************//** * \brief Draw a single line sequence. * * \author gernot * \date 2018-09-07 * \version 1.0 **********************************************************************/ bool CLineOpenGL_1_00::Draw( Render::TPrimitive primitive_type, //!< in: primitive type of the coordinates - lines, line strip, line loop, lines adjacency or line strip adjacency size_t no_of_coords, //!< in: number of coordinates and number of elements (size) of the coordinate array const float *x_coords, //!< int pointer to an array of the x coordinates const float *y_coords ) //!< int pointer to an array of the y coordinates { // A new sequence can't be started within an active sequence if ( _active_sequence ) { ASSERT( false ); return false; } ASSERT( Render::BasePrimitive(primitive_type) == Render::TBasePrimitive::line ); // start `glBegin` / `glEnd` sequence glBegin( OpenGL::Primitive(primitive_type) ); // draw the line sequence for ( size_t i = 0; i < no_of_coords; ++ i ) glVertex2f( x_coords[i], y_coords[i] ); // complete sequence glEnd(); return true; } /******************************************************************//** * \brief Draw a single line sequence. * * \author gernot * \date 2018-09-07 * \version 1.0 **********************************************************************/ bool CLineOpenGL_1_00::Draw( Render::TPrimitive primitive_type, //!< in: primitive type of the coordinates - lines, line strip, line loop, lines adjacency or line strip adjacency size_t no_of_coords, //!< in: number of coordinates and number of elements (size) of the coordinate array const double *x_coords, //!< int pointer to an array of the x coordinates const double *y_coords ) //!< int pointer to an array of the y coordinates { // A new sequence can't be started within an active sequence if ( _active_sequence ) { ASSERT( false ); return false; } ASSERT( Render::BasePrimitive(primitive_type) == Render::TBasePrimitive::line ); // start `glBegin` / `glEnd` sequence glBegin( OpenGL::Primitive(primitive_type) ); // draw the line sequence for ( size_t i = 0; i < no_of_coords; ++ i ) glVertex2d( x_coords[i], y_coords[i] ); // complete sequence glEnd(); return true; } /******************************************************************//** * \brief Start a new line sequence. * * \author gernot * \date 2018-09-07 * \version 1.0 **********************************************************************/ bool CLineOpenGL_1_00::StartSequence( Render::TPrimitive primitive_type, //!< in: primitive type of the coordinates - lines, line strip, line loop, lines adjacency or line strip adjacency unsigned int tuple_size ) //!< in: kind of the coordinates - 2: 2D (x, y), 3: 3D (x, y, z), 4: homogeneous (x, y, z, w) { // A new sequence can't be started within an active sequence if ( _active_sequence ) { ASSERT( false ); return false; } ASSERT( Render::BasePrimitive(primitive_type) == Render::TBasePrimitive::line ); ASSERT( tuple_size == 2 || tuple_size == 3 || tuple_size == 4 ); _active_sequence = true; _tuple_size = tuple_size; // start `glBegin` / `glEnd` sequence glBegin( OpenGL::Primitive(primitive_type) ); return true; } /******************************************************************//** * \brief Complete an active line sequence. * * \author gernot * \date 2018-09-07 * \version 1.0 **********************************************************************/ bool CLineOpenGL_1_00::EndSequence( void ) { // A sequence can't be completed if there is no active sequence if ( _active_sequence == false ) { ASSERT( false ); return false; } _active_sequence = false; _tuple_size = 0; // complete sequence glEnd(); return true; } /******************************************************************//** * \brief Specify a new vertex coordinate in an active line sequence. * * \author gernot * \date 2018-09-07 * \version 1.0 **********************************************************************/ bool CLineOpenGL_1_00::DrawSequence( float x, //!< in: x coordinate float y, //!< in: y coordinate float z ) //!< in: z coordinate { // A sequence has to be active, to specify a new vertex coordinate if ( _active_sequence == false ) { ASSERT( false ); return false; } // specify the vertex coordinate glVertex3f( x, y, z ); return true; } /******************************************************************//** * \brief Specify a new vertex coordinate in an active line sequence. * * \author gernot * \date 2018-09-07 * \version 1.0 **********************************************************************/ bool CLineOpenGL_1_00::DrawSequence( double x, //!< in: x coordinate double y, //!< in: y coordinate double z ) //!< in: z coordinate { // A sequence has to be active, to specify a new vertex coordinate if ( _active_sequence == false ) { ASSERT( false ); return false; } // specify the vertex coordinate glVertex3d( x, y, z ); return true; } /******************************************************************//** * \brief Specify a sequence of new vertex coordinates in an active * line sequence. * * \author gernot * \date 2018-09-07 * \version 1.0 **********************************************************************/ bool CLineOpenGL_1_00::DrawSequence( size_t coords_size, //!< in: number of elements (size) of the coordinate array - `coords_size` = `tuple_size` * "number of coordinates" const float *coords ) //!< in: pointer to an array of the vertex coordinates { // A sequence has to be active, to specify new vertex coordinates if ( _active_sequence == false ) { ASSERT( false ); return false; } // draw the line sequence if ( _tuple_size == 2 ) { for ( const float *ptr = coords, *end_ptr = coords + coords_size; ptr < end_ptr; ptr += 2 ) glVertex2fv( ptr ); } else if ( _tuple_size == 3 ) { for ( const float *ptr = coords, *end_ptr = coords + coords_size; ptr < end_ptr; ptr += 3 ) glVertex3fv( ptr ); } else if ( _tuple_size == 4 ) { for ( const float *ptr = coords, *end_ptr = coords + coords_size; ptr < end_ptr; ptr += 4 ) glVertex4fv( ptr ); } return true; } /******************************************************************//** * \brief Specify a sequence of new vertex coordinates in an active * line sequence. * * \author gernot * \date 2018-09-07 * \version 1.0 **********************************************************************/ bool CLineOpenGL_1_00::DrawSequence( size_t coords_size, //!< in: number of elements (size) of the coordinate array - `coords_size` = `tuple_size` * "number of coordinates" const double *coords ) //!< in: pointer to an array of the vertex coordinates { // A sequence has to be active, to specify new vertex coordinates if ( _active_sequence == false ) { ASSERT( false ); return false; } // draw the line sequence if ( _tuple_size == 2 ) { for ( const double *ptr = coords, *end_ptr = coords + coords_size; ptr < end_ptr; ptr += 2 ) glVertex2dv( ptr ); } else if ( _tuple_size == 3 ) { for ( const double *ptr = coords, *end_ptr = coords + coords_size; ptr < end_ptr; ptr += 3 ) glVertex3dv( ptr ); } else if ( _tuple_size == 4 ) { for ( const double *ptr = coords, *end_ptr = coords + coords_size; ptr < end_ptr; ptr += 4 ) glVertex4dv( ptr ); } return true; } } // Line } // OpenGL
e03c7ef7ce02b42e39d1e3e6aa14e55ac2fd5d7d
1b4f97da8e2a209561ce794091fbb5e3968b8fa3
/src/WPIMock.cpp
a5809aa0185f27f642a3e5b1a45ace1fa96a0dbf
[]
no_license
multiplemonomials/FRC-3128-2015
4bc7923f6b0297921a70054d638201a11dba3699
dca9738473b201caf1cbceca2b0e8dccf3290e2a
refs/heads/master
2021-01-10T22:01:30.315910
2014-08-31T15:12:05
2014-08-31T15:12:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,816
cpp
WPIMock.cpp
/* * WPIMock.cpp * * Until the actual Linux-native WPILib is released, * this file is used to link and test the program. * * It holds replacements for the WPILib functions that are * invoked. */ #include <LogMacros.h> #include <WPILib.h> //master switch for the use of libjoystick to get real joystick values from usb //#define LIBJOYSTICK_ENABLED //port to connect to joystick on #define LIBJOYSTICK_PORT "/dev/input/js2" #ifdef LIBJOYSTICK_ENABLED #include <libjoystick/Joystick.h> #endif uint32_t DigitalInput::Get() { LOG_DEBUG("DigitalInput::Get called.") return 0; } SensorBase::SensorBase() { LOG_DEBUG("SensorBase::SensorBase() called.") } AnalogChannel::AnalogChannel(uint8_t moduleNumber, uint32_t channel) :m_channel(channel), m_module(nullptr), m_accumulator(nullptr), m_accumulatorOffset(0), m_shouldUseVoltageForPID(false), m_table(nullptr) { LOG_DEBUG("AnalogChannel::AnalogChannel(" << (short)(moduleNumber) << ", " << channel << ") called.") } float AnalogChannel::GetVoltage() { //LOG_DEBUG("AnalogChannel::GetVoltage() called."); return 0.0; } int32_t Encoder::GetRaw() { LOG_DEBUG("Encoder::GetRaw() called.") return 0; } void Relay::Set(Value value) { LOG_DEBUG("Relay::Set(" << value << ") called.") } Gyro::Gyro(uint8_t moduleNumber, uint32_t channel) :m_analog(nullptr), m_voltsPerDegreePerSecond(0), m_offset(0), m_channelAllocated(true), m_center(0), m_pidSource(PIDSource::PIDSourceParameter::kAngle), m_table(nullptr) { LOG_DEBUG("Gyro::Gyro(" << (short)(moduleNumber) << ", " << channel << ") called.") } Gyro::~Gyro() { } float Gyro::GetAngle() { LOG_DEBUG("Gyro::GetAngle() called.") return 0.0; } double Gyro::GetRate() { LOG_DEBUG("Gyro::GetRate() called.") return 0.0; } void Gyro::Reset() { LOG_DEBUG("Gyro::Reset() called.") } DigitalInput::DigitalInput(unsigned char module, unsigned int channel) :m_channel(channel), m_module(nullptr), m_lastValue(false), m_table(nullptr) { LOG_DEBUG("DigitalInput::DigitalInput(" << (short)(module) << ", " << channel << ") called.") } DigitalInput::~DigitalInput() { } Talon::Talon(uint8_t moduleNumber, uint32_t channel) { LOG_DEBUG("Talon::Talon(" << (short)moduleNumber << ", " << channel << ") called.") } void Talon::Set(float value, uint8_t syncGroup) { LOG_DEBUG("Talon::Set(" << value << ") called.") } float Talon::Get() { LOG_DEBUG("Talon::Get() called.") return 0.0; } void Talon::PIDWrite(float output) { LOG_DEBUG("Talon::PIDWrite(" << output << ") called.") } Talon::~Talon() { } Relay::Relay(uint8_t moduleNumber, uint32_t channel, Direction direction) :m_table(nullptr), m_channel(channel), m_direction(direction), m_module(nullptr) { LOG_DEBUG("Relay::Relay(" << (short)moduleNumber << ", " << channel << ", " << direction << ") called.") } Relay::~Relay() { } #ifdef LIBJOYSTICK_ENABLED static joy::Joystick testingJoystick(std::string("/dev/input/js2")); #endif Joystick::Joystick(unsigned int port) :m_ds(nullptr), m_port(port), m_axes(nullptr), m_buttons(nullptr) { LOG_DEBUG("Joystick::Joystick(" << port << ") called.") } Joystick::~Joystick() { } bool Joystick::GetRawButton(uint32_t button) { #ifdef LIBJOYSTICK_ENABLED bool rawValue = testingJoystick.getButtonValue(button - 1); LOG_DEBUG("Joystick::GetRawButton(" << button << ") called, returning " << std::boolalpha << rawValue) return rawValue; #else LOG_DEBUG("Joystick::GetRawButton(" << button << ") called.") return false; #endif } float Joystick::GetRawAxis(uint32_t axis) { #ifdef LIBJOYSTICK_ENABLED float rawValue = (testingJoystick.getAxisValue(axis - 1) / 32768.0); LOG_DEBUG("Joystick::GetRawAxis(" << axis << ") called, returning " << rawValue) return rawValue; #else LOG_DEBUG("Joystick::GetRawAxis(" << axis << ") called.") return 0.0; #endif }
44d05b1226a26f8080647d5d5f78281c1b6a43d9
4b1b1c57ceb40c4b5c99ce4a942067d31de950c0
/src/PortalArea.h
a73688992d8680174d05bed17f26f16bd7198659
[]
no_license
HourglassGame/HourglassII
bb39febd0179fa1c661c115f97d029cb7849b9fd
9ee35c78e8d942e455caf32c7008ab0e7dba87d3
refs/heads/master
2023-05-24T22:53:15.745500
2018-12-05T03:34:22
2018-12-05T03:34:22
46,217,706
2
0
null
null
null
null
UTF-8
C++
false
false
7,127
h
PortalArea.h
#ifndef HG_PORTAL_AREA_H #define HG_PORTAL_AREA_H #include "TimeDirection.h" #include <ostream> #include <tuple> namespace hg { class PortalArea; std::ostream &operator<<(std::ostream &os, PortalArea const &toPrint); class PortalArea final { auto comparison_tuple() const -> decltype(auto) { return std::tie( index_, x_, y_, xaim_, yaim_, width_, height_, xspeed_, yspeed_, collisionOverlap_, timeDirection_, destinationIndex_, xDestination_, yDestination_, relativeTime_, timeDestination_, relativeDirection_, destinationDirection_, illegalDestination_, fallable_, isLaser_, winner_ ); } public: PortalArea( int index, int x, int y, int xaim, int yaim, int width, int height, int xspeed, int yspeed, int collisionOverlap, TimeDirection timeDirection, int destinationIndex, int xDestination, int yDestination, bool relativeTime, int timeDestination, bool relativeDirection, TimeDirection destinationDirection, int illegalDestination, bool fallable, bool isLaser, bool winner ) : index_(index), x_(x), y_(y), xaim_(xaim), yaim_(yaim), width_(width), height_(height), xspeed_(xspeed), yspeed_(yspeed), collisionOverlap_(collisionOverlap), timeDirection_(timeDirection), destinationIndex_(destinationIndex), xDestination_(xDestination), yDestination_(yDestination), relativeTime_(relativeTime), timeDestination_(timeDestination), relativeDirection_(relativeDirection), destinationDirection_(destinationDirection), illegalDestination_(illegalDestination), fallable_(fallable), isLaser_(isLaser), winner_(winner) { //not strictly necessary, just providing normalised values where the values are not used if (winner_) { winner_ = true; relativeTime_ = false; timeDestination_ = 1; relativeDirection_ = false; destinationDirection_ = TimeDirection::FORWARDS; } } //Index is used for identifying illegal-portals //Maybe we should add a simple way for //triggers to attach information to guys. //This would allow `shouldPort` to manage //illegal-portals. int getIndex() const { return index_; } int getX() const { return x_; } int getY() const { return y_; } int getXaim() const { return xaim_; } int getYaim() const { return yaim_; } int getWidth() const { return width_; } int getHeight() const { return height_; } int getXspeed() const { return xspeed_; } int getYspeed() const { return yspeed_; } int getCollisionOverlap() const { return collisionOverlap_; } TimeDirection getTimeDirection() const { return timeDirection_; } int getDestinationIndex() const { return destinationIndex_; } int getXdestination() const { return xDestination_; } int getYdestination() const { return yDestination_; } bool getRelativeTime() const { return relativeTime_; } int getTimeDestination() const { return timeDestination_; } bool getRelativeDirection() const { return relativeDirection_; } TimeDirection getDestinationDirection() const { return destinationDirection_; } int getIllegalDestination() const { return illegalDestination_; } bool getFallable() const { return fallable_; } bool getIsLaser() const { return isLaser_; } bool getWinner() const { return winner_; } friend std::ostream &operator<<(std::ostream &os, PortalArea const &toPrint) { os << '{'; #define HG_PORTAL_AREA_PRINT(field) os << #field << "=" << toPrint.field HG_PORTAL_AREA_PRINT(index_) << ','; HG_PORTAL_AREA_PRINT(x_) << ','; HG_PORTAL_AREA_PRINT(y_) << ','; HG_PORTAL_AREA_PRINT(xaim_) << ','; HG_PORTAL_AREA_PRINT(yaim_) << ','; HG_PORTAL_AREA_PRINT(width_) << ','; HG_PORTAL_AREA_PRINT(height_) << ','; HG_PORTAL_AREA_PRINT(xspeed_) << ','; HG_PORTAL_AREA_PRINT(yspeed_) << ','; HG_PORTAL_AREA_PRINT(collisionOverlap_) << ','; HG_PORTAL_AREA_PRINT(timeDirection_) << ','; HG_PORTAL_AREA_PRINT(destinationIndex_) << ','; HG_PORTAL_AREA_PRINT(xDestination_) << ','; HG_PORTAL_AREA_PRINT(yDestination_) << ','; HG_PORTAL_AREA_PRINT(relativeTime_) << ','; HG_PORTAL_AREA_PRINT(timeDestination_) << ','; HG_PORTAL_AREA_PRINT(relativeDirection_) << ','; HG_PORTAL_AREA_PRINT(destinationDirection_) << ','; HG_PORTAL_AREA_PRINT(illegalDestination_) << ','; HG_PORTAL_AREA_PRINT(fallable_) << ','; HG_PORTAL_AREA_PRINT(isLaser_) << ','; HG_PORTAL_AREA_PRINT(winner_); #undef HG_PORTAL_AREA_PRINT os << '}'; return os; } bool operator==(PortalArea const &o) const { return comparison_tuple() == o.comparison_tuple(); } private: //The Illegal-Portal system explained: //The motivation for Illegal-Portal is that we sometimes want fallable //portals where the guy/box will not immediately fall through a new portal when they arrive. //That is --- we sometimes want to make it so guys/boxes cannot immediately fall through portals //upon arriving, but must experience at least one frame of 'not intersecting with the portal' before //'intersecting with the portal' will once again trigger porting. //This behaviour is mediated by three properties: //Portal.index_: A positive integer identifier (not necessecarily unique) given to each portal //Portal.illegalDestination_: The "index_" of the portal that the arriving guy shouldn't fall through //(Guy/Box).illegalPortal: The "index_" of the portal that the guy/box mustn't fall through until it has 'walked off' the portal. // `-1` indicates that the guy/box may fall through any portal. //This behaviour is implemented by hg::PhysicsEngine (at time of writing: PhysicsEngineUtilities_def.h). int index_; int x_; int y_; int xaim_; int yaim_; int width_; int height_; int xspeed_; int yspeed_; int collisionOverlap_; TimeDirection timeDirection_; int destinationIndex_; int xDestination_; int yDestination_; bool relativeTime_; int timeDestination_; bool relativeDirection_; TimeDirection destinationDirection_; int illegalDestination_; bool fallable_; bool isLaser_; bool winner_; }; }//namespace hg #endif //HG_PORTAL_AREA_H
63b4e4bdd78f727c7ba97e7b4d4bd102502de6e1
3a1c6383fa90c3da1a7672277f074fa4b8c6cff4
/EsView.h
00669f06d749debd5547950983bc95e244410243
[]
no_license
a1a2y3/ES
6b86223965a5e879a5570ddeaca1dba660fe2cc7
223b7dfe7e7392f174733eac2f5b0df534d540f0
refs/heads/master
2016-08-12T08:53:21.131053
2015-05-21T06:50:07
2015-05-21T06:50:07
35,996,456
0
0
null
null
null
null
GB18030
C++
false
false
2,321
h
EsView.h
// EsView.h : CEsView 类的接口 #pragma once #include "opencv\cv.h" class CTargetRectDlg; class CEsDoc; class CEsView : public CScrollView { protected: // 仅从序列化创建 CEsView(); DECLARE_DYNCREATE(CEsView) // 属性 public: CEsDoc* GetDocument() const; // 操作 public: CEsDoc *m_pDoc; BOOL m_bDialogOK; CTargetRectDlg* *m_pDialog; BOOL *m_pIsTargetSetted; CvPoint2D32f *m_pTarget; int m_TargetCount; CRect m_DialogRect; BOOL m_bShowTargDlg; CPoint m_OldPt; CPoint m_MousePt; BOOL m_bDrawLine; BOOL m_bDrawTarget; BOOL m_bTargetSetCanceld; // 重写 public: virtual void OnDraw(CDC* pDC); // 重写以绘制该视图 virtual BOOL PreCreateWindow(CREATESTRUCT& cs); protected: virtual void OnInitialUpdate(); // 构造后第一次调用 virtual BOOL OnPreparePrinting(CPrintInfo* pInfo); virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo); virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo); // 实现 public: void ReleaseMem(); void DrawCrossOnTarget(CvPoint2D32f Target, int TargetNo=-1); void DrawMaskOnTarget(CvPoint2D32f Target, int TargetNo=-1); void DrawRectOnTarget(CvPoint2D32f Target, int TargetNo=-1); void InitiateTarget(int TargetCount); void ResizeWindow(); void DrawCursor(CPoint point); virtual ~CEsView(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // 生成的消息映射函数 protected: afx_msg void OnFilePrintPreview(); afx_msg void OnRButtonUp(UINT nFlags, CPoint point); afx_msg void OnContextMenu(CWnd* pWnd, CPoint point); DECLARE_MESSAGE_MAP() public: afx_msg void OnMouseMove(UINT nFlags, CPoint point); afx_msg void OnSelectPoints(); afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg void OnLButtonUp(UINT nFlags, CPoint point); afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags); afx_msg void OnManualSelectTarget(); afx_msg void OnCenterFromCorners(); }; #ifndef _DEBUG // EsView.cpp 中的调试版本 inline CEsDoc* CEsView::GetDocument() const { return reinterpret_cast<CEsDoc*>(m_pDocument); } #endif
2ac473e73ecf732a8b3af1eda8653d7ab757c3c8
c482082eeadd0df4fc4758220cd5e0351f5932e5
/modules/mobile/PartitionJob.cpp
db2e5bbe3556e9e43db68061d50f96fcae0c00f5
[ "CC0-1.0" ]
permissive
calamares/calamares-extensions
8557d90ac390269fed6826eb1c01863ced4eb714
dc3550eccd084a785199e3de3e56e067173d4649
refs/heads/calamares
2023-09-01T14:00:11.488619
2023-08-28T21:52:02
2023-08-28T21:52:02
124,537,473
29
26
null
2023-09-05T14:38:13
2018-03-09T12:24:36
QML
UTF-8
C++
false
false
4,619
cpp
PartitionJob.cpp
/* SPDX-FileCopyrightText: 2020 Oliver Smith <ollieparanoid@postmarketos.org> * SPDX-License-Identifier: GPL-3.0-or-later */ #include "PartitionJob.h" #include "GlobalStorage.h" #include "JobQueue.h" #include "Settings.h" #include "utils/CalamaresUtilsSystem.h" #include "utils/Logger.h" #include <QDir> #include <QFileInfo> PartitionJob::PartitionJob( const QString& cmdInternalStoragePrepare, const QString& cmdLuksFormat, const QString& cmdLuksOpen, const QString& cmdMkfsRoot, const QString& cmdMount, const QString& targetDeviceRoot, const QString& targetDeviceRootInternal, bool installFromExternalToInternal, bool isFdeEnabled, const QString& password ) : Calamares::Job() , m_cmdInternalStoragePrepare( cmdInternalStoragePrepare ) , m_cmdLuksFormat( cmdLuksFormat ) , m_cmdLuksOpen( cmdLuksOpen ) , m_cmdMkfsRoot( cmdMkfsRoot ) , m_cmdMount( cmdMount ) , m_targetDeviceRoot( targetDeviceRoot ) , m_targetDeviceRootInternal( targetDeviceRootInternal ) , m_installFromExternalToInternal( installFromExternalToInternal ) , m_isFdeEnabled( isFdeEnabled ) , m_password( password ) { } QString PartitionJob::prettyName() const { return "Creating and formatting installation partition"; } /* Fill the "global storage", so the following jobs (like unsquashfs) work. The code is similar to modules/partition/jobs/FillGlobalStorageJob.cpp in Calamares. */ void FillGlobalStorage( const QString device, const QString pathMount ) { using namespace Calamares; GlobalStorage* gs = JobQueue::instance()->globalStorage(); QVariantList partitions; QVariantMap partition; /* See mapForPartition() in FillGlobalStorageJob.cpp */ partition[ "device" ] = device; partition[ "mountPoint" ] = "/"; partition[ "claimed" ] = true; /* Ignored by calamares modules used in combination with the "mobile" * module, so we can get away with leaving them empty for now. */ partition[ "uuid" ] = ""; partition[ "fsName" ] = ""; partition[ "fs" ] = ""; partitions << partition; gs->insert( "partitions", partitions ); gs->insert( "rootMountPoint", pathMount ); } Calamares::JobResult PartitionJob::exec() { using namespace Calamares; using namespace CalamaresUtils; using namespace std; const QString pathMount = "/mnt/install"; const QString cryptName = "calamares_crypt"; QString cryptDev = "/dev/mapper/" + cryptName; QString passwordStdin = m_password + "\n"; QString dev = m_targetDeviceRoot; QList< QPair< QStringList, QString > > commands = {}; if ( m_installFromExternalToInternal ) { dev = m_targetDeviceRootInternal; commands.append( { { { "sh", "-c", m_cmdInternalStoragePrepare }, QString() }, } ); } commands.append( { { { "mkdir", "-p", pathMount }, QString() } } ); if ( m_isFdeEnabled ) { commands.append( { { { "sh", "-c", m_cmdLuksFormat + " " + dev }, passwordStdin }, { { "sh", "-c", m_cmdLuksOpen + " " + dev + " " + cryptName }, passwordStdin }, { { "sh", "-c", m_cmdMkfsRoot + " " + cryptDev }, QString() }, { { "sh", "-c", m_cmdMount + " " + cryptDev + " " + pathMount }, QString() }, } ); } else { commands.append( { { { "sh", "-c", m_cmdMkfsRoot + " " + dev }, QString() }, { { "sh", "-c", m_cmdMount + " " + dev + " " + pathMount }, QString() } } ); } foreach ( auto command, commands ) { const QStringList args = command.first; const QString stdInput = command.second; const QString pathRoot = "/"; ProcessResult res = System::runCommand( System::RunLocation::RunInHost, args, pathRoot, stdInput, chrono::seconds( 600 ) ); if ( res.getExitCode() ) { return JobResult::error( "Command failed:<br><br>" "'" + args.join( " " ) + "'<br><br>" " with output:<br><br>" "'" + res.getOutput() + "'" ); } } FillGlobalStorage( m_isFdeEnabled ? cryptDev : dev, pathMount ); return JobResult::ok(); }
ee36236008b88d2c731452a6b381a84ae8e01187
9525510c8f514c842b66bc7f43a6c20b5ff8ba93
/projMtx_classes/MainCityLayer.cpp
fce3d6b3233cae1b19f55157a2037cdb31e9bba6
[]
no_license
qjsy/QjGit
7f1810b50f166c5ef58512d0407efd18f8a4f9a6
651d4733002e13ccffef573173a4536cb9d23d7a
refs/heads/master
2016-09-09T14:21:35.540068
2014-03-12T15:30:24
2014-03-12T15:30:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,663
cpp
MainCityLayer.cpp
// // MainCityLayer.cpp // hero // // Created by yangjie on 2013/11/28. // // 主城层(主界面首页) // 隶属于主场景 // #include "MainCityLayer.h" #include "customMessage.h" #include "GameState.h" #include "NetConnection.h" #include "GamePlayer.h" #include "Battle.h" #define CONTAINER_TAG 1500 #define M_CITY_IMAGE_FILE "mcity.pvr.ccz" #define M_CITY_LIST_FILE "mcity.plist" #define MC_MENU_HIGH_LIGTH_OFFSET_H 0.0f #define MC_MENU_HIGH_LIGTH_OFFSET_V 8.0f /* * 构造函数 */ MainCityLayer::MainCityLayer(): m_pGameState(GameState::getInstance()) ,m_pBattle(Battle::getInstance()) ,m_touchEnable(true) { memset(m_menuButtonSprite, '\0', sizeof(m_menuButtonSprite)); // 逐鹿中原 m_menuButtonPosition[0][0] = ccp(460.0f, 0.0f); // 按钮 m_menuButtonPosition[0][1] = ccp(465.0f, 80.0f); // 文字 m_menuEnable[0] = true; // 铜雀台 m_menuButtonPosition[1][0] = ccp(0.0f, 320.0f); // 按钮 m_menuButtonPosition[1][1] = ccp(50.0f, 290.0f); // 文字 m_menuEnable[1] = true; // 升阶 m_menuButtonPosition[2][0] = ccp(175.0f, 190.0f); // 按钮 m_menuButtonPosition[2][1] = ccp(245.0f, 145.0f); // 文字 m_menuEnable[2] = true; // 驿站 m_menuButtonPosition[3][0] = ccp(420.0f, 245.0f); // 按钮 m_menuButtonPosition[3][1] = ccp(505.0f, 230.0f); // 文字 m_menuEnable[3] = true; // 铁匠铺 m_menuButtonPosition[4][0] = ccp(180.0f, 45.0f); // 按钮 m_menuButtonPosition[4][1] = ccp(190.0f, 20.0f); // 文字 m_menuEnable[4] = true; // 国战 m_menuButtonPosition[5][0] = ccp(460.0f, 365.0f); // 按钮 m_menuButtonPosition[5][1] = ccp(485, 350.0f); // 文字 m_menuEnable[5] = true; // 左未开放 m_menuButtonPosition[6][0] = ccp(0.0f, 105.0f); // 按钮 m_menuButtonPosition[6][1] = ccp(30.0f, 95.0f); // 文字 m_menuEnable[6] = false; // 监狱 m_menuButtonPosition[7][0] = ccp(310, 325.0f); // 按钮 m_menuButtonPosition[7][1] = ccp(330.0f, 315.0f); // 文字 m_menuEnable[7] = true; } /* * 析构函数 */ MainCityLayer::~MainCityLayer() { CCSpriteFrameCache* pSpriteFrameCache = CCSpriteFrameCache::sharedSpriteFrameCache(); CCTextureCache* pTextureCache = CCTextureCache::sharedTextureCache(); pSpriteFrameCache->removeSpriteFramesFromFile(M_CITY_LIST_FILE); pTextureCache->removeTextureForKey(M_CITY_IMAGE_FILE); } /* * 初始化 */ bool MainCityLayer::init() { // super init if (!CCLayer::init()) { return false; } this->setTouchEnabled(true); /* * 初始化 */ CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile(M_CITY_LIST_FILE, M_CITY_IMAGE_FILE); this->addChild(m_pSBN = CCSpriteBatchNode::create(M_CITY_IMAGE_FILE)); // 主城背景图 CCSprite* pBgSprite = CCSprite::createWithSpriteFrameName("MC_cityBg.png"); pBgSprite->setAnchorPoint(CCPointZero); pBgSprite->setPosition(ccp(0.0f, m_pGameState->getBottomOffset() + 122.0f)); m_pSBN->addChild(pBgSprite, 1, CONTAINER_TAG); /* * 按钮 */ // 逐鹿中原 pBgSprite->addChild(m_menuButtonSprite[0][0] = CCSprite::createWithSpriteFrameName("MC_6.png"), 9); m_menuButtonSprite[0][0]->setAnchorPoint(CCPointZero); pBgSprite->addChild(m_menuButtonSprite[0][1] = CCSprite::createWithSpriteFrameName("MC_F_6.png"), 11); m_menuButtonSprite[0][1]->setAnchorPoint(CCPointZero); pBgSprite->addChild(m_menuButtonSprite[0][2] = CCSprite::createWithSpriteFrameName("MC_6s.png"), 10); m_menuButtonSprite[0][2]->setAnchorPoint(CCPointZero); // 铜雀台 pBgSprite->addChild(m_menuButtonSprite[1][0] = CCSprite::createWithSpriteFrameName("MC_4.png"), 9); m_menuButtonSprite[1][0]->setAnchorPoint(CCPointZero); pBgSprite->addChild(m_menuButtonSprite[1][1] = CCSprite::createWithSpriteFrameName("MC_F_4.png"), 11); m_menuButtonSprite[1][1]->setAnchorPoint(CCPointZero); pBgSprite->addChild(m_menuButtonSprite[1][2] = CCSprite::createWithSpriteFrameName("MC_4s.png"), 10); m_menuButtonSprite[1][2]->setAnchorPoint(CCPointZero); // 升阶 pBgSprite->addChild(m_menuButtonSprite[2][0] = CCSprite::createWithSpriteFrameName("MC_2.png"), 9); m_menuButtonSprite[2][0]->setAnchorPoint(CCPointZero); pBgSprite->addChild(m_menuButtonSprite[2][1] = CCSprite::createWithSpriteFrameName("MC_F_2.png"), 11); m_menuButtonSprite[2][1]->setAnchorPoint(CCPointZero); pBgSprite->addChild(m_menuButtonSprite[2][2] = CCSprite::createWithSpriteFrameName("MC_2s.png"), 10); m_menuButtonSprite[2][2]->setAnchorPoint(CCPointZero); // 驿站 pBgSprite->addChild(m_menuButtonSprite[3][0] = CCSprite::createWithSpriteFrameName("MC_5.png"), 9); m_menuButtonSprite[3][0]->setAnchorPoint(CCPointZero); pBgSprite->addChild(m_menuButtonSprite[3][1] = CCSprite::createWithSpriteFrameName("MC_F_5.png"), 11); m_menuButtonSprite[3][1]->setAnchorPoint(CCPointZero); pBgSprite->addChild(m_menuButtonSprite[3][2] = CCSprite::createWithSpriteFrameName("MC_5s.png"), 10); m_menuButtonSprite[3][2]->setAnchorPoint(CCPointZero); // 铁匠铺 pBgSprite->addChild(m_menuButtonSprite[4][0] = CCSprite::createWithSpriteFrameName("MC_3.png"), 9); m_menuButtonSprite[4][0]->setAnchorPoint(CCPointZero); pBgSprite->addChild(m_menuButtonSprite[4][1] = CCSprite::createWithSpriteFrameName("MC_F_3.png"), 11); m_menuButtonSprite[4][1]->setAnchorPoint(CCPointZero); pBgSprite->addChild(m_menuButtonSprite[4][2] = CCSprite::createWithSpriteFrameName("MC_3s.png"), 10); m_menuButtonSprite[4][2]->setAnchorPoint(CCPointZero); // 国战 pBgSprite->addChild(m_menuButtonSprite[5][0] = CCSprite::createWithSpriteFrameName("MC_1.png"), 9); m_menuButtonSprite[5][0]->setAnchorPoint(CCPointZero); pBgSprite->addChild(m_menuButtonSprite[5][1] = CCSprite::createWithSpriteFrameName("MC_F_1.png"), 11); m_menuButtonSprite[5][1]->setAnchorPoint(CCPointZero); pBgSprite->addChild(m_menuButtonSprite[5][2] = CCSprite::createWithSpriteFrameName("MC_1s.png"), 10); m_menuButtonSprite[5][2]->setAnchorPoint(CCPointZero); // 左未开放 pBgSprite->addChild(m_menuButtonSprite[6][0] = CCSprite::createWithSpriteFrameName("MC_zuo.png"), 9); m_menuButtonSprite[6][0]->setAnchorPoint(CCPointZero); pBgSprite->addChild(m_menuButtonSprite[6][1] = CCSprite::createWithSpriteFrameName("wkfs.png"), 11); m_menuButtonSprite[6][1]->setAnchorPoint(CCPointZero); pBgSprite->addChild(m_menuButtonSprite[6][2] = CCSprite::createWithSpriteFrameName("MC_zuo.png"), 10); m_menuButtonSprite[6][2]->setAnchorPoint(CCPointZero); // 监狱 pBgSprite->addChild(m_menuButtonSprite[7][0] = CCSprite::createWithSpriteFrameName("MC_7.png"), 12); m_menuButtonSprite[7][0]->setAnchorPoint(CCPointZero); pBgSprite->addChild(m_menuButtonSprite[7][1] = CCSprite::createWithSpriteFrameName("MC_F_7.png"), 14); m_menuButtonSprite[7][1]->setAnchorPoint(CCPointZero); pBgSprite->addChild(m_menuButtonSprite[7][2] = CCSprite::createWithSpriteFrameName("MC_7s.png"), 13); m_menuButtonSprite[7][2]->setAnchorPoint(CCPointZero); _initMenuButton(); return true; } // void MainCityLayer::_initMenuButton(void) { ((CCSprite*)m_pSBN->getChildByTag(CONTAINER_TAG))->setVisible(true); for (unsigned int i = 0; i < MC_MENU_NUMBER; i++) { m_menuButtonSprite[i][0]->setVisible(true); m_menuButtonSprite[i][0]->setPosition(m_menuButtonPosition[i][0]); m_menuButtonSprite[i][1]->setVisible(true); m_menuButtonSprite[i][1]->setPosition(m_menuButtonPosition[i][1]); m_menuButtonSprite[i][2]->setVisible(false); } /*for*/ } // void MainCityLayer::registerWithTouchDispatcher(void) { CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, kCCMenuHandlerPriority, false); } // bool MainCityLayer::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent) { if (!m_touchEnable) return false; _initMenuButton(); m_touchBeganMenuIndex = -1; CCSprite* pBg = static_cast<CCSprite*>(m_pSBN->getChildByTag(CONTAINER_TAG)); CCPoint touchPoint = pBg->convertTouchToNodeSpace(pTouch); for (unsigned int i = 0; i < MC_MENU_NUMBER; i++) { if (m_menuEnable[i] && m_menuButtonSprite[i][0]->boundingBox().containsPoint(touchPoint)) { m_touchBeganMenuIndex = i; m_menuButtonSprite[i][0]->setVisible(false); m_menuButtonSprite[i][2]->setVisible(true); CCPoint menuPos = m_menuButtonPosition[i][0]; CCPoint textPos = m_menuButtonPosition[i][1]; menuPos.x += MC_MENU_HIGH_LIGTH_OFFSET_H; menuPos.y += MC_MENU_HIGH_LIGTH_OFFSET_V; textPos.x += MC_MENU_HIGH_LIGTH_OFFSET_H; textPos.y += MC_MENU_HIGH_LIGTH_OFFSET_V; m_menuButtonSprite[i][1]->setPosition(textPos); m_menuButtonSprite[i][2]->setPosition(menuPos); break; } } /*for*/ return true; } // void MainCityLayer::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent) { _initMenuButton(); CCSprite* pBg = static_cast<CCSprite*>(m_pSBN->getChildByTag(CONTAINER_TAG)); CCPoint touchPoint = pBg->convertTouchToNodeSpace(pTouch); for (unsigned int i = 0; i < MC_MENU_NUMBER; i++) { if (m_menuEnable[i] && m_menuButtonSprite[i][0]->boundingBox().containsPoint(touchPoint)) { m_menuButtonSprite[i][0]->setVisible(false); m_menuButtonSprite[i][2]->setVisible(true); CCPoint menuPos = m_menuButtonPosition[i][0]; CCPoint textPos = m_menuButtonPosition[i][1]; menuPos.x += MC_MENU_HIGH_LIGTH_OFFSET_H; menuPos.y += MC_MENU_HIGH_LIGTH_OFFSET_V; textPos.x += MC_MENU_HIGH_LIGTH_OFFSET_H; textPos.y += MC_MENU_HIGH_LIGTH_OFFSET_V; m_menuButtonSprite[i][1]->setPosition(textPos); m_menuButtonSprite[i][2]->setPosition(menuPos); break; } } /*for*/ } // void MainCityLayer::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent) { CCSprite* pBg = static_cast<CCSprite*>(m_pSBN->getChildByTag(CONTAINER_TAG)); CCPoint touchPoint = pBg->convertTouchToNodeSpace(pTouch); int selectedMenuIndex = -1; for (unsigned int i = 0; i < MC_MENU_NUMBER; i++) { if (m_menuEnable[i] && m_touchBeganMenuIndex == i && m_menuButtonSprite[i][0]->boundingBox().containsPoint(touchPoint)) { selectedMenuIndex = i + 1; break; } } /*for*/ _initMenuButton(); if (selectedMenuIndex > 0) /* 玩家选择了某个菜单选项 */ { onMcMenuSelect(selectedMenuIndex); } } // void MainCityLayer::ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent) { _initMenuButton(); } /* * 响应菜单选择 */ void MainCityLayer::onMcMenuSelect(const unsigned int menuIndex) { switch (menuIndex) { case 1: // 逐鹿中原 { m_pBattle->setCWar(false); m_pBattle->setBattlePkMode(BPM_PVE); CCNotificationCenter::sharedNotificationCenter()->postNotification(ON_MESSAGE_ZHULU_STRING); } break; case 2: // 铜雀台 { NetConnection* pNetConnection = NetConnection::getInstance(); char szPostBuffer[MAX_POSTTO_SERVER_BUFFER_SIZE]; memset(szPostBuffer, '\0', MAX_POSTTO_SERVER_BUFFER_SIZE); // 构造 post sprintf(szPostBuffer, "c=contest&a=enter&uid=%s", GamePlayer::getInstance()->getUid().c_str()); char szHttpTag[] = HTTP_ENTER_TONGQUETAI; pNetConnection->commitPostRequestData(szPostBuffer, szHttpTag); } break; case 3: // 升级升阶 CCNotificationCenter::sharedNotificationCenter()->postNotification(ON_MESSAGE_LEVUP_STRING); break; case 4: // 驿站 CCNotificationCenter::sharedNotificationCenter()->postNotification(ON_MESSAGE_YIZHAN_STRING); break; case 5: // 铁匠铺 CCNotificationCenter::sharedNotificationCenter()->postNotification(ON_MESSAGE_TIEJIANG_STRING); break; case 6: // 国战 { NetConnection* pNetConnection = NetConnection::getInstance(); char szPostBuffer[MAX_POSTTO_SERVER_BUFFER_SIZE]; memset(szPostBuffer, '\0', MAX_POSTTO_SERVER_BUFFER_SIZE); strcpy(szPostBuffer, "c=cwar&a=enter"); char szHttpTag[] = HTTP_REQUEST_ENTERCWAR_TAG; strcat(szPostBuffer, "&uid="); strcat(szPostBuffer, GamePlayer::getInstance()->getUid().c_str()); CCLog("post 进入国战 = %s", szPostBuffer); pNetConnection->commitPostRequestData(szPostBuffer, szHttpTag); } break; case 7: // 左未开放 break; case 8: // 监狱 // { NetConnection* pNetConnection = NetConnection::getInstance(); char szPostBuffer[MAX_POSTTO_SERVER_BUFFER_SIZE]; memset(szPostBuffer, '\0', MAX_POSTTO_SERVER_BUFFER_SIZE); strcpy(szPostBuffer, "c=prison&a=enter"); char szHttpTag[] = HTTP_REQUEST_JIANYUINIT_TAG; strcat(szPostBuffer, "&uid="); strcat(szPostBuffer, GamePlayer::getInstance()->getUid().c_str()); CCLog("post 购买 = %s", szPostBuffer); pNetConnection->commitPostRequestData(szPostBuffer, szHttpTag); } break; default: break; } } /* * 设置不可见的不可触摸 */ void MainCityLayer::setVisible(bool visible) { CCLayer::setVisible(visible); this->setTouchEnabled(visible); m_touchEnable = visible; if (visible) _initMenuButton(); } void MainCityLayer::restoreTouchUICompent() { m_touchEnable = true; _initMenuButton(); } void MainCityLayer::moveOutTouchUICompent() { m_touchEnable = false; for (unsigned int i = 0; i < MC_MENU_NUMBER; i++) { m_menuButtonSprite[i][0]->setVisible(false); m_menuButtonSprite[i][1]->setVisible(false); m_menuButtonSprite[i][2]->setVisible(false); } /*for*/ }
d99b098bd05103331522ac051862c62ac6b46282
64865b5965c8810d199bdad9e70fdc257d3a2919
/src/headers/Simulation.hpp
3fe307662e9b09aa74e48d79fc197a76f9e43b5c
[]
no_license
Gravechapa/wrappy-2019
cf5371815c4f180144706c92155bff434f3c57f7
e7ba45291e8046f010ffcd92ece7ee1e9efd9da9
refs/heads/master
2020-06-07T20:34:26.545722
2019-06-30T05:17:40
2019-06-30T05:17:40
193,088,937
0
0
null
2019-06-30T05:17:41
2019-06-21T11:47:02
CMake
UTF-8
C++
false
false
550
hpp
Simulation.hpp
#ifdef UNIX #include <filesystem> namespace fs = std::filesystem; #endif #ifdef WINDOWS #include <filesystem> namespace fs = std::experimental::filesystem::v1; #endif #include "GUI.hpp" class Simulation { public: Simulation(const fs::path &path); void run(); private: void rotate(bool clockwise); void move(Bot::Direction direction); void useBooster(Booster::BoosterType type, std::optional<sf::Vector2<int32_t>> coords); Map _map; GUI _gui; std::list<Booster> _boosters; Bot _bot; uint32_t _time{0}; };
353f51ed8feda33617c415d85c33a39053757433
46c75ae487bf116dafc7ce5a291895aeca3184b0
/Rover/Mobility.cpp
eea23d51f60d27ab54bdaf7a1f6d63d98e308f2e
[ "MIT" ]
permissive
mgarciacruzz/Rover
94e8674e6c7e4e2be2b532d752732ef6917c3502
4b0b0efcd827388c17e59bc1f4ab98ca0076d4de
refs/heads/master
2020-04-21T10:54:38.577284
2019-09-30T04:31:14
2019-09-30T04:31:14
169,502,133
0
0
null
null
null
null
UTF-8
C++
false
false
718
cpp
Mobility.cpp
// Rover Communication System #include "Mobility.h" // Constructor Mobility::Mobility(uint8_t rightMotorPos, uint8_t leftMotorPos){ leftMotor = new AF_DCMotor(leftMotorPos); rightMotor = new AF_DCMotor(rightMotorPos); } // Destructor Mobility::~Mobility(){/* Nothing to destruct*/} void Mobility::init(){ (*leftMotor).setSpeed(255); (*rightMotor).setSpeed(255); } // Methods void Mobility::moveForward(){ (*rightMotor).run(FORWARD); (*leftMotor).run(FORWARD); } void Mobility::moveBack(){ (*rightMotor).run(BACKWARD); (*leftMotor).run(BACKWARD); } void Mobility::moveLeft(){ } void Mobility::moveRight(){ } void Mobility::stop(){ (*rightMotor).run(RELEASE); (*leftMotor).run(RELEASE); }
de32f12c716db887be896def9a0fc6146144ce7d
f63706944c5a45b011453b792bc25908fa355af5
/client/parametersmodel.h
a3644cdf2d5caa3c5b4cd32471498accefde717a
[]
no_license
172270/QElectricPartsCatalog
7332451f3c2b6f2769f5c3e398a6526c9dafeb3e
5e64ed85b4407cef3956dcaa8e00ce54b172e2ce
refs/heads/master
2020-12-26T20:30:38.073889
2014-11-05T16:54:55
2014-11-05T16:54:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,615
h
parametersmodel.h
#ifndef PARAMETERSMODEL_H #define PARAMETERSMODEL_H #include <QAbstractTableModel> #include <QStandardItem> #include <QList> #include "messages/parameter.h" class ParametersModel : public QAbstractTableModel { Q_OBJECT public: explicit ParametersModel(QObject *parent = 0); signals: public slots: // QAbstractItemModel interface public: void res(){ beginResetModel(); int count = m_data.count(); for(int i =0;i<count;i++){ delete m_data.takeAt(0); } } void add(Parameter *p){ m_data.append(p); } void resModel(){ endResetModel(); } QModelIndex index(int row, int column, const QModelIndex &parent) const { Q_UNUSED(parent); if (row >= m_data.size() || row < 0 || column >= 8) return QModelIndex(); Parameter* pkt = m_data.at(row); return createIndex(row, column, pkt); } QModelIndex parent(const QModelIndex &child) const { Q_UNUSED(child); return QModelIndex(); } int rowCount(const QModelIndex &parent) const { Q_UNUSED(parent) // if(parent.isValid()) return m_data.size(); // return 0; } int columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); return 3; } QVariant data(const QModelIndex &index, int role) const { if(!index.isValid()) return QVariant(); if(index.row() > m_data.size() ) return QVariant(); Parameter *p= m_data.at(index.row()); if (role == Qt::DisplayRole ) { if (index.column() == 0){ // return name(symbol) return QString(p->getName() +" "+ ( p->getSymbol().size()>0?QString("("+p->getSymbol()+")"):QString("") ) ); } else if(index.column() == 1){ // return type return QString::number(p->config().valueType() ); ///TODO add method that will return a string with parameter name } else if(index.column() == 2){ // zakresy QString str, ret; if (p->config().has_minvalue() && p->config().has_maxvalue() ){ str.append("Zakres zmiennej (%1, %2)"); ret = str.arg(p->config().minvalue()).arg(p->config().maxvalue()); } if (p->config().has_minlength() && p->config().has_maxlength() ){ str.clear(); if(ret.size()>0){ str.append("oraz "); } str.append("długość textu zmiennej (%1, %2)"); ret.append(str.arg(p->config().minlength()).arg(p->config().maxlength())); } return ret; } } else if( role == Qt::ToolTipRole){ return p->getDescription(); } return QVariant(); } private: QList<Parameter*> m_data; // QAbstractItemModel interface public: QMap<int, QVariant> itemData(const QModelIndex &index) const { QMap<int, QVariant> data; int row = index.row(); Parameter *p = m_data.at(row); data.insert(p->kIdFieldNumber, p->id()); data.insert(p->kConfigFieldNumber, p->config().toJSON() ); data.insert(p->kDescriptionFieldNumber, p->getDescription()); data.insert(p->kNameFieldNumber, p->getName()); data.insert(p->kSymbolFieldNumber, p->getSymbol()); return data; } }; #endif // PARAMETERSMODEL_H
bf9d5da98536f45c3e5ceee57acc2101d11c2b4c
e675422b69ebd2343747b57e3ead927f9fdf6a6e
/cppserver/source/ClothesChange_Common/Public/ArGlobalData.h
58859109882a22e34502f455c3601750cc68ef04
[]
no_license
xeonye/chinesehistory
3b4bab9d4cc2c366d33051dd4a6c7209866873b1
d8a9843efac06589db5eef3427bf71f84807f422
refs/heads/master
2020-03-19T09:16:00.535754
2017-10-12T13:17:35
2017-10-12T13:17:35
null
0
0
null
null
null
null
GB18030
C++
false
false
3,810
h
ArGlobalData.h
#include <unordered_map> #include "DataDefine.h" #include "PublicTableDefine.h" using std::unordered_map; // 从AR表里计算出来的数据, 方便以后调用 //for t_arTask.txt struct Ar_Task_Item_Data{ Ar_Task_Item_Data() :m_nId(0) , m_nRewardId(0) , m_nRandomWeight(0){}; int m_nId; int m_nRewardId; int m_nRandomWeight;//表里数据累加之和 }; class Data_Ar_Task{ public: Data_Ar_Task() :m_nTotalWeight(0){}; ~Data_Ar_Task(){}; void addItem(const _DBC_T_AR_TASK * pLine); int getTotalWeight() const { return m_nTotalWeight; }; int getAwardIdByRandomWeight(int nRandWeight) const; void setVectorNum(int num){ m_oItem.reserve(num); }; private: int m_nTotalWeight; vector<Ar_Task_Item_Data> m_oItem; }; //for t_arRewardId.txt struct Reward_Item_Data{ Reward_Item_Data() :m_nChestId(invalid_ar_chest_id), m_RandomWeight(0){}; int m_nChestId; int m_RandomWeight;//表里数据累加之和 }; class Line_Data_Ar_RewardId{ public: Line_Data_Ar_RewardId() :m_nRewardid(0), m_nTotalWeight(0){ m_vecRewardInfo.reserve(AR_GOOD_REWARD_CFG_NUM); }; ~Line_Data_Ar_RewardId(){}; int getWeight() const { return m_nTotalWeight; }; int getChestIdByRandomWeight(int nRandomWeight) const; void setWeight(int nWeight) { m_nTotalWeight = nWeight; }; void setRewardId(int nRewardid){ m_nRewardid = nRewardid; }; int getRewardId() const { return m_nRewardid; }; void addRewardItem(const Reward_Item_Data &item){ m_vecRewardInfo.push_back(item); }; private: int m_nTotalWeight; vector<Reward_Item_Data> m_vecRewardInfo; int m_nRewardid; }; class Data_Ar_RewardId{ public: Data_Ar_RewardId() {}; ~Data_Ar_RewardId(){}; void addData(const _DBC_T_AR_REWARD_ID *pLine); int getTotalWeight(int nRewardid) const; int getChestIdByRandomWeight(int nArRewardId,int nRandomWeight) const; private: unordered_map<int,Line_Data_Ar_RewardId> m_mapArReward;//first:rewardid }; //for t_arChestInfo.txt struct Ar_ChestInfo_Item_Data{ Ar_ChestInfo_Item_Data() :m_nClothesId(0) , m_nClothesNum(0) , m_nWeightGot(0) , m_nExchangeMoney1Got(0) , m_nExchangeMoney2Got(0){}; int m_nClothesId; int m_nClothesNum; int m_nWeightGot; int m_nExchangeMoney1Got; int m_nExchangeMoney2Got; }; class Line_Data_Ar_ChestInfo{ public: Line_Data_Ar_ChestInfo() :m_nTotalWeightsGot(0) ,m_nTotalExchangeMoney1Got(0) ,m_nTotalExchangeMoney2Got(0){}; ~Line_Data_Ar_ChestInfo(){}; bool isInIt(int nclothesId) const; int getClothesIdWeightGot(int nclothesId) const; int getTotalExchangeMoney1Got() const { return m_nTotalExchangeMoney1Got; }; int getTotalExchangeMoney2Got() const { return m_nTotalExchangeMoney2Got; }; int getClothesIdNum(int nClothesId) const ; void setTotalWeightsGot(int nTotalWeights){ m_nTotalWeightsGot = nTotalWeights; }; void setTotalExchangeMoney1Got(int nTotalExchangeMoney1Got){ m_nTotalExchangeMoney1Got = nTotalExchangeMoney1Got; }; void setTotalExchangeMoney2Got(int nTotalExchangeMoney2Got){ m_nTotalExchangeMoney2Got = nTotalExchangeMoney2Got; }; void addItemData(const Ar_ChestInfo_Item_Data &data){ m_mapChestItemData[data.m_nClothesId] = data; }; private: unordered_map<int,Ar_ChestInfo_Item_Data> m_mapChestItemData;//first:clothesid int m_nTotalWeightsGot; int m_nTotalExchangeMoney1Got; int m_nTotalExchangeMoney2Got; }; class Data_Ar_ChestInfo{ public: Data_Ar_ChestInfo(){}; ~Data_Ar_ChestInfo(){}; void addData(const _DBC_T_AR_CHEST_INFO *pLine); bool isInIt(int nChestId,int nclothesId) const; int getTotalWeightGot(int nChestId,const set<int> &ClothesIdSet) const ; int getTotalExchangeMoney1Got(int nChestId) const ; int getTotalExchangeMoney2Got(int nChestId) const ; int getClothesIdNum(int nChestId,int nclothesid) const; private: unordered_map<int, Line_Data_Ar_ChestInfo> m_mapArChestInfo;//first:chestid };
0486427a5b5eabe60909da1d2499b831ceb6b8e6
0ce69de361c56ffd82a213a782ad0604ca787141
/CSE329 Prelude to competitive coding/codes_2/14_oct_18.cpp
cb5192b22c86e3085c235792a53e08fb19826c02
[]
no_license
Sandipghosh98/My_Programs
842ac20134d1d0e6e9adb7d1613f8c82d0daa72a
a1a5041628b7d1a47223832c103c83c2a864af34
refs/heads/master
2020-06-13T02:33:18.381343
2019-06-30T10:26:16
2019-06-30T10:26:16
194,502,828
0
0
null
null
null
null
UTF-8
C++
false
false
777
cpp
14_oct_18.cpp
#include<bits/stdc++.h> using namespace std; // Job sequencing problem /*struct Job{ int id,li,ti; }; bool cmp(Job a,Job b){ return a.li * b.ti > b.li * a.ti; } void opt_seq(Job arr[],int n) { for(int i=0;i<n;i++) cout<<arr[i].id<<" "; } int main() { Job arr[]={{1,2,4},{2,3,1000},{3,4,2},{4,1,5}}; int n=sizeof(arr)/sizeof(arr[0]); sort(arr,arr+n,cmp); opt_seq(arr,n); }*/ // Job selection problem double max_vol(int a[],int n,int p) { double ans=0; for(int i=0;i<n;i++) { ans+=pow((1-p),n-1-i)*a[i]; cout<<a[i]<<" "; cout<<ans<<endl; } return ans; } int main() { int s[]={70,80,10,20}; int n=sizeof(s)/sizeof(s[0]); sort(s,s+n); double p=0.10; cout<<max_vol(s,n,p); }
13fd4f4930a5c08ab35eefc994bf816e9646db42
c2b8a46ae41d258e7009569885e7e873a163cad2
/QtOsgBridge/src/EventProcessingState.cpp
72317e87b2da83d3f69038483bec366cb8f6d9ef
[]
no_license
ccliuyang/QtOsgBridge
2b18bf0529b5dd578b0891e6180d8c752065aa53
c9849a7649944375ea6917d72528f48cee5ee6c5
refs/heads/master
2023-08-27T20:00:17.951328
2021-11-07T08:30:19
2021-11-07T08:30:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,742
cpp
EventProcessingState.cpp
#include <QtOsgBridge/EventProcessingState.h> #include <QMouseEvent> namespace QtOsgBridge { EventProcessingState::EventProcessingState(osgHelper::ioc::Injector& injector) : AbstractEventState(injector) , m_isMouseCaptured(false) { } bool EventProcessingState::eventFilter(QObject* object, QEvent* event) { if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::MouseButtonRelease) { const auto mouseEvent = dynamic_cast<QMouseEvent*>(event); assert_return(mouseEvent, false); m_isMouseDown[static_cast<Qt::MouseButton>(mouseEvent->button())] = (event->type() == QEvent::Type::MouseButtonPress); } switch (event->type()) { case QEvent::Type::KeyPress: case QEvent::Type::KeyRelease: { const auto keyEvent = dynamic_cast<QKeyEvent*>(event); assert_return(keyEvent, false); m_isKeyDown[static_cast<Qt::Key>(keyEvent->key())] = (event->type() == QEvent::Type::KeyPress); return onKeyEvent(keyEvent); } case QEvent::Type::MouseButtonPress: case QEvent::Type::MouseButtonRelease: case QEvent::Type::MouseButtonDblClick: case QEvent::Type::MouseMove: { const auto mouseEvent = dynamic_cast<QMouseEvent*>(event); assert_return(mouseEvent, false); switch (event->type()) { case QEvent::Type::MouseButtonPress: { if (!m_mouseDragData) { const osg::Vec2f origin(static_cast<float>(mouseEvent->position().x()), static_cast<float>(mouseEvent->position().y())); m_mouseDragData = MouseDragData{ mouseEvent->button(), false, origin, origin }; } break; } case QEvent::Type::MouseMove: { if (!m_mouseDragData) { break; } if (!m_mouseDragData->moved) { onDragBegin(m_mouseDragData->button, m_mouseDragData->origin); m_mouseDragData->moved = true; } const osg::Vec2f pos(static_cast<float>(mouseEvent->position().x()), static_cast<float>(mouseEvent->position().y())); if (m_isMouseCaptured) { const auto delta = m_capturedMousePos - mouseEvent->globalPosition(); onDragMove(m_mouseDragData->button, m_mouseDragData->origin, pos, osg::Vec2f(static_cast<int>(delta.x()), static_cast<int>(delta.y()))); } else { onDragMove(m_mouseDragData->button, m_mouseDragData->origin, pos, m_mouseDragData->lastPos - pos); } m_mouseDragData->lastPos = pos; break; } case QEvent::Type::MouseButtonRelease: { if (m_mouseDragData && (m_mouseDragData->button == mouseEvent->button())) { onDragEnd(m_mouseDragData->button, m_mouseDragData->origin, osg::Vec2f(static_cast<float>(mouseEvent->position().x()), static_cast<float>(mouseEvent->position().y()))); m_mouseDragData.reset(); } break; } default: break; } if (event->type() == QEvent::Type::MouseMove && m_isMouseCaptured) { QCursor::setPos(m_capturedMousePos); } return onMouseEvent(mouseEvent); } case QEvent::Type::Wheel: { const auto wheelEvent = dynamic_cast<QWheelEvent*>(event); assert_return(wheelEvent, false); return onWheelEvent(wheelEvent); } default: break; } return AbstractEventState::eventFilter(object, event); } bool EventProcessingState::onKeyEvent(QKeyEvent* event) { return false; } bool EventProcessingState::onMouseEvent(QMouseEvent* event) { return false; } bool EventProcessingState::onWheelEvent(QWheelEvent* event) { return false; } void EventProcessingState::onDragBegin(Qt::MouseButton button, const osg::Vec2f& origin) { } void EventProcessingState::onDragMove(Qt::MouseButton button, const osg::Vec2f& origin, const osg::Vec2f& position, const osg::Vec2f& change) { } void EventProcessingState::onDragEnd(Qt::MouseButton button, const osg::Vec2f& origin, const osg::Vec2f& position) { } bool EventProcessingState::isKeyDown(Qt::Key key) const { if (m_isKeyDown.count(key) == 0) { return false; } return m_isKeyDown.find(key)->second; } bool EventProcessingState::isMouseButtonDown(Qt::MouseButton button) const { if (m_isMouseDown.count(button) == 0) { return false; } return m_isMouseDown.find(button)->second; } bool EventProcessingState::isMouseDragging(const std::optional<Qt::MouseButton>& button) const { return m_mouseDragData && m_mouseDragData->moved && (!button || (*button == m_mouseDragData->button)); } void EventProcessingState::setCaptureMouse(bool on) { if (m_isMouseCaptured == on) { return; } m_isMouseCaptured = on; m_capturedMousePos = QCursor::pos(); } } // namespace QtOsgBridge
934b070b1632e81bf4c7bb21e7859a91872fcf63
5c6194e025346e672d8d6d760d782eed0e61bb7d
/developer/VSSDK/VisualStudioIntegration/Common/Source/CPP/VSL/MockInterfaces/VSLMockIVsTextMacroHelper.h
6a1cd94fe5716fa73fe6f9933fe862e1b2de0526
[ "MIT" ]
permissive
liushouhuo/windows
888c4d9f8ae37ff60dd959eaf15879b8afdb161f
9e211d0cd5cacbd62c9c6ac764a6731985d60e26
refs/heads/master
2021-09-03T06:34:51.320672
2018-01-06T12:48:51
2018-01-06T12:48:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,152
h
VSLMockIVsTextMacroHelper.h
/*************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. This code is licensed under the Visual Studio SDK license terms. THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. This code is a part of the Visual Studio Library. ***************************************************************************/ #ifndef IVSTEXTMACROHELPER_H_10C49CA1_2F46_11D3_A504_00C04F5E0BA5 #define IVSTEXTMACROHELPER_H_10C49CA1_2F46_11D3_A504_00C04F5E0BA5 #if _MSC_VER > 1000 #pragma once #endif #include "textmgr.h" #pragma warning(push) #pragma warning(disable : 4510) // default constructor could not be generated #pragma warning(disable : 4610) // can never be instantiated - user defined constructor required #pragma warning(disable : 4512) // assignment operator could not be generated #pragma warning(disable : 6011) // Dereferencing NULL pointer (a NULL derference is just another kind of failure for a unit test namespace VSL { class IVsTextMacroHelperNotImpl : public IVsTextMacroHelper { VSL_DECLARE_NONINSTANTIABLE_BASE_CLASS(IVsTextMacroHelperNotImpl) public: typedef IVsTextMacroHelper Interface; STDMETHOD(RecordNewLine)()VSL_STDMETHOD_NOTIMPL STDMETHOD(RecordTypeChar)( /*[in]*/ OLECHAR /*wchChar*/, /*[in]*/ BOOL /*fIsOvertype*/)VSL_STDMETHOD_NOTIMPL STDMETHOD(RecordTypeChars)( /*[in]*/ LPCOLESTR /*pwszChars*/, /*[in]*/ BOOL /*fIsOvertype*/)VSL_STDMETHOD_NOTIMPL STDMETHOD(RecordRemovePreviousTyping)( /*[in]*/ LPCOLESTR /*pwszPrevChars*/)VSL_STDMETHOD_NOTIMPL STDMETHOD(RecordDelete)( /*[in]*/ BOOL /*fLeft*/, /*[in]*/ UINT /*uiReps*/)VSL_STDMETHOD_NOTIMPL STDMETHOD(RecordDeleteSpace)( /*[in]*/ BOOL /*fVertical*/)VSL_STDMETHOD_NOTIMPL STDMETHOD(RecordMoveSelectionRel)( /*[in]*/ MOVESELECTION_REL_TYPE /*mst*/, /*[in]*/ BOOL /*fBackwards*/, /*[in]*/ BOOL /*fExtend*/)VSL_STDMETHOD_NOTIMPL STDMETHOD(RecordMoveSelectionAbs)( /*[in]*/ MOVESELECTION_ABS_TYPE /*mst*/, /*[in]*/ BOOL /*fExtend*/)VSL_STDMETHOD_NOTIMPL STDMETHOD(RecordCollapseSelection)()VSL_STDMETHOD_NOTIMPL STDMETHOD(RecordSelectAll)()VSL_STDMETHOD_NOTIMPL STDMETHOD(RecordSwapAnchor)()VSL_STDMETHOD_NOTIMPL STDMETHOD(RecordEnterBoxMode)()VSL_STDMETHOD_NOTIMPL STDMETHOD(RecordActivateDocument)()VSL_STDMETHOD_NOTIMPL STDMETHOD(RecordGotoLine)( /*[in]*/ long /*iLine*/, /*[in]*/ BOOL /*fExtend*/)VSL_STDMETHOD_NOTIMPL STDMETHOD(RecordCut)()VSL_STDMETHOD_NOTIMPL STDMETHOD(RecordCopy)()VSL_STDMETHOD_NOTIMPL STDMETHOD(RecordPaste)()VSL_STDMETHOD_NOTIMPL STDMETHOD(RecordBookmarkClearAll)()VSL_STDMETHOD_NOTIMPL STDMETHOD(RecordBookmarkSetClear)( /*[in]*/ BOOL /*fSet*/)VSL_STDMETHOD_NOTIMPL STDMETHOD(RecordBookmarkNextPrev)( /*[in]*/ BOOL /*fNext*/)VSL_STDMETHOD_NOTIMPL STDMETHOD(RecordChangeCase)( /*[in]*/ CASESELECTION_TYPE /*cst*/)VSL_STDMETHOD_NOTIMPL STDMETHOD(RecordIndentUnindent)( /*[in]*/ BOOL /*fIndent*/)VSL_STDMETHOD_NOTIMPL STDMETHOD(RecordFormatSelection)()VSL_STDMETHOD_NOTIMPL STDMETHOD(RecordTabifyUntabify)( /*[in]*/ BOOL /*fTabify*/)VSL_STDMETHOD_NOTIMPL STDMETHOD(RecordInsertFile)( /*[in]*/ LPCOLESTR /*pwszName*/)VSL_STDMETHOD_NOTIMPL }; class IVsTextMacroHelperMockImpl : public IVsTextMacroHelper, public MockBase { VSL_DECLARE_NONINSTANTIABLE_BASE_CLASS(IVsTextMacroHelperMockImpl) public: VSL_DEFINE_MOCK_CLASS_TYPDEFS(IVsTextMacroHelperMockImpl) typedef IVsTextMacroHelper Interface; struct RecordNewLineValidValues { HRESULT retValue; }; STDMETHOD(RecordNewLine)() { VSL_DEFINE_MOCK_METHOD_NOARGS(RecordNewLine) VSL_RETURN_VALIDVALUES(); } struct RecordTypeCharValidValues { /*[in]*/ OLECHAR wchChar; /*[in]*/ BOOL fIsOvertype; HRESULT retValue; }; STDMETHOD(RecordTypeChar)( /*[in]*/ OLECHAR wchChar, /*[in]*/ BOOL fIsOvertype) { VSL_DEFINE_MOCK_METHOD(RecordTypeChar) VSL_CHECK_VALIDVALUE(wchChar); VSL_CHECK_VALIDVALUE(fIsOvertype); VSL_RETURN_VALIDVALUES(); } struct RecordTypeCharsValidValues { /*[in]*/ LPCOLESTR pwszChars; /*[in]*/ BOOL fIsOvertype; HRESULT retValue; }; STDMETHOD(RecordTypeChars)( /*[in]*/ LPCOLESTR pwszChars, /*[in]*/ BOOL fIsOvertype) { VSL_DEFINE_MOCK_METHOD(RecordTypeChars) VSL_CHECK_VALIDVALUE_STRINGW(pwszChars); VSL_CHECK_VALIDVALUE(fIsOvertype); VSL_RETURN_VALIDVALUES(); } struct RecordRemovePreviousTypingValidValues { /*[in]*/ LPCOLESTR pwszPrevChars; HRESULT retValue; }; STDMETHOD(RecordRemovePreviousTyping)( /*[in]*/ LPCOLESTR pwszPrevChars) { VSL_DEFINE_MOCK_METHOD(RecordRemovePreviousTyping) VSL_CHECK_VALIDVALUE_STRINGW(pwszPrevChars); VSL_RETURN_VALIDVALUES(); } struct RecordDeleteValidValues { /*[in]*/ BOOL fLeft; /*[in]*/ UINT uiReps; HRESULT retValue; }; STDMETHOD(RecordDelete)( /*[in]*/ BOOL fLeft, /*[in]*/ UINT uiReps) { VSL_DEFINE_MOCK_METHOD(RecordDelete) VSL_CHECK_VALIDVALUE(fLeft); VSL_CHECK_VALIDVALUE(uiReps); VSL_RETURN_VALIDVALUES(); } struct RecordDeleteSpaceValidValues { /*[in]*/ BOOL fVertical; HRESULT retValue; }; STDMETHOD(RecordDeleteSpace)( /*[in]*/ BOOL fVertical) { VSL_DEFINE_MOCK_METHOD(RecordDeleteSpace) VSL_CHECK_VALIDVALUE(fVertical); VSL_RETURN_VALIDVALUES(); } struct RecordMoveSelectionRelValidValues { /*[in]*/ MOVESELECTION_REL_TYPE mst; /*[in]*/ BOOL fBackwards; /*[in]*/ BOOL fExtend; HRESULT retValue; }; STDMETHOD(RecordMoveSelectionRel)( /*[in]*/ MOVESELECTION_REL_TYPE mst, /*[in]*/ BOOL fBackwards, /*[in]*/ BOOL fExtend) { VSL_DEFINE_MOCK_METHOD(RecordMoveSelectionRel) VSL_CHECK_VALIDVALUE(mst); VSL_CHECK_VALIDVALUE(fBackwards); VSL_CHECK_VALIDVALUE(fExtend); VSL_RETURN_VALIDVALUES(); } struct RecordMoveSelectionAbsValidValues { /*[in]*/ MOVESELECTION_ABS_TYPE mst; /*[in]*/ BOOL fExtend; HRESULT retValue; }; STDMETHOD(RecordMoveSelectionAbs)( /*[in]*/ MOVESELECTION_ABS_TYPE mst, /*[in]*/ BOOL fExtend) { VSL_DEFINE_MOCK_METHOD(RecordMoveSelectionAbs) VSL_CHECK_VALIDVALUE(mst); VSL_CHECK_VALIDVALUE(fExtend); VSL_RETURN_VALIDVALUES(); } struct RecordCollapseSelectionValidValues { HRESULT retValue; }; STDMETHOD(RecordCollapseSelection)() { VSL_DEFINE_MOCK_METHOD_NOARGS(RecordCollapseSelection) VSL_RETURN_VALIDVALUES(); } struct RecordSelectAllValidValues { HRESULT retValue; }; STDMETHOD(RecordSelectAll)() { VSL_DEFINE_MOCK_METHOD_NOARGS(RecordSelectAll) VSL_RETURN_VALIDVALUES(); } struct RecordSwapAnchorValidValues { HRESULT retValue; }; STDMETHOD(RecordSwapAnchor)() { VSL_DEFINE_MOCK_METHOD_NOARGS(RecordSwapAnchor) VSL_RETURN_VALIDVALUES(); } struct RecordEnterBoxModeValidValues { HRESULT retValue; }; STDMETHOD(RecordEnterBoxMode)() { VSL_DEFINE_MOCK_METHOD_NOARGS(RecordEnterBoxMode) VSL_RETURN_VALIDVALUES(); } struct RecordActivateDocumentValidValues { HRESULT retValue; }; STDMETHOD(RecordActivateDocument)() { VSL_DEFINE_MOCK_METHOD_NOARGS(RecordActivateDocument) VSL_RETURN_VALIDVALUES(); } struct RecordGotoLineValidValues { /*[in]*/ long iLine; /*[in]*/ BOOL fExtend; HRESULT retValue; }; STDMETHOD(RecordGotoLine)( /*[in]*/ long iLine, /*[in]*/ BOOL fExtend) { VSL_DEFINE_MOCK_METHOD(RecordGotoLine) VSL_CHECK_VALIDVALUE(iLine); VSL_CHECK_VALIDVALUE(fExtend); VSL_RETURN_VALIDVALUES(); } struct RecordCutValidValues { HRESULT retValue; }; STDMETHOD(RecordCut)() { VSL_DEFINE_MOCK_METHOD_NOARGS(RecordCut) VSL_RETURN_VALIDVALUES(); } struct RecordCopyValidValues { HRESULT retValue; }; STDMETHOD(RecordCopy)() { VSL_DEFINE_MOCK_METHOD_NOARGS(RecordCopy) VSL_RETURN_VALIDVALUES(); } struct RecordPasteValidValues { HRESULT retValue; }; STDMETHOD(RecordPaste)() { VSL_DEFINE_MOCK_METHOD_NOARGS(RecordPaste) VSL_RETURN_VALIDVALUES(); } struct RecordBookmarkClearAllValidValues { HRESULT retValue; }; STDMETHOD(RecordBookmarkClearAll)() { VSL_DEFINE_MOCK_METHOD_NOARGS(RecordBookmarkClearAll) VSL_RETURN_VALIDVALUES(); } struct RecordBookmarkSetClearValidValues { /*[in]*/ BOOL fSet; HRESULT retValue; }; STDMETHOD(RecordBookmarkSetClear)( /*[in]*/ BOOL fSet) { VSL_DEFINE_MOCK_METHOD(RecordBookmarkSetClear) VSL_CHECK_VALIDVALUE(fSet); VSL_RETURN_VALIDVALUES(); } struct RecordBookmarkNextPrevValidValues { /*[in]*/ BOOL fNext; HRESULT retValue; }; STDMETHOD(RecordBookmarkNextPrev)( /*[in]*/ BOOL fNext) { VSL_DEFINE_MOCK_METHOD(RecordBookmarkNextPrev) VSL_CHECK_VALIDVALUE(fNext); VSL_RETURN_VALIDVALUES(); } struct RecordChangeCaseValidValues { /*[in]*/ CASESELECTION_TYPE cst; HRESULT retValue; }; STDMETHOD(RecordChangeCase)( /*[in]*/ CASESELECTION_TYPE cst) { VSL_DEFINE_MOCK_METHOD(RecordChangeCase) VSL_CHECK_VALIDVALUE(cst); VSL_RETURN_VALIDVALUES(); } struct RecordIndentUnindentValidValues { /*[in]*/ BOOL fIndent; HRESULT retValue; }; STDMETHOD(RecordIndentUnindent)( /*[in]*/ BOOL fIndent) { VSL_DEFINE_MOCK_METHOD(RecordIndentUnindent) VSL_CHECK_VALIDVALUE(fIndent); VSL_RETURN_VALIDVALUES(); } struct RecordFormatSelectionValidValues { HRESULT retValue; }; STDMETHOD(RecordFormatSelection)() { VSL_DEFINE_MOCK_METHOD_NOARGS(RecordFormatSelection) VSL_RETURN_VALIDVALUES(); } struct RecordTabifyUntabifyValidValues { /*[in]*/ BOOL fTabify; HRESULT retValue; }; STDMETHOD(RecordTabifyUntabify)( /*[in]*/ BOOL fTabify) { VSL_DEFINE_MOCK_METHOD(RecordTabifyUntabify) VSL_CHECK_VALIDVALUE(fTabify); VSL_RETURN_VALIDVALUES(); } struct RecordInsertFileValidValues { /*[in]*/ LPCOLESTR pwszName; HRESULT retValue; }; STDMETHOD(RecordInsertFile)( /*[in]*/ LPCOLESTR pwszName) { VSL_DEFINE_MOCK_METHOD(RecordInsertFile) VSL_CHECK_VALIDVALUE_STRINGW(pwszName); VSL_RETURN_VALIDVALUES(); } }; } // namespace VSL #pragma warning(pop) #endif // IVSTEXTMACROHELPER_H_10C49CA1_2F46_11D3_A504_00C04F5E0BA5
2af2c5d6bbe2ef02a372fecc1f40262c055650b3
3aa7fdc14bfa63caaf3d27d7bb46b9e5f2d49f10
/WEEK_03/assignment_01/src/ofApp.h
db072b45fdc7f01eb8a7ae1cfd2f521a4ae2373e
[]
no_license
sonya-irsay/creativecode
48f3fa9e9283de3ab11f540b62f75d0e88699d54
dae4dc0b2303b4ba832f375b5de5f71ed3c0cf6c
refs/heads/master
2021-01-20T13:13:29.968491
2017-11-14T01:23:27
2017-11-14T01:23:27
101,734,231
0
0
null
null
null
null
UTF-8
C++
false
false
906
h
ofApp.h
#pragma once #include "ofMain.h" #include "CoolLine.h" //HAVE TO INCLUDE HEADER OF COOLBALL //define length of array (can never be changed) //practice of all Caps, no semicolon #define NUMBALLS 100 class ofApp : public ofBaseApp { public: void setup(); void update(); void draw(); void keyPressed(int key); void keyReleased(int key); void mouseMoved(int x, int y); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(int x, int y, int button); void mouseEntered(int x, int y); void mouseExited(int x, int y); void windowResized(int w, int h); void dragEvent(ofDragInfo dragInfo); void gotMessage(ofMessage msg); //same structure as int x; //type name of instance of the class(we make up) CoolLine coolerLine; //1. creating an array** CoolLine lotsOfLines[NUMBALLS]; //2. using a vector** vector<CoolLine> moreLines; };
e62112acbeae1a909ee028b131d43931134408b3
6095794c10460a56793b41f666ec4bd7e8c24151
/src/rosban_fa/gp_trainer.cpp
8014271419294b13b4928be00989c9c0b0734a14
[]
no_license
Rhoban/rosban_fa
ac545fb2badcb16629a7fac225f079c1e817b1be
13665f15688ea09c54f8c3020c78e96c9f7d4e19
refs/heads/master
2021-09-06T02:39:05.468720
2017-10-24T15:41:03
2017-10-24T15:41:03
100,256,286
0
0
null
null
null
null
UTF-8
C++
false
false
1,809
cpp
gp_trainer.cpp
#include "rosban_fa/gp_trainer.h" #include "rosban_fa/gp.h" #include "rosban_gp/core/squared_exponential.h" using rosban_gp::CovarianceFunction; using rosban_gp::GaussianProcess; using rosban_gp::SquaredExponential; namespace rosban_fa { GPTrainer::GPTrainer() { autotune_conf.nb_trials = 2; autotune_conf.rprop_conf->max_iterations = 50; autotune_conf.rprop_conf->epsilon = std::pow(10,-6); autotune_conf.rprop_conf->tuning_space = rosban_gp::RProp::TuningSpace::Log; ga_conf.nb_trials = 10; ga_conf.rprop_conf->max_iterations = 1000; ga_conf.rprop_conf->epsilon = std::pow(10,-6); } std::unique_ptr<FunctionApproximator> GPTrainer::train(const Eigen::MatrixXd & inputs, const Eigen::MatrixXd & observations, const Eigen::MatrixXd & limits) const { checkConsistency(inputs, observations, limits); std::unique_ptr<std::vector<rosban_gp::GaussianProcess>> gps(new std::vector<rosban_gp::GaussianProcess>()); for (int output_dim = 0; output_dim < observations.cols(); output_dim++) { std::unique_ptr<CovarianceFunction> cov_func(new SquaredExponential(inputs.rows())); gps->push_back(GaussianProcess(inputs, observations.col(output_dim), std::move(cov_func))); (*gps)[output_dim].autoTune(autotune_conf); } return std::unique_ptr<FunctionApproximator>(new GP(std::move(gps), ga_conf)); } std::string GPTrainer::class_name() const { return "GPTrainer"; } void GPTrainer::to_xml(std::ostream &out) const { autotune_conf.write("autotune_conf", out); ga_conf.write("ga_conf", out); } void GPTrainer::from_xml(TiXmlNode *node) { autotune_conf.tryRead(node, "auto_tune_conf"); ga_conf.tryRead(node, "ga_conf"); } }
8e1ae50f756e3eecf1675b44248e58fe7249db13
660ed951b06d7a8abf77d30483fe718f70d98c4c
/EngineV1/Minigin/Sprite.h
5ded9bb0d90d4c8d17cce568001756c2bc91f094
[]
no_license
mowenli/EngineV1
2eb54e64593895d6226b0e5aeda57753cffe35fb
438ffeee8384804f9a8fae589c7e78f7f95c778e
refs/heads/master
2022-10-22T22:38:35.403076
2020-06-15T22:13:39
2020-06-15T22:13:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,311
h
Sprite.h
#pragma once class GameObject; class TextureComponent; class Sprite { public: Sprite(GameObject* pObject, const std::string& name); ~Sprite(); Sprite(const Sprite& other) = delete; Sprite(Sprite&& other) = delete; Sprite& operator=(const Sprite& other) = delete; Sprite& operator=(Sprite&& other) = delete; void Update(float elapsedSec); void Render() const; void Reset(); void SaveAttributes(rapidxml::xml_document<>* pDoc, rapidxml::xml_node<>* pNode); void SetAttributes(TextureComponent* pTexture, const std::string& texturePath, float spriteWidth, float spriteHeight, float timeBetweenFrames, float spacePerFrame, int rows, int columns); void DrawInterface(); std::string GetName() { return m_Name; } char* GetNameRef() { return m_Name; } void Play(bool play) { m_IsPlaying = play; } void Flip(bool flip); bool HasReachedEndOfSeq() const { return m_HasReachedEndOfSeq; } private: TextureComponent* m_pTexture = nullptr; Vector4f m_SrcRect = {0, 0, 16, 16}; char m_Name[25] = { }; char m_TexturePath[40] = { }; float m_TimeBetweenFrames = 1; float m_SpacePerFrame = 16; float m_Timer = 0; int m_Rows = 1; int m_Columns = 8; int m_CurrentFrame = 0; int m_TotalFrames = 8; bool m_HasReachedEndOfSeq = false; bool m_IsPlaying = false; bool m_IsFlipped = false; };
4ea2657790a08b856750812bbe91fb2a649c91ff
c254c37b30fba0c41b3157dd5581e03035df43c1
/C++ Solutions/URI/2395 - Transporte de Conteineres.cpp
7ad805f1bd9bee59193ed0e78f7a32be77810b46
[]
no_license
AntonioSanchez115/Competitive-Programming
12c8031bbb0c82d99b4615d414f5eb727ac5a113
49dac0119337a45fe8cbeae50d7d8563140a3119
refs/heads/master
2022-02-14T10:51:19.125143
2022-01-26T07:59:34
2022-01-26T07:59:34
186,081,160
1
0
null
null
null
null
UTF-8
C++
false
false
204
cpp
2395 - Transporte de Conteineres.cpp
#include <bits/stdc++.h> using namespace std; int main() { long a,b,c,x,y,z; cin >> a >> b >> c >> x >> y >> z; cout << ((long)(x/a)) * ((long)(y/b)) * ((long)(z/c)) << '\n'; return 0; }
740055cfc3c284c82c65c722a27b8e228595e14c
36bb421c9639f314044eba6d2ae66a8485eccd49
/gfg/swapFLLF.cpp
273a92626f056ae1996b5b0d17a61689f5fdc081
[]
no_license
abhijeet2096/cc
ec82d44b56fc3d4807eab686cd2f8d6764c29dfe
535f6c29a713cdc8fa311aa1d13ee780dcde33cc
refs/heads/master
2020-03-28T02:25:35.911636
2018-10-24T16:31:46
2018-10-24T16:31:46
147,569,325
0
0
null
2018-10-24T16:31:47
2018-09-05T19:30:02
C++
UTF-8
C++
false
false
436
cpp
swapFLLF.cpp
#include <bits/stdc++.h> using namespace std; void swap(char &a,char &b); int main() { int T; cin >> T; while(T--) { string a,b; cin >> a >> b; swap(a[0],b[b.length()-1]); swap(b[0],a[a.length()-1]); cout << a << " " << b << endl; } return 0; } void swap(char &a,char &b) { char tmp; tmp = a; a = b; b = tmp; }
4324c7ed01556c9c2aa0ada7805a2a775d866064
5fb8e7b1a005f31afa59630d2f7164a6b6ccc214
/code_COMPAS/COMPAS/pulsarAccretionInducedEvolution.cpp
c472b45ca539a6eb37ecafbb9785713425581908
[]
no_license
FloorBroekgaarden/DCO-random-code
9bb709f2cb308b8dd88536e0ae20503b7e8b082b
edf81dab55568a577917901e6d489d637cc7394c
refs/heads/main
2023-05-04T16:40:40.988383
2021-05-31T14:20:43
2021-05-31T14:20:43
345,443,153
0
0
null
null
null
null
UTF-8
C++
false
false
13,951
cpp
pulsarAccretionInducedEvolution.cpp
#include "pulsarAccretionInducedEvolution.h" //The function to calculate isolated spin down rate double calculateSpinDownRate(double omega, double momentOfInteria, double magneticField, double neutronStarRadius, double alpha){ /* * Calculates the spin down rate for isolated neutron stars in SI * * See Equation X in arxiv.xxxx * * Parameters * -------------- * * omega : double * angular velocity in SI * momentOfInteria : double * Moment of Interia of the neutron star calculated using equation of state in kg m^2 * magneticField : double * Magnetic field in Tesla * neutronStarRadius : double * Radius of the neutron star in metres * alpha : double * Angle between the spin and magnetic axes in radians * * Returns * ------------ * Spin down rate of an isolated neutron star in SI * */ double omegaDotTop = 8.0 * pi * pow(omega, 3.0)* pow(neutronStarRadius, 6.0) * pow(magneticField, 2.0)* 1.0 ; //pow ( sin (alpha*0.0174533), 2.0); double omegaDotBottom = 3.0* mu_0 * pow(c, 3.0) * momentOfInteria; double omegaDot = - omegaDotTop / omegaDotBottom; return (omegaDot); } //The function to calculate isolated omega double isolatedOmega(double omega, double momentOfInteria, double initialMagneticField, double finalMagneticField, double neutronStarRadius, double alpha, double magneticFieldLowerLimit, double stepsize,double tau){ /* * Calculates the spin down rate for isolated neutron stars in SI * * See Equation X in arxiv.xxxx * * Parameters * -------------- * * omega : double * angular velocity in SI * momentOfInteria : double * Moment of Interia of the neutron star calculated using equation of state in kg m^2 * magneticField : double * Magnetic field in Tesla * neutronStarRadius : double * Radius of the neutron star in metres * alpha : double * Angle between the spin and magnetic axes in radians * * Returns * ------------ * Spin down rate of an isolated neutron star in SI * */ double constantTop = 8.0 * pi * pow(neutronStarRadius, 6.0) * 1.0 ; //pow ( sin(alpha*0.0174533), 2.0); double constantBottom = 3.0* mu_0 * pow(c, 3.0) * momentOfInteria; double constant = constantTop / constantBottom; double oneOverOmegaSquaredTermOne = pow(magneticFieldLowerLimit, 2.0) * stepsize ; double oneOverOmegaSquaredTermTwo = tau * magneticFieldLowerLimit * (finalMagneticField - initialMagneticField) ; double oneOverOmegaSquaredTermThree = (tau/2.0) * (pow(finalMagneticField, 2.0) - pow(initialMagneticField, 2.0)) ; double oneOverOmegaSquared = ((constant * 2.0) * ( oneOverOmegaSquaredTermOne - oneOverOmegaSquaredTermTwo - oneOverOmegaSquaredTermThree ) + 1.0/(pow(omega,2.0))) ; omega = pow(oneOverOmegaSquared, -0.5); return ( omega ); } // The function to calculate isolated decay of magnnetic field of the neutron star double isolatedMagneticFieldDecayFunction(double stepsize, double tau, double magneticFieldLowerLimit, double initialMagneticField){ /* * Calculates accretion induced magnetic field decay for an accreting neutron star * * See Equation X in arxiv.xxxx * * Parameters * ------------- * * tau : double * exponenetial scaled down factor in seconds * magneticFiledLowerLimit : double * Lower cut-off limit of magnetic filed for a neutron star in Tesla * initialMagneticField : double * Initial magnetic field of the neutron star in Tesla * * Returns * ----------- * Magnetic filed of a neutron star due to accretion in Tesla */ double isolatedMagneticFieldDecay = magneticFieldLowerLimit + exp(-stepsize/tau)*(initialMagneticField - magneticFieldLowerLimit); return (isolatedMagneticFieldDecay); } //The function to calculate Alfven Radius double alfvenRadiusFunction(double mass, double mdot, double radius, double magneticField){ /* * Calculates the Alfven radius for an accreting neutron star * * See Equation X in arxiv.xxxxxx * * Parameters * ----------- * mass : double * Mass of the neutron star in kg * modt : double * Mass transfer rate from the secondary in kg/s * radius : double * Radius of the neutron star in m * magneticField : double * Magnetic field of the neutron star in Tesla * * Returns * ---------- * alfvenRadius : double * Alfven radius in m */ double p = ((pow(radius,6.0))/(pow(mass,0.5)*mdot)); double q = pow(p, 2.0/7.0 ); double alfvenRadiusWithoutMagneticField = constPartOfAlfvenRadius*q; double alfvenRadius = alfvenRadiusWithoutMagneticField * pow(magneticField,4.0/7.0); return (q); } // The function to calculate accretion induce decay of magnnetic field of the neutron star double accretionInducedMagneticFieldDecayFunction(double massGainPerTimeStep, double kappa, double magneticFieldLowerLimit, double magneticField){ /* * Calculates accretion induced magnetic field decay for an accreting neutron star * * See Equation X in arxiv.xxxx * * Parameters * ------------- * massGainPerTimeStep : double * Mass loss from the secondary for each iteration rate in kg * kappa : double * Magnetic filed decay scale * magneticFiledLowerLimit : double * Lower cut-off limit of magnetic filed for a neutron star in Tesla * magneticField : double * Previuos magnetic field in Tesla * Msol : constant * Solar Mass in kg * Returns * ----------- * Magnetic filed of a neutron star due to accretion in Tesla */ double accretionInducedMagneticField = magneticFieldLowerLimit + exp(-(1.0/kappa)*massGainPerTimeStep)*(magneticField-magneticFieldLowerLimit); //std::cout << "kappa = " << kappa << std::endl; // old exp(-(1.0/kappa)*massGainPerTimeStep/Msol) // std::cout << "argument of exponent = " << -(1.0/kappa)*massGainPerTimeStep << std::endl; // std::cout << "exponential term = " << exp(-(1.0/kappa)*massGainPerTimeStep) << std::endl; // std::cout << "part of acc ind mag fld " <<exp(-(1.0/kappa)*massGainPerTimeStep)*(magneticField-magneticFieldLowerLimit) << std::endl; return (accretionInducedMagneticField); } //The function to calculate the angular momentum of an accreting neutron star double angularMomentumDueToAccretionFunction (double epsilon, double alfvenRadius, double massGainPerTimeStep, double velocityDifference){ /* * Calculates the angular momentum for an accreting neutron star * * See Equation X in arxiv.xxxxxx * * Parameters * ----------- * epsilon : double * Uncertainty due to mass loss * alfvenRadius : double * Alfven radius of the neutron star in m * massGainPerTimeStep : double * Mass loss from the secondary for each iteration rate in kg * velocityDiffernce : double * Differnce in the keplerian angular velocity and surface angular velocity of the neutron star in m * Returns * -------- * angular momentum of the neutron star due to accretion in kg m^2 sec^-1 * * */ double angularMomentumDueToAccretion = 0.25*epsilon*pow(alfvenRadius,2.0)*massGainPerTimeStep*velocityDifference ; return (angularMomentumDueToAccretion); } // The function to calculate the angular velocity differnce double velocityDifferenceFunction (double surfaceAngularVelocity, double mass, double alfvenRadius){ /* * Differnce in the keplerian angular velocity and surface angular velocity of the neutron star in m * * See Equation X in arxiv.xxxxxx * * Parameters * ------------- * surfaceAngularVelocity : double * Surface angular velocity of the neutron star in SI (same as the "omega" we calculate) * mass : double * alfvenRadius : double * Alfven radius of the neutron star in m * Returns * ----------- * Differnce in the keplerian angular velocity and surface angular velocity of the neutron star in SI * */ double keplarianVelocityAtAlfvenRadius = sqrt(G*mass)/sqrt(alfvenRadius/2.0); double keplarianAngularVelocityAtAlfvenRadius = 2.0* (keplarianVelocityAtAlfvenRadius/alfvenRadius); double velocityDifference = keplarianAngularVelocityAtAlfvenRadius - surfaceAngularVelocity ; return (velocityDifference); } // //The function to update the magnetic field and spins of neutron stars void updateMagneticFieldAndSpin(int booleanCheckForAccretion, bool commonEnvelopeFlag, double stepsize, double momentOfInertia, double mass, double radius, double massGainPerTimeStep, double kappa, double epsilon, double tau, double magneticFieldLowerLimit, double &angularMomentum, double &omega, double &magneticField, double &omegaOverTime, double alpha){ /* * Description goes here * * Parameters * ----------- * * booleanCheckForAccretion : integer * returns 1 when there is accretion, returns 0 when there is no accretion * commonEnvelopeFlag : bool * True if there is a common envelope * stepsize : double * timestep size for integartion in seconds * momentOfInertia : double * Moment of Inertia of the neutron star calculated using equation of state in kg m^2 * mass : double * Mass of the neutron star in kg * modt : double * Mass transfer rate from the secondary in kg/s * radius : double * Radius of the neutron star in m * massGainPerTimeStep : double * Mass loss from the secondary for each iteration rate in kg * kappa : double * Magnetic filed decay scale * epsilon : double * Uncertainty due to mass loss * tau : double * exponenetial scaled down factor in seconds * magneticFiledLowerLimit : double * Lower cut-off limit of magnetic filed for a neutron star in Tesla * angular momentum : double * Angular momentum of the neutron star in kg m^2 sec^-1 * magneticField : double * Previuos magnetic field in Tesla * omegaOverTime : double * Rate of change of angular velocity in * alpha : double * Angle between the spin and magnetic axes in radians * Returns * --------- * Angular Momentum of a neutron star */ //stepsize = stepsize/5.0 ; double initialMagneticField = magneticField ; //Check point to decide if the neutron star is accreting if(booleanCheckForAccretion==false and commonEnvelopeFlag == false){ magneticField = isolatedMagneticFieldDecayFunction(stepsize, tau, magneticFieldLowerLimit, initialMagneticField) ; omega = isolatedOmega(omega, momentOfInertia, initialMagneticField, magneticField, radius, alpha, magneticFieldLowerLimit, stepsize, tau); omegaOverTime = calculateSpinDownRate(omega, momentOfInertia, magneticField, radius, alpha) ; angularMomentum = omega * momentOfInertia ; } else if((booleanCheckForAccretion==true) and (massGainPerTimeStep > 0.0 )) { // std:: cout << "booleanCheckForAccretion " << booleanCheckForAccretion << std:: endl; //std::cout << "massGainPerTimestep " << massGainPerTimeStep << std::endl; double mdot = massGainPerTimeStep/stepsize ; double alfvenRadius = alfvenRadiusFunction(mass, mdot, radius, magneticField); double velocityDifference = velocityDifferenceFunction(omega, mass, alfvenRadius); magneticField = accretionInducedMagneticFieldDecayFunction(massGainPerTimeStep, kappa, magneticFieldLowerLimit, magneticField) ; double deltaAngularMomentum = angularMomentumDueToAccretionFunction(epsilon, alfvenRadius, massGainPerTimeStep, velocityDifference); angularMomentum = angularMomentum + deltaAngularMomentum ; omega = angularMomentum/momentOfInertia; omegaOverTime = (deltaAngularMomentum/stepsize)/momentOfInertia ; } else if((commonEnvelopeFlag==true) and (massGainPerTimeStep > 0.0 )) { //std:: cout << "commonEnvelopeFlag " << commonEnvelopeFlag << std:: endl; //std::cout << "massGainPerTimestep " << massGainPerTimeStep << std::endl; double mdot = massGainPerTimeStep/stepsize ; double alfvenRadius = alfvenRadiusFunction(mass, mdot, radius, magneticField); double velocityDifference = velocityDifferenceFunction(omega, mass, alfvenRadius); //std::cout << "B before acc " << magneticField << std::endl; magneticField = accretionInducedMagneticFieldDecayFunction(massGainPerTimeStep, kappa, magneticFieldLowerLimit, magneticField) ; //std::cout << "B after acc " << magneticField << std::endl; //std::cout << "choose whether to allow spin up during CE. Currently allows by default" << std::endl; double deltaAngularMomentum = angularMomentumDueToAccretionFunction(epsilon, alfvenRadius, massGainPerTimeStep, velocityDifference); angularMomentum = angularMomentum + deltaAngularMomentum ; //std::cout << "omega before CE = " << omega << std::endl; omega = angularMomentum/momentOfInertia; omegaOverTime = (deltaAngularMomentum/stepsize)/momentOfInertia ; //std::cout << "omega after CE = " << omega << std::endl; } else { //std:: cout << "something is wrong " << std:: endl; //std:: cout << "massGainPerTimeStep " << massGainPerTimeStep << std:: endl; //std:: cout << "booleanCheckForAccretion " << booleanCheckForAccretion << std:: endl; } }
2c183beccb5a3904488040aedc5960c62d414046
2ee075999b336de7bb747305887d4972db05b1d7
/Examples/SlidesCPP/CreateNewPresentation.cpp
cd2a7bd7f3c606ca2f8175d2839bb2d6767fc644
[ "LicenseRef-scancode-proprietary-license", "MIT" ]
permissive
aspose-slides/Aspose.Slides-for-C
71b33abe29ffbd08595888db9248200f49c8962a
6b309e7944974cd3080371c0a5156796a9672991
refs/heads/master
2023-09-03T12:33:47.550667
2023-08-25T09:03:38
2023-08-25T09:03:38
115,446,199
22
11
MIT
2023-02-09T15:52:54
2017-12-26T18:36:16
C++
UTF-8
C++
false
false
688
cpp
CreateNewPresentation.cpp
#include "stdafx.h" #include "SlidesExamples.h" using namespace Aspose::Slides; using namespace Export; using namespace System; void CreateNewPresentation() { //ExStart:CreateNewPresentation // The path to the documents directory. const String outPath = u"../out/SampleChartresult.pptx"; //Instantiate Presentation class that represents PPTX file SharedPtr<Presentation> pres = MakeObject<Presentation>(); SharedPtr<ISlide> slide = pres->get_Slides()->idx_get(0); // Add an autoshape of type line slide->get_Shapes()->AddAutoShape(ShapeType::Line, 50.0, 150.0, 300.0, 0.0); //Saving presentation pres->Save(outPath, SaveFormat::Pptx); //ExEnd:CreateNewPresentation }
db7a9afdd02474a74c9a3cfe0da8f3e8889a4f45
0a92762681a3a50c6cc7b3d75984cbe4d4fe8f24
/Qt_LoRa_Gateway/dlghistory.cpp
953bf63417a265b1b5eb2603f4fbc720b3bc7014
[]
no_license
fyyy4030/Qt-LoRa-Gateway
997635816b069ddd9a50486a20db8da26b6b7dd2
20525edaaddba70eab4d98a340b935b05e6651bd
refs/heads/master
2021-12-11T12:37:08.242814
2016-11-12T21:17:49
2016-11-12T21:17:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,263
cpp
dlghistory.cpp
#include "dlghistory.h" #include "ui_dlghistory.h" #include <QSettings> #include <QDateTime> dlgHistory::dlgHistory(QWidget *parent) : QDialog(parent, (Qt::WindowTitleHint | Qt::WindowCloseButtonHint)), ui(new Ui::dlgHistory) { ui->setupUi(this); connect(ui->historyList->model(), SIGNAL(rowsInserted(QModelIndex,int,int)), ui->historyList, SLOT(scrollToBottom())); } dlgHistory::~dlgHistory() { delete ui; } void dlgHistory::addItem(QString data) { ui->historyList->addItem(QDateTime::currentDateTimeUtc().toString("MMM dd HH:mm:ss ") + data); } void dlgHistory::showEvent(QShowEvent *event) { Q_UNUSED(event); //specify registry key QSettings settings( QSettings::UserScope,"MoeTronix", "SerialTerminal"); settings.beginGroup("HistoryWindow"); restoreGeometry(settings.value("geometry").toByteArray()); //bool ismin = settings.value("minstate", false).toBool(); settings.endGroup(); } void dlgHistory::closeEvent(QCloseEvent *event) { Q_UNUSED(event); QSettings settings( QSettings::UserScope,"MoeTronix", "SerialTerminal"); settings.beginGroup("HistoryWindow"); settings.setValue("geometry", saveGeometry()); settings.setValue("minstate",isMinimized()); settings.endGroup(); }
71c1d3196f71d232d44ec359add6ab7c851ee02e
027ac9d704e0fc6c67daad5adb0f072c2f7e3d53
/Goop/detect_event.h
acf945785eada90a155b6fd7bdf928234566b769
[]
no_license
wesz/gusanos
f725df18481c75bae3f95de87fa3288bb946d2ef
61557268c979c6bd4ff6e0336e2351690036a710
refs/heads/master
2020-05-27T22:54:21.658507
2014-02-11T02:27:42
2014-02-11T02:27:42
16,716,622
8
3
null
null
null
null
UTF-8
C++
false
false
559
h
detect_event.h
#ifndef DETECT_EVENT_H #define DETECT_EVENT_H #include "events.h" class Event; class BaseObject; struct DetectEvent : public Event { DetectEvent( float range, bool detectOwner, int detectFilter ); DetectEvent(std::vector<BaseAction*>&, float range, bool detectOwner, int detectFilter); ~DetectEvent(); void check( BaseObject* ownerObject ); //Event* m_event; float m_range; bool m_detectOwner; unsigned int m_detectFilter; // detect filters ored together, 1 is worms filter, 2^n for the custom filters with n > 0 }; #endif // DETECT_EVENT_H
e8ed081233450bafb6750f29e0de99b1169f2d29
3a77c41cbca375861fbb7ff809782feea0ce0660
/include/Engine/Renderer/Framebuffer.hpp
1cb3faede461cb26aa50e81a8a75445b6508af0c
[]
no_license
ntaylorbishop/Chromatica
6e460a54e40935a847393ef290bb21ee0e6b49f0
2c5c891e116fd5a35084f058f0deeb762c65fe0f
refs/heads/master
2021-01-11T20:12:56.052317
2017-01-28T02:34:35
2017-01-28T02:34:35
79,067,917
0
0
null
null
null
null
UTF-8
C++
false
false
960
hpp
Framebuffer.hpp
#pragma once #include "Engine/General.hpp" #include "Engine/Renderer.hpp" class Framebuffer { public: //STRUCTORS INITIALIZATION Framebuffer(); Framebuffer(int width, int height, vector<eTextureFormat> color_formats, eTextureFormat depth_stencil_format); Framebuffer(std::vector<Texture*> colors, size_t color_count, Texture* depth_stencil_target); Framebuffer(std::vector<Texture*> colors, size_t color_count); //GETTERS SETTERS //GETTERS SETTERS int GetPixelWidth() const { return m_pixelWidth; } int GetPixelHeight() const { return m_pixelHeight; } uint GetFBOHandle() const { return m_fboHandle; } int GetColorCount() const { return m_colorTargets.size(); } Texture* GetColorTexture() const { return m_colorTargets[0]; } Texture* GetDepthTexture() const { return m_depthStencilTarget; } private: uint32_t m_fboHandle; std::vector<Texture*> m_colorTargets; Texture* m_depthStencilTarget; int m_pixelWidth; int m_pixelHeight; };
c5906c5bbdc1b440007e46e28bba93e8ecddef19
fa53c6987bb825b8ac951fe622427213f719099e
/Assignment -03/Car_parking.cpp
934153d9789066a9cde0c1ffa4f7a95ba24c67d4
[]
no_license
ShreyanshNanda/oop
82bde0e41ac81ab6234e8ee7e3de0e707d7bc2b0
524f2ffd74b0a40f88286b03e13a4ce520eafa96
refs/heads/master
2022-12-30T07:59:11.330491
2020-10-21T13:38:50
2020-10-21T13:38:50
279,008,759
0
0
null
null
null
null
UTF-8
C++
false
false
1,247
cpp
Car_parking.cpp
#include<iostream> using namespace std; class parking { private: double charges,minimum; int z; public: double hours; double calculateCharges() { minimum=2.00; if(hours<=3 ) { charges=minimum; } if(hours>3 && hours <=24) { charges=2.00; z=hours-3; for(int i=0;i<z;i++) { charges=charges+.50; } } if(charges>10.00) { charges=10.00; } return charges; } void input() { cout<<"Enter number of hours : "<<endl; cin>>hours; } }; int main() { parking p1,p2,p3,p4; p1.input(); p2.input(); p3.input(); cout<<"car"<<" "<<"Hours "<<" "<<"Charge"<<endl; cout<<"1 "<<" "<<p1.hours<<" "<<p1.calculateCharges()<<endl; cout<<"2 "<<" "<<p2.hours<<" "<<p2.calculateCharges()<<endl; cout<<"3 "<<" "<<p3.hours<<" "<<p3.calculateCharges()<<endl; cout<<"Total"<<" "<<p1.hours+p2.hours+p3.hours<<" "<<p1.calculateCharges()+p2.calculateCharges()+p3.calculateCharges()<<endl; }
20f3bed3d6f6a658e7fcd65824351c24c725695b
41ec88c269c8cfdc651c7d6eec9bb7ba5dd221b7
/base/task_monitor.cpp
204e3239b8621c2ba5e65ea35d5314324c2006d0
[]
no_license
jin02023343/EST-CTRL-Y8-QT
386ed4c81450a8d41947356048dee8fd0b0aec1d
1257a7df0742912b9703d5905784aaaf5d5a170d
refs/heads/master
2021-09-11T13:45:33.053839
2018-04-08T06:47:12
2018-04-08T06:47:12
103,356,013
0
1
null
null
null
null
UTF-8
C++
false
false
4,552
cpp
task_monitor.cpp
#include "task_monitor.h" #include "./system/sys_database.h" #include "resource_manager.h" #define MONITOR_HOURS_BEFORE_INSTALL (300) CTaskMonitor::CTaskMonitor() { m_iOneTimeVersionGet = false; } void CTaskMonitor::InitDog() { } void CTaskMonitor::Dogging() { } void CTaskMonitor::TimeoutMonitor() { if (!g_dbsys.operationx.cState) return; //start date QDateTime dtStart(QDate(2000+g_dbsys.dateStart.year,g_dbsys.dateStart.month,g_dbsys.dateStart.day)); dtStart = dtStart.addSecs(g_dbsys.operationx.tHour*3600 + g_dbsys.operationx.tMinute*60); //time out date QDateTime dTimeout = dtStart.addMonths((g_dbsys.operationx.cNowNum-1) * g_dbsys.operationx.cPeriodLength); QDateTime dToday = QDateTime::currentDateTime(); //time out and cPeriods > 0 if (( dToday >= dTimeout ) && ( g_dbsys.operationx.cPeriods > 0 )) { g_dbsys.operation.bTimeout = true; //change ram g_systemDb->SaveSystemCfg("operation/bTimeout",g_dbsys.operation.bTimeout); //save to disk } } void CTaskMonitor::InstallMonitor() { //如果已经输入过识别码,不再验证300个小时是否到 if(g_dbsys.operationx.keyInstalled == 1) return; if( g_dbsys.dbsystem.mTotalTime > MONITOR_HOURS_BEFORE_INSTALL) { g_dbsys.operationx.keyNeed = true; } } void CTaskMonitor::DateLostMonitor() { //如果已经输入过识别码,并且分期付款已经结束,不再查看电池信息 if(g_dbsys.operationx.keyInstalled == 1) if (!g_dbsys.operationx.cState) return; //如果开启分期付款,且时间早于2015,则认为需要输入密码 QDate dt = QDate::currentDate(); //check at start up only if(dt.year() <= 2016) { g_dbsys.operation.bTimeNeedSet = true; g_dbsys.operation.bStopRunMach = true; } } void CTaskMonitor::Init_TaskMonitor() { InitDog() ; m_lCounter = 0; timerSecond = 0; //timerMinute = 0; timerMinute = g_systemDb->getSystemCfg("dbsystem/mTimerMinute",0).toUInt(); //load minute from disk timerTick.start(); DateLostMonitor(); //check if the date is lost TimeoutMonitor(); //period monitor InstallMonitor(); //install monitor } void CTaskMonitor::On_TaskMonitor() { //g_nCounter 10ms g_nCounter = timerTick.elapsed()/10; if (g_nCounter - m_lCounter < 100) return; m_lCounter = g_nCounter; Dogging(); timerSecond++; if(timerSecond == 60) { timerSecond = 0; timerMinute++ ; g_systemDb->SaveSystemCfg("dbsystem/mTimerMinute",timerMinute); //save minute from disk //autorun mode,save mSelfRunTime every 1 minute. if(g_systemDb->isAutoRun()) { g_dbsys.dbsystem.mSelfRunTime++; g_systemDb->SaveSystemCfg("dbsystem/mSelfRunTime",g_dbsys.dbsystem.mSelfRunTime); } } if(timerMinute >= 60) { timerMinute=0; //mOperationTime save every 1 hour. g_dbsys.dbsystem.mOperationTime++; g_systemDb->SaveSystemCfg("dbsystem/mOperationTime",g_dbsys.dbsystem.mOperationTime); //total time ,save every 1 hour g_dbsys.dbsystem.mTotalTime++; g_systemDb->SaveSystemCfg("dbsystem/mTotalTime",g_dbsys.dbsystem.mTotalTime); TimeoutMonitor(); //period monitor //check every hour ,for period password InstallMonitor(); //install monitor //check every hour ,for install password } //net client mode;g_bCommunicate is detected by network if(g_dbsys.utility.mNetTcpMode == TARGET_TCP_CLIENT) { if(g_netBase) { if(g_netBase->isConnected()) { g_systemDb->g_bCommunicate = true; RsMgr->g_simBase->setVisible(false); return; } } g_systemDb->g_bCommunicate = false; return; } //g_bMotionSimulate mode; do not detected g_bCommunicate if(g_systemDb->g_bMotionSimulate) return; //other mode; use comm as g_bCommunicate source if (g_taskComCtrl->isPacketChanged()) g_systemDb->g_bCommunicate = true; else g_systemDb->g_bCommunicate = false; if(!m_iOneTimeVersionGet) { if(g_taskComCtrl) { if(g_dbsys.utility.mPlatform == PF_NDT_10_A) return; g_taskComCtrl->CreateTask(CMD_FUNC_VER,NULL,0); m_iOneTimeVersionGet = true; } } }
f0b67ee0438637f1e20b0152a4ecf376e207e996
4371008ca86c2e9ef7f8b9fe2ec3742439b2ac62
/Crafter/spider.h
957fbd8dba93ddf52d802caaddacf11745cbdb81
[]
no_license
gitLofer/CraftingSystem
65560c662db52feafe9fd24b06c3ce538c2c86a2
c8f192cc5f91c9eb279fc69912ebb6dfda18db75
refs/heads/master
2021-05-16T20:56:27.819367
2020-05-07T15:13:50
2020-05-07T15:13:50
250,466,105
0
0
null
null
null
null
UTF-8
C++
false
false
1,415
h
spider.h
#ifndef SPIDER_H_INCLUDED #define SPIDER_H_INCLUDED #include "hostileMob.h" #include "armorSet.h" #include "item.h" #include "list.hpp" #include "player.h" class Spider : public HostileMob { private: bool isAggressive; bool isPoisonous; public: Spider() { isAggressive = false; isPoisonous = false; blockHeight = 1; } Spider(bool aggro, bool poison, int dmg, bool daytime, List<Item> drops, int dropChance, int h, int bh, int sa, int s, int hp) : HostileMob ( dmg, daytime, drops, dropChance, h, bh, sa, s, hp) { isAggressive = aggro; isPoisonous = poison; } Spider(const Spider &z) { isAggressive = z.isAggressive; isPoisonous = z.isPoisonous; // Entity health = z.health; blockHeight = z.blockHeight; startingArmour = z.startingArmour; speed = z.speed; //Mob dropCollection = z.dropCollection; chanceOfDrop = z.chanceOfDrop; //HostileMob damage = z.damage; isDay = z.isDay; } bool getAggro() {return isAggressive;} bool getPoison() {return isPoisonous;} void setAggro(bool b) {isAggressive = b;} void setPoison(bool b) {isPoisonous = b;} void dealDamage (Player pl) { pl.beDamaged(damage); return; } }; #endif // SPIDER_H_INCLUDED
1814ee04d869b31c06e9a7b8af9393088f8aebe4
0d9c3b631a8a7f5c0122b93d771cce4774932728
/c++/homework/102403203 7-41 25題.cpp
b446dbca4d46c8886ea4aa288ad1048cf42c4b3b
[]
no_license
KuanChunChen/Practice_collage_code
28c26cd0de55b778a3101156228c0174f207658c
eaac311da4d53b98d42c4114d3af464f611ba525
refs/heads/master
2021-04-26T22:06:54.690770
2018-03-06T05:27:58
2018-03-06T05:27:58
124,023,420
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
247
cpp
102403203 7-41 25題.cpp
// 102403203 ³¯«a¶v // 7-41 25ÃD #include<stdio.h> #include<stdlib.h> int main() { int a,b; for(a=1;a<=5;a++) {for(b=1;b<=a;b++) printf("%d",a); printf("\n"); } system("pause"); return 0 ; }
1b63ccf80d87b2864c7b8550b7453026cf58c816
992c90b4fb654cab0e5a2a568aa154c175398b1d
/debugcombinationSum/main.cpp
9d0fd025fbaf31cc678814361fd6060719821035
[]
no_license
Chuongdv/advance-algorithm
d94a8e64cd6ec3f62087934028a89b09636017ff
fb5312a6e672f4c873056122091200d4b64951ce
refs/heads/master
2020-12-01T17:01:59.119967
2019-12-29T05:00:53
2019-12-29T05:00:53
230,704,905
0
0
null
null
null
null
UTF-8
C++
false
false
2,225
cpp
main.cpp
#include <iostream> #include <string> #include <vector> using namespace std; string result; vector<int> a; vector<int> temp; /* void print() { cout << "temp : " ; for(auto i = temp.begin(); i != temp.end(); i++) { cout << *i << " "; } cout << endl; } */ void backtrack(int sum, int k) { for(int i = k; i < a.size(); i++) { if(a.at(i) == sum) { temp.push_back(a.at(i)); result.push_back('('); for(int j = 0; j < temp.size(); j++) { result.push_back('0' + temp.at(j)); result.push_back(' '); } result.pop_back(); result.push_back(')'); temp.pop_back(); } else if(a.at(i) < sum) { temp.push_back(a.at(i)); sum -= a.at(i); backtrack(sum, i); sum += a.at(i); temp.pop_back(); } } } std::string combinationSum(std::vector<int> &b, int sum) { int loop = a.size(); for(int i = 0;i < loop; i++) { for(int j = i + 1; j < a.size(); j++) { if(a.at(i) > a.at(j) ) { swap(a.at(i), a.at(j)); cout << "loop: " << loop << ": "; for(int i = 0; i < a.size(); i++) cout << a.at(i) << " "; cout << endl; } else if(a.at(i) == a.at(j)) { a.at(j) = 1000000 + a.size() - loop; loop -= 1; cout << "loop: " << loop << ": "; for(int i = 0; i < a.size(); i++) cout << a.at(i) << " "; cout << endl; } } // cout << "loop: " << loop << ": "; // for(int i = 0; i < a.size(); i++) // cout << a.at(i) << " "; // cout << endl; } a.resize(loop); for(int i = 0; i < a.size(); i++) cout << a.at(i) << " "; cout << endl; backtrack(sum, 0); return result; } int main() { int sum; int n; cin >> n >> sum; int tmp; for(int i = 0; i < n; i++) { cin >> tmp; a.push_back(tmp); } combinationSum(a, sum); cout << result; return 0; }
795a340535d17091ff25ffa6cd6e42cbaf8d1d33
adfc2e5cc8c77574bf911dbe899dca63ac7d8564
/ScorerLib/PairRelationScorer.cpp
752b41e026edb81e097cc4f9ef08babb7e0450c3
[]
no_license
ialhashim/topo-blend
818279ffd0c3c25a68d33cc2b97d007e1bdc7ed6
39b13612ebd645a65eda854771b517371f2f858a
refs/heads/master
2020-12-25T19:03:40.666581
2015-03-13T18:17:18
2015-03-13T18:17:18
32,125,014
25
2
null
null
null
null
UTF-8
C++
false
false
2,977
cpp
PairRelationScorer.cpp
#include "PairRelationScorer.h" void PairRelationScorer::isParalOrthoCoplanar(PairRelation &cpr) { Structure::Node * n1 = cpr.n1; Structure::Node * n2 = cpr.n2; Vector_3 d1, d2; bool iscurve1 = node2direction(n1, d1); bool iscurve2 = node2direction(n2, d2); double err(0.0); if ( iscurve1 == iscurve2 ) { if ( cpr.type == PARALLEL) { err = errorOfParallel(d1, d2); } else if ( cpr.type == ORTHOGONAL) { err = errorOfOrthogonal(d1, d2); } } else// curve & sheet { if ( cpr.type == ORTHOGONAL) { err = errorOfParallel(d1, d2); } } cpr.deviation = fixDeviationByPartName(n1->id, n2->id, err); cpr.diameter = computePairDiameter(cpr); } double PairRelationScorer::evaluate(QVector<QVector<PairRelation> > &pairss, QVector<PART_LANDMARK> &corres) { double resultMean(0.0), resultMax(0.0); int num(0); double dist = graph_->bbox().diagonal().norm(); for ( int j = 0; j < pairss.size(); ++j) { QVector<PairRelation>& pairs = pairss[j]; //if (logLevel_>0) //{ // if ( j == 0 ) // logStream_ << "pairs in source shape \n"; // else // logStream_ << "\n\n pairs in target shape \n"; //} for ( int i = 0; i < pairs.size(); ++i) { PairRelation& pr = pairs[i]; std::vector<Structure::Node*> nodes1 = findNodesInB(pr.n1->id, graph_, corres, j==0); std::vector<Structure::Node*> nodes2 = findNodesInB(pr.n2->id, graph_, corres, j==0); //if (logLevel_>0) //{ // logStream_ << pr << "\n correspond to: \n"; //} for ( int i1 = 0; i1 < (int) nodes1.size(); ++i1) { for ( int i2 = 0; i2 < (int) nodes2.size(); ++i2) { PairRelation cpr(nodes1[i1], nodes2[i2]); cpr.type = pr.type; isParalOrthoCoplanar(cpr); if (cpr.deviation < pr.deviation) cpr.deviation = 0; else { cpr.deviation = cpr.deviation - pr.deviation; cpr.deviation = cpr.deviation * cpr.diameter / dist; } resultMean += cpr.deviation; ++num; if ( resultMax < cpr.deviation) { resultMax = cpr.deviation; } if (logLevel_>0 && cpr.deviation > 0) // { logStream_ << num << "\n"; if ( j == 0 ) logStream_ << "pairs in source shape \n"; else logStream_ << "pairs in target shape \n"; logStream_ << pr << "correspond to: \n"; logStream_ << "<" << nodes1[i1]->id << ", " << nodes2[i2]->id << "> size <" << nodes1[i1]->bbox().diagonal().norm() << ", " << nodes2[i2]->bbox().diagonal().norm() << ", "<< dist << ">:" << cpr.deviation << "\n\n"; } } } } } if (logLevel_>0 ) { logStream_ << "mean score: " << 1-resultMean/num << "\n"; logStream_ << "max score: " << 1-resultMax << "\n"; } return 1-resultMax; }
e71263efb396951942a812a4bf07fd9a6378477e
f3243845fc1e85b51f1d6f1c345e7d00863b4912
/pricer/pricing/Monte_Carlo.h
7ab4aaca631e0f0c898915518e3d883bb9c76d00
[ "MIT" ]
permissive
coupetmaxence/pricing-dashboard
c7dbab004112b44d42358a138d91b792bcc34f18
1c53dc7003a82beca91deb38be1baa24d4d856bc
refs/heads/master
2020-04-10T20:36:13.637909
2018-03-29T22:18:50
2018-03-29T22:18:50
124,287,538
1
0
null
null
null
null
UTF-8
C++
false
false
274
h
Monte_Carlo.h
#ifndef _MONTECARLO_H_INCLUDED_ #define _MONTECARLO_H_INCLUDED_ # include "../derivatives/Derivative.h" namespace pricers { class Monte_Carlo { public: static double price(derivatives::Derivative* derivative, int nbr_simulations, int nbr_steps); }; } #endif
0027e8ee5002a8b3d56f19b92824153881148a04
232ba484bad746f5fc2cc6d1e30dc8583344052d
/skyline/UncertainObject.cpp
76bfde3a2b957a7170756eb8c65cb6aa009e0238
[]
no_license
candybaby/skyline
d9338fda36996e6b4e43af13801e713cb2f7e228
e35329ee18c0e112ff0fd6c603512e3cd24abb8f
refs/heads/master
2021-01-19T13:01:57.929529
2015-02-07T13:34:05
2015-02-07T13:34:05
25,974,678
0
0
null
null
null
null
UTF-8
C++
false
false
1,437
cpp
UncertainObject.cpp
#include "UncertainObject.h" UncertainObject::UncertainObject(void) { _isPruned = false; _cache = 0; } UncertainObject::~UncertainObject(void) { while (instances.size() > 0) { Instance* delData = instances.back(); instances.pop_back(); delete delData; } } void UncertainObject::SetName(string value) { name = value; } string UncertainObject::GetName() { return name; } void UncertainObject::SetTimestamp(int value) { timestamp = value; } int UncertainObject::GetTimestamp() { return timestamp; } void UncertainObject::AddInstance(Instance* value) { instances.push_back(value); } vector<Instance*> UncertainObject::GetInstances() { return instances; } double UncertainObject::GetSkylineProbability() { double result = 0; if (_cache == 0) { for (vector<Instance*>::iterator it = instances.begin(); it < instances.end(); it++) { Instance* instance = *it; result += instance->GetSkylineProbability() * instance->GetProbability(); } _cache = result; } else { result = _cache; } return result; } void UncertainObject::SetPruned(bool flag) { _isPruned = flag; } bool UncertainObject::GetPruned() { return _isPruned; } void UncertainObject::SetMax(int* max) { _max = max; } int* UncertainObject::GetMax() { return _max; } void UncertainObject::SetMin(int* min) { _min = min; } int* UncertainObject::GetMin() { return _min; } void UncertainObject::NeedReCompute() { _cache = 0; }
df3f2ba69cf009d19f5d756fd398eb113c6e07b8
6aeccfb60568a360d2d143e0271f0def40747d73
/sandbox/contract/boost/contract/aux_/macro/code_/loop_variant.hpp
70678cdda1e3ef6f7d4690837f37042dccfa76bf
[ "BSL-1.0" ]
permissive
ttyang/sandbox
1066b324a13813cb1113beca75cdaf518e952276
e1d6fde18ced644bb63e231829b2fe0664e51fac
refs/heads/trunk
2021-01-19T17:17:47.452557
2013-06-07T14:19:55
2013-06-07T14:19:55
13,488,698
1
3
null
2023-03-20T11:52:19
2013-10-11T03:08:51
C++
UTF-8
C++
false
false
4,294
hpp
loop_variant.hpp
// Copyright (C) 2008-2013 Lorenzo Caminiti // Distributed under the Boost Software License, Version 1.0 // (see accompanying file LICENSE_1_0.txt or a copy at // http://www.boost.org/LICENSE_1_0.txt) // http://www.boost.org/doc/libs/release/libs/contract/doc/html/index.html #ifndef BOOST_CONTRACT_AUX_CODE_LOOP_VARIANT_HPP_ #define BOOST_CONTRACT_AUX_CODE_LOOP_VARIANT_HPP_ #include <boost/contract/broken.hpp> #include <boost/contract/aux_/symbol.hpp> #include <boost/contract/aux_/call/globals.hpp> #include <boost/contract/aux_/macro/code_/const_expr.hpp> #include <boost/contract/detail/preprocessor/keyword/const.hpp> // PRIVATE // #define BOOST_CONTRACT_AUX_CODE_LOOP_VARIANT_VAR_ \ /* NOTE: this name should not be made unique (using id, etc) so to */ \ /* give error is multiple loop variants used within same loop */ \ /* (only 1 loop invariant for loop because that's theoretically correct */ \ /* and because there is only 1 old loop variant variable) */ \ BOOST_CONTRACT_AUX_SYMBOL( (loop_variant) ) #define BOOST_CONTRACT_AUX_CODE_LOOP_VARIANT_FUNC_(id) \ BOOST_CONTRACT_AUX_SYMBOL( (loop_variant_func)(id) ) #define BOOST_CONTRACT_AUX_CODE_LOOP_VARIANT_CHECK_AND_UPDATE_(expr) \ try \ { \ ::contract::aux::call_globals<>::is_checking_contract = true; \ /* assert loop variant never negative (but can be zero) */ \ if(!(BOOST_CONTRACT_AUX_CODE_LOOP_VARIANT_VAR_ >= 0)) \ { \ throw ::contract::broken(__FILE__, __LINE__, \ BOOST_PP_STRINGIZE(expr) " >= 0 " \ " /* non-negative loop variant */"); \ } \ /* assert either 1st iteration (old loop variant not initialized */ \ /* yet) or loop variant monotonically decreasing */ \ if(!( \ BOOST_CONTRACT_AUX_CODE_LOOP_VARIANT_OLD_VAR.value == \ ::contract::aux::loop_variant::uninitialized \ || BOOST_CONTRACT_AUX_CODE_LOOP_VARIANT_VAR_ < \ BOOST_CONTRACT_AUX_CODE_LOOP_VARIANT_OLD_VAR.value \ )) \ { \ throw ::contract::broken(__FILE__, __LINE__, \ BOOST_PP_STRINGIZE(expr) " < oldof " \ BOOST_PP_STRINGIZE(expr) \ " /* monotonically decreasing loop variant */"); \ } \ ::contract::aux::call_globals<>::is_checking_contract = false; \ } \ catch(...) \ { \ ::contract::aux::call_globals<>::is_checking_contract = false; \ ::contract::loop_variant_broken(::contract::FROM_BODY); \ } \ /* update old loop variant with variant calc in this iteration */ \ BOOST_CONTRACT_AUX_CODE_LOOP_VARIANT_OLD_VAR.value = \ BOOST_CONTRACT_AUX_CODE_LOOP_VARIANT_VAR_; #define BOOST_CONTRACT_AUX_CODE_LOOP_VARIANT_CONST_(id, tpl, const_expr) \ BOOST_PP_LIST_ENUM(BOOST_CONTRACT_AUX_CODE_CONST_EXPR_TOKENS(id, tpl, \ ::contract::aux::loop_variant::value_type, \ BOOST_CONTRACT_AUX_CODE_LOOP_VARIANT_FUNC_(id), const_expr)) \ ::contract::aux::loop_variant::value_type \ BOOST_CONTRACT_AUX_CODE_LOOP_VARIANT_VAR_ = \ BOOST_CONTRACT_AUX_CODE_LOOP_VARIANT_FUNC_(id)(); \ BOOST_CONTRACT_AUX_CODE_LOOP_VARIANT_CHECK_AND_UPDATE_( \ BOOST_CONTRACT_DETAIL_PP_CONST_EXPR_TRAITS_EXPR( \ BOOST_CONTRACT_DETAIL_PP_CONST_EXPR_TRAITS(const_expr))) #define BOOST_CONTRACT_AUX_CODE_LOOP_VARIANT_(id, tpl, expr) \ ::contract::aux::loop_variant::value_type \ BOOST_CONTRACT_AUX_CODE_LOOP_VARIANT_VAR_ = expr; \ BOOST_CONTRACT_AUX_CODE_LOOP_VARIANT_CHECK_AND_UPDATE_(expr) // PUBLIC // #define BOOST_CONTRACT_AUX_CODE_LOOP_VARIANT_OLD_VAR \ BOOST_CONTRACT_AUX_SYMBOL( (loop_variant_old) ) #define BOOST_CONTRACT_AUX_CODE_LOOP_VARIANT(id, tpl, expr) \ /* loop variant cannot be a compile-time static expression */ \ /* (metafunction) because it must dynamically decrease at run-time */ \ /* but const-expr allowed for variant expr */ \ BOOST_PP_IIF(BOOST_CONTRACT_DETAIL_PP_KEYWORD_IS_CONST_FRONT(expr), \ BOOST_CONTRACT_AUX_CODE_LOOP_VARIANT_CONST_ \ , \ BOOST_CONTRACT_AUX_CODE_LOOP_VARIANT_ \ )(id, tpl, expr) #endif // #include guard
ac3e18226301db17ca71376d6b05ae1c8a6b3024
dc8c73278f38d89fb8f99e581b621610a3f15b04
/lesson23/main.cpp
458a7084077b1135a935ae35c79933b1bab9a50a
[]
no_license
Theresating/cppstudy
0c6cfc57e80f882b3a93eaf6c91301cc0a93cd84
3f8424a2e8c09c0d819d17e009adf6544f5017d2
refs/heads/master
2021-01-19T05:44:18.492694
2016-07-09T15:25:51
2016-07-09T15:25:51
61,977,110
0
0
null
null
null
null
GB18030
C++
false
false
2,957
cpp
main.cpp
/* while语句 (一)while语法形式 1.定义: while也用于实现循环,本质与for相似 2.形式: while(expr) statement 3.步骤: 3.1判断:expr为假时,退出循环;否则执行2 2.2执行语句statement(循环体) 3.3回到2进行下一轮 4.例子: 和for没有本质区别,以下代码实现了for功能 char buf[100]; int i = 0 ; while (i<100) { buf[i] = i + 1; i++; } char buf[100]; int i = 0; while (1) { if (i>=100) { break;//终止循环 } buf[i] = i + 1; i++; } 5.区别: 与for没有区别 同样的例子用while实现 6.例题: 例1: 求小于100的奇数的平方和: int sum = 0; int i = 1; while (i < 100)//此处加断点(F9),F5,F10(按一次向下执行一步) { sum += i*i;//此处可以看到局部变量一直在变1->3->5... i += 2; } 例2: 让用户从控制台输入一系列正整数,当用户输入为0时表示结束, 存储这些数并求他们的总和。要点:不知道用户会输入多少个数 int buf[100];//buffer int count = 0;//计数 while (1) { int n ; printf("please input:"); scanf_s("%d", &n); if (n<=0) { break; } buf[count] = n; count += 1; } printf("total: %d \n", count); int sum = 0; for (int i = 0; i<count; i++) { sum += buf[i];//数组元素之和,而不是加n,因为n已经存再数组中 } printf("result : %d \n", sum); 例3: 令用户输入一个整数(十进制),判断他有几位 int n = 3456;//scanf最后加便于调试 scanf_s("%d", &n);//scanf后面不加换行符 int count = 0; while (n != 0) { n /= 10; count++; //调试->窗口->内存、局部变量、自动窗口 //345,34,3,0 } printf("count:%d \n", count); 注:调试时可以不用输入一步,直接给值进行调试,调试速度更快省时省力 (二)do while 语句 1.定义: 本质和while、for完全相同 2.形式: do { statement }while(expr); 3.步骤: 3.1执行do{}里面的循环体 3.2判断expr是否为真,为真是继续下一轮,为假时继续 4.特点:循环体至少执行一次 5.例子: 让用户输入一个介于0-100的整数,返回它的平方值, 如果用户输入的数在此区间之外,令其重新输入 分析: 至少执行一次,如果一次正确则结束,否则反复输入 int n = 0; do { printf("please input:"); scanf_s("%d", &n); } while (n<0||n>100); printf("%d \n", n*n); (三)小结 1.while、for、do while本质上完全相同 2.形式略有区别常用while和for */ return 0; }
64e8480f6eb040378597338c8fb561801dc5445c
abfda71ae4f0384b14604ffa842aa9d5ad2e4a5f
/src/Treiber/TasterLed.cpp
815d1e3eab9d03dbefd80c68726670a50f9ffe9c
[]
no_license
niocio01/arduino-board-game
0be7d5bbe99748fc22d27209dd4aec7f1f6c8209
9c2f57885aae5aaa5f272c5f0a67b5a06ae6c420
refs/heads/master
2020-12-31T07:10:34.292430
2017-05-22T19:50:34
2017-05-22T19:50:34
80,560,791
2
0
null
2017-03-21T13:10:50
2017-01-31T20:48:55
C++
UTF-8
C++
false
false
1,011
cpp
TasterLed.cpp
#include "Treiber/TasterLed.h" #include "Treiber/LedTreiber.h" void TasterLed_Setzen(GlobalTypes_Spieler_t spieler, TasterLed_Nummer_t nummer, GlobalTypes_Farbe_t farbe) { if (spieler == SpielerEins) { switch(nummer) { case LedEins: LedTreiber_LedSchalten(257, farbe); break; case LedZwei: LedTreiber_LedSchalten(258, farbe); break; case LedDrei: LedTreiber_LedSchalten(259, farbe); break; case LedVier: LedTreiber_LedSchalten(260, farbe); break; } } else { switch(nummer) { case LedEins: LedTreiber_LedSchalten(265, farbe); break; case LedZwei: LedTreiber_LedSchalten(266, farbe); break; case LedDrei: LedTreiber_LedSchalten(267, farbe); break; case LedVier: LedTreiber_LedSchalten(268, farbe); break; } } }
e577cb5ce0fbf524c39d930eb6ab21c20e0220a3
1f032ac06a2fc792859a57099e04d2b9bc43f387
/c3/70/b1/44/deb572a17823680e57af3da35e070ffe5ffe16d0441b676004a40978d4b45a08a50ed6bd44f1214f042c977eca63f8553bf6d5a90ee5d8d857835154/sw.cpp
ca073f0d8a3b12085d05bfa226a9b0f1928adf28
[]
no_license
SoftwareNetwork/specifications
9d6d97c136d2b03af45669bad2bcb00fda9d2e26
ba960f416e4728a43aa3e41af16a7bdd82006ec3
refs/heads/master
2023-08-16T13:17:25.996674
2023-08-15T10:45:47
2023-08-15T10:45:47
145,738,888
0
0
null
null
null
null
UTF-8
C++
false
false
8,215
cpp
sw.cpp
#pragma sw require pub.egorpugin.primitives.filesystem-master void build(Solution &s) { auto &p = s.addProject("copperspice", "1.5.2"); p += Git("https://github.com/copperspice/copperspice", "cs-{v}"); auto read_files_from_cmake = [](const path &fn, const String &var) -> Strings { if (!fs::exists(fn)) return {}; auto str = read_file(fn); auto p = str.find("set(" + var); if (p != str.npos) { auto b = str.find("}", p); auto e = str.find(")", b); auto strs = split_string(str.substr(b + 1, e - b - 1), " \r\n\t"); for (auto &s : strs) { static const String cmsd = "${CMAKE_CURRENT_SOURCE_DIR}/"; if (s.find(cmsd) == 0) s = s.substr(cmsd.size()); if (s.find("/") == 0) s = s.substr(1); } return strs; } return {}; }; auto macro_generate_public = [&read_files_from_cmake] (auto &t, const String &var, const String &module, const Strings &dirs, const String &prefix) { for (auto &d : dirs) { for (auto &f : read_files_from_cmake(t.SourceDir / prefix / d / (d + ".cmake"), var)) t.writeFileOnce(path(module) / path(f).filename(), "#include <" + normalize_path(t.SourceDir / prefix / d / (boost::to_lower_copy(f) + ".h")) + ">"); } }; auto macro_generate_private = [&read_files_from_cmake] (auto &t, const String &var, const String &module, const Strings &dirs, const String &prefix) { for (auto &d : dirs) { for (auto &f : read_files_from_cmake(t.SourceDir / prefix / d / (d + ".cmake"), var)) t.configureFile(t.SourceDir / prefix / f, t.BinaryPrivateDir / path(module) / "private" / path(f).filename(), ConfigureFlags::CopyOnly); } }; auto macro_generate_misc = [&read_files_from_cmake] (auto &t, const String &var, const path &module, const Strings &dirs, const String &prefix) { for (auto &d : dirs) { for (auto &f : read_files_from_cmake(t.SourceDir / prefix / d / (d + ".cmake"), var)) t.configureFile(t.SourceDir / prefix / f, path(module) / path(f).filename(), ConfigureFlags::CopyOnly); } }; auto add_files = [&macro_generate_public, &macro_generate_private, &macro_generate_misc] (auto &t, const String &d) { Strings dirs; for (auto &d : fs::directory_iterator(t.SourceDir / ("src/" + d))) { if (fs::is_directory(d)) dirs.push_back(d.path().filename().u8string()); } auto fcap = d; fcap[0] = toupper(fcap[0]); auto cap = boost::to_upper_copy(d); t += IncludeDirectory(t.BinaryPrivateDir / ("Qt" + fcap) / "private"); t.Public += IncludeDirectory(t.BinaryDir / ("Qt" + fcap)); for (auto &p : dirs) t += IncludeDirectory("src/" + d + "/" + p); macro_generate_public(t, cap + "_PUBLIC_INCLUDES", "Qt" + fcap, dirs, "src/" + d); macro_generate_private(t, cap + "_PRIVATE_INCLUDES", "Qt" + fcap, dirs, "src/" + d); macro_generate_misc(t, cap + "_INCLUDES", "Qt" + fcap, dirs, "src/" + d); return dirs; }; auto remove_platform_files = [](auto &core) { core -= ".*unix.*"_rr; core -= ".*mac.*"_rr; core -= ".*linux.*"_rr; core -= ".*glib.*"_rr; }; auto &harfbuzz = p.addTarget<StaticLibrary>("third_party.harfbuzz"); { harfbuzz.setRootDirectory("src/3rdparty/harfbuzz"); harfbuzz -= "src/.*"_rr; harfbuzz += "src/harfbuzz.c", "src/harfbuzz-impl.c", "src/harfbuzz-stream.c", "src/harfbuzz-shaper-all.cpp"; if (s.Settings.TargetOS.Type == OSType::Windows) { harfbuzz.Private += "UNICODE"_d; harfbuzz.Public += "WIN32"_d; } } auto &wintab = p.addTarget<StaticLibraryTarget>("third_party.wintab"); wintab.setRootDirectory("src/3rdparty/wintab"); auto &core = p.addTarget<Library>("core"); { core.setChecks("cs"); core += "src/core/.*"_rr; remove_platform_files(core); core -= ".*nacl.*"_rr; core -= ".*iconv.*"_rr; core -= ".*kqueue.*"_rr; core -= ".*inotify.*"_rr; core -= ".*dnotify.*"_rr; core -= ".*fsevents.*"_rr; core -= ".*fork.*"_rr; core -= ".*qelapsedtimer_generic.cpp"_rr; core -= ".*qcrashhandler.cpp"_rr; core -= "src/core/tools/qunicodetables.cpp"; core += "QT_BUILD_CORE_LIB"_def; core += "BUILDING_LIB_CS_STRING="_def; core += "BUILDING_LIB_CS_SIGNAL="_def; core += "BUILD_DATE=\"\""_def; core.Protected += "org.sw.demo.madler.zlib"_dep; core += "org.sw.demo.unicode.icu.i18n"_dep; core.Protected += harfbuzz; if (s.Settings.TargetOS.Type == OSType::Windows) { core.Protected += "NOMINMAX"_def; core.Public += "UNICODE="_def; core += "ws2_32.lib"_slib; core += "user32.lib"_slib; core += "ole32.lib"_slib; } auto &v = p.pkg.version; core.Variables["HEX_VERSION"] = (v.getMajor() << 16) + (v.getMinor() << 8) + v.getPatch(); core.configureFile("src/core/global/cs_build_info.h.in", "cs_build_info.h"); core.configureFile("cmake/qt-acconfig.h.cmake", "qt-acconfig.h"); core.patch("src/core/tools/qlocale_icu.cpp", "reinterpret_cast<UChar *>", "(UChar *)"); core.patch("src/core/tools/qlocale_icu.cpp", "reinterpret_cast<const UChar *>", "(const UChar *)"); core.Protected += IncludeDirectory(core.BinaryPrivateDir / "QtCore" / "private"); auto dirs = add_files(core, "core"); macro_generate_misc(core, "CORE_INCLUDES", "QtCore", dirs, "src/core"); macro_generate_misc(core, "CORE_REGEX_INCLUDES", "QtCore/regex", dirs, "src/core"); } auto add_target = [&p, &core, &add_files, &remove_platform_files](const String &name) -> decltype(auto) { auto &t = p.addTarget<Library>(name); t += FileRegex("src/" + name, ".*", true); remove_platform_files(t); t += Definition("QT_BUILD_" + boost::to_upper_copy(name) + "_LIB"); t.Public += core; t.CompileOptions.push_back("-bigobj"); add_files(t, name); return t; }; auto &xml = add_target("xml"); return; auto &gui = add_target("gui"); gui -= ".*x11.*"_rr; gui -= ".*qpa.*"_rr; gui -= ".*qws.*"_rr; gui += wintab; gui += "org.sw.demo.freetype"_dep; gui += "org.sw.demo.jpeg"_dep; gui += "org.sw.demo.mng"_dep; gui += "org.sw.demo.tiff"_dep; gui += "org.sw.demo.google.angle.egl"_dep; } void check(Checker &c) { auto &s = c.addSet("cs"); s.checkIncludeExists("cups/cups.h"); s.checkIncludeExists("dirent.h"); s.checkIncludeExists("dlfcn.h"); s.checkIncludeExists("fcntl.h"); s.checkIncludeExists("features.h"); s.checkIncludeExists("grp.h"); s.checkIncludeExists("libpq-fe.h"); s.checkIncludeExists("mysql.h"); s.checkIncludeExists("netinet/in.h"); s.checkIncludeExists("net/if.h"); s.checkIncludeExists("pg_config.h"); s.checkIncludeExists("pthread.h"); s.checkIncludeExists("pwd.h"); s.checkIncludeExists("signal.h"); s.checkIncludeExists("sys/ioctl.h"); s.checkIncludeExists("sys/ipc.h"); s.checkIncludeExists("sys/param.h"); s.checkIncludeExists("sys/shm.h"); s.checkIncludeExists("sys/socket.h"); s.checkIncludeExists("sys/stat.h"); s.checkIncludeExists("sys/time.h"); s.checkIncludeExists("sys/types.h"); s.checkIncludeExists("sys/wait.h"); s.checkIncludeExists("unistd.h"); s.checkTypeSize("size_t"); s.checkLibraryFunctionExists("mysqlclient", "my_init"); s.checkLibraryFunctionExists("pq", "PQconnectdbParams"); }
3171b91fbfe31c5f77e5e63f340791d0656c9ea0
30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a
/CodesNew/1261.cpp
e8e6a868604e05db55a11c2e0e693891638abddc
[]
no_license
thegamer1907/Code_Analysis
0a2bb97a9fb5faf01d983c223d9715eb419b7519
48079e399321b585efc8a2c6a84c25e2e7a22a61
refs/heads/master
2020-05-27T01:20:55.921937
2019-11-20T11:15:11
2019-11-20T11:15:11
188,403,594
2
1
null
null
null
null
UTF-8
C++
false
false
754
cpp
1261.cpp
#include <stdio.h> #include <math.h> #include <string.h> #include <iostream> #include <algorithm> #include <vector> #include <map> #include <utility> #include <stack> #include <queue> #include <set> #include <list> #include <bitset> using namespace std; #define fi first #define se second #define long long long typedef pair<int,int> ii; typedef pair<int,ii> iii; int arr[100003]; int main() { //ios_base::sync_with_stdio(); cin.tie(0); cout.tie(0); // freopen("input.in", "r", stdin); int n; scanf("%d", &n); for(int i = 0; i < n; i++) { scanf("%d", &arr[i]); arr[i] -= i; } int mx = 1e9, ans = 0; for(int i = 0; i < n; i++) { if((arr[i]+n-1)/n < mx) { mx = (arr[i]+n-1)/n; ans = i+1; } } printf("%d\n", ans); }
902d778cd85577f3d94cdc3301bc09f686a28329
0676ef0e5bf5c2d99e68474c6cf5a087ab0a6726
/Classes/ShieldMonster.h
b28560f0be141ba0b76c3ee37c4ed196e7da8bf0
[]
no_license
duyuit/DrawForYourLife
90b40f44a2e39913fb520d409882d7b62cceed8f
3450080ab9e32cfc7ebcaa2a9c6b27d909e239ce
refs/heads/master
2020-03-21T02:44:22.335438
2018-08-10T06:50:29
2018-08-10T06:50:29
138,015,557
0
0
null
2018-07-26T05:41:32
2018-06-20T10:13:31
C++
UTF-8
C++
false
false
132
h
ShieldMonster.h
#pragma once #include "Monster.h" class ShieldMonster:public Monster { public: ShieldMonster(Sonic* sonic); ~ShieldMonster(); };
01c4b005269515e8f089e0078b74df0143468c1a
d41ebea78a3f0d717c482e9f3ef677b27a64a2d7
/ENGINE_/FeaServer.Engine.OpenCL/src/Program2.cpp
d947ce151fad9c89b054afef4793db5d7366bfa1
[]
no_license
JiujiangZhu/feaserver
c8b89b2c66bf27cecf7afa7775a5f3c466e482d5
864077bb3103cbde78a2b51e8e2536b5d87e6712
refs/heads/master
2020-05-18T00:58:56.385143
2012-09-14T14:28:41
2012-09-14T14:28:41
39,262,812
1
1
null
null
null
null
UTF-8
C++
false
false
5,130
cpp
Program2.cpp
#pragma region License /* The MIT License Copyright (c) 2009 Sky Morey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma endregion // http://www.thebigblob.com/getting-started-with-opencl-and-gpu-computing/ #include <stdlib.h> #include <stdio.h> #include "Core.h" #define MAX_SOURCE_SIZE (0x100000) int amain(void) { // Create the two input vectors int i; const int LIST_SIZE = 1000; int *A = (int*)malloc(sizeof(int)*LIST_SIZE); int *B = (int*)malloc(sizeof(int)*LIST_SIZE); for (i = 0; i < LIST_SIZE; i++) { A[i] = i; B[i] = LIST_SIZE - i; } // Load the kernel source code into the array source_str FILE *fp; char *source_str; size_t source_size; fp = fopen("C:\\_APPLICATION\\FEASERVER\\ENGINE_\\FeaServer.Engine.OpenCL\\src\\vector_add_kernel.cl", "r"); if (!fp) { fprintf(stderr, "Failed to load kernel.\n"); exit(1); } source_str = (char*)malloc(MAX_SOURCE_SIZE); source_size = fread( source_str, 1, MAX_SOURCE_SIZE, fp); fclose(fp); // Get platform and device information cl_platform_id platform_id = NULL; cl_device_id device_id = NULL; cl_uint ret_num_devices; cl_uint ret_num_platforms; cl_int ret; ret = clGetPlatformIDs(1, &platform_id, &ret_num_platforms); ret = clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_DEFAULT, 1, &device_id, &ret_num_devices); // Create an OpenCL context cl_context context = clCreateContext(NULL, 1, &device_id, NULL, NULL, &ret); // Create a command queue cl_command_queue command_queue = clCreateCommandQueue(context, device_id, 0, &ret); // Create memory buffers on the device for each vector cl_mem a_mem_obj = clCreateBuffer(context, CL_MEM_READ_ONLY, LIST_SIZE * sizeof(int), NULL, &ret); cl_mem b_mem_obj = clCreateBuffer(context, CL_MEM_READ_ONLY, LIST_SIZE * sizeof(int), NULL, &ret); cl_mem c_mem_obj = clCreateBuffer(context, CL_MEM_WRITE_ONLY, LIST_SIZE * sizeof(int), NULL, &ret); // Copy the lists A and B to their respective memory buffers ret = clEnqueueWriteBuffer(command_queue, a_mem_obj, CL_TRUE, 0, LIST_SIZE * sizeof(int), A, 0, NULL, NULL); ret = clEnqueueWriteBuffer(command_queue, b_mem_obj, CL_TRUE, 0, LIST_SIZE * sizeof(int), B, 0, NULL, NULL); // Create a program from the kernel source cl_program program = clCreateProgramWithSource(context, 1, (const char **)&source_str, (const size_t *)&source_size, &ret); // Build the program ret = clBuildProgram(program, 1, &device_id, NULL, NULL, NULL); // Create the OpenCL kernel cl_kernel kernel = clCreateKernel(program, "vector_add", &ret); // Set the arguments of the kernel ret = clSetKernelArg(kernel, 0, sizeof(cl_mem), (void *)&a_mem_obj); ret = clSetKernelArg(kernel, 1, sizeof(cl_mem), (void *)&b_mem_obj); ret = clSetKernelArg(kernel, 2, sizeof(cl_mem), (void *)&c_mem_obj); // Execute the OpenCL kernel on the list size_t global_item_size = LIST_SIZE; // Process the entire lists size_t local_item_size = 1; // Process one item at a time ret = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global_item_size, &local_item_size, 0, NULL, NULL); // Read the memory buffer C on the device to the local variable C int *C = (int*)malloc(sizeof(int)*LIST_SIZE); ret = clEnqueueReadBuffer(command_queue, c_mem_obj, CL_TRUE, 0, LIST_SIZE * sizeof(int), C, 0, NULL, NULL); // Display the result to the screen for (i = 0; i < LIST_SIZE; i++) printf("%d + %d = %d\n", A[i], B[i], C[i]); // Clean up ret = clFlush(command_queue); ret = clFinish(command_queue); ret = clReleaseKernel(kernel); ret = clReleaseProgram(program); ret = clReleaseMemObject(a_mem_obj); ret = clReleaseMemObject(b_mem_obj); ret = clReleaseMemObject(c_mem_obj); ret = clReleaseCommandQueue(command_queue); ret = clReleaseContext(context); free(A); free(B); free(C); return 0; }
38a9c3a224743fcf8631d2f74b2d24e4c8682616
618e55cef1a98ae8f9f80dd4078df1668a312bb6
/Engine/Source/SDL/TSdl.ipp
9197ece2fde8633a3390e2e0518b2238edea1861
[ "MIT" ]
permissive
TzuChieh/Photon-v2
8eb54ee9f3ae51bb241896a2fc62d10b553eaab9
498724a7ae4f42884499ee13e548013b2799ea7f
refs/heads/master
2023-08-31T22:43:30.667848
2023-08-23T09:43:14
2023-08-23T09:43:14
70,727,398
93
8
MIT
2019-03-04T12:18:54
2016-10-12T18:07:46
C++
UTF-8
C++
false
false
3,373
ipp
TSdl.ipp
#pragma once #include "SDL/TSdl.h" #include "SDL/ISdlResource.h" #include "SDL/Introspect/SdlClass.h" #include "SDL/Introspect/SdlStruct.h" #include "SDL/sdl_helpers.h" #include "Common/assertion.h" #include "Common/logging.h" #include <utility> namespace ph { template<CSdlResource T> inline constexpr ESdlTypeCategory TSdl<T>::getCategory() { return sdl::category_of<T>(); } template<CSdlResource T> inline std::shared_ptr<T> TSdl<T>::makeResource() { static_assert(CHasSdlClassDefinition<T>, "No SDL class definition found. Did you call PH_DEFINE_SDL_CLASS() in the body of type T?"); const SdlClass* clazz = T::getSdlClass(); PH_ASSERT(clazz); // Creates an uninitialized resource std::shared_ptr<ISdlResource> resource = clazz->createResource(); // Could be empty due to `T` being abstract or being defined to be uninstantiable if(!resource) { PH_DEFAULT_LOG_WARNING( "default resource creation failed, {} could be abstract or defined to be uninstantiable", clazz->genPrettyName()); return nullptr; } clazz->initDefaultResource(*resource); // Obtain typed resource. This dynamic cast also guard against the case where // `T` might not actually have SDL class defined locally but inherited (i.e., the resource // created was in fact not of type `T`). std::shared_ptr<T> typedResource = std::dynamic_pointer_cast<T>(std::move(resource)); if(!typedResource) { PH_DEFAULT_LOG_WARNING( "default resource creation failed, {} may not have SDL class defined", clazz->genPrettyName()); } return typedResource; } template<CSdlResource T> template<typename... DeducedArgs> inline T TSdl<T>::make(DeducedArgs&&... args) { static_assert(std::is_constructible_v<T, DeducedArgs...>, "SDL class type T is not constructible using the specified arguments."); T instance(std::forward<DeducedArgs>(args)...); if constexpr(CHasSdlClassDefinition<T>) { const SdlClass* clazz = T::getSdlClass(); PH_ASSERT(clazz); clazz->initDefaultResource(instance); } else if(CHasSdlStructDefinition<T>) { static_assert(CSdlStructSupportsInitToDefault<T>, "SDL struct definition of T does not support initializing to default values"); const auto* ztruct = T::getSdlStruct(); PH_ASSERT(ztruct); ztruct->initDefaultStruct(instance); } else { static_assert(CHasSdlClassDefinition<T> || CHasSdlStructDefinition<T>, "No SDL class/struct definition found. Did you call " "PH_DEFINE_SDL_CLASS()/PH_DEFINE_SDL_STRUCT() in the body of type T?"); } return instance; } template<CSdlResource T> inline std::shared_ptr<T> TSdl<T>::loadResource(const Path& file) { if constexpr(CHasSdlClassDefinition<T>) { auto loadedResource = detail::load_single_resource(T::getSdlClass(), file); #if PH_DEBUG if(loadedResource) { PH_ASSERT(std::dynamic_pointer_cast<T>(loadedResource)); } #endif // Static cast is enough here as the result is guaranteed to have the specified // class if non-null. return std::static_pointer_cast<T>(loadedResource); } else { PH_STATIC_ASSERT_DEPENDENT_FALSE(T, "Cannot load resource without SDL class definition. Did you call PH_DEFINE_SDL_CLASS() " "in the body of type T?"); } } template<CSdlResource T> inline void TSdl<T>::saveResource(const std::shared_ptr<T>& resource, const Path& file) { detail::save_single_resource(resource, file); } }// end namespace ph
5dfebd314855886655f13c9f3fe9482482a67c02
815144a8e3d3159884d663f27a64880a140ae281
/src/thread/barrier.cc
c98a792751e4380016601d863531d946593ee771
[]
no_license
hueng9527/ppcode
32fa358003078d70c1ec43eae7ccaa153a97a70b
0a88070afbba402c72d662ac86d80349004c0cf7
refs/heads/master
2022-11-09T19:34:39.416995
2020-06-21T12:17:36
2020-06-21T12:17:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
944
cc
barrier.cc
#include "barrier.h" #include <pthread.h> #include "../log.h" namespace ppcode { static Logger::ptr g_logger = LOG_ROOT(); Barrier::Barrier(int count) { int rt = pthread_barrier_init(&m_barrier, nullptr, count); if (rt) { LOG_ERROR(g_logger) << "pthread_barrier_init failed, rt=" << rt; throw std::logic_error("pthread_barrier_init failed"); } } Barrier::~Barrier() { int rt = pthread_barrier_destroy(&m_barrier); if (rt) { LOG_ERROR(g_logger) << "pthread_barrier_destroy failed, rt=" << rt; } } bool Barrier::wait() { int rt; do { rt = pthread_barrier_wait(&m_barrier); } while (rt == EINTR); if (rt == PTHREAD_BARRIER_SERIAL_THREAD) { return true; } if (rt) { LOG_ERROR(g_logger) << "pthread_barrier_wait failed, rt=" << rt; throw std::logic_error("pthread_barrier_wait failed"); } return false; } } // namespace ppcode
b2a02b55bd6ee6939009dbcb7c64ace8621214fd
05381f782138b057fe0769eb58d9b6e1977f3cbc
/191.number-of-1-bits.cpp
99bdb3a5588d8735150b30d9a15c213c13ebf700
[]
no_license
Li-Shu14/.leetcode
8c73ee97cb765df2724df0e7f88b2d8697d828dc
466f0cf3c5d8d63ddf70abf499db70973db84dbc
refs/heads/master
2023-04-03T06:55:48.170489
2023-03-20T15:07:11
2023-03-20T15:07:11
210,150,410
0
0
null
null
null
null
UTF-8
C++
false
false
472
cpp
191.number-of-1-bits.cpp
/* * @lc app=leetcode id=191 lang=cpp * * [191] Number of 1 Bits */ // @lc code=start class Solution { public: int hammingWeight1(uint32_t n) { int bits = 0; int mask = 1; for (int i = 0; i < 32; i++) { if ((n & mask) != 0) { bits++; } mask <<= 1; } return bits; } int hammingWeight(uint32_t n) { return hammingWeight1(n); } }; // @lc code=end
26a462391185562bed8bfd522fa81e2224d64d94
8742e6c7c233642dcbb9edcc3fad1dd01f215512
/PacMan/PacMan/Game.cpp
8454ef69bd45db98be2130ccaaf065b711ca8632
[]
no_license
Kolyan4ik316/PacMan
c068d58f6f0115a6697c0f04c90830d09135f6e3
2a7b057c9fff2186d2c7c6dc711e9ac5f2d9b7ce
refs/heads/main
2023-03-03T04:48:41.229324
2021-02-13T15:16:44
2021-02-13T15:16:44
324,156,503
0
0
null
null
null
null
UTF-8
C++
false
false
7,316
cpp
Game.cpp
#include "Game.h" HGE *Game::hge = NULL; int Game::screenWidth = 800; int Game::screenHeight = 600; bool Game::windowed = true;; std::string Game::nameOfWindow = "PacMan"; std::string Game::windowMode = "4:3"; std::stack<State*> Game::states = std::stack<State*>(); Game::Game() { InitWindow(); // Here we use global pointer to HGE interface. // Instead you may use hgeCreate() every // time you need access to HGE. Just be sure to // have a corresponding hge->Release() // for each call to hgeCreate() hge = hgeCreate(HGE_VERSION); } void Game::InitWindow() { std::string path = "Configs\\window.ini"; std::ifstream ifs; ifs.open(path.c_str()); // if file is already exist if(ifs.is_open()) { //Reading variables std::string tempStr; while(!ifs.eof()) { ifs>> tempStr; if(!tempStr.compare("[Window_Width]")) { ifs>>screenWidth; } if(!tempStr.compare("[Window_Height]")) { ifs>>screenHeight; } if(!tempStr.compare("[Windowed]")) { ifs>>windowed; } if(!tempStr.compare("[Resolution_Mode]")) { ifs>>windowMode; } if(!tempStr.compare("[Window_Name]")) { nameOfWindow.clear(); while(getline(ifs,tempStr)) { nameOfWindow += tempStr; } } } } else { //if not exist creating new file in same path std::ofstream ofs; ofs.open(path.c_str()); if(ofs.is_open()) { //Writing variables ofs<<"[Window_Width]\n" <<screenWidth<<"\n" <<"[Window_Height]\n" <<screenHeight<<"\n" <<"[Windowed]\n" <<windowed<<"\n" <<"[Resolution_Mode]\n" <<windowMode.c_str()<<"\n" <<"[Window_Name]\n" <<nameOfWindow.c_str()<<"\n"; } else { // if can't create throw(std::exception("Unknown error while writing to file window.ini")); } ofs.close(); } ifs.close(); } void Game::InitDiff() { std::string path = "Configs\\difficult.ini"; std::ifstream ifs; ifs.open(path.c_str()); // if file is already exist if(ifs.is_open()) { //Reading variables std::string tempStr; while(!ifs.eof()) { ifs>> tempStr; if(tempStr.compare("[Easy]") == 0) { ifs>> tempStr; State::DiffAtributes tempAttr; while(tempStr.compare("[End]")) { if(!tempStr.compare("[Num_of_ghosts]") ) { ifs>>tempAttr.num_of_ghosts; } if(!tempStr.compare("[Speed_of_ghosts]")) { ifs>>tempAttr.speed_of_ghosts; } if(!tempStr.compare("[Release_delay]")) { ifs>>tempAttr.release_delay; } if(!tempStr.compare("[PacMan_speed]")) { ifs>>tempAttr.pacMan_speed; } ifs>> tempStr; } states.top()->LoadDifficults(tempAttr); } if(!tempStr.compare("[Normal]")) { ifs>> tempStr; State::DiffAtributes tempAttr; while(tempStr.compare("[End]")) { if(!tempStr.compare("[Num_of_ghosts]")) { ifs>>tempAttr.num_of_ghosts; } if(!tempStr.compare("[Speed_of_ghosts]")) { ifs>>tempAttr.speed_of_ghosts; } if(!tempStr.compare("[Release_delay]")) { ifs>>tempAttr.release_delay; } if(!tempStr.compare("[PacMan_speed]")) { ifs>>tempAttr.pacMan_speed; } ifs>> tempStr; } states.top()->LoadDifficults(tempAttr); } if(!tempStr.compare("[Hard]")) { ifs>> tempStr; State::DiffAtributes tempAttr; while(tempStr.compare("[End]")) { if(!tempStr.compare("[Num_of_ghosts]")) { ifs>>tempAttr.num_of_ghosts; } if(!tempStr.compare("[Speed_of_ghosts]")) { ifs>>tempAttr.speed_of_ghosts; } if(!tempStr.compare("[Release_delay]")) { ifs>>tempAttr.release_delay; } if(!tempStr.compare("[PacMan_speed]")) { ifs>>tempAttr.pacMan_speed; } ifs>> tempStr; } states.top()->LoadDifficults(tempAttr); } } } else { //if not exist creating new file in same path std::ofstream ofs; ofs.open(path.c_str()); if(ofs.is_open()) { //Writing variables ofs<<"[Easy]\n" <<"[Num_of_ghosts]\n" <<3<<"\n" <<"[Speed_of_ghosts]\n" <<50.0<<"\n" <<"[Release_delay]\n" <<10.0<<"\n" <<"[PacMan_speed]\n" <<110.0<<"\n" <<"[End]\n" <<"[Normal]\n" <<"[Num_of_ghosts]\n" <<4<<"\n" <<"[Speed_of_ghosts]\n" <<60.0<<"\n" <<"[Release_delay]\n" <<10.0<<"\n" <<"[PacMan_speed]\n" <<100.0<<"\n" <<"[End]\n" <<"[Hard]\n" <<"[Num_of_ghosts]\n" <<5<<"\n" <<"[Speed_of_ghosts]\n" <<70.0<<"\n" <<"[Release_delay]\n" <<7.0<<"\n" <<"[PacMan_speed]\n" <<100.0<<"\n" <<"[End]"; } else { // if can't create throw(std::exception("Unknown error while writing to file difficult.ini")); } ofs.close(); } ifs.close(); } void Game::InitStates() { // Pushing main menu states.push(new MainMenu(&states, hge)); InitDiff(); //states.top()->SetDifficult(2); } void Game::ChangePreference() { // Set the window title hge->System_SetState(HGE_TITLE, nameOfWindow.c_str()); // Run in windowed mode // Default window size is 800x600 hge->System_SetState(HGE_WINDOWED, windowed); hge->System_SetState(HGE_SCREENWIDTH, screenWidth); hge->System_SetState(HGE_SCREENHEIGHT, screenHeight); hge->System_SetState(HGE_SCREENBPP, 32); } void Game::Run() { // Set our frame function hge->System_SetState(HGE_FRAMEFUNC, Update); hge->System_SetState(HGE_RENDERFUNC, Render); ChangePreference(); if(hge->System_Initiate()) { // Creating main menu InitStates(); states.top()->SetReoslution(windowMode); // Starting programm itself hge->System_Start(); } else { // If HGE initialization failed show error message throw(std::exception(hge->System_GetErrorMessage())); } //Cleaning states // Bug is fixed; QuitFromApplication(); // Restore video mode and free // all allocated resources hge->System_Shutdown(); // Release the HGE interface. // If there are no more references, // the HGE object will be deleted. hge->Release(); } void Game::QuitFromApplication() { // cleaning our states pointers // for (unsgned int i = 0; i< states.size(); i++) not erasing first element while(!states.empty()) { //states.top()->FreeResources(); delete states.top(); states.pop(); } } bool Game::Update() { // if container have states game will updating if(!states.empty()) { //We are gonna to use timer from a lib, becouse in this version of c++ //chrono is not exist :) states.top()->Update(hge->Timer_GetDelta()); if(states.top()->CloseGame()) { QuitFromApplication(); return true; } if(states.top()->ToMainMenu()) { while(states.size() != 1) { delete states.top(); states.pop(); } return false; } if(states.top()->GetQuit()) { delete states.top(); states.pop(); } // Continue execution return false; } else { // By returning "true" we tell HGE // to stop running the application. return true; } } bool Game::Render() { // if container have states game will rendering if (!states.empty()) { hge->Gfx_BeginScene(); // Clear screen with black color hge->Gfx_Clear(0); states.top()->Render(); // End rendering and update the screen hge->Gfx_EndScene(); } // RenderFunc should always return false return false; } Game::~Game() { }
db5d9c847ff25108d3be531d685be1f9bf357a49
b013121b638169d43dfa04730ce6347b91169aaf
/cpu/reg.cpp
c769b5a92446d88a842b4c0c7afe56167cfc9881
[]
no_license
Ohyoukillkenny/riscv-simulator
709a238aee5cd309f9901ad203fa6dd28b86fd94
548f598723748bbcd07faf27bef0e949139366f8
refs/heads/master
2022-11-03T11:40:50.412069
2022-09-24T23:55:15
2022-09-24T23:55:15
157,607,761
8
8
null
null
null
null
UTF-8
C++
false
false
2,167
cpp
reg.cpp
// // Created by Lingkun Kong on 11/14/18. // #include <iostream> #include "reg.h" reg::reg() { for (int i = 0; i< 33; i++){ regs[i] = 0; } } uint32_t reg::get_reg(uint8_t addr){ if (addr > 32){ std::cout << "Reg: invalid register address" << std::endl; std::runtime_error("Reg: invalid address of register"); return 0; } return regs[addr]; } uint16_t reg::get_reg_high(uint8_t addr) { if (addr > 32){ std::cout << "Reg: invalid register address" << std::endl; std::runtime_error("Reg: invalid address of register"); return 0; } uint16_t res = regs[addr] >> 16; return res; } uint16_t reg::get_reg_low(uint8_t addr) { if (addr > 32){ std::cout << "Reg: invalid register address" << std::endl; std::runtime_error("Reg: invalid address of register"); return 0; } uint32_t res = regs[addr] & 0x0000ffff; return (uint16_t) res; } void reg::set_reg(uint8_t addr, uint32_t val) { if (addr > 32){ std::cout << "Reg: invalid register address" << std::endl; std::runtime_error("Reg: invalid address of register"); return; } if (addr == 0){ std::cout << "Reg Warning: you are trying to set x0" << std::endl; return; } regs[addr] = val; } void reg::set_reg_high(uint8_t addr, uint16_t val) { if (addr > 32){ std::cout << "Reg: invalid register address" << std::endl; std::runtime_error("Reg: invalid address of register"); return; } if (addr == 0){ std::cout << "Reg Warning: you are trying to set x0" << std::endl; return; } uint32_t mask = val << 16; regs[addr] = (regs[addr] & 0x0000ffff) | mask; } void reg::set_reg_low(uint8_t addr, uint16_t val) { if (addr > 32){ std::cout << "Reg: invalid register address" << std::endl; std::runtime_error("Reg: invalid address of register"); return; } if (addr == 0){ std::cout << "Reg Warning: you are trying to set x0" << std::endl; return; } regs[addr] = (regs[addr] & 0xffff0000) + val; }
aaa158498ce309287867b6605d9ac1c49051e8a5
9fd6a9c5ce4e8e2d6de08f375ca7afa8eefd7d7d
/HW7/AllCodesAndSolutions/socket_error_message.cpp
4502adfe62e9a8281739e17122d55daa1bb462d6
[]
no_license
dkStephanos/softwareDesignAssignments
4f6e8b9794f04ee3b0b0190de16b6c7535eeaeb4
ef1c6ca59b56fb35129695b32e8ae07f3e617c0d
refs/heads/master
2021-03-16T14:10:07.156612
2020-04-28T22:26:17
2020-04-28T22:26:17
246,914,857
0
0
null
null
null
null
UTF-8
C++
false
false
3,335
cpp
socket_error_message.cpp
// -------------------------socket_error_message.cpp ------------------------------------------ // // Author: Phil Pfeiffer // Date: August 1999 // Last modified: April 2020 // // Translate (WinSock's) socket API error codes into intelligible messages // // The error messages for the WinSock interface were developed from // the Winsock 1.1 standard, "Windows Sockets 1.1 Specification - Socket Library Reference" // (URL: http://www.winsock.com/wsresource/winsock1/ws_c.html). //---------------------------------------------------------------------------------------------- #include "socket_error_message.h" // ===================================================== // static class data // ===================================================== // *** for ensuring that supporting socket DLL is loaded and unloaded *** sockets_dll_init_class socket_error_message_class::dll_init_object_; // ===================================================== // constructors // ===================================================== //------------------------------------------------------------- // first form of constructor - // generate error message for user-supplied routine, // relative to global error variable //------------------------------------------------------------- // socket_error_message_class::socket_error_message_class(const string& caller_name, const long error_code) : error_message_(get_socket_error_message(error_code, caller_name)) { } //------------------------------------------------------------- // second form of constructor - copy constructor //------------------------------------------------------------- // socket_error_message_class::socket_error_message_class(const socket_error_message_class& source) : error_message_(source.error_message_) { } // ====================================== // assignment operator -- standard object copy // ====================================== // socket_error_message_class& socket_error_message_class::operator =(const socket_error_message_class& source) { error_message_ = source.error_message_; return *this; } // ====================================== // inspector // ====================================== //-------------------------------------------------------------- // get_message() - get object's error message //-------------------------------------------------------------- // string socket_error_message_class::get_message(void) const { return error_message_; } // ====================================== // facilitator // ====================================== //-------------------------------------------------------------- // insert() - insert error message into stream //-------------------------------------------------------------- // void socket_error_message_class::insert(ostream& os) const { os << error_message_; } // ==================================== // destructor // ==================================== // socket_error_message_class::~socket_error_message_class(void) { } // *===*====*===*====*===*====*===*====*===*====*===*====*===*====*===*==== // auxiliary operators [boilerplate] // *===*====*===*====*===*====*===*====*===*====*===*====*===*====*===*==== ostream& operator<<(ostream& os, const socket_error_message_class& ex) { ex.insert(os); return os; }
f6711eac1d532cb71322e2a895c8911c76d34f58
59e32ce927898a212fda136708f4475393817cf3
/lopez/lopez-src/hangar.cpp
c269e5a8bbcea5ef53f9698ca81fd01519b7a7d0
[]
no_license
romancardenas/CDPP_AdvancedRules-codename-Lopez
0f6524df51e2fdf8e430c40e773729a2d71c1bea
d777e50d4e63484de6aa07e5c8482a3a9d49eeb8
refs/heads/master
2022-03-25T02:57:12.406494
2019-11-21T21:17:36
2019-11-21T21:17:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,495
cpp
hangar.cpp
/** include files **/ #include <string> /** my include files **/ #include "modulo.h" // class modulo #include "message.h" // class ExternalMessage, InternalMessage #include "parsimu.h" // ParallelMainSimulator::Instance().getParameter( ... ) using namespace std; /** public functions **/ /******************************************************************* * Function Name: modulo * Description: ********************************************************************/ modulo::modulo( const string &name ) : Atomic( name ) , recibe_avion( this->addInputPort( "recibe_avion" ) ) , emergencia( this->addOutputPort( "emergencia" ) ) , sigue_avion( this->addOutputPort( "sigue_avion" ) ) , salida_hangar( this->addOutputPort( "salida_hangar" ) ) , en_uso( this->addOutputPort( "en_uso" ) ) { string time( ParallelMainSimulator::Instance().getParameter( this->description(), "preparation" ) ) ; if( time != "" ) preparationTime = time ; } /******************************************************************* * Function Name: initFunction * Precondition: El tiempo del proximo evento interno es ... ********************************************************************/ Model &modulo::initFunction() { avion_numero=0 ; velocidad=0 return *this ; } /******************************************************************* * Function Name: externalFunction * Description: ********************************************************************/ Model &modulo::externalFunction( const ExternalMessage &msg ) { if( msg.port() == recibe_avion ) { avion_numero = msg.value() ; velocidad = floor(msg.value()) ;//Toma su parte entera avion_numero = avion_numero - velocidad ; //El Id del vuelo queda en avion_numero this->holdIn( active, preparationTime ); } return *this; } /******************************************************************* * Function Name: internalFunction * Description: ********************************************************************/ Model &modulo::internalFunction( const InternalMessage & ) { this->passivate(); return *this ; } /******************************************************************* * Function Name: outputFunction * Description: ********************************************************************/ Model &modulo::outputFunction( const InternalMessage &msg ) { this->sendOutput( msg.time(), sigue_avion , (velocidad + avion_numero)) ; return *this ; }
87418b3f84fe054bc5e9620fd904bcf52cf1607a
e077b8d8856e5d1e54b6c3b738d759d9998a5a9d
/src/kernel/src/entry.cpp
9dd89305ec04e49def9338074fa0fc1d2f491cb2
[ "MIT" ]
permissive
Watch-Later/chino-os
ee7c16b678697261cc722b026af1563d2d319008
e4b444983a059231636b81dc5f33206e16a859c2
refs/heads/master
2022-10-17T05:11:42.210672
2020-06-15T02:47:59
2020-06-15T02:47:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,133
cpp
entry.cpp
// MIT License // // Copyright (c) 2020 SunnyCase // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include <chino/ddk/directory.h> #include <chino/ddk/kernel.h> #include <chino/ddk/object.h> #include <chino/io.h> #include <chino/threading/process.h> #include <chino/threading/scheduler.h> #include <ulog.h> #ifdef _MSC_VER #include <intrin.h> #endif using namespace chino; using namespace chino::threading; extern result<void, error_code> chino_start_shell(); void chino::panic(std::string_view message) noexcept { if (message.empty()) ULOG_CRITICAL("kernel panic!\n"); else ULOG_CRITICAL("%s\n", message.data()); #ifdef _MSC_VER __debugbreak(); #endif while (1) ; } result<void, error_code> kernel::kernel_main() { try_(kernel::logging_init()); try_(kernel_process_init()); current_sched().start(); // Should not reach here while (1) ; } uint32_t kernel::kernel_system_thread_main(void *arg) { kernel::io_manager_init().expect("IO system setup failed"); chino_start_shell().expect("Shell startup failed"); return 0; }
61edd3c0dfdaf1b319215cbc262df92a04773579
9a3f1a62fbdc3da3f01fc9feaeffd29aa481cea8
/examples/remoteSAM/remoteSAM.ino
07ecb7e551d485aebd12b3d81e0545026d9938d6
[]
no_license
usini/ESP8266SAM
a9bbc1ad43c084cb4093ee320ac08f34523f028d
fa88f9a612e3d03d85741e8e35bdd9bc83614863
refs/heads/master
2022-05-27T17:02:07.870819
2020-05-04T09:12:09
2020-05-04T09:12:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,855
ino
remoteSAM.ino
// In a webbrowser go to http://sam.local/say/{message} to make it speak // ex: http://sam.local/say/hello world #include <Arduino.h> #include <ESP8266SAM.h> #include "AudioOutputI2SNoDAC.h" #include <ESP8266mDNS.h> #include <ESP8266NetBIOS.h> #include <ESP8266SSDP.h> //Library for SSDP (Show ESP in Network on Windows) #include <ESP8266WebServer.h> //Library for WebServer #include <WiFiManager.h> #include <uri/UriBraces.h> AudioOutputI2SNoDAC *out = NULL; ESP8266WebServer server(80); //Web Server on port 80 WiFiManager wifiManager; const char* NAME = "SAM"; void setup() { Serial.begin(115200); out = new AudioOutputI2SNoDAC(); out->begin(); wifiManager.autoConnect(NAME); MDNS.begin(NAME); MDNS.addService("http", "tcp", 80); NBNS.begin(NAME); server.on(UriBraces("/say/{}"), []() { String message_encoded = server.pathArg(0); String message_decoded = urldecode(message_encoded); const char* message = message_decoded.c_str(); Serial.println(message_encoded); Serial.println(message_decoded); Serial.println(message); ESP8266SAM *sam = new ESP8266SAM; sam->Say(out, message); delete sam; server.send(200, "text/plain", "OK"); }); server.on("/description.xml", HTTP_GET, []() { SSDP.schema(server.client()); }); server.begin(); ssdp(); } void ssdp() { //Simple Service Discovery Protocol : Display ESP in Windows Network Tab SSDP.setSchemaURL("description.xml"); SSDP.setHTTPPort(80); SSDP.setName(NAME); SSDP.setDeviceType("upnp: rootdevice"); SSDP.setSerialNumber("000000000001"); SSDP.setURL("/say/connected"); SSDP.setModelName("ESP8266SAM"); SSDP.setModelNumber("0000000000001"); SSDP.setModelURL("https://github.com/earlephilhower/ESP8266SAM"); SSDP.setManufacturer("earlephilhower"); SSDP.setManufacturerURL("https://github.com/earlephilhower/"); SSDP.begin(); } void loop() { server.handleClient(); } char* string2char(String command) { if (command.length() != 0) { char *p = const_cast<char*>(command.c_str()); return p; } else { return ""; } } unsigned char h2int(char c) { if (c >= '0' && c <= '9') { return ((unsigned char)c - '0'); } if (c >= 'a' && c <= 'f') { return ((unsigned char)c - 'a' + 10); } if (c >= 'A' && c <= 'F') { return ((unsigned char)c - 'A' + 10); } return (0); } String urldecode(String str) { String encodedString = ""; char c; char code0; char code1; for (int i = 0; i < str.length(); i++) { c = str.charAt(i); if (c == '+') { encodedString += ' '; } else if (c == '%') { i++; code0 = str.charAt(i); i++; code1 = str.charAt(i); c = (h2int(code0) << 4) | h2int(code1); encodedString += c; } else { encodedString += c; } yield(); } return encodedString; }
c99a9bc8faf3ea51e06259c2ad6879597d3586e4
3d144a23e67c839a4df1c073c6a2c842508f16b2
/lib/Sema/TypeCheckMacros.cpp
40e6b7ba9141c776d5fd1633461e6e017d008ab9
[ "Apache-2.0", "Swift-exception" ]
permissive
apple/swift
c2724e388959f6623cf6e4ad6dc1cdd875fd0592
98ada1b200a43d090311b72eb45fe8ecebc97f81
refs/heads/main
2023-08-16T10:48:25.985330
2023-08-16T09:00:42
2023-08-16T09:00:42
44,838,949
78,897
15,074
Apache-2.0
2023-09-14T21:19:23
2015-10-23T21:15:07
C++
UTF-8
C++
false
false
66,055
cpp
TypeCheckMacros.cpp
//===--- TypeCheckMacros.cpp - Macro Handling ----------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file implements support for the evaluation of macros. // //===----------------------------------------------------------------------===// #include "TypeCheckMacros.h" #include "../AST/InlinableText.h" #include "TypeChecker.h" #include "TypeCheckType.h" #include "swift/ABI/MetadataValues.h" #include "swift/AST/ASTContext.h" #include "swift/AST/ASTMangler.h" #include "swift/AST/ASTNode.h" #include "swift/AST/CASTBridging.h" #include "swift/AST/DiagnosticsFrontend.h" #include "swift/AST/Expr.h" #include "swift/AST/FreestandingMacroExpansion.h" #include "swift/AST/MacroDefinition.h" #include "swift/AST/NameLookupRequests.h" #include "swift/AST/PluginLoader.h" #include "swift/AST/PluginRegistry.h" #include "swift/AST/PrettyStackTrace.h" #include "swift/AST/SourceFile.h" #include "swift/AST/TypeCheckRequests.h" #include "swift/Basic/Defer.h" #include "swift/Basic/Lazy.h" #include "swift/Basic/SourceManager.h" #include "swift/Basic/StringExtras.h" #include "swift/Demangling/Demangler.h" #include "swift/Demangling/ManglingMacros.h" #include "swift/Parse/Lexer.h" #include "swift/Sema/IDETypeChecking.h" #include "swift/Subsystems.h" #include "llvm/Config/config.h" using namespace swift; extern "C" void *swift_ASTGen_resolveMacroType(const void *macroType); extern "C" void swift_ASTGen_destroyMacro(void *macro); extern "C" void *swift_ASTGen_resolveExecutableMacro( const char *moduleName, ptrdiff_t moduleNameLength, const char *typeName, ptrdiff_t typeNameLength, void * opaquePluginHandle); extern "C" void swift_ASTGen_destroyExecutableMacro(void *macro); extern "C" ptrdiff_t swift_ASTGen_checkMacroDefinition( void *diagEngine, void *sourceFile, const void *macroSourceLocation, char **expansionSourcePtr, ptrdiff_t *expansionSourceLength, ptrdiff_t **replacementsPtr, ptrdiff_t *numReplacements ); extern "C" ptrdiff_t swift_ASTGen_expandFreestandingMacro( void *diagEngine, void *macro, uint8_t externalKind, const char *discriminator, ptrdiff_t discriminatorLength, uint8_t rawMacroRole, void *sourceFile, const void *sourceLocation, const char **evaluatedSource, ptrdiff_t *evaluatedSourceLength); extern "C" ptrdiff_t swift_ASTGen_expandAttachedMacro( void *diagEngine, void *macro, uint8_t externalKind, const char *discriminator, ptrdiff_t discriminatorLength, const char *qualifiedType, ptrdiff_t qualifiedTypeLength, const char *conformances, ptrdiff_t conformancesLength, uint8_t rawMacroRole, void *customAttrSourceFile, const void *customAttrSourceLocation, void *declarationSourceFile, const void *declarationSourceLocation, void *parentDeclSourceFile, const void *parentDeclSourceLocation, const char **evaluatedSource, ptrdiff_t *evaluatedSourceLength); extern "C" bool swift_ASTGen_initializePlugin(void *handle, void *diagEngine); extern "C" void swift_ASTGen_deinitializePlugin(void *handle); extern "C" bool swift_ASTGen_pluginServerLoadLibraryPlugin( void *handle, const char *libraryPath, const char *moduleName, void *diagEngine); #if SWIFT_SWIFT_PARSER /// Look for macro's type metadata given its external module and type name. static void const * lookupMacroTypeMetadataByExternalName(ASTContext &ctx, StringRef moduleName, StringRef typeName, LoadedLibraryPlugin *plugin) { // Look up the type metadata accessor as a struct, enum, or class. const Demangle::Node::Kind typeKinds[] = { Demangle::Node::Kind::Structure, Demangle::Node::Kind::Enum, Demangle::Node::Kind::Class }; void *accessorAddr = nullptr; for (auto typeKind : typeKinds) { auto symbolName = Demangle::mangledNameForTypeMetadataAccessor( moduleName, typeName, typeKind); accessorAddr = plugin->getAddressOfSymbol(symbolName.c_str()); if (accessorAddr) break; } if (!accessorAddr) return nullptr; // Call the accessor to form type metadata. using MetadataAccessFunc = const void *(MetadataRequest); auto accessor = reinterpret_cast<MetadataAccessFunc*>(accessorAddr); return accessor(MetadataRequest(MetadataState::Complete)); } #endif /// Translate an argument provided as a string literal into an identifier, /// or return \c None and emit an error if it cannot be done. llvm::Optional<Identifier> getIdentifierFromStringLiteralArgument( ASTContext &ctx, MacroExpansionExpr *expansion, unsigned index) { auto argList = expansion->getArgs(); // If there's no argument here, an error was diagnosed elsewhere. if (!argList || index >= argList->size()) { return llvm::None; } auto arg = argList->getExpr(index); auto stringLiteral = dyn_cast<StringLiteralExpr>(arg); if (!stringLiteral) { ctx.Diags.diagnose( arg->getLoc(), diag::external_macro_arg_not_type_name, index ); return llvm::None; } auto contents = stringLiteral->getValue(); if (!Lexer::isIdentifier(contents)) { ctx.Diags.diagnose( arg->getLoc(), diag::external_macro_arg_not_type_name, index ); return llvm::None; } return ctx.getIdentifier(contents); } /// For a macro expansion expression that is known to be #externalMacro, /// handle the definition. static MacroDefinition handleExternalMacroDefinition( ASTContext &ctx, MacroExpansionExpr *expansion) { // Dig out the module and type name. auto moduleName = getIdentifierFromStringLiteralArgument(ctx, expansion, 0); if (!moduleName) { return MacroDefinition::forInvalid(); } auto typeName = getIdentifierFromStringLiteralArgument(ctx, expansion, 1); if (!typeName) { return MacroDefinition::forInvalid(); } return MacroDefinition::forExternal(*moduleName, *typeName); } MacroDefinition MacroDefinitionRequest::evaluate( Evaluator &evaluator, MacroDecl *macro ) const { ASTContext &ctx = macro->getASTContext(); // If no definition was provided, the macro is... undefined, of course. auto definition = macro->definition; if (!definition) return MacroDefinition::forUndefined(); auto sourceFile = macro->getParentSourceFile(); #if SWIFT_SWIFT_PARSER char *externalMacroNamePtr; ptrdiff_t externalMacroNameLength; ptrdiff_t *replacements; ptrdiff_t numReplacements; auto checkResult = swift_ASTGen_checkMacroDefinition( &ctx.Diags, sourceFile->getExportedSourceFile(), macro->getLoc().getOpaquePointerValue(), &externalMacroNamePtr, &externalMacroNameLength, &replacements, &numReplacements); // Clean up after the call. SWIFT_DEFER { free(externalMacroNamePtr); free(replacements); }; if (checkResult < 0 && ctx.CompletionCallback) { // If the macro failed to check and we are in code completion mode, pretend // it's an arbitrary macro. This allows us to get call argument completions // inside `#externalMacro`. checkResult = BridgedMacroDefinitionKind::BridgedExpandedMacro; } if (checkResult < 0) return MacroDefinition::forInvalid(); switch (static_cast<BridgedMacroDefinitionKind>(checkResult)) { case BridgedExpandedMacro: // Handle expanded macros below. break; case BridgedExternalMacro: { // An external macro described as ModuleName.TypeName. Get both identifiers. assert(!replacements && "External macro doesn't have replacements"); StringRef externalMacroStr(externalMacroNamePtr, externalMacroNameLength); StringRef externalModuleName, externalTypeName; std::tie(externalModuleName, externalTypeName) = externalMacroStr.split('.'); Identifier moduleName = ctx.getIdentifier(externalModuleName); Identifier typeName = ctx.getIdentifier(externalTypeName); return MacroDefinition::forExternal(moduleName, typeName); } case BridgedBuiltinExternalMacro: return MacroDefinition::forBuiltin(BuiltinMacroKind::ExternalMacro); } // Type-check the macro expansion. Type resultType = macro->mapTypeIntoContext(macro->getResultInterfaceType()); constraints::ContextualTypeInfo contextualType { TypeLoc::withoutLoc(resultType), // FIXME: Add a contextual type purpose for macro definition checking. ContextualTypePurpose::CTP_CoerceOperand }; PrettyStackTraceDecl debugStack("type checking macro definition", macro); Type typeCheckedType = TypeChecker::typeCheckExpression( definition, macro, contextualType, TypeCheckExprFlags::DisableMacroExpansions); if (!typeCheckedType) return MacroDefinition::forInvalid(); // Dig out the macro that was expanded. auto expansion = cast<MacroExpansionExpr>(definition); auto expandedMacro = dyn_cast_or_null<MacroDecl>(expansion->getMacroRef().getDecl()); if (!expandedMacro) return MacroDefinition::forInvalid(); // Handle external macros after type-checking. auto builtinKind = expandedMacro->getBuiltinKind(); if (builtinKind == BuiltinMacroKind::ExternalMacro) return handleExternalMacroDefinition(ctx, expansion); // Expansion string text. StringRef expansionText(externalMacroNamePtr, externalMacroNameLength); // Copy over the replacements. SmallVector<ExpandedMacroReplacement, 2> replacementsVec; for (unsigned i: range(0, numReplacements)) { replacementsVec.push_back( { static_cast<unsigned>(replacements[3*i]), static_cast<unsigned>(replacements[3*i+1]), static_cast<unsigned>(replacements[3*i+2])}); } return MacroDefinition::forExpanded(ctx, expansionText, replacementsVec); #else macro->diagnose(diag::macro_unsupported); return MacroDefinition::forInvalid(); #endif } static LoadedExecutablePlugin * initializeExecutablePlugin(ASTContext &ctx, LoadedExecutablePlugin *executablePlugin, StringRef libraryPath, Identifier moduleName) { // Lock the plugin while initializing. // Note that'executablePlugn' can be shared between multiple ASTContext. executablePlugin->lock(); SWIFT_DEFER { executablePlugin->unlock(); }; // FIXME: Ideally this should be done right after invoking the plugin. // But plugin loading is in libAST and it can't link ASTGen symbols. if (!executablePlugin->isInitialized()) { #if SWIFT_SWIFT_PARSER if (!swift_ASTGen_initializePlugin(executablePlugin, &ctx.Diags)) { return nullptr; } // Resend the compiler capability on reconnect. auto *callback = new std::function<void(void)>( [executablePlugin]() { (void)swift_ASTGen_initializePlugin( executablePlugin, /*diags=*/nullptr); }); executablePlugin->addOnReconnect(callback); executablePlugin->setCleanup([executablePlugin] { swift_ASTGen_deinitializePlugin(executablePlugin); }); #endif } // If this is a plugin server, load the library. if (!libraryPath.empty()) { #if SWIFT_SWIFT_PARSER llvm::SmallString<128> resolvedLibraryPath; auto fs = ctx.SourceMgr.getFileSystem(); if (auto err = fs->getRealPath(libraryPath, resolvedLibraryPath)) { ctx.Diags.diagnose(SourceLoc(), diag::compiler_plugin_not_loaded, executablePlugin->getExecutablePath(), err.message()); return nullptr; } std::string resolvedLibraryPathStr(resolvedLibraryPath); std::string moduleNameStr(moduleName.str()); bool loaded = swift_ASTGen_pluginServerLoadLibraryPlugin( executablePlugin, resolvedLibraryPathStr.c_str(), moduleNameStr.c_str(), &ctx.Diags); if (!loaded) return nullptr; // Set a callback to load the library again on reconnections. auto *callback = new std::function<void(void)>( [executablePlugin, resolvedLibraryPathStr, moduleNameStr]() { (void)swift_ASTGen_pluginServerLoadLibraryPlugin( executablePlugin, resolvedLibraryPathStr.c_str(), moduleNameStr.c_str(), /*diags=*/nullptr); }); executablePlugin->addOnReconnect(callback); // Remove the callback and deallocate it when this ASTContext is destructed. ctx.addCleanup([executablePlugin, callback]() { executablePlugin->removeOnReconnect(callback); delete callback; }); #endif } return executablePlugin; } LoadedCompilerPlugin CompilerPluginLoadRequest::evaluate(Evaluator &evaluator, ASTContext *ctx, Identifier moduleName) const { PluginLoader &loader = ctx->getPluginLoader(); const auto &entry = loader.lookupPluginByModuleName(moduleName); if (!entry.executablePath.empty()) { if (LoadedExecutablePlugin *executablePlugin = loader.loadExecutablePlugin(entry.executablePath)) { return initializeExecutablePlugin(*ctx, executablePlugin, entry.libraryPath, moduleName); } } else if (!entry.libraryPath.empty()) { if (LoadedLibraryPlugin *libraryPlugin = loader.loadLibraryPlugin(entry.libraryPath)) { return libraryPlugin; } } return nullptr; } static llvm::Optional<ExternalMacroDefinition> resolveInProcessMacro(ASTContext &ctx, Identifier moduleName, Identifier typeName, LoadedLibraryPlugin *plugin) { #if SWIFT_SWIFT_PARSER /// Look for the type metadata given the external module and type names. auto macroMetatype = lookupMacroTypeMetadataByExternalName( ctx, moduleName.str(), typeName.str(), plugin); if (macroMetatype) { // Check whether the macro metatype is in-process. if (auto inProcess = swift_ASTGen_resolveMacroType(macroMetatype)) { // Make sure we clean up after the macro. ctx.addCleanup([inProcess]() { swift_ASTGen_destroyMacro(inProcess); }); return ExternalMacroDefinition{ ExternalMacroDefinition::PluginKind::InProcess, inProcess}; } } #endif return llvm::None; } static llvm::Optional<ExternalMacroDefinition> resolveExecutableMacro(ASTContext &ctx, LoadedExecutablePlugin *executablePlugin, Identifier moduleName, Identifier typeName) { #if SWIFT_SWIFT_PARSER if (auto *execMacro = swift_ASTGen_resolveExecutableMacro( moduleName.str().data(), moduleName.str().size(), typeName.str().data(), typeName.str().size(), executablePlugin)) { // Make sure we clean up after the macro. ctx.addCleanup( [execMacro]() { swift_ASTGen_destroyExecutableMacro(execMacro); }); return ExternalMacroDefinition{ ExternalMacroDefinition::PluginKind::Executable, execMacro}; } #endif return llvm::None; } llvm::Optional<ExternalMacroDefinition> ExternalMacroDefinitionRequest::evaluate(Evaluator &evaluator, ASTContext *ctx, Identifier moduleName, Identifier typeName) const { // Try to load a plugin module from the plugin search paths. If it // succeeds, resolve in-process from that plugin CompilerPluginLoadRequest loadRequest{ctx, moduleName}; LoadedCompilerPlugin loaded = evaluateOrDefault(evaluator, loadRequest, nullptr); if (auto loadedLibrary = loaded.getAsLibraryPlugin()) { if (auto inProcess = resolveInProcessMacro( *ctx, moduleName, typeName, loadedLibrary)) return *inProcess; } if (auto *executablePlugin = loaded.getAsExecutablePlugin()) { if (auto executableMacro = resolveExecutableMacro(*ctx, executablePlugin, moduleName, typeName)) { return executableMacro; } } return llvm::None; } /// Adjust the given mangled name for a macro expansion to produce a valid /// buffer name. static std::string adjustMacroExpansionBufferName(StringRef name) { if (name.empty()) { return "<macro-expansion>"; } std::string result; if (name.startswith(MANGLING_PREFIX_STR)) { result += MACRO_EXPANSION_BUFFER_MANGLING_PREFIX; name = name.drop_front(StringRef(MANGLING_PREFIX_STR).size()); } result += name; result += ".swift"; return result; } llvm::Optional<unsigned> ExpandMacroExpansionExprRequest::evaluate(Evaluator &evaluator, MacroExpansionExpr *mee) const { ConcreteDeclRef macroRef = mee->getMacroRef(); assert(macroRef && isa<MacroDecl>(macroRef.getDecl()) && "MacroRef should be set before expansion"); auto *macro = cast<MacroDecl>(macroRef.getDecl()); if (macro->getMacroRoles().contains(MacroRole::Expression)) { return expandMacroExpr(mee); } // For a non-expression macro, expand it as a declaration. else if (macro->getMacroRoles().contains(MacroRole::Declaration) || macro->getMacroRoles().contains(MacroRole::CodeItem)) { if (!mee->getSubstituteDecl()) { (void)mee->createSubstituteDecl(); } // Return the expanded buffer ID. return evaluateOrDefault( evaluator, ExpandMacroExpansionDeclRequest(mee->getSubstituteDecl()), llvm::None); } // Other macro roles may also be encountered here, as they use // `MacroExpansionExpr` for resolution. In those cases, do not expand. return llvm::None; } ArrayRef<unsigned> ExpandMemberAttributeMacros::evaluate(Evaluator &evaluator, Decl *decl) const { if (decl->isImplicit()) return { }; // Member attribute macros do not apply to macro-expanded members. if (decl->isInMacroExpansionInContext()) return { }; auto *parentDecl = decl->getDeclContext()->getAsDecl(); if (!parentDecl || !isa<IterableDeclContext>(parentDecl)) return { }; if (isa<PatternBindingDecl>(decl)) return { }; SmallVector<unsigned, 2> bufferIDs; parentDecl->forEachAttachedMacro(MacroRole::MemberAttribute, [&](CustomAttr *attr, MacroDecl *macro) { if (auto bufferID = expandAttributes(attr, macro, decl)) bufferIDs.push_back(*bufferID); }); return parentDecl->getASTContext().AllocateCopy(bufferIDs); } ArrayRef<unsigned> ExpandSynthesizedMemberMacroRequest::evaluate( Evaluator &evaluator, Decl *decl ) const { SmallVector<unsigned, 2> bufferIDs; decl->forEachAttachedMacro(MacroRole::Member, [&](CustomAttr *attr, MacroDecl *macro) { if (auto bufferID = expandMembers(attr, macro, decl)) bufferIDs.push_back(*bufferID); }); return decl->getASTContext().AllocateCopy(bufferIDs); } ArrayRef<unsigned> ExpandPeerMacroRequest::evaluate(Evaluator &evaluator, Decl *decl) const { SmallVector<unsigned, 2> bufferIDs; decl->forEachAttachedMacro(MacroRole::Peer, [&](CustomAttr *attr, MacroDecl *macro) { if (auto bufferID = expandPeers(attr, macro, decl)) bufferIDs.push_back(*bufferID); }); return decl->getASTContext().AllocateCopy(bufferIDs); } static Identifier makeIdentifier(ASTContext &ctx, StringRef name) { return ctx.getIdentifier(name); } static Identifier makeIdentifier(ASTContext &ctx, std::nullptr_t) { return Identifier(); } bool swift::isInvalidAttachedMacro(MacroRole role, Decl *attachedTo) { switch (role) { case MacroRole::Expression: case MacroRole::Declaration: case MacroRole::CodeItem: llvm_unreachable("Invalid macro role for attached macro"); case MacroRole::Accessor: // Only var decls and subscripts have accessors. if (isa<AbstractStorageDecl>(attachedTo) && !isa<ParamDecl>(attachedTo)) return false; break; case MacroRole::MemberAttribute: case MacroRole::Member: // Nominal types and extensions can have members. if (isa<NominalTypeDecl>(attachedTo) || isa<ExtensionDecl>(attachedTo)) return false; break; case MacroRole::Peer: // Peer macros are allowed on everything except parameters. if (!isa<ParamDecl>(attachedTo)) return false; break; case MacroRole::Conformance: case MacroRole::Extension: // Only primary declarations of nominal types if (isa<NominalTypeDecl>(attachedTo)) return false; break; } return true; } static void diagnoseInvalidDecl(Decl *decl, MacroDecl *macro, llvm::function_ref<bool(DeclName)> coversName) { auto &ctx = decl->getASTContext(); // Diagnose invalid declaration kinds. if (isa<ImportDecl>(decl) || isa<OperatorDecl>(decl) || isa<PrecedenceGroupDecl>(decl) || isa<MacroDecl>(decl) || isa<ExtensionDecl>(decl)) { decl->diagnose(diag::invalid_decl_in_macro_expansion, decl->getDescriptiveKind()); decl->setInvalid(); if (auto *extension = dyn_cast<ExtensionDecl>(decl)) { extension->setExtendedNominal(nullptr); } return; } // Diagnose `@main` types. if (auto *mainAttr = decl->getAttrs().getAttribute<MainTypeAttr>()) { ctx.Diags.diagnose(mainAttr->getLocation(), diag::invalid_main_type_in_macro_expansion); mainAttr->setInvalid(); } // Diagnose default literal type overrides. if (auto *typeAlias = dyn_cast<TypeAliasDecl>(decl)) { auto name = typeAlias->getBaseIdentifier(); #define EXPRESSIBLE_BY_LITERAL_PROTOCOL_WITH_NAME(_, __, typeName, \ supportsOverride) \ if (supportsOverride && name == makeIdentifier(ctx, typeName)) { \ typeAlias->diagnose(diag::literal_type_in_macro_expansion, \ makeIdentifier(ctx, typeName)); \ typeAlias->setInvalid(); \ return; \ } #include "swift/AST/KnownProtocols.def" #undef EXPRESSIBLE_BY_LITERAL_PROTOCOL_WITH_NAME } // Diagnose value decls with names not covered by the macro if (auto *value = dyn_cast<ValueDecl>(decl)) { auto name = value->getName(); // Unique names are always permitted. if (MacroDecl::isUniqueMacroName(name.getBaseName().userFacingName())) return; if (coversName(name)) { return; } value->diagnose(diag::invalid_macro_introduced_name, name, macro->getBaseName()); } } /// Diagnose macro expansions that produce any of the following declarations: /// - Import declarations /// - Operator and precedence group declarations /// - Macro declarations /// - Extensions /// - Types with `@main` attributes /// - Top-level default literal type overrides /// - Value decls with names not covered by the macro declaration. static void validateMacroExpansion(SourceFile *expansionBuffer, MacroDecl *macro, ValueDecl *attachedTo, MacroRole role) { // Gather macro-introduced names llvm::SmallVector<DeclName, 2> introducedNames; macro->getIntroducedNames(role, attachedTo, introducedNames); llvm::SmallDenseSet<DeclName, 2> introducedNameSet( introducedNames.begin(), introducedNames.end()); auto coversName = [&](DeclName name) -> bool { return (introducedNameSet.count(name) || introducedNameSet.count(name.getBaseName()) || introducedNameSet.count(MacroDecl::getArbitraryName())); }; for (auto *decl : expansionBuffer->getTopLevelDecls()) { // Certain macro roles can generate special declarations. if ((isa<AccessorDecl>(decl) && role == MacroRole::Accessor) || (isa<ExtensionDecl>(decl) && role == MacroRole::Conformance)) { continue; } if (role == MacroRole::Extension) { auto *extension = dyn_cast<ExtensionDecl>(decl); for (auto *member : extension->getMembers()) { diagnoseInvalidDecl(member, macro, coversName); } continue; } diagnoseInvalidDecl(decl, macro, coversName); } } /// Determine whether the given source file is from an expansion of the given /// macro. static bool isFromExpansionOfMacro(SourceFile *sourceFile, MacroDecl *macro, MacroRole role) { while (sourceFile) { auto expansion = sourceFile->getMacroExpansion(); if (!expansion) return false; if (auto expansionExpr = dyn_cast_or_null<MacroExpansionExpr>( expansion.dyn_cast<Expr *>())) { if (expansionExpr->getMacroRef().getDecl() == macro) return true; } else if (auto expansionDecl = dyn_cast_or_null<MacroExpansionDecl>( expansion.dyn_cast<Decl *>())) { if (expansionDecl->getMacroRef().getDecl() == macro) return true; } else if (auto *macroAttr = sourceFile->getAttachedMacroAttribute()) { auto *decl = expansion.dyn_cast<Decl *>(); auto *macroDecl = decl->getResolvedMacro(macroAttr); if (!macroDecl) return false; return macroDecl == macro && sourceFile->getFulfilledMacroRole() == role; } else { llvm_unreachable("Unknown macro expansion node kind"); } sourceFile = sourceFile->getEnclosingSourceFile(); } return false; } /// Expand a macro definition. static std::string expandMacroDefinition( ExpandedMacroDefinition def, MacroDecl *macro, ArgumentList *args) { ASTContext &ctx = macro->getASTContext(); std::string expandedResult; StringRef originalText = def.getExpansionText(); unsigned startIdx = 0; for (const auto replacement: def.getReplacements()) { // Add the original text up to the first replacement. expandedResult.append( originalText.begin() + startIdx, originalText.begin() + replacement.startOffset); // Add the replacement text. auto argExpr = args->getArgExprs()[replacement.parameterIndex]; SmallString<32> argTextBuffer; auto argText = extractInlinableText(ctx.SourceMgr, argExpr, argTextBuffer); expandedResult.append(argText); // Update the starting position. startIdx = replacement.endOffset; } // Add the remaining text. expandedResult.append( originalText.begin() + startIdx, originalText.end()); return expandedResult; } static GeneratedSourceInfo::Kind getGeneratedSourceInfoKind(MacroRole role) { switch (role) { case MacroRole::Expression: return GeneratedSourceInfo::ExpressionMacroExpansion; case MacroRole::Declaration: case MacroRole::CodeItem: return GeneratedSourceInfo::FreestandingDeclMacroExpansion; case MacroRole::Accessor: return GeneratedSourceInfo::AccessorMacroExpansion; case MacroRole::MemberAttribute: return GeneratedSourceInfo::MemberAttributeMacroExpansion; case MacroRole::Member: return GeneratedSourceInfo::MemberMacroExpansion; case MacroRole::Peer: return GeneratedSourceInfo::PeerMacroExpansion; case MacroRole::Conformance: return GeneratedSourceInfo::ConformanceMacroExpansion; case MacroRole::Extension: return GeneratedSourceInfo::ExtensionMacroExpansion; } llvm_unreachable("unhandled MacroRole"); } // If this storage declaration is a variable with an explicit initializer, // return the range from the `=` to the end of the explicit initializer. static llvm::Optional<SourceRange> getExplicitInitializerRange(AbstractStorageDecl *storage) { auto var = dyn_cast<VarDecl>(storage); if (!var) return llvm::None; auto pattern = var->getParentPatternBinding(); if (!pattern) return llvm::None; unsigned index = pattern->getPatternEntryIndexForVarDecl(var); SourceLoc equalLoc = pattern->getEqualLoc(index); SourceRange initRange = pattern->getOriginalInitRange(index); if (equalLoc.isInvalid() || initRange.End.isInvalid()) return llvm::None; return SourceRange(equalLoc, initRange.End); } static CharSourceRange getExpansionInsertionRange(MacroRole role, ASTNode target, SourceManager &sourceMgr) { switch (role) { case MacroRole::Accessor: { auto storage = cast<AbstractStorageDecl>(target.get<Decl *>()); auto bracesRange = storage->getBracesRange(); // Compute the location where the accessors will be added. if (bracesRange.Start.isValid()) { // We have braces already, so insert them inside the leading '{'. return CharSourceRange( Lexer::getLocForEndOfToken(sourceMgr, bracesRange.Start), 0); } else if (auto initRange = getExplicitInitializerRange(storage)) { // The accessor had an initializer, so the initializer (including // the `=`) is replaced by the accessors. return Lexer::getCharSourceRangeFromSourceRange(sourceMgr, *initRange); } else { // The accessors go at the end. SourceLoc endLoc = storage->getEndLoc(); if (auto var = dyn_cast<VarDecl>(storage)) { if (auto pattern = var->getParentPattern()) endLoc = pattern->getEndLoc(); } return CharSourceRange(Lexer::getLocForEndOfToken(sourceMgr, endLoc), 0); } } case MacroRole::MemberAttribute: { SourceLoc startLoc; if (auto valueDecl = dyn_cast<ValueDecl>(target.get<Decl *>())) startLoc = valueDecl->getAttributeInsertionLoc(/*forModifier=*/false); else startLoc = target.getStartLoc(); return CharSourceRange(startLoc, 0); } case MacroRole::Member: { // Semantically, we insert members right before the closing brace. SourceLoc rightBraceLoc; if (auto nominal = dyn_cast<NominalTypeDecl>(target.get<Decl *>())) { rightBraceLoc = nominal->getBraces().End; } else { auto ext = cast<ExtensionDecl>(target.get<Decl *>()); rightBraceLoc = ext->getBraces().End; } return CharSourceRange(rightBraceLoc, 0); } case MacroRole::Peer: { SourceLoc afterDeclLoc = Lexer::getLocForEndOfToken(sourceMgr, target.getEndLoc()); return CharSourceRange(afterDeclLoc, 0); break; } case MacroRole::Conformance: { SourceLoc afterDeclLoc = Lexer::getLocForEndOfToken(sourceMgr, target.getEndLoc()); return CharSourceRange(afterDeclLoc, 0); } case MacroRole::Extension: { SourceLoc afterDeclLoc = Lexer::getLocForEndOfToken(sourceMgr, target.getEndLoc()); return CharSourceRange(afterDeclLoc, 0); } case MacroRole::Expression: case MacroRole::Declaration: case MacroRole::CodeItem: return Lexer::getCharSourceRangeFromSourceRange(sourceMgr, target.getSourceRange()); } llvm_unreachable("unhandled MacroRole"); } static SourceFile * createMacroSourceFile(std::unique_ptr<llvm::MemoryBuffer> buffer, MacroRole role, ASTNode target, DeclContext *dc, CustomAttr *attr) { ASTContext &ctx = dc->getASTContext(); SourceManager &sourceMgr = ctx.SourceMgr; // Dump macro expansions to standard output, if requested. if (ctx.LangOpts.DumpMacroExpansions) { llvm::errs() << buffer->getBufferIdentifier() << "\n------------------------------\n" << buffer->getBuffer() << "\n------------------------------\n"; } CharSourceRange generatedOriginalSourceRange = getExpansionInsertionRange(role, target, sourceMgr); GeneratedSourceInfo::Kind generatedSourceKind = getGeneratedSourceInfoKind(role); // Create a new source buffer with the contents of the expanded macro. unsigned macroBufferID = sourceMgr.addNewSourceBuffer(std::move(buffer)); auto macroBufferRange = sourceMgr.getRangeForBuffer(macroBufferID); GeneratedSourceInfo sourceInfo{generatedSourceKind, generatedOriginalSourceRange, macroBufferRange, target.getOpaqueValue(), dc, attr}; sourceMgr.setGeneratedSourceInfo(macroBufferID, sourceInfo); // Create a source file to hold the macro buffer. This is automatically // registered with the enclosing module. auto macroSourceFile = new (ctx) SourceFile( *dc->getParentModule(), SourceFileKind::MacroExpansion, macroBufferID, /*parsingOpts=*/{}, /*isPrimary=*/false); macroSourceFile->setImports(dc->getParentSourceFile()->getImports()); return macroSourceFile; } static uint8_t getRawMacroRole(MacroRole role) { switch (role) { case MacroRole::Expression: return 0; case MacroRole::Declaration: return 1; case MacroRole::Accessor: return 2; case MacroRole::MemberAttribute: return 3; case MacroRole::Member: return 4; case MacroRole::Peer: return 5; case MacroRole::CodeItem: return 7; // Use the same raw macro role for conformance and extension // in ASTGen. case MacroRole::Conformance: case MacroRole::Extension: return 8; } } /// Evaluate the given freestanding macro expansion. static SourceFile * evaluateFreestandingMacro(FreestandingMacroExpansion *expansion, StringRef discriminatorStr = "") { auto *dc = expansion->getDeclContext(); ASTContext &ctx = dc->getASTContext(); SourceLoc loc = expansion->getPoundLoc(); auto moduleDecl = dc->getParentModule(); auto sourceFile = moduleDecl->getSourceFileContainingLocation(loc); if (!sourceFile) return nullptr; MacroDecl *macro = cast<MacroDecl>(expansion->getMacroRef().getDecl()); auto macroRoles = macro->getMacroRoles(); assert(macroRoles.contains(MacroRole::Expression) || macroRoles.contains(MacroRole::Declaration) || macroRoles.contains(MacroRole::CodeItem)); if (isFromExpansionOfMacro(sourceFile, macro, MacroRole::Expression) || isFromExpansionOfMacro(sourceFile, macro, MacroRole::Declaration) || isFromExpansionOfMacro(sourceFile, macro, MacroRole::CodeItem)) { ctx.Diags.diagnose(loc, diag::macro_recursive, macro->getName()); return nullptr; } // Evaluate the macro. std::unique_ptr<llvm::MemoryBuffer> evaluatedSource; /// The discriminator used for the macro. LazyValue<std::string> discriminator([&]() -> std::string { if (!discriminatorStr.empty()) return discriminatorStr.str(); #if SWIFT_SWIFT_PARSER Mangle::ASTMangler mangler; return mangler.mangleMacroExpansion(expansion); #else return ""; #endif }); // Only one freestanding macro role is permitted, so look at the roles to // figure out which one to use. MacroRole macroRole = macroRoles.contains(MacroRole::Expression) ? MacroRole::Expression : macroRoles.contains(MacroRole::Declaration) ? MacroRole::Declaration : MacroRole::CodeItem; auto macroDef = macro->getDefinition(); switch (macroDef.kind) { case MacroDefinition::Kind::Undefined: case MacroDefinition::Kind::Invalid: // Already diagnosed as an error elsewhere. return nullptr; case MacroDefinition::Kind::Builtin: { switch (macroDef.getBuiltinKind()) { case BuiltinMacroKind::ExternalMacro: ctx.Diags.diagnose(loc, diag::external_macro_outside_macro_definition); return nullptr; } } case MacroDefinition::Kind::Expanded: { // Expand the definition with the given arguments. auto result = expandMacroDefinition(macroDef.getExpanded(), macro, expansion->getArgs()); evaluatedSource = llvm::MemoryBuffer::getMemBufferCopy( result, adjustMacroExpansionBufferName(*discriminator)); break; } case MacroDefinition::Kind::External: { // Retrieve the external definition of the macro. auto external = macroDef.getExternalMacro(); ExternalMacroDefinitionRequest request{&ctx, external.moduleName, external.macroTypeName}; auto externalDef = evaluateOrDefault(ctx.evaluator, request, llvm::None); if (!externalDef) { ctx.Diags.diagnose(loc, diag::external_macro_not_found, external.moduleName.str(), external.macroTypeName.str(), macro->getName()); macro->diagnose(diag::decl_declared_here, macro); return nullptr; } // Code item macros require `CodeItemMacros` feature flag. if (macroRoles.contains(MacroRole::CodeItem) && !ctx.LangOpts.hasFeature(Feature::CodeItemMacros)) { ctx.Diags.diagnose(loc, diag::macro_experimental, "code item", "CodeItemMacros"); return nullptr; } #if SWIFT_SWIFT_PARSER PrettyStackTraceFreestandingMacroExpansion debugStack( "expanding freestanding macro", expansion); // Builtin macros are handled via ASTGen. auto *astGenSourceFile = sourceFile->getExportedSourceFile(); if (!astGenSourceFile) return nullptr; const char *evaluatedSourceAddress; ptrdiff_t evaluatedSourceLength; swift_ASTGen_expandFreestandingMacro( &ctx.Diags, externalDef->opaqueHandle, static_cast<uint32_t>(externalDef->kind), discriminator->data(), discriminator->size(), getRawMacroRole(macroRole), astGenSourceFile, expansion->getSourceRange().Start.getOpaquePointerValue(), &evaluatedSourceAddress, &evaluatedSourceLength); if (!evaluatedSourceAddress) return nullptr; evaluatedSource = llvm::MemoryBuffer::getMemBufferCopy( {evaluatedSourceAddress, (size_t)evaluatedSourceLength}, adjustMacroExpansionBufferName(*discriminator)); free((void *)evaluatedSourceAddress); break; #else ctx.Diags.diagnose(loc, diag::macro_unsupported); return nullptr; #endif } } return createMacroSourceFile(std::move(evaluatedSource), isa<MacroExpansionDecl>(expansion) ? MacroRole::Declaration : MacroRole::Expression, expansion->getASTNode(), dc, /*attr=*/nullptr); } llvm::Optional<unsigned> swift::expandMacroExpr(MacroExpansionExpr *mee) { SourceFile *macroSourceFile = ::evaluateFreestandingMacro(mee); if (!macroSourceFile) return llvm::None; DeclContext *dc = mee->getDeclContext(); ASTContext &ctx = dc->getASTContext(); SourceManager &sourceMgr = ctx.SourceMgr; auto macroBufferID = *macroSourceFile->getBufferID(); auto macroBufferRange = sourceMgr.getRangeForBuffer(macroBufferID); // Retrieve the parsed expression from the list of top-level items. auto topLevelItems = macroSourceFile->getTopLevelItems(); Expr *expandedExpr = nullptr; if (topLevelItems.size() != 1) { ctx.Diags.diagnose( macroBufferRange.getStart(), diag::expected_macro_expansion_expr); return macroBufferID; } auto codeItem = topLevelItems.front(); if (auto *expr = codeItem.dyn_cast<Expr *>()) expandedExpr = expr; if (!expandedExpr) { ctx.Diags.diagnose( macroBufferRange.getStart(), diag::expected_macro_expansion_expr); return macroBufferID; } auto expandedType = mee->getType(); // Type-check the expanded expression. // FIXME: Would like to pass through type checking options like "discarded" // that are captured by TypeCheckExprOptions. constraints::ContextualTypeInfo contextualType { TypeLoc::withoutLoc(expandedType), // FIXME: Add a contextual type purpose for macro expansion. ContextualTypePurpose::CTP_CoerceOperand }; PrettyStackTraceExpr debugStack( ctx, "type checking expanded macro", expandedExpr); Type realExpandedType = TypeChecker::typeCheckExpression( expandedExpr, dc, contextualType); if (!realExpandedType) return macroBufferID; assert((expandedType->isEqual(realExpandedType) || realExpandedType->hasError()) && "Type checking changed the result type?"); mee->setRewritten(expandedExpr); return macroBufferID; } /// Expands the given macro expansion declaration. llvm::Optional<unsigned> swift::expandFreestandingMacro(MacroExpansionDecl *med) { SourceFile *macroSourceFile = ::evaluateFreestandingMacro(med); if (!macroSourceFile) return llvm::None; MacroDecl *macro = cast<MacroDecl>(med->getMacroRef().getDecl()); DeclContext *dc = med->getDeclContext(); validateMacroExpansion(macroSourceFile, macro, /*attachedTo*/nullptr, MacroRole::Declaration); PrettyStackTraceDecl debugStack( "type checking expanded declaration macro", med); auto topLevelItems = macroSourceFile->getTopLevelItems(); for (auto item : topLevelItems) { if (auto *decl = item.dyn_cast<Decl *>()) decl->setDeclContext(dc); } return *macroSourceFile->getBufferID(); } static SourceFile *evaluateAttachedMacro(MacroDecl *macro, Decl *attachedTo, CustomAttr *attr, bool passParentContext, MacroRole role, ArrayRef<ProtocolDecl *> conformances = {}, StringRef discriminatorStr = "") { DeclContext *dc; if (role == MacroRole::Peer) { dc = attachedTo->getDeclContext(); } else if (role == MacroRole::Conformance || role == MacroRole::Extension) { // Conformance macros always expand to extensions at file-scope. dc = attachedTo->getDeclContext()->getParentSourceFile(); } else { dc = attachedTo->getInnermostDeclContext(); } ASTContext &ctx = dc->getASTContext(); auto moduleDecl = dc->getParentModule(); auto attrSourceFile = moduleDecl->getSourceFileContainingLocation(attr->AtLoc); if (!attrSourceFile) return nullptr; auto declSourceFile = moduleDecl->getSourceFileContainingLocation(attachedTo->getStartLoc()); if (!declSourceFile) return nullptr; Decl *parentDecl = nullptr; SourceFile *parentDeclSourceFile = nullptr; if (passParentContext) { parentDecl = attachedTo->getDeclContext()->getAsDecl(); if (!parentDecl) return nullptr; parentDeclSourceFile = moduleDecl->getSourceFileContainingLocation(parentDecl->getLoc()); if (!parentDeclSourceFile) return nullptr; } if (isFromExpansionOfMacro(attrSourceFile, macro, role) || isFromExpansionOfMacro(declSourceFile, macro, role) || isFromExpansionOfMacro(parentDeclSourceFile, macro, role)) { attachedTo->diagnose(diag::macro_recursive, macro->getName()); return nullptr; } // Evaluate the macro. std::unique_ptr<llvm::MemoryBuffer> evaluatedSource; /// The discriminator used for the macro. LazyValue<std::string> discriminator([&]() -> std::string { if (!discriminatorStr.empty()) return discriminatorStr.str(); #if SWIFT_SWIFT_PARSER Mangle::ASTMangler mangler; return mangler.mangleAttachedMacroExpansion(attachedTo, attr, role); #else return ""; #endif }); std::string extendedType; { llvm::raw_string_ostream OS(extendedType); if (role == MacroRole::Extension || role == MacroRole::Conformance) { auto *nominal = dyn_cast<NominalTypeDecl>(attachedTo); PrintOptions options; options.FullyQualifiedExtendedTypesIfAmbiguous = true; nominal->getDeclaredType()->print(OS, options); } else { OS << ""; } } std::string conformanceList; { llvm::raw_string_ostream OS(conformanceList); if (role == MacroRole::Extension) { llvm::interleave( conformances, [&](const ProtocolDecl *protocol) { protocol->getDeclaredType()->print(OS); }, [&] { OS << ", "; } ); } else { OS << ""; } } auto macroDef = macro->getDefinition(); switch (macroDef.kind) { case MacroDefinition::Kind::Undefined: case MacroDefinition::Kind::Invalid: // Already diagnosed as an error elsewhere. return nullptr; case MacroDefinition::Kind::Builtin: { switch (macroDef.getBuiltinKind()) { case BuiltinMacroKind::ExternalMacro: // FIXME: Error here. return nullptr; } } case MacroDefinition::Kind::Expanded: { // Expand the definition with the given arguments. auto result = expandMacroDefinition( macroDef.getExpanded(), macro, attr->getArgs()); evaluatedSource = llvm::MemoryBuffer::getMemBufferCopy( result, adjustMacroExpansionBufferName(*discriminator)); break; } case MacroDefinition::Kind::External: { // Retrieve the external definition of the macro. auto external = macroDef.getExternalMacro(); ExternalMacroDefinitionRequest request{ &ctx, external.moduleName, external.macroTypeName }; auto externalDef = evaluateOrDefault(ctx.evaluator, request, llvm::None); if (!externalDef) { attachedTo->diagnose(diag::external_macro_not_found, external.moduleName.str(), external.macroTypeName.str(), macro->getName() ); macro->diagnose(diag::decl_declared_here, macro); return nullptr; } #if SWIFT_SWIFT_PARSER PrettyStackTraceDecl debugStack("expanding attached macro", attachedTo); auto *astGenAttrSourceFile = attrSourceFile->getExportedSourceFile(); if (!astGenAttrSourceFile) return nullptr; auto *astGenDeclSourceFile = declSourceFile->getExportedSourceFile(); if (!astGenDeclSourceFile) return nullptr; void *astGenParentDeclSourceFile = nullptr; const void *parentDeclLoc = nullptr; if (passParentContext) { astGenParentDeclSourceFile = parentDeclSourceFile->getExportedSourceFile(); if (!astGenParentDeclSourceFile) return nullptr; parentDeclLoc = parentDecl->getStartLoc().getOpaquePointerValue(); } Decl *searchDecl = attachedTo; if (auto var = dyn_cast<VarDecl>(attachedTo)) searchDecl = var->getParentPatternBinding(); const char *evaluatedSourceAddress; ptrdiff_t evaluatedSourceLength; swift_ASTGen_expandAttachedMacro( &ctx.Diags, externalDef->opaqueHandle, static_cast<uint32_t>(externalDef->kind), discriminator->data(), discriminator->size(), extendedType.data(), extendedType.size(), conformanceList.data(), conformanceList.size(), getRawMacroRole(role), astGenAttrSourceFile, attr->AtLoc.getOpaquePointerValue(), astGenDeclSourceFile, searchDecl->getStartLoc().getOpaquePointerValue(), astGenParentDeclSourceFile, parentDeclLoc, &evaluatedSourceAddress, &evaluatedSourceLength); if (!evaluatedSourceAddress) return nullptr; evaluatedSource = llvm::MemoryBuffer::getMemBufferCopy( {evaluatedSourceAddress, (size_t)evaluatedSourceLength}, adjustMacroExpansionBufferName(*discriminator)); free((void *)evaluatedSourceAddress); break; #else attachedTo->diagnose(diag::macro_unsupported); return nullptr; #endif } } SourceFile *macroSourceFile = createMacroSourceFile( std::move(evaluatedSource), role, attachedTo, dc, attr); validateMacroExpansion(macroSourceFile, macro, dyn_cast<ValueDecl>(attachedTo), role); return macroSourceFile; } bool swift::accessorMacroOnlyIntroducesObservers( MacroDecl *macro, const MacroRoleAttr *attr ) { // Will this macro introduce observers? bool foundObserver = false; for (auto name : attr->getNames()) { if (name.getKind() == MacroIntroducedDeclNameKind::Named && (name.getName().getBaseName().userFacingName() == "willSet" || name.getName().getBaseName().userFacingName() == "didSet")) { foundObserver = true; } else { // Introduces something other than an observer. return false; } } if (foundObserver) return true; // WORKAROUND: Older versions of the Observation library make // `ObservationIgnored` an accessor macro that implies that it makes a // stored property computed. Override that, because we know it produces // nothing. if (macro->getName().getBaseName().userFacingName() == "ObservationIgnored") { return true; } return false; } bool swift::accessorMacroIntroducesInitAccessor( MacroDecl *macro, const MacroRoleAttr *attr ) { for (auto name : attr->getNames()) { if (name.getKind() == MacroIntroducedDeclNameKind::Named && (name.getName().getBaseName().getKind() == DeclBaseName::Kind::Constructor)) return true; } return false; } llvm::Optional<unsigned> swift::expandAccessors(AbstractStorageDecl *storage, CustomAttr *attr, MacroDecl *macro) { // Evaluate the macro. auto macroSourceFile = ::evaluateAttachedMacro(macro, storage, attr, /*passParentContext=*/false, MacroRole::Accessor); if (!macroSourceFile) return llvm::None; PrettyStackTraceDecl debugStack( "type checking expanded accessor macro", storage); // Trigger parsing of the sequence of accessor declarations. This has the // side effect of registering those accessor declarations with the storage // declaration, so there is nothing further to do. bool foundNonObservingAccessor = false; bool foundNonObservingAccessorInMacro = false; bool foundInitAccessor = false; for (auto accessor : storage->getAllAccessors()) { if (accessor->isInitAccessor()) foundInitAccessor = true; if (!accessor->isObservingAccessor()) { foundNonObservingAccessor = true; if (accessor->isInMacroExpansionInContext()) foundNonObservingAccessorInMacro = true; } } auto roleAttr = macro->getMacroRoleAttr(MacroRole::Accessor); bool expectedNonObservingAccessor = !accessorMacroOnlyIntroducesObservers(macro, roleAttr); if (foundNonObservingAccessorInMacro) { // If any non-observing accessor was added, mark the initializer as // subsumed unless it has init accessor, because the initializer in // such cases could be used for memberwise initialization. if (auto var = dyn_cast<VarDecl>(storage)) { if (auto binding = var->getParentPatternBinding(); !var->getAccessor(AccessorKind::Init)) { unsigned index = binding->getPatternEntryIndexForVarDecl(var); binding->setInitializerSubsumed(index); } } // Also remove didSet and willSet, because they are subsumed by a // macro expansion that turns a stored property into a computed one. if (auto accessor = storage->getParsedAccessor(AccessorKind::WillSet)) storage->removeAccessor(accessor); if (auto accessor = storage->getParsedAccessor(AccessorKind::DidSet)) storage->removeAccessor(accessor); } // Make sure we got non-observing accessors exactly where we expected to. if (foundNonObservingAccessor != expectedNonObservingAccessor) { storage->diagnose( diag::macro_accessor_missing_from_expansion, macro->getName(), !expectedNonObservingAccessor); } // 'init' accessors must be documented in the macro role attribute. if (foundInitAccessor && !accessorMacroIntroducesInitAccessor(macro, roleAttr)) { storage->diagnose( diag::macro_init_accessor_not_documented, macro->getName()); // FIXME: Add the appropriate "names: named(init)". } return macroSourceFile->getBufferID(); } ArrayRef<unsigned> ExpandAccessorMacros::evaluate( Evaluator &evaluator, AbstractStorageDecl *storage ) const { llvm::SmallVector<unsigned, 1> bufferIDs; storage->forEachAttachedMacro(MacroRole::Accessor, [&](CustomAttr *customAttr, MacroDecl *macro) { if (auto bufferID = expandAccessors( storage, customAttr, macro)) bufferIDs.push_back(*bufferID); }); return storage->getASTContext().AllocateCopy(bufferIDs); } llvm::Optional<unsigned> swift::expandAttributes(CustomAttr *attr, MacroDecl *macro, Decl *member) { // Evaluate the macro. auto macroSourceFile = ::evaluateAttachedMacro(macro, member, attr, /*passParentContext=*/true, MacroRole::MemberAttribute); if (!macroSourceFile) return llvm::None; PrettyStackTraceDecl debugStack( "type checking expanded declaration macro", member); auto topLevelDecls = macroSourceFile->getTopLevelDecls(); for (auto decl : topLevelDecls) { // Add the new attributes to the semantic attribute list. SmallVector<DeclAttribute *, 2> attrs(decl->getAttrs().begin(), decl->getAttrs().end()); for (auto *attr : attrs) { member->getAttrs().add(attr); } } return macroSourceFile->getBufferID(); } llvm::Optional<unsigned> swift::expandMembers(CustomAttr *attr, MacroDecl *macro, Decl *decl) { // Evaluate the macro. auto macroSourceFile = ::evaluateAttachedMacro(macro, decl, attr, /*passParentContext=*/false, MacroRole::Member); if (!macroSourceFile) return llvm::None; PrettyStackTraceDecl debugStack( "type checking expanded declaration macro", decl); auto topLevelDecls = macroSourceFile->getTopLevelDecls(); for (auto member : topLevelDecls) { // Note that synthesized members are not considered implicit. They have // proper source ranges that should be validated, and ASTScope does not // expand implicit scopes to the parent scope tree. if (auto *nominal = dyn_cast<NominalTypeDecl>(decl)) { nominal->addMember(member); } else if (auto *extension = dyn_cast<ExtensionDecl>(decl)) { extension->addMember(member); } } return macroSourceFile->getBufferID(); } llvm::Optional<unsigned> swift::expandPeers(CustomAttr *attr, MacroDecl *macro, Decl *decl) { auto macroSourceFile = ::evaluateAttachedMacro(macro, decl, attr, /*passParentContext=*/false, MacroRole::Peer); if (!macroSourceFile) return llvm::None; PrettyStackTraceDecl debugStack("applying expanded peer macro", decl); return macroSourceFile->getBufferID(); } ArrayRef<unsigned> ExpandExtensionMacros::evaluate(Evaluator &evaluator, NominalTypeDecl *nominal) const { SmallVector<unsigned, 2> bufferIDs; for (auto customAttrConst : nominal->getSemanticAttrs().getAttributes<CustomAttr>()) { auto customAttr = const_cast<CustomAttr *>(customAttrConst); auto *macro = nominal->getResolvedMacro(customAttr); if (!macro) continue; // Prefer the extension role MacroRole role; if (macro->getMacroRoles().contains(MacroRole::Extension)) { role = MacroRole::Extension; } else if (macro->getMacroRoles().contains(MacroRole::Conformance)) { role = MacroRole::Conformance; } else { continue; } if (auto bufferID = expandExtensions(customAttr, macro, role, nominal)) bufferIDs.push_back(*bufferID); } return nominal->getASTContext().AllocateCopy(bufferIDs); } llvm::Optional<unsigned> swift::expandExtensions(CustomAttr *attr, MacroDecl *macro, MacroRole role, NominalTypeDecl *nominal) { if (nominal->getDeclContext()->isLocalContext()) { nominal->diagnose(diag::local_extension_macro); return llvm::None; } // Collect the protocol conformances that the macro can add. The // macro should not add conformances that are already stated in // the original source. SmallVector<ProtocolDecl *, 2> potentialConformances; macro->getIntroducedConformances(nominal, potentialConformances); SmallVector<ProtocolDecl *, 2> introducedConformances; for (auto protocol : potentialConformances) { SmallVector<ProtocolConformance *, 2> existingConformances; nominal->lookupConformance(protocol, existingConformances); bool hasExistingConformance = llvm::any_of( existingConformances, [&](ProtocolConformance *conformance) { return conformance->getSourceKind() != ConformanceEntryKind::PreMacroExpansion; }); if (!hasExistingConformance) { introducedConformances.push_back(protocol); } } auto macroSourceFile = ::evaluateAttachedMacro(macro, nominal, attr, /*passParentContext=*/false, role, introducedConformances); if (!macroSourceFile) return llvm::None; PrettyStackTraceDecl debugStack( "applying expanded extension macro", nominal); auto topLevelDecls = macroSourceFile->getTopLevelDecls(); for (auto *decl : topLevelDecls) { auto *extension = dyn_cast<ExtensionDecl>(decl); if (!extension) continue; // Bind the extension to the original nominal type. extension->setExtendedNominal(nominal); nominal->addExtension(extension); // Most other macro-generated declarations are visited through calling // 'visitAuxiliaryDecls' on the original declaration the macro is attached // to. We don't do this for macro-generated extensions, because the // extension is not a peer of the original declaration. Instead of // requiring all callers of 'visitAuxiliaryDecls' to understand the // hoisting behavior of macro-generated extensions, we make the // extension accessible through 'getTopLevelDecls()'. if (auto file = dyn_cast<FileUnit>( decl->getDeclContext()->getModuleScopeContext())) file->getOrCreateSynthesizedFile().addTopLevelDecl(extension); // Don't validate documented conformances for the 'conformance' role. if (role == MacroRole::Conformance) continue; // Extension macros can only add conformances that are documented by // the `@attached(extension)` attribute. for (auto inherited : extension->getInherited()) { auto constraint = TypeResolution::forInterface( extension->getDeclContext(), TypeResolverContext::GenericRequirement, /*unboundTyOpener*/ nullptr, /*placeholderHandler*/ nullptr, /*packElementOpener*/ nullptr) .resolveType(inherited.getTypeRepr()); // Already diagnosed or will be diagnosed later. if (constraint->is<ErrorType>() || !constraint->isConstraintType()) continue; std::function<bool(Type)> isUndocumentedConformance = [&](Type constraint) -> bool { if (auto *proto = constraint->getAs<ParameterizedProtocolType>()) return !llvm::is_contained(potentialConformances, proto->getProtocol()); if (auto *proto = constraint->getAs<ProtocolType>()) return !llvm::is_contained(potentialConformances, proto->getDecl()); return llvm::any_of( constraint->castTo<ProtocolCompositionType>()->getMembers(), isUndocumentedConformance); }; if (isUndocumentedConformance(constraint)) { extension->diagnose( diag::undocumented_conformance_in_expansion, constraint, macro->getBaseName()); extension->setInvalid(); } } } return macroSourceFile->getBufferID(); } /// Emits an error and returns \c true if the maro reference may /// introduce arbitrary names at global scope. static bool diagnoseArbitraryGlobalNames(DeclContext *dc, UnresolvedMacroReference macroRef, MacroRole macroRole) { auto &ctx = dc->getASTContext(); assert(macroRole == MacroRole::Declaration || macroRole == MacroRole::Peer); if (!dc->isModuleScopeContext()) return false; bool isInvalid = false; namelookup::forEachPotentialResolvedMacro( dc, macroRef.getMacroName(), macroRole, [&](MacroDecl *decl, const MacroRoleAttr *attr) { if (!isInvalid && attr->hasNameKind(MacroIntroducedDeclNameKind::Arbitrary)) { ctx.Diags.diagnose(macroRef.getSigilLoc(), diag::global_arbitrary_name, getMacroRoleString(macroRole)); isInvalid = true; // If this is an attached macro, mark the attribute as invalid // to avoid diagnosing an unknown attribute later. if (auto *attr = macroRef.getAttr()) { attr->setInvalid(); } } }); return isInvalid; } ConcreteDeclRef ResolveMacroRequest::evaluate(Evaluator &evaluator, UnresolvedMacroReference macroRef, DeclContext *dc) const { // Macro expressions and declarations have their own stored macro // reference. Use it if it's there. if (auto *expansion = macroRef.getFreestanding()) { if (auto ref = expansion->getMacroRef()) return ref; } auto &ctx = dc->getASTContext(); auto roles = macroRef.getMacroRoles(); // When a macro is not found for a custom attribute, it may be a non-macro. // So bail out to prevent diagnostics from the contraint system. if (macroRef.getAttr()) { auto foundMacros = namelookup::lookupMacros( dc, macroRef.getMacroName(), roles); if (foundMacros.empty()) return ConcreteDeclRef(); } // Freestanding and peer macros applied at top-level scope cannot introduce // arbitrary names. Introducing arbitrary names means that any lookup // into this scope must expand the macro. This is a problem, because // resolving the macro can invoke type checking other declarations, e.g. // anything that the macro arguments depend on. If _anything_ the macro // depends on performs name unqualified name lookup, e.g. type resolution, // we'll get circularity errors. It's better to prevent this by banning // these macros at global scope if any of the macro candidates introduce // arbitrary names. if (diagnoseArbitraryGlobalNames(dc, macroRef, MacroRole::Declaration) || diagnoseArbitraryGlobalNames(dc, macroRef, MacroRole::Peer)) return ConcreteDeclRef(); // If we already have a MacroExpansionExpr, use that. Otherwise, // create one. MacroExpansionExpr *macroExpansion; if (auto *expansion = macroRef.getFreestanding()) { if (auto *expr = dyn_cast<MacroExpansionExpr>(expansion)) { macroExpansion = expr; } else { macroExpansion = new (ctx) MacroExpansionExpr( dc, expansion->getExpansionInfo(), roles); } } else { SourceRange genericArgsRange = macroRef.getGenericArgsRange(); macroExpansion = MacroExpansionExpr::create( dc, macroRef.getSigilLoc(), macroRef.getMacroName(), macroRef.getMacroNameLoc(), genericArgsRange.Start, macroRef.getGenericArgs(), genericArgsRange.End, macroRef.getArgs(), roles); } Expr *result = macroExpansion; TypeChecker::typeCheckExpression( result, dc, {}, TypeCheckExprFlags::DisableMacroExpansions); // If we couldn't resolve a macro decl, the attribute is invalid. if (!macroExpansion->getMacroRef() && macroRef.getAttr()) macroRef.getAttr()->setInvalid(); // Macro expressions and declarations have their own stored macro // reference. If we got a reference, store it there, too. // FIXME: This duplication of state is really unfortunate. if (auto ref = macroExpansion->getMacroRef()) { if (auto *expansion = macroRef.getFreestanding()) { expansion->setMacroRef(ref); } } return macroExpansion->getMacroRef(); } ArrayRef<Type> ResolveExtensionMacroConformances::evaluate(Evaluator &evaluator, const MacroRoleAttr *attr, const Decl *decl) const { auto *dc = decl->getDeclContext(); auto &ctx = dc->getASTContext(); SmallVector<Type, 2> protocols; for (auto *typeExpr : attr->getConformances()) { if (auto *typeRepr = typeExpr->getTypeRepr()) { auto resolved = TypeResolution::forInterface( dc, TypeResolverContext::GenericRequirement, /*unboundTyOpener*/ nullptr, /*placeholderHandler*/ nullptr, /*packElementOpener*/ nullptr) .resolveType(typeRepr); if (resolved->is<ErrorType>()) continue; if (!resolved->isConstraintType()) { diagnoseAndRemoveAttr( decl, attr, diag::extension_macro_invalid_conformance, resolved); continue; } typeExpr->setType(MetatypeType::get(resolved)); protocols.push_back(resolved); } else { // If there's no type repr, we already have a resolved instance // type, e.g. because the type expr was deserialized. protocols.push_back(typeExpr->getInstanceType()); } } return ctx.AllocateCopy(protocols); } // MARK: for IDE. SourceFile *swift::evaluateAttachedMacro(MacroDecl *macro, Decl *attachedTo, CustomAttr *attr, bool passParentContext, MacroRole role, StringRef discriminator) { return ::evaluateAttachedMacro(macro, attachedTo, attr, passParentContext, role, {}, discriminator); } SourceFile * swift::evaluateFreestandingMacro(FreestandingMacroExpansion *expansion, StringRef discriminator) { return ::evaluateFreestandingMacro(expansion, discriminator); }
4e3e35568d128aa8e8ca0a40b8317712134b6043
fe94f365dcd7974eeeaa932f6dd0bee7018d2c24
/RoomGameV2/Television.h
7b743af18495d935148c96d12deff619b3d6e9f7
[]
no_license
mikelrob/RoomGameV2
afcb5f5274d46548ad39db870cc79145c46ce322
d5c64ac646ddcbd79d8c46a1458483a2bf082920
refs/heads/master
2020-04-06T05:26:15.787800
2013-11-04T23:12:19
2013-11-04T23:12:19
14,126,511
1
0
null
null
null
null
UTF-8
C++
false
false
321
h
Television.h
#ifndef TELEVISION_H #define TELEVISION_H #include "gameobject.h" class Television : public GameObject { public: Television(string newName, int newID):GameObject(newName, newID), isOn(false) {} ~Television(); Result examine(); Result turnOn(); Result turnOff(); private: bool isOn; }; #endif
77efbcd36f61d9e750ce65dd756306b1181c4c13
81fdc75229f7139898d20419739149dc0469c564
/arduino/MorseCode.ino
619ff90744d25275ea55da05a1b55862821fe6f2
[]
no_license
brenopolanski/labs
e9145d6d9802f2986daa318811a80a96350501fb
548a1f4b72f7c98c24c3c86fd02e1eeecd5b4c4c
refs/heads/master
2023-04-06T20:48:07.462810
2022-09-28T14:18:58
2022-09-28T14:18:58
22,954,064
2
0
null
2023-03-20T19:55:37
2014-08-14T13:05:00
JavaScript
UTF-8
C++
false
false
682
ino
MorseCode.ino
const int PORT = 13; int F[] = {150, 150, 400, 150}; int A[] = {150, 400}; int C[] = {400, 150, 400, 150}; int I[] = {150, 150}; int S[] = {150, 150, 150}; void setup() { pinMode(PORT, OUTPUT); // link: https://programmingelectronics.com/using-the-print-function-with-arduino-part-1/ Serial.begin(9600); } void showMorseCode(int time[]) { for (int i = 0; i < sizeof(time); i++){ digitalWrite(PORT, HIGH); delay(time[i]); digitalWrite(PORT, LOW); delay(time[i]); } Serial.println("Console test"); } void loop() { showMorseCode(F); showMorseCode(A); showMorseCode(C); showMorseCode(I); showMorseCode(S); showMorseCode(A); delay(5000); }
27c6c0444a4c0498e7b4ca8b7a15ebc04606e697
1c17c5cad20da319eb88c38e3e9927a165d85662
/src/SparrowCompiler/AstDump.cpp
e4173eb474abbbc1387b416a90ed9fb9e86c4a7c
[ "MIT" ]
permissive
Sparrow-lang/sparrow
e14dec2847c59dceebe48a1d4b1ec3ef45a5d379
b1cf41f79b52665d8208f8fb5a7539d764286daa
refs/heads/master
2020-04-04T07:16:42.690182
2019-12-01T19:19:01
2019-12-01T19:19:01
34,960,748
89
8
MIT
2019-12-01T19:19:02
2015-05-02T19:34:26
LLVM
UTF-8
C++
false
false
8,743
cpp
AstDump.cpp
#include <StdInc.h> #include "AstDump.h" #include "Nest/Utils/Diagnostic.hpp" #include "Nest/Utils/cppif/StringRef.hpp" #include "Nest/Utils/cppif/NodeUtils.hpp" #include "Nest/Api/Node.h" #include "Nest/Api/NodeArray.h" #include "Nest/Api/Type.h" using Nest::begin; using Nest::end; using Nest::Node; using Nest::size; using Nest::StringRef; using Nest::TypeRef; struct JsonContext { FILE* f; int indent; bool insideArray; bool firstAttribute; bool oneLine; const Nest_SourceCode* sourceCodeFilter; std::unordered_set<void*> writtenPointers; }; bool _satisfiesFilter(JsonContext* ctx, Node* node) { auto loc = node->location; if (loc.sourceCode != ctx->sourceCodeFilter) return false; return true; } void _writeSpaces(JsonContext* ctx) { static const int indentSize = 2; static const int spacesLen = 20; char spaces[spacesLen + 1] = " "; int toWrite = indentSize * ctx->indent; // Write in big chunks while (toWrite > spacesLen) { fwrite(spaces, 1, spacesLen, ctx->f); toWrite -= spacesLen; } // Write the remaining of spaces if (toWrite > 0) fwrite(spaces, 1, toWrite, ctx->f); } void _writePrefix(JsonContext* ctx, const char* prefix) { if (ctx->firstAttribute) ctx->firstAttribute = false; else if (ctx->oneLine) { fputs(", ", ctx->f); } else { fputc(',', ctx->f); } if (!ctx->oneLine) { fputc('\n', ctx->f); _writeSpaces(ctx); } if (!ctx->insideArray) { fputs("\"", ctx->f); fputs(prefix, ctx->f); fputs("\": ", ctx->f); } } void _writeNumber(JsonContext* ctx, const char* name, long long val) { _writePrefix(ctx, name); fprintf(ctx->f, "%lld", val); } void _writeFloatingNumber(JsonContext* ctx, const char* name, double val) { _writePrefix(ctx, name); fprintf(ctx->f, "%f", val); } void _writeStringL(JsonContext* ctx, const char* name, const char* val, size_t size) { // Check if the string contains some 'strange' characters bool hasStrangeCharacters = false; for (size_t i = 0; i < size; ++i) { char ch = val[i]; if (!isprint(ch) || ch == '\\' || ch == '\"') { hasStrangeCharacters = true; break; } } _writePrefix(ctx, name); fputc('"', ctx->f); if (!hasStrangeCharacters) fputs(val, ctx->f); else { for (size_t i = 0; i < size; ++i) { unsigned char ch = val[i]; if (ch == '\\') fputs("\\\\", ctx->f); else if (ch == '"') fputs("\\\"", ctx->f); else if (isprint(ch)) fputc(ch, ctx->f); else { unsigned char hi = (ch & 0xF0) >> 4; unsigned char lo = ch & 0x0F; static const char* hexChars = "0123456789ABCDEF"; char hex[6] = {'\\', 'u', '0', '0', hexChars[hi], hexChars[lo]}; fwrite(hex, 1, 6, ctx->f); } } } fputc('"', ctx->f); } void _writeString(JsonContext* ctx, const char* name, const char* val) { _writeStringL(ctx, name, val, strlen(val)); } void _writeStringSR(JsonContext* ctx, const char* name, StringRef val) { _writeStringL(ctx, name, val.begin, val.end - val.begin); } void _startObject(JsonContext* ctx, const char* name) { _writePrefix(ctx, name); fputs("{", ctx->f); ++ctx->indent; ctx->firstAttribute = true; ctx->insideArray = false; } void _endObject(JsonContext* ctx) { --ctx->indent; if (!ctx->oneLine) { fputc('\n', ctx->f); _writeSpaces(ctx); } fputc('}', ctx->f); ctx->firstAttribute = false; } void _startArray(JsonContext* ctx, const char* name) { _writePrefix(ctx, name); fputc('[', ctx->f); ++ctx->indent; ctx->firstAttribute = true; ctx->insideArray = true; } void _endArray(JsonContext* ctx) { if (!ctx->oneLine) fputc('\n', ctx->f); --ctx->indent; _writeSpaces(ctx); fputc(']', ctx->f); ctx->firstAttribute = false; ctx->insideArray = false; } void _writeType(JsonContext* ctx, const char* name, TypeRef t) { _startObject(ctx, name); // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) auto ref = reinterpret_cast<size_t>((void*)t); _writeNumber(ctx, "ref", ref); if (t) _writeString(ctx, "desc", t->description); _endObject(ctx); } void _writeNode(JsonContext* ctx, const char* name, Node* node); void _writeNodeData(JsonContext* ctx, Node* node) { // Node kind _writeString(ctx, "kind", Nest_nodeKindName(node)); // Location _startObject(ctx, "location"); ctx->oneLine = true; _startObject(ctx, "start"); _writeNumber(ctx, "line", node->location.start.line); _writeNumber(ctx, "col", node->location.start.col); _endObject(ctx); _startObject(ctx, "end"); _writeNumber(ctx, "line", node->location.end.line); _writeNumber(ctx, "col", node->location.end.col); _endObject(ctx); _endObject(ctx); ctx->oneLine = false; // Write the properties if (node->properties.end != node->properties.begin) { _startArray(ctx, "properties"); Nest_NodeProperty* p = node->properties.begin; for (; p != node->properties.end; ++p) { ctx->insideArray = true; _startObject(ctx, ""); ctx->oneLine = true; _writeStringSR(ctx, "name", p->name); _writeNumber(ctx, "kind", (int)p->kind); if (p->passToExpl) _writeNumber(ctx, "passToExpl", 1); switch (p->kind) { case propInt: _writeNumber(ctx, "val", p->value.intValue); break; case propString: _writeStringSR(ctx, "val", p->value.stringValue); break; case propNode: ctx->oneLine = false; _writeNode(ctx, "val", p->value.nodeValue); break; case propType: _writeType(ctx, "val", p->value.typeValue); break; case propPtr: // Don't write this break; } _endObject(ctx); ctx->oneLine = false; } _endArray(ctx); } // Write node type if (node->type) _writeType(ctx, "type", node->type); // Write its children if (size(node->children) > 0) { _startArray(ctx, "children"); for (Node* n : node->children) { ctx->insideArray = true; _writeNode(ctx, "", n); } _endArray(ctx); } // Write the referred nodes if (size(node->referredNodes) > 0) { _startArray(ctx, "referredNodes"); for (Node* n : node->referredNodes) { ctx->insideArray = true; _writeNode(ctx, "", n); } _endArray(ctx); } // Write the explanation of the node if (node->explanation && node->explanation != node) _writeNode(ctx, "explanation", node->explanation); } void _writeNode(JsonContext* ctx, const char* name, Node* node) { _startObject(ctx, name); if (!node || !_satisfiesFilter(ctx, node)) { // Null pointer (or not satisfies the filter) ctx->oneLine = true; _writeNumber(ctx, "ref", 0); } else { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) auto ref = reinterpret_cast<size_t>((void*)node); auto it = ctx->writtenPointers.find((void*)node); if (it == ctx->writtenPointers.end()) { // First time we see this pointer ctx->writtenPointers.insert((void*)node); _writeNumber(ctx, "ref", ref); _startObject(ctx, "obj"); _writeNodeData(ctx, node); _endObject(ctx); } else { // The object was already serialized ctx->oneLine = true; _writeNumber(ctx, "ref", ref); } } _endObject(ctx); ctx->oneLine = false; } void dumpAstNode(Node* node, const char* filename) { ASSERT(node); cout << "Dumping AST nodes to: " << filename << endl; // NOLINTNEXTLINE(cppcoreguidelines-owning-memory) FILE* f = fopen(filename, "w"); if (!f) { Nest_reportFmt(node->location, diagWarning, "Cannot open %s to dump AST node", filename); return; } JsonContext ctx = {f, 0}; ctx.firstAttribute = true; ctx.insideArray = true; ctx.sourceCodeFilter = node->location.sourceCode; _writeNode(&ctx, "", node); // NOLINTNEXTLINE(cppcoreguidelines-owning-memory) fclose(f); }
f5bf746dda81a508c23f95ec46ceee87e7ee6ab4
dcd7007dfa14283b7e17ed3259c4f1520978cd24
/Classes/TerminatingDoorView.h
b2b5d7bff24e1b59104211cdae8ea4013c45f8a6
[]
no_license
timeloopServices/2D-Platformer
02ff941058186a68159c913325dd5cde8492e42a
fc5dae79b264043855ab0f17a74f5086e1008ffb
refs/heads/master
2021-01-13T15:18:14.838971
2016-12-12T05:13:36
2016-12-12T05:13:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
391
h
TerminatingDoorView.h
#ifndef _TERMINATING_DOOR_VIEW_H_ #define _TERMINATING_DOOR_VIEW_H_ #include "GameElementView.h" #include "cocos2d.h" class TerminatingDoorView : public GameElementView { private: Sprite* m_sprite; TerminatingDoorView(); ~TerminatingDoorView(); bool init(); public: static TerminatingDoorView* create(); }; #endif // !_TERMINATING_DOOR_VIEW_H_
15a06c1fd183507452e6619aaf976f3ea4e4cf62
c1ce1b303de794a4dc8f0d2f2d14e9d771d5e754
/APG4b/Chapter3/Ex22_Sort_by_second_value.cpp
32a6b1303981d469a144fced1cd97f2ccb07cdc7
[]
no_license
reiya0104/AtCoder
8790f302e31fa95aaf9ea16e443802d7b9f34bbf
16d6257b82a0807fa07d830e22d1143c32173072
refs/heads/master
2023-05-09T17:29:12.394495
2021-06-21T02:39:16
2021-06-21T02:39:16
342,526,657
0
0
null
null
null
null
UTF-8
C++
false
false
443
cpp
Ex22_Sort_by_second_value.cpp
#include <bits/stdc++.h> using namespace std; int main() { int N; cin >> N; using pii = pair<int, int>; vector<pii> data(N, make_pair(0, 0)); for (pii &v: data) { cin >> v.second >> v.first; } sort(data.begin(), data.end()); for (pii &v: data) { v = make_pair(v.second, v.first); } for (auto v: data) { cout << v.first << " " << v.second << endl; } }
9585d17742240da54c08966568fe2543d575f357
e1031beddacbbbadb2dc33f5c16d776bee9ce071
/PoCPCP/gadgetlib/gadgetlib/common_use.hpp
effefa8b967dad1679775906e4ff94bdc77061b1
[ "MIT" ]
permissive
elibensasson/SCI-POC
ed7b68dcfcf58f6a5f3d61c7d60aad65cdca3c4e
7e2286ca126d8cdf482ca4081e20d750f57c050e
refs/heads/master
2021-01-20T08:29:41.309276
2017-05-03T13:46:54
2017-05-03T13:46:54
90,152,307
9
1
null
null
null
null
UTF-8
C++
false
false
4,463
hpp
common_use.hpp
#ifndef GADGETLIB3_COMMON_USE_HPP_ #define GADGETLIB3_COMMON_USE_HPP_ #include <NTL/GF2E.h> #include <algorithm> #include <vector> #include <math.h> #include <algebraLib/FieldElement.hpp> #include <algebraLib/CircuitPolynomial.hpp> #include <algebraLib/variable.hpp> #include <gadgetlib/infrastructure.hpp> namespace gadgetlib{ ::NTL::GF2X getPrimitivePoly(); void initGF2EwithPrimitivePoly(); NTL::GF2E getGF2E_X(); Algebra::FieldElement getBit(Algebra::FieldElement elem, int i); //::NTL::GF2E& getGenerator2toTheNthPower(const unsigned int n); const Algebra::FieldElement& getGenerator2toTheNthPower(const unsigned int n); ::NTL::GF2E getGeneratorPower(const unsigned int n); enum class Opcode : int { MEMORY = -2, NONE = -1, AND = 0, OR = 1, XOR = 2, NOT = 3, ADD = 4, SUB = 5, MULL = 6, UMULH = 7, SMULH = 8, UDIV = 9, UMOD = 10, SHL = 11, SHR = 12, SHAR = 13, CMPE = 14, CMPA = 15, CMPAE = 16, CMPG = 17, CMPGE = 18, MOV = 19, CMOV = 20, JMP = 21, CJMP = 22, CNJMP = 23, RESERVED_OPCODE_24 = 24, RESERVED_OPCODE_25 = 25, STOREB = 26, LOADB = 27, STOREW = 28, LOADW = 29, READ = 30, ANSWER = 31, NUM_OPCODES = 32 }; // enum Opcode /*************************************************************************************************/ /*************************************************************************************************/ /**************************** ****************************/ /**************************** Selector Functions ****************************/ /**************************** ****************************/ /*************************************************************************************************/ /*************************************************************************************************/ //useful for constructing SelectorSum objects std::vector<Algebra::Variable> getPCVars(const Algebra::UnpackedWord& pc); // We need the unpakcedPC be at least the log(programLength). // The polynomial is Product ( Algebra::CircuitPolynomial getSelector(int programLength, int instructionLine, Algebra::UnpackedWord unpakedPC); /*************************************************************************************************/ /*************************************************************************************************/ /******************* ******************/ /******************* Memory Info ******************/ /******************* ******************/ /*************************************************************************************************/ /*************************************************************************************************/ class MemoryInfo{ private: int serialNumber_; bool isMemOp_; bool isLoadOp_; Algebra::FElem timestamp_; int timestampDegree_; Algebra::FElem address_; Algebra::FElem value_; public: MemoryInfo(); MemoryInfo(int serialNumber, bool isMemOp, bool isLoadOp, const Algebra::FElem& timestamp, int timestampDegree, const Algebra::FElem& address, const Algebra::FElem& value); int getSerialNumber() const{ return serialNumber_; } bool getIsMemOp() const{ return isMemOp_; } bool getIsLoadOp() const { return isLoadOp_; } Algebra::FElem getTimestamp() const{ return timestamp_; } int getTimestampDegree() const{ return timestampDegree_; } Algebra::FElem getAddress() const { return address_; } Algebra::FElem getValue() const{ return value_; } void updateIsMemOp(bool isMemOp){ isMemOp_ = isMemOp; } void updateIsLoadOp(bool isLoadOp){ isLoadOp_ = isLoadOp; } void updateAddress(const Algebra::FElem& address){ address_ = address; } void updateSerialNumber(int serialNumber){ serialNumber_ = serialNumber; } void updateValue(const Algebra::FElem& value){ value_ = value; } void updateTimestamp(Algebra::FElem timestamp, int timestampDegree); }; inline bool operator==(const MemoryInfo& a, const MemoryInfo& b){ return (a.getSerialNumber() == b.getSerialNumber() && a.getIsMemOp() == b.getIsMemOp() && a.getIsLoadOp() == b.getIsLoadOp() && a.getTimestamp() == b.getTimestamp() && a.getAddress() == b.getAddress() && a.getValue() == b.getValue()); } bool sortMemoryInfo(MemoryInfo a, MemoryInfo b); } // namespace #endif // GADGETLIB3_COMMON_USE_HPP_
5d18e5bfe30d0cc919bca6541fc0d6dbce81e4f6
abbda3a32dfca9649a80fe9cd139d96db5cfd3d0
/include/framework/memory/MemoryPoolObject.h
652baf47da7ceed87f6b579a31e37fac42339c56
[]
no_license
kaulszhang/base
71504ddb5c723b565cf881731e8b72b09a4bc790
a7793f8206bde26bd91a522d4f925fb923e6f6fc
refs/heads/master
2021-01-17T12:07:33.896641
2017-03-07T01:40:50
2017-03-07T01:40:50
84,057,340
5
2
null
null
null
null
GB18030
C++
false
false
4,129
h
MemoryPoolObject.h
// MemoryPoolObject.h #ifndef _FRAMEWORK_MEMORY_MEMORY_POOL_OBJECT_H_ #define _FRAMEWORK_MEMORY_MEMORY_POOL_OBJECT_H_ #include "framework/thread/NullLock.h" #include "framework/memory/PrivateMemory.h" #include "framework/memory/BigFixedPool.h" namespace framework { namespace memory { // 申请不到内存,不抛出异常 template < typename _Ty, typename _Pl = framework::memory::BigFixedPool, typename _Lk = framework::thread::NullLock > struct MemoryPoolObjectNoThrow { public: typedef _Ty object_type; typedef _Pl pool_type; typedef _Lk lock_type; typedef MemoryPoolObjectNoThrow pool_object_type; public: MemoryPoolObjectNoThrow() { } template <typename _Ty1> MemoryPoolObjectNoThrow( MemoryPoolObjectNoThrow<_Ty1, _Pl, _Lk> const & r) { } public: static void set_pool( _Pl const & p) { pool().~_Pl(); new (&pool())_Pl(p); } static _Pl const & get_pool() { return pool(); } static void clear_pool() { pool().clear(); } static size_t set_pool_capacity( size_t size) { return pool().capacity(size); } public: void * operator new( size_t size) throw () { return alloc(size); } void operator delete( void * ptr) throw () { free(ptr); } public: template <typename _Ty1> struct rebind { typedef MemoryPoolObjectNoThrow<_Ty1, _Pl, _Lk> type; }; private: void *operator new[] (size_t) throw (); void operator delete[] (void *) throw (); protected: static void * alloc( size_t size) { assert(size == sizeof(_Ty)); typename _Lk::scoped_lock scoped_lock(lock()); return pool().alloc(size); } static void free( void * ptr) { typename _Lk::scoped_lock scoped_lock(lock()); return pool().free(ptr); } protected: static _Pl init_pool() { return _Pl(PrivateMemory()); } static _Pl & pool() { static _Pl pl(_Ty::init_pool()); return pl; } static _Lk & lock() { static _Lk lk; return lk; } }; // 申请不到内存,抛出异常 template < typename _Ty, typename _Pl = framework::memory::BigFixedPool, typename _Lk = framework::thread::NullLock > struct MemoryPoolObject : MemoryPoolObjectNoThrow<_Ty, _Pl, _Lk> { public: void * operator new( size_t size) throw (std::bad_alloc) { void * addr = MemoryPoolObjectNoThrow<_Ty, _Pl, _Lk>::alloc(size); if (addr == NULL) throw std::bad_alloc(); return addr; } private: void *operator new[] (size_t) throw (std::bad_alloc); public: template <typename _Ty1> struct rebind { typedef MemoryPoolObject<_Ty1, _Pl, _Lk> type; }; }; } // namespace memory } // namespace framework #endif // _FRAMEWORK_MEMORY_MEMORY_POOL_OBJECT_H_
c10764d0a1060f74101d0ec0b453ce417fd2e5c5
30f17239efb0852b4d645b6b4a61e019e7d4ad66
/test_suite/RandomWalk/plugin/TpsTestRandomWalkOrderParam.cpp
1a3d95bc8447a467ad9d5ca4f1c80e188d3f2858
[]
no_license
mfhossam1992/libtps
ac0a2de9857f968d7155419d510510f610748126
983d4651455b8f99c1e24f19756f0fea2c5eac50
refs/heads/master
2020-11-26T07:20:02.857443
2013-01-24T18:31:25
2013-01-24T18:31:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,567
cpp
TpsTestRandomWalkOrderParam.cpp
/* LibTPS -- A Transition Path Sampling Library (LibTPS) Open Source Software License Copyright 2012 The Regents of the University of Michigan All rights reserved. LibTPS may contain modifications ("Contributions") provided, and to which copyright is held, by various Contributors who have granted The Regents of the University of Michigan the right to modify and/or distribute such Contributions. You may redistribute, use, and create derivate works of LibTPS, in source and binary forms, provided you abide by the following conditions: * Redistributions of source code must retain the above copyright notice, this list of conditions, and the following disclaimer both in the code and prominently in any materials provided with the distribution. * 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. * Apart from the above required attributions, neither the name of the copyright holder nor the names of LibTPS's contributors may be used to endorse or promote products derived from this software without specific prior written permission. Disclaimer THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR ANY WARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT 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. */ /* * TpsTestRandomWalkOrderParam.cpp * tpsapi * * Created by askeys on 6/11/09. * Copyright 2009 The Regents of the University of Michigan. All rights reserved. * */ #include "TpsTestRandomWalkOrderParam.h" #include "TpsSimulationPluginAtomic.h" #include "TpsTrajectory.h" #include "TpsTimeslice.h" #include <cmath> #include <iostream> TpsTestRandomWalkOrderParam::TpsTestRandomWalkOrderParam(double min_distance) : _min_distance(min_distance) { } void TpsTestRandomWalkOrderParam::setDistanceCutoff(double min_distance) { _min_distance = min_distance; } bool TpsTestRandomWalkOrderParam::hA(TpsTrajectory& traj) { //this is ignored for full function of path return true; } bool TpsTestRandomWalkOrderParam::hB(TpsTrajectory& traj) { double r = evaluate(traj, -1); //std::cerr << "HB " << r << "\n"; if (r > _min_distance) { return true; } else { return false; } } double TpsTestRandomWalkOrderParam::evaluate( TpsTrajectory& traj, int timeslice_number) { TpsSimulationPluginAtomic& sim = traj.getSimulationPlugin().safeDowncastToAtomicPlugin(); std::vector< std::vector<double> > x, x0; sim.readRestart(traj.getTimeslice(0).getFilename().c_str()); sim.copyPositionsTo(x0); int last_timeslice = traj.getNumberOfTimeslices()-1; sim.readRestart(traj.getTimeslice(last_timeslice).getFilename().c_str()); sim.copyPositionsTo(x); double rsq = 0.0; int dim = sim.getDimensions(); for (int k=0; k<dim; k++) { double dx = x[0][k] - x0[0][k]; rsq += dx*dx; } return sqrt(rsq); }
140f8fb79699c2b1c76688c1b751bc122212bebf
0329788a6657e212944fd1dffb818111e62ee2b0
/docs/snippets/cpp/VS_Snippets_Winforms/Classic Margins.Left Example/CPP/source.cpp
ad5c8dd3c9c609e00932882c178872b848dcad24
[ "CC-BY-4.0", "MIT" ]
permissive
MicrosoftDocs/visualstudio-docs
3e506da16412dfee1f83e82a600c7ce0041c0f33
bff072c38fcfc60cd02c9d1d4a7959ae26a8e23c
refs/heads/main
2023-09-01T16:13:32.046442
2023-09-01T14:26:34
2023-09-01T14:26:34
73,740,273
1,050
1,984
CC-BY-4.0
2023-09-14T17:04:58
2016-11-14T19:36:53
Python
UTF-8
C++
false
false
2,027
cpp
source.cpp
#using <System.dll> #using <System.Windows.Forms.dll> #using <System.Drawing.dll> using namespace System; using namespace System::IO; using namespace System::Drawing; using namespace System::Drawing::Printing; using namespace System::Windows::Forms; public ref class Sample: public Form { protected: StreamReader^ streamToPrint; String^ filePath; String^ printer; System::Drawing::Font^ printFont; public: // <Snippet1> void Printing() { try { /* This assumes that a variable of type string, named filePath, has been set to the path of the file to print. */ streamToPrint = gcnew StreamReader( filePath ); try { printFont = gcnew System::Drawing::Font( "Arial",10 ); PrintDocument^ pd = gcnew PrintDocument; /* This assumes that a method, named pd_PrintPage, has been defined. pd_PrintPage handles the PrintPage event. */ pd->PrintPage += gcnew PrintPageEventHandler( this, &Sample::pd_PrintPage ); /* This assumes that a variable of type string, named printer, has been set to the printer's name. */ pd->PrinterSettings->PrinterName = printer; // Set the left and right margins to 1 inch. pd->DefaultPageSettings->Margins->Left = 100; pd->DefaultPageSettings->Margins->Right = 100; // Set the top and bottom margins to 1.5 inches. pd->DefaultPageSettings->Margins->Top = 150; pd->DefaultPageSettings->Margins->Bottom = 150; pd->Print(); } finally { streamToPrint->Close(); } } catch ( Exception^ ex ) { MessageBox::Show( String::Concat( "An error occurred printing the file - ", ex->Message ) ); } } // </Snippet1> private: void pd_PrintPage( Object^, PrintPageEventArgs^ ){} };
7ce95b35744ff767c413daf78abc5d0497b04829
a82990cc2fc20822d526934dbf87f2c4c3f2f39b
/PJ_Common/GlobalPlayer.cpp
15a928fd233bac0aa40fcc94f6cad7827265a417
[]
no_license
Willdiedog/ms_robot
8327c49eb1d74eed53d8da59aa18b3fdecb80bfd
270c6ea389c15826caa6ea2fa30186e5ea2fbf32
refs/heads/master
2023-03-18T00:04:50.270007
2017-08-25T12:12:19
2017-08-25T12:12:19
null
0
0
null
null
null
null
GB18030
C++
false
false
1,986
cpp
GlobalPlayer.cpp
#include "Precompiled.h" mstr GlobalPlayer::Create_Encrypt_AccountInfo(mstr& xUsername, mstr& xPassword) { mstr x = GETSTRMD5(xUsername); x += xPassword; return GETSTRMD5(x); } DWORD GlobalPlayer::GetNickNameColorByRebornSum(Int32 xRebornSum) { switch (xRebornSum) { case 0x00: { return 0xFFFFFFFF; }break; case 0x01: { return 0xFF00BB00; }break; case 0x02: { return 0xFF008800; }break; case 0x03: { return 0xFFBBBB00; }break; case 0x04: { return 0xFF888800; }break; case 0x05: { return 0xFF00BBBB; }break; case 0x06: { return 0xFF008888; }break; case 0x07: { return 0xFF0000BB; }break; case 0x08: { return 0xFF000088; }break; case 0x09: { return 0xFFBB00BB; }break; case 0x0A: { return 0xFF880088; }break; case 0x0B: { return 0xFFBB0000; }break; case 0x0C: { return 0xFF880000; }break; default: { return 0xFF000000; }break; } } //Int32 GlobalPlayer::FindFirstFreeBagPos(MsProtoDictionary<Int64, item>& xProtoDict_Bag, Int32 xMaxPosCount) //{ // MsSet<Int32> xSetPos; // FAST_FOREACH(xProtoDict_Bag) { xSetPos.Add(xEnumValue.item_pos()); } // // for (Int32 i = 0; i < xMaxPosCount; i++) // { // if (!xSetPos.Contains(i)) // { // return i; // } // } // return INVALID_NID; //} //// 根据背包数据查找指定前面空格数 //MsList<Int32> GlobalPlayer::FindFrontFreeBagPos(MsProtoDictionary<Int64, item>& xProtoDict_Bag, Int32 xFindPosCount, Int32 xMaxPosCount) //{ // MsSet<Int32> xSetPos; // FAST_FOREACH(xProtoDict_Bag) { xSetPos.Add(xEnumValue.item_pos()); } // // MsList<Int32> xList; // for (Int32 i = 0; i < xMaxPosCount; i++) // { // if (!xSetPos.Contains(i)) // { // xList.Add(i); // if (xList.GetCount() == xFindPosCount) // { // return xList; // } // } // } // return xList; //}
58a225b3e20dafa2d63c34e9a6cae6149c773461
ddadb6feaade6710ecfb5d448b9f1faf257d6875
/proj.android/app/jni/AndroidPlatformUtils.cpp
acf754abbbb7f92991faf7277774d3d02073ad08
[]
no_license
prespondek/Elixir
218d864d19347580b69096c42b699709e07f4ebf
f2ad0da6945255fd68b128e6a4c752454e621708
refs/heads/master
2020-06-09T11:28:33.516502
2019-06-24T05:51:50
2019-06-24T05:51:50
193,430,069
0
0
null
null
null
null
UTF-8
C++
false
false
3,258
cpp
AndroidPlatformUtils.cpp
#include "AndroidPlatformUtils.h" #include "platform/android/jni/JniHelper.h" #include <jni.h> const char* const CLASS_NAME = "com/bridge/platform/util/PlatformUtilBridge"; AndroidPlatformUtils::AndroidPlatformUtils() { } AndroidPlatformUtils::~AndroidPlatformUtils() { } void AndroidPlatformUtils::downloadUrl ( const std::string& url, const std::string& path, const std::function<void(const std::string& url,const std::string& path, bool success)>& func ) { CCLOG("PlatformUtils::downloadUrl"); auto iter = _func_list.insert(std::pair<std::string, std::function<void(const std::string& url,const std::string& path, bool success)>>(path, func)); if (iter.second == false) return; cocos2d::JniMethodInfo t; if (cocos2d::JniHelper::getStaticMethodInfo(t, CLASS_NAME, "downloadUrl", "(Ljava/lang/String;Ljava/lang/String;)V")) { jstring jpath = t.env->NewStringUTF(path.c_str()); jstring jurl = t.env->NewStringUTF(url.c_str()); t.env->CallStaticVoidMethod(t.classID, t.methodID, jurl, jpath); t.env->DeleteLocalRef(t.classID); t.env->DeleteLocalRef(jpath); t.env->DeleteLocalRef(jurl); } } void AndroidPlatformUtils::createUUID ( std::string& uuid ) { CCLOG("PlatformUtils::createUUID"); cocos2d::JniMethodInfo t; if (cocos2d::JniHelper::getStaticMethodInfo(t, CLASS_NAME, "createUUID", "()Ljava/lang/String;")) { jstring jobj = (jstring)t.env->CallStaticObjectMethod(t.classID, t.methodID); const char *js = t.env->GetStringUTFChars(jobj, NULL); uuid = js; t.env->ReleaseStringUTFChars(jobj, js); t.env->DeleteLocalRef(t.classID); } } void AndroidPlatformUtils::getBuildNumber ( std::string& out_version, std::string& out_build ) { CCLOG("PlatformUtils::getBuildNumber"); cocos2d::JniMethodInfo t; if (cocos2d::JniHelper::getStaticMethodInfo(t, CLASS_NAME, "getVersionNumber", "()Ljava/lang/String;")) { jstring jobj = (jstring)t.env->CallStaticObjectMethod(t.classID, t.methodID); const char *js = t.env->GetStringUTFChars(jobj, NULL); out_version = js; t.env->ReleaseStringUTFChars(jobj, js); t.env->DeleteLocalRef(t.classID); } if (cocos2d::JniHelper::getStaticMethodInfo(t, CLASS_NAME, "getBuildNumber", "()Ljava/lang/String;")) { jstring jobj = (jstring)t.env->CallStaticObjectMethod(t.classID, t.methodID); const char *js = t.env->GetStringUTFChars(jobj, NULL); out_build = js; t.env->ReleaseStringUTFChars(jobj, js); t.env->DeleteLocalRef(t.classID); } } void AndroidPlatformUtils::downloadCallback( const std::string& url, const std::string& path, bool success) { auto iter = _func_list.find(path); if (iter != _func_list.end()) { iter->second(url,path,success); } } bool AndroidPlatformUtils::init() { return true; } extern "C" { JNIEXPORT void JNICALL Java_com_bridge_platform_util_PlatformUtilBridge_downloadComplete (JNIEnv* env, jclass clazz, jstring jurl, jstring jpath, jboolean jsuccess) { CCLOG("Java_com_bridge_platform_util_PlatformUtilBridge_downloadComplete"); AndroidPlatformUtils* util = static_cast<AndroidPlatformUtils*>(PlatformUtils::getInstance()); std::string url = cocos2d::JniHelper::jstring2string(jurl); std::string path = cocos2d::JniHelper::jstring2string(jpath); util->downloadCallback(url,path,jsuccess); } }
d86ff83c9e5160c56ea3f51ca55cd511284ff643
ebe777eb11ad52c6fc6922c498515c64be54818c
/Hello2/main.cpp
45cdb753048276611974dcb8208ecd1e6e49e59a
[]
no_license
Virusxxxxxxx/Qt
02a5be208ecb82cafa37900ef030c1f9762770c8
09c6c520a56a530cdaae4b82c68f80fbb76a702b
refs/heads/master
2020-04-26T12:08:58.564656
2019-03-03T06:30:05
2019-03-03T06:30:05
173,539,895
0
0
null
null
null
null
UTF-8
C++
false
false
189
cpp
main.cpp
#include <QLabel> #include <QApplication> int main(int argc, char *argv[]) { QApplication app(argc, argv); QLabel lable("Hello,world"); lable.show(); return app.exec(); }
c19ea466db28aea92f67a9394e0495aee8c2172d
c5f34f9e9f5fbe7786f9a6762036f826397ff9e6
/LinkedList/Solution_146.hpp
c970cceb20e0662b799017506309cf966c31f42d
[]
no_license
Iamnvincible/myleetcode
77b0dbf88f124940a2afc6b5a212e6985e3f2889
03b179d8c0a40d83466d5239d84ea69b359f0cfb
refs/heads/master
2021-08-23T09:53:01.652127
2021-06-18T13:28:44
2021-06-18T13:28:44
150,224,748
0
0
null
null
null
null
UTF-8
C++
false
false
2,318
hpp
Solution_146.hpp
#ifndef SOLUTION_146 #define SOLUTION_146 /* Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1. put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item. Follow up: Could you do both operations in O(1) time complexity? 设计一个最近最少使用LRU的数据结构 借助标准库已经实现的双向链表和map数据结构,实现常数时间内的get和put操作 哈希表查找效率高 双向链表的插入和删除效率高 */ #include <list> #include <unordered_map> class LRUCache { public: LRUCache(int capacity) { this->capacity = capacity; } int get(int key) { //没找到 if (cacheMap.find(key) == cacheMap.end()) return -1; //找到了 //把节点移动到链表头部 //把cacheList中cacheMap[key]所指向位置的元素移动到 // cacheList.begin()之前 cacheList.splice(cacheList.begin(), cacheList, cacheMap[key]); //更新原来key指向元素的位置 cacheMap[key] = cacheList.begin(); return cacheMap[key]->value; } void put(int key, int value) { //如果链表中没有这个key if (cacheMap.find(key) == cacheMap.end()) { //是否以及达到容量 if (cacheList.size() == capacity) { //删除链表尾部元素 cacheMap.erase(cacheList.back().key); cacheList.pop_back(); } //插入新key cacheList.push_front(CacheNode(key, value)); cacheMap[key] = cacheList.begin(); } //有这个key,更新value else { cacheMap[key]->value = value; cacheList.splice(cacheList.begin(), cacheList, cacheMap[key]); cacheMap[key] = cacheList.begin(); } } private: struct CacheNode { int key; int value; CacheNode(int k, int v) : key(k), value(v) {} }; //一个双向链表记录节点结构体 std::list<CacheNode> cacheList; //一个map记录key对应结构体在链表中的位置 std::unordered_map<int, std::list<CacheNode>::iterator> cacheMap; //容量 int capacity; }; #endif
a5dce266b58bc56cb2a554567bf17eaa559f3cf2
974d04d2ea27b1bba1c01015a98112d2afb78fe5
/paddle/fluid/framework/ir/cost_model.h
558f158e84e727388a2750d378c21afd36d0a084
[ "Apache-2.0" ]
permissive
PaddlePaddle/Paddle
b3d2583119082c8e4b74331dacc4d39ed4d7cff0
22a11a60e0e3d10a3cf610077a3d9942a6f964cb
refs/heads/develop
2023-08-17T21:27:30.568889
2023-08-17T12:38:22
2023-08-17T12:38:22
65,711,522
20,414
5,891
Apache-2.0
2023-09-14T19:20:51
2016-08-15T06:59:08
C++
UTF-8
C++
false
false
2,575
h
cost_model.h
// Copyright (c) 2021 PaddlePaddle 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. #pragma once #include <functional> #include <map> #include <memory> #include <string> #include <unordered_map> #include <unordered_set> #include <vector> #include "paddle/fluid/framework/ir/graph.h" #include "paddle/fluid/framework/ir/node.h" #include "paddle/fluid/framework/program_desc.h" #include "paddle/fluid/platform/profiler.h" #include "paddle/fluid/platform/profiler/event_tracing.h" namespace paddle { namespace framework { class CostData { public: CostData() {} ~CostData(); // Support global block only // TODO(zhhsplendid): add support for sub-block double GetOpTimeMs(int op_id) const; double GetOpMemoryBytes(int op_id) const; double GetWholeTimeMs() const; double GetWholeMemoryBytes() const; const ir::Graph* GetGraph() const; const ProgramDesc* GetProgram() const; // Support Time Event only // TODO(zhhsplendid): add memory bool SetCostData( const ProgramDesc& program, const std::vector<std::vector<platform::Event>>& time_events); static const double NOT_MEASURED; private: ir::Graph* graph_{nullptr}; ProgramDesc* program_{nullptr}; std::map<int, double> op_time_ms_; // from Op Node id to time std::map<int, double> op_memory_bytes_; // from Op Node id to total memory bytes std::map<int, double> comm_; // from Op Node id to communicate cost double whole_time_ms_{ NOT_MEASURED}; // time cost of the whole program or graph double whole_memory_bytes_{ NOT_MEASURED}; // memory cost of the whole program or graph double whole_comm_{ NOT_MEASURED}; // communication cost of the whole program or graph }; class CostModel { public: CostModel() {} ~CostModel() {} CostData ProfileMeasure( const ProgramDesc& main_program, const ProgramDesc& startup_program, const std::string& device, const std::vector<std::string>& fetch_cost_list) const; }; } // namespace framework } // namespace paddle
30108fd14768235f5982194480e97d4c9a96102a
84b3d094cbef467b07026249908096625b5bbf66
/include/sops.h
e6d5f509e631eecb4adc03966faceb803c0ac80e
[ "MIT" ]
permissive
skyformat99/sswitch
e41038da1c876b40fd23ea54d1b6978dcc4e8381
8fe722deaff871a4db687bc637a7555d4ecc03cc
refs/heads/master
2021-01-17T22:32:11.640088
2016-05-29T01:11:44
2016-05-29T01:11:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,165
h
sops.h
/* Simple Operators for C++0x(SOPS) v0.1 Copyright(c) 2016 by GuruWand. It is freely distributable under the terms of an MIT-style license. */ #ifndef _SOPS_H_ #define _SOPS_H_ #if !defined(__GXX_EXPERIMENTAL_CXX0X__) && _MSC_VER < 1600 #error "Require C++0x or above" #endif #ifdef __cplusplus template <typename T1, typename T2> class SBetweenOperator { private: T1 m_start; T2 m_end; public: inline SBetweenOperator(T1 start, T2 end) { m_start = start; m_end = end; } template <typename T> inline bool Compare(T num) { return m_start <= num && num <= m_end; } }; template <typename T> inline bool operator ==(T num, SBetweenOperator<T, T> se) { return se.Compare(num); } template <typename T> inline bool operator !=(T num, SBetweenOperator<T, T> se) { return !se.Compare(num); } #define sbetween(s,e) == SBetweenOperator<decltype(s), decltype(e)>(s,e) #define not_sbetween(s,e) != SBetweenOperator<decltype(s), decltype(e)>(s,e) #ifndef between # define between sbetween # define not_between not_sbetween #endif //!between #else // !__cplusplus #endif // !__cplusplus #endif // !_SOPS_H_
7e67c5456e2a28588291e43d2e37cda245bb751f
c4535129a3913e44606fde1493f25f3886ddc77f
/Chapter11/chrono/chrono.cpp
86bcc44c1c06c2bc8c2ed46c0d24ac321707ec71
[ "MIT" ]
permissive
abhishekchauh0n/Embedded-Programming-with-Modern-CPP-Cookbook
f7f9f0a27fdcc138693e4ec75a1243e794ba000a
80b8513c68194e4ecb31b49ae827b4fd0f8df573
refs/heads/master
2022-12-17T16:24:10.112825
2020-09-03T12:09:34
2020-09-03T12:09:34
293,453,792
0
0
null
null
null
null
UTF-8
C++
false
false
390
cpp
chrono.cpp
#include <iostream> #include <chrono> using namespace std::chrono_literals; int main() { auto a = std::chrono::system_clock::now(); auto b = a + 1s; auto c = a + 200ms; std::cout << "a < b ? " << (a < b ? "yes" : "no") << std::endl; std::cout << "a < c ? " << (a < c ? "yes" : "no") << std::endl; std::cout << "b < c ? " << (b < c ? "yes" : "no") << std::endl; return 0; }
f17524eb33f2fb87be7eb23d6d0455be2117cd1d
5d0c6904606f08117d89d57454d70a7d57f9ddd2
/leetcode/lwh/Daily_461 汉明距离.cpp
9ae9e477b511a417369ac7133328c0268f9b538a
[]
no_license
VeggieOrz/Algorithm-Practice
148122aaf9b92e592c9e58c9ebb7e65cd9aa52cb
79110e8b3b95e30447c05bda890be0d6e08027ca
refs/heads/master
2021-06-28T06:43:35.880375
2021-06-07T09:28:46
2021-06-07T09:28:46
235,788,813
0
1
null
2020-12-25T09:55:02
2020-01-23T12:18:52
C++
UTF-8
C++
false
false
648
cpp
Daily_461 汉明距离.cpp
/* * 题目:461. 汉明距离 * 链接:https://leetcode-cn.com/problems/hamming-distance/ * 知识点:位运算 */ class Solution { public: // 方法一 int hammingDistance(int x, int y) { int ans = 0; while (x || y) { if ((x & 1) != (y & 1)) { ans++; } x >>= 1; y >>= 1; } return ans; } // 方法二 int lowbit(int x) { return x & -x; } int hammingDistance(int x, int y) { int ans = 0; for (int i = x ^ y; i > 0; i -= lowbit(i)) { ans++; } return ans; } };
57e0503fd12ac6cf0622c3046d3dddc5f4fd4c16
12eab058faa68f697b96ffb0ccee3b4b30577e05
/mopney.cpp
a14bf7aee400bc03af70126b51c1ce5bc4971cbe
[]
no_license
DDWC1603/lab-exercise-chapter-4-suga935
2bcb9cfe62bc138082975e1854b046ebfde8e80b
89c4b54850132fe20ba90a60e249f170f0706db7
refs/heads/master
2021-05-11T21:55:32.787254
2018-01-15T02:14:11
2018-01-15T02:14:11
117,482,055
0
0
null
null
null
null
UTF-8
C++
false
false
383
cpp
mopney.cpp
#include <iostream> using namespace std; int main(){ int i,j,rows; cout <<"\n\n display the pattern like right angle triangle using an asterisk:\n"; cout <<"---------------------------------------------------------------------\n"; cout <<"input number of rows:"; cin >>rows; for(i=1;i<=rows;i++) { for(j=1;i<=i;j++) cout << "+"; cout << endl; } }
8c5b5f946a73bdc70f89b4a8ae5b03d956c028bf
93313b8c1ccc109b86c196a004b4110fdaac23d3
/csgo/hooks/surface/lock_cursor.cpp
bab1deffe1120ff0692255117a04fc822a407628
[]
no_license
thetrollerro/troll_sdk
23863ee124ed2d0941ec7ac16cb62081d677322d
bf4388b5267d12ea3f92bd0f4c3552244b194cf8
refs/heads/master
2022-12-29T21:04:56.507350
2020-10-20T09:57:51
2020-10-20T09:57:51
289,305,433
0
0
null
null
null
null
UTF-8
C++
false
false
263
cpp
lock_cursor.cpp
#include "../hooks.hpp" void __fastcall hooks::lock_cursor::hook( void* ecx, void* edx ) { if ( menu::opened ) { interfaces::surface->unlock_cursor( ); interfaces::inputsystem->reset_input_state( ); return; } o_lockcursor( interfaces::surface, edx ); }
c81e4202d174b394b2934a4cfbf44f1310cc3052
feedea5726e54ca32ed30fe5dccf1a22bca7f9d6
/call_by_ref/call_ref_obj.cpp
ac272fff562db8383e10aa96c63d8d03b8e87bef
[]
no_license
nawazlj/CPP-Programs
22603090fb21efe096ea311186af31e3f59382f6
3bfc3d5ca9c9e5a1b4ab3c627ac12b2e6cdb9614
refs/heads/master
2021-01-01T17:22:24.693759
2014-07-26T06:08:55
2014-07-26T06:08:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
368
cpp
call_ref_obj.cpp
#include <iostream.h> #include <conio.h> class cl { int id; public: int i; cl(int i); ~cl(); void neg(cl &o) { o.i = -o.i; } // no temporary created }; cl::cl(int num) { cout << "Constructing " << num << "\n"; id = num; } cl::~cl() { cout << "Destructing " << id << "\n"; } int main() { clrscr(); cl o(1); o.i = 10; o.neg(o); cout << o.i << "\n"; getch(); return 0; }
9663982e4388ed232eacd7f59a8b5905614251b8
c8a6e4c62c5cea2a4f0e1f4b8f849017bd71151f
/libraries/AODV/RREQ.cpp
41f4379354a75a932a2b4265e38b295def97823f
[]
no_license
mikeadkinsibotta/IntegratedRoutingAdmissionControl
7c3d65b2c5fc33216b5b08ed5d01f47bb94c4ca7
bf6f518b2a06ebb10d0e751860cac0d5a81e94f6
refs/heads/master
2021-06-10T13:37:58.167771
2016-10-11T02:30:45
2016-10-11T02:30:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,723
cpp
RREQ.cpp
#include "RREQ.h" RREQ::RREQ(const XBeeAddress64& sourceAddr, const uint32_t sourceSeqNum, const uint32_t broadcastId, const XBeeAddress64& destAddr, const uint32_t destSeqNum, const uint8_t hopCount) { this->destAddr = destAddr; this->broadcastId = broadcastId; this->sourceAddr = sourceAddr; this->hopCount = hopCount; this->destSeqNum = destSeqNum; this->sourceSeqNum = sourceSeqNum; } RREQ::RREQ(uint8_t * dataPtr) { sourceAddr.setMsb( (uint32_t(dataPtr[5]) << 24) + (uint32_t(dataPtr[6]) << 16) + (uint16_t(dataPtr[7]) << 8) + dataPtr[8]); sourceAddr.setLsb( (uint32_t(dataPtr[9]) << 24) + (uint32_t(dataPtr[10]) << 16) + (uint16_t(dataPtr[11]) << 8) + dataPtr[12]); sourceSeqNum = dataPtr[13]; broadcastId = dataPtr[14]; destAddr.setMsb( (uint32_t(dataPtr[15]) << 24) + (uint32_t(dataPtr[16]) << 16) + (uint16_t(dataPtr[17]) << 8) + dataPtr[18]); destAddr.setLsb( (uint32_t(dataPtr[19]) << 24) + (uint32_t(dataPtr[20]) << 16) + (uint16_t(dataPtr[21]) << 8) + dataPtr[22]); destSeqNum = dataPtr[23]; hopCount = dataPtr[24]; } uint32_t RREQ::getBroadcastId() const { return broadcastId; } void RREQ::setBroadcastId(uint32_t broadcastId) { this->broadcastId = broadcastId; } const XBeeAddress64& RREQ::getDestAddr() const { return destAddr; } void RREQ::setDestAddr(const XBeeAddress64& destAddr) { this->destAddr = destAddr; } uint8_t RREQ::getHopCount() const { return hopCount; } void RREQ::setHopCount(const uint8_t hopCount) { this->hopCount = hopCount; } uint32_t RREQ::getSourceSeqNum() const { return sourceSeqNum; } void RREQ::setSourceSeqNum(uint32_t sourceSeqNum) { this->sourceSeqNum = sourceSeqNum; } const XBeeAddress64& RREQ::getSourceAddr() const { return sourceAddr; } void RREQ::setSourceAddr(const XBeeAddress64& sourceAddr) { this->sourceAddr = sourceAddr; } uint32_t RREQ::getDestSeqNum() const { return destSeqNum; } void RREQ::setDestSeqNum(uint32_t destSeqNum) { this->destSeqNum = destSeqNum; } void RREQ::incrementHopCount() { hopCount++; } bool RREQ::compare(const RREQ &j) const { if (!sourceAddr.equals(j.sourceAddr)) return false; else if (broadcastId != j.broadcastId) return false; return true; } void RREQ::print() const { SerialUSB.print("RREQ"); SerialUSB.print("<SourceAddress: "); sourceAddr.printAddressASCII(&SerialUSB); SerialUSB.print(", SourceSeqNum: "); SerialUSB.print(sourceSeqNum); SerialUSB.print(", BroadcastId: "); SerialUSB.print(broadcastId); SerialUSB.print(", DestinationAddress: "); destAddr.printAddressASCII(&SerialUSB); SerialUSB.print(", DestinationSeqNum: "); SerialUSB.print(destSeqNum); SerialUSB.print(", HopCount: "); SerialUSB.print(hopCount); SerialUSB.println('>'); }
d6c9aec965f71f886abb702284d5c85a577ae351
3b504b276dd420cca1aab3ecc8163d30dff2e78d
/runtime/vm/ast_transformer.cc
d21ef31e26dafffa79edb2925079af9d759daf74
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
abarth/sdk
cd4c63775094537b54eb8f5a3af33b6670094166
0fcc4ee0247407082b2621ea5f904c90e5cf93ad
refs/heads/master
2021-01-19T03:51:10.492854
2017-04-05T17:12:41
2017-04-05T17:12:42
87,337,333
2
0
null
2017-04-05T17:25:14
2017-04-05T17:25:13
null
UTF-8
C++
false
false
20,557
cc
ast_transformer.cc
// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "vm/ast_transformer.h" #include "vm/object_store.h" #include "vm/parser.h" #include "vm/thread.h" namespace dart { // Quick access to the current thread. #define T (thread()) // Quick access to the current zone. #define Z (thread()->zone()) // Quick synthetic token position. #define ST(token_pos) ((token_pos).ToSynthetic()) // Nodes that are unreachable from already parsed expressions. #define FOR_EACH_UNREACHABLE_NODE(V) \ V(AwaitMarker) \ V(Case) \ V(CatchClause) \ V(CloneContext) \ V(ClosureCall) \ V(DoWhile) \ V(If) \ V(InitStaticField) \ V(InlinedFinally) \ V(For) \ V(Jump) \ V(Stop) \ V(LoadInstanceField) \ V(NativeBody) \ V(Primary) \ V(Return) \ V(Sequence) \ V(StoreInstanceField) \ V(Switch) \ V(TryCatch) \ V(While) #define DEFINE_UNREACHABLE(BaseName) \ void AwaitTransformer::Visit##BaseName##Node(BaseName##Node* node) { \ UNREACHABLE(); \ } FOR_EACH_UNREACHABLE_NODE(DEFINE_UNREACHABLE) #undef DEFINE_UNREACHABLE AwaitTransformer::AwaitTransformer(SequenceNode* preamble, LocalScope* async_temp_scope) : preamble_(preamble), temp_cnt_(0), async_temp_scope_(async_temp_scope), thread_(Thread::Current()) { ASSERT(async_temp_scope_ != NULL); } AstNode* AwaitTransformer::Transform(AstNode* expr) { expr->Visit(this); return result_; } LocalVariable* AwaitTransformer::EnsureCurrentTempVar() { String& symbol = String::ZoneHandle(Z, Symbols::NewFormatted(T, "%d", temp_cnt_)); symbol = Symbols::FromConcat(T, Symbols::AwaitTempVarPrefix(), symbol); ASSERT(!symbol.IsNull()); // Look up the variable in the scope used for async temp variables. LocalVariable* await_tmp = async_temp_scope_->LocalLookupVariable(symbol); if (await_tmp == NULL) { // We need a new temp variable; add it to the function's top scope. await_tmp = new (Z) LocalVariable(TokenPosition::kNoSource, TokenPosition::kNoSource, symbol, Object::dynamic_type()); async_temp_scope_->AddVariable(await_tmp); // After adding it to the top scope, we can look it up from the preamble. // The following call includes an ASSERT check. await_tmp = GetVariableInScope(preamble_->scope(), symbol); } return await_tmp; } LocalVariable* AwaitTransformer::GetVariableInScope(LocalScope* scope, const String& symbol) { LocalVariable* var = scope->LookupVariable(symbol, false); ASSERT(var != NULL); return var; } LocalVariable* AwaitTransformer::AddNewTempVarToPreamble( AstNode* node, TokenPosition token_pos) { LocalVariable* tmp_var = EnsureCurrentTempVar(); ASSERT(token_pos.IsSynthetic() || token_pos.IsNoSource()); preamble_->Add(new (Z) StoreLocalNode(token_pos, tmp_var, node)); NextTempVar(); return tmp_var; } LoadLocalNode* AwaitTransformer::MakeName(AstNode* node) { LocalVariable* temp = AddNewTempVarToPreamble(node, ST(node->token_pos())); return new (Z) LoadLocalNode(ST(node->token_pos()), temp); } void AwaitTransformer::VisitLiteralNode(LiteralNode* node) { result_ = node; } void AwaitTransformer::VisitTypeNode(TypeNode* node) { if (node->is_deferred_reference()) { // Deferred references must use a temporary even after loading // happened, so that the number of await temps is the same as // before the loading. result_ = MakeName(node); } else { result_ = node; } } void AwaitTransformer::VisitAwaitNode(AwaitNode* node) { // Await transformation: // // :await_temp_var_X = <expr>; // AwaitMarker(kNewContinuationState); // :result_param = _awaitHelper( // :await_temp_var_X, // :async_then_callback, // :async_catch_error_callback, // :async_op); // return; // (return_type() == kContinuationTarget) // // :saved_try_ctx_var = :await_saved_try_ctx_var_y; // :await_temp_var_(X+1) = :result_param; const TokenPosition token_pos = ST(node->token_pos()); LocalVariable* async_op = GetVariableInScope(preamble_->scope(), Symbols::AsyncOperation()); LocalVariable* async_then_callback = GetVariableInScope(preamble_->scope(), Symbols::AsyncThenCallback()); LocalVariable* async_catch_error_callback = GetVariableInScope( preamble_->scope(), Symbols::AsyncCatchErrorCallback()); LocalVariable* result_param = GetVariableInScope(preamble_->scope(), Symbols::AsyncOperationParam()); LocalVariable* error_param = GetVariableInScope( preamble_->scope(), Symbols::AsyncOperationErrorParam()); LocalVariable* stack_trace_param = GetVariableInScope( preamble_->scope(), Symbols::AsyncOperationStackTraceParam()); AstNode* transformed_expr = Transform(node->expr()); LocalVariable* await_temp = AddNewTempVarToPreamble(transformed_expr, ST(node->token_pos())); AwaitMarkerNode* await_marker = new (Z) AwaitMarkerNode(async_temp_scope_, node->scope(), token_pos); preamble_->Add(await_marker); // :result_param = _awaitHelper( // :await_temp, // :async_then_callback, // :async_catch_error_callback, // :async_op) const Library& async_lib = Library::Handle(Library::AsyncLibrary()); const Function& async_await_helper = Function::ZoneHandle( Z, async_lib.LookupFunctionAllowPrivate(Symbols::AsyncAwaitHelper())); ASSERT(!async_await_helper.IsNull()); ArgumentListNode* async_await_helper_args = new (Z) ArgumentListNode(token_pos); async_await_helper_args->Add(new (Z) LoadLocalNode(token_pos, await_temp)); async_await_helper_args->Add( new (Z) LoadLocalNode(token_pos, async_then_callback)); async_await_helper_args->Add( new (Z) LoadLocalNode(token_pos, async_catch_error_callback)); async_await_helper_args->Add(new (Z) LoadLocalNode(token_pos, async_op)); StaticCallNode* await_helper_call = new (Z) StaticCallNode( node->token_pos(), async_await_helper, async_await_helper_args); preamble_->Add( new (Z) StoreLocalNode(token_pos, result_param, await_helper_call)); ReturnNode* continuation_return = new (Z) ReturnNode(token_pos); continuation_return->set_return_type(ReturnNode::kContinuationTarget); preamble_->Add(continuation_return); // If this expression is part of a try block, also append the code for // restoring the saved try context that lives on the stack and possibly the // saved try context of the outer try block. if (node->saved_try_ctx() != NULL) { preamble_->Add(new (Z) StoreLocalNode( token_pos, node->saved_try_ctx(), new (Z) LoadLocalNode(token_pos, node->async_saved_try_ctx()))); if (node->outer_saved_try_ctx() != NULL) { preamble_->Add(new (Z) StoreLocalNode( token_pos, node->outer_saved_try_ctx(), new (Z) LoadLocalNode(token_pos, node->outer_async_saved_try_ctx()))); } } else { ASSERT(node->outer_saved_try_ctx() == NULL); } // Load the async_op variable. It is unused, but the observatory uses it // to determine if a breakpoint is inside an asynchronous function. LoadLocalNode* load_async_op = new (Z) LoadLocalNode(token_pos, async_op); preamble_->Add(load_async_op); LoadLocalNode* load_error_param = new (Z) LoadLocalNode(token_pos, error_param); LoadLocalNode* load_stack_trace_param = new (Z) LoadLocalNode(token_pos, stack_trace_param); SequenceNode* error_ne_null_branch = new (Z) SequenceNode(token_pos, ChainNewScope(preamble_->scope())); error_ne_null_branch->Add( new (Z) ThrowNode(token_pos, load_error_param, load_stack_trace_param)); preamble_->Add(new (Z) IfNode( token_pos, new (Z) ComparisonNode( token_pos, Token::kNE, load_error_param, new (Z) LiteralNode(token_pos, Object::null_instance())), error_ne_null_branch, NULL)); result_ = MakeName(new (Z) LoadLocalNode(token_pos, result_param)); } // Transforms boolean expressions into a sequence of evaluatons that only lazily // evaluate subexpressions. // // Example: // // (a || b) only evaluates b if a is false // // Transformation (roughly): // // t_1 = a; // if (!t_1) { // t_2 = b; // } // t_3 = t_1 || t_2; // Compiler takes care that lazy evaluation takes place // on this level. AstNode* AwaitTransformer::LazyTransform(const Token::Kind logical_op, AstNode* new_left, AstNode* right) { ASSERT(logical_op == Token::kAND || logical_op == Token::kOR); AstNode* result = NULL; const Token::Kind compare_logical_op = (logical_op == Token::kAND) ? Token::kEQ : Token::kNE; SequenceNode* eval = new (Z) SequenceNode(ST(new_left->token_pos()), ChainNewScope(preamble_->scope())); SequenceNode* saved_preamble = preamble_; preamble_ = eval; result = Transform(right); preamble_ = saved_preamble; IfNode* right_body = new (Z) IfNode(ST(new_left->token_pos()), new (Z) ComparisonNode( ST(new_left->token_pos()), compare_logical_op, new_left, new (Z) LiteralNode(ST(new_left->token_pos()), Bool::True())), eval, NULL); preamble_->Add(right_body); return result; } LocalScope* AwaitTransformer::ChainNewScope(LocalScope* parent) { return new (Z) LocalScope(parent, parent->function_level(), parent->loop_level()); } void AwaitTransformer::VisitBinaryOpNode(BinaryOpNode* node) { AstNode* new_left = Transform(node->left()); AstNode* new_right = NULL; // Preserve lazy evaluaton. if ((node->kind() == Token::kAND) || (node->kind() == Token::kOR)) { new_right = LazyTransform(node->kind(), new_left, node->right()); } else { new_right = Transform(node->right()); } result_ = MakeName(new (Z) BinaryOpNode(node->token_pos(), node->kind(), new_left, new_right)); } void AwaitTransformer::VisitComparisonNode(ComparisonNode* node) { AstNode* new_left = Transform(node->left()); AstNode* new_right = Transform(node->right()); result_ = MakeName(new (Z) ComparisonNode(node->token_pos(), node->kind(), new_left, new_right)); } void AwaitTransformer::VisitUnaryOpNode(UnaryOpNode* node) { AstNode* new_operand = Transform(node->operand()); result_ = MakeName( new (Z) UnaryOpNode(node->token_pos(), node->kind(), new_operand)); } // ::= (<condition>) ? <true-branch> : <false-branch> // void AwaitTransformer::VisitConditionalExprNode(ConditionalExprNode* node) { AstNode* new_condition = Transform(node->condition()); SequenceNode* new_true = new (Z) SequenceNode( ST(node->true_expr()->token_pos()), ChainNewScope(preamble_->scope())); SequenceNode* saved_preamble = preamble_; preamble_ = new_true; AstNode* new_true_result = Transform(node->true_expr()); SequenceNode* new_false = new (Z) SequenceNode( ST(node->false_expr()->token_pos()), ChainNewScope(preamble_->scope())); preamble_ = new_false; AstNode* new_false_result = Transform(node->false_expr()); preamble_ = saved_preamble; IfNode* new_if = new (Z) IfNode(ST(node->token_pos()), new_condition, new_true, new_false); preamble_->Add(new_if); result_ = MakeName(new (Z) ConditionalExprNode( ST(node->token_pos()), new_condition, new_true_result, new_false_result)); } void AwaitTransformer::VisitArgumentListNode(ArgumentListNode* node) { ArgumentListNode* new_args = new (Z) ArgumentListNode(node->token_pos()); for (intptr_t i = 0; i < node->length(); i++) { new_args->Add(Transform(node->NodeAt(i))); } new_args->set_names(node->names()); result_ = new_args; } void AwaitTransformer::VisitArrayNode(ArrayNode* node) { GrowableArray<AstNode*> new_elements; for (intptr_t i = 0; i < node->length(); i++) { new_elements.Add(Transform(node->ElementAt(i))); } result_ = new (Z) ArrayNode(node->token_pos(), node->type(), new_elements); } void AwaitTransformer::VisitStringInterpolateNode(StringInterpolateNode* node) { ArrayNode* new_value = Transform(node->value())->AsArrayNode(); result_ = MakeName(new (Z) StringInterpolateNode(node->token_pos(), new_value)); } void AwaitTransformer::VisitClosureNode(ClosureNode* node) { AstNode* new_receiver = node->receiver(); if (new_receiver != NULL) { new_receiver = Transform(new_receiver); } result_ = MakeName(new (Z) ClosureNode(node->token_pos(), node->function(), new_receiver, node->scope())); } void AwaitTransformer::VisitInstanceCallNode(InstanceCallNode* node) { AstNode* new_receiver = Transform(node->receiver()); ArgumentListNode* new_args = Transform(node->arguments())->AsArgumentListNode(); result_ = MakeName(new (Z) InstanceCallNode(node->token_pos(), new_receiver, node->function_name(), new_args, node->is_conditional())); } void AwaitTransformer::VisitStaticCallNode(StaticCallNode* node) { ArgumentListNode* new_args = Transform(node->arguments())->AsArgumentListNode(); result_ = MakeName( new (Z) StaticCallNode(node->token_pos(), node->function(), new_args)); } void AwaitTransformer::VisitConstructorCallNode(ConstructorCallNode* node) { ArgumentListNode* new_args = Transform(node->arguments())->AsArgumentListNode(); result_ = MakeName( new (Z) ConstructorCallNode(node->token_pos(), node->type_arguments(), node->constructor(), new_args)); } void AwaitTransformer::VisitInstanceGetterNode(InstanceGetterNode* node) { AstNode* new_receiver = Transform(node->receiver()); result_ = MakeName(new (Z) InstanceGetterNode(node->token_pos(), new_receiver, node->field_name(), node->is_conditional())); } void AwaitTransformer::VisitInstanceSetterNode(InstanceSetterNode* node) { AstNode* new_receiver = node->receiver(); if (new_receiver != NULL) { new_receiver = Transform(new_receiver); } AstNode* new_value = Transform(node->value()); result_ = MakeName(new (Z) InstanceSetterNode(node->token_pos(), new_receiver, node->field_name(), new_value, node->is_conditional())); } void AwaitTransformer::VisitStaticGetterNode(StaticGetterNode* node) { AstNode* new_receiver = node->receiver(); if (new_receiver != NULL) { new_receiver = Transform(new_receiver); } StaticGetterNode* new_getter = new (Z) StaticGetterNode( node->token_pos(), new_receiver, node->cls(), node->field_name()); new_getter->set_owner(node->owner()); result_ = MakeName(new_getter); } void AwaitTransformer::VisitStaticSetterNode(StaticSetterNode* node) { AstNode* new_receiver = node->receiver(); if (new_receiver != NULL) { new_receiver = Transform(new_receiver); } AstNode* new_value = Transform(node->value()); StaticSetterNode* new_setter = node->function().IsNull() ? new (Z) StaticSetterNode(node->token_pos(), new_receiver, node->cls(), node->field_name(), new_value) : new (Z) StaticSetterNode(node->token_pos(), new_receiver, node->field_name(), node->function(), new_value); result_ = MakeName(new_setter); } void AwaitTransformer::VisitLoadLocalNode(LoadLocalNode* node) { result_ = MakeName(node); } void AwaitTransformer::VisitStoreLocalNode(StoreLocalNode* node) { AstNode* new_value = Transform(node->value()); result_ = MakeName( new (Z) StoreLocalNode(node->token_pos(), &node->local(), new_value)); } void AwaitTransformer::VisitLoadStaticFieldNode(LoadStaticFieldNode* node) { result_ = MakeName(node); } void AwaitTransformer::VisitStoreStaticFieldNode(StoreStaticFieldNode* node) { AstNode* new_value = Transform(node->value()); result_ = MakeName(new (Z) StoreStaticFieldNode( node->token_pos(), Field::ZoneHandle(Z, node->field().Original()), new_value)); } void AwaitTransformer::VisitLoadIndexedNode(LoadIndexedNode* node) { AstNode* new_array = Transform(node->array()); AstNode* new_index = Transform(node->index_expr()); result_ = MakeName(new (Z) LoadIndexedNode(node->token_pos(), new_array, new_index, node->super_class())); } void AwaitTransformer::VisitStoreIndexedNode(StoreIndexedNode* node) { AstNode* new_array = Transform(node->array()); AstNode* new_index = Transform(node->index_expr()); AstNode* new_value = Transform(node->value()); result_ = MakeName(new (Z) StoreIndexedNode( node->token_pos(), new_array, new_index, new_value, node->super_class())); } void AwaitTransformer::VisitAssignableNode(AssignableNode* node) { AstNode* new_expr = Transform(node->expr()); result_ = MakeName(new (Z) AssignableNode(node->token_pos(), new_expr, node->type(), node->dst_name())); } void AwaitTransformer::VisitLetNode(LetNode* node) { // Add all the initializer nodes to the preamble and the // temporary variables to the scope for async temporary variables. // The temporary variables will be captured as a side effect of being // added to a scope, and the subsequent nodes that are added to the // preample can access them. for (intptr_t i = 0; i < node->num_temps(); i++) { async_temp_scope_->AddVariable(node->TempAt(i)); AstNode* new_init_val = Transform(node->InitializerAt(i)); preamble_->Add(new (Z) StoreLocalNode(node->token_pos(), node->TempAt(i), new_init_val)); } // Add all expressions but the last to the preamble. We must do // this because subexpressions of the awaitable expression we // are currently transforming may depend on each other, // e.g. await foo(a++, a++). Thus we must preserve the order of the // transformed subexpressions. for (intptr_t i = 0; i < node->nodes().length() - 1; i++) { preamble_->Add(Transform(node->nodes()[i])); } // The last expression in the let node is the value of the node. // The result of the transformed let node is this expression. ASSERT(node->nodes().length() > 0); const intptr_t last_node_index = node->nodes().length() - 1; result_ = Transform(node->nodes()[last_node_index]); } void AwaitTransformer::VisitThrowNode(ThrowNode* node) { AstNode* new_exception = Transform(node->exception()); result_ = MakeName( new (Z) ThrowNode(node->token_pos(), new_exception, node->stacktrace())); } } // namespace dart
83096fc240ce160519e174446431d7d730e86d4b
05592f35197b7243f3e886f78f71ed82234b1dc8
/include/mylibrary/item.h
ac127ab8fc3f61fa79f37fa1eb23db4af0d70e92
[ "MIT" ]
permissive
CS126SP20/final-project-swee4
402c3e90a8815e653486f9d0e3d355f71e28de26
50c443c95516bdfbb6b83825998ce68033282f35
refs/heads/master
2023-02-18T10:19:16.574531
2021-01-23T14:11:19
2021-01-23T14:11:19
257,195,750
0
0
null
null
null
null
UTF-8
C++
false
false
3,053
h
item.h
// Copyright (c) 2020 [Sue Wee]. All rights reserved. #ifndef FINALPROJECT_MYLIBRARY_ITEM_H_ #define FINALPROJECT_MYLIBRARY_ITEM_H_ #include "mylibrary/ciAnimatedGif.h" #include <string> namespace mylibrary { using std::string; /** * Class to represent items that the character is able to pick up and update their stats with, or add to * their inventory. */ class Item { public: /** * Default constructor for an Item, which sets most values to be empty except for the image, which it sets to a * bee by default, which was arbitrarily chosen. This constructor is necessary for the program to run. */ Item(); /** * Creates an item based on the dynamic type that is passed down from the Tile class during Tile dynamic type * assignment. * @param dynamic_type The string representation of the dynamic type that is represented by the item. */ Item(const string& dynamic_type); /** * Gets the gif of the item. * @return Visual of the item. */ cinder::ciAnimatedGifRef& GetImage(); /** * Gets the acronym for the buff category that the item corresponds to, which is based on the first two letters * of the dynamic type string that is loaded in from the maps. * @return Acronym for the buff category of the item. */ string GetBuffAcronym(); /** * Gets the value of how much the item will increase the character's current stats that aligns with the category * of the buff, if the character were to pick up the item. * @return Value of how much the character's stats will increase in the corresponding buff's category. */ size_t GetValue(); /** * Gets the description of the item, which contains the name, its buff's category, and the value of the buff, * excluding bees. Bees will use the description that is assigned in the Tile class. * @return Description of the item. */ string GetDescription(); /** * Instructions on how to interact with the item. * @return Instruction of how to pick up the item. */ string GetInteractionInstructions(); private: /** Gif representation of the item. **/ cinder::ciAnimatedGifRef image; /** Acronym of the buff that corresponds to the item. **/ string buff_acronym; /** Buff category that corresponds to the item. **/ string buff; /** Value of how much the character's corresponding stat will increase if they were to pick up the item.**/ size_t value; /** Description of the item. **/ string description; /** Name of the item. **/ string name; /** Instructions on how to interact with the item. **/ string interaction_instructions; /** * Assign the name, image, and value of the item based on the dynamic type that it is. * @param dynamic_type Dynamic type derived from the text file of the scene loaded in. */ void AssignNameImageAndValue(const string& dynamic_type); }; } // namespace mylibrary #endif // FINALPROJECT_MYLIBRARY_ITEM_H_
38e79e4b8986d3a7933b3c057362f2e83a737687
f1960e86ffed49ead6cbb02c07559ac304bd22e2
/cmmdc pana la val 0/main.cpp
38c6e4a151af5cbb0f1d8c23b2f42935b73db283
[]
no_license
skiry/Highschool
6aa09f28f0952c06953f9b8b417c32ef9970f6d4
319b05c33db733a4108b6fbd73328cca159caff3
refs/heads/master
2021-05-14T12:25:57.251753
2018-01-06T00:24:36
2018-01-06T00:24:36
116,405,336
1
0
null
null
null
null
UTF-8
C++
false
false
411
cpp
main.cpp
#include <iostream> using namespace std; int a,cmin=9999999,b; int main() {cout<<"Dati o valoare lui a : "; cin>>a; cout<<"Dati o valoare lui b : "; cin>>b; while(a!=0) { while(a!=b) {if(a>b) a=a-b; else b=b-a; if(b<cmin) cmin=b;} cout<<"Dati o alta valoare lui a,pana cand ii dati valoarea 0 : "; cin>>a; }cout<<"CMMDC este "<<cmin<<endl; return 0; }
2b4f387f9b81661c91a16efc0c523cc4cd2e238d
dc78997e3c1904a7c62825b924eff5ea508237ce
/cyclefinding.cpp
a2e73066072be44349a493407a66a3ff02e41b68
[ "MIT" ]
permissive
Mohamed-Aziz-Ben-Nessir/comparative-programming
45b0f92ce35f5728e946defe95472dd01ca75167
69ff173277d66daf73fbe41a6229b489ab5243ea
refs/heads/main
2023-07-19T02:30:13.767980
2021-09-14T14:55:50
2021-09-14T14:55:50
374,184,379
1
0
null
null
null
null
UTF-8
C++
false
false
1,255
cpp
cyclefinding.cpp
#include <bits/stdc++.h> #define endl "\n" using namespace std; #define int long long int class triplet{ public: int first; int second; int third; }; int n, m; vector<triplet> edges; vector<int> dist; vector<int> relaxant; void bellman_ford() { int x; for(int i = 1; i <= n; ++i) { x = -1; for(auto e: edges) { int u = e.first; int v = e.second; int d = e.third; if(dist[u]+d < dist[v]) { dist[v] = d+dist[u]; relaxant[v] = u; x = v; } } } // n relaxations if(x == -1) cout << "NO" << endl; else { for(int i = 1; i <= n; ++i) { x = relaxant[x]; } vector<int> cycle; for(int v = x; ; v = relaxant[v]) { cycle.push_back(v); if(v == x and cycle.size() > 1) break; } reverse(cycle.begin(), cycle.end()); cout << "YES" << endl; for(auto v: cycle) { cout << v << " "; } cout << endl; } } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> n >> m; dist.resize(n+1); relaxant.resize(n+1); edges.resize(m); for(int i = 0; i < m; ++i) { struct triplet inp; cin >> inp.first >> inp.second >> inp.third; edges[i] = inp; } for(int i = 1; i <= n; ++i) { relaxant[i] = -1; } bellman_ford(); }
0f9176c00cd82983321862ce0756bfd4fb03bc13
18ab3e4aafdfe0bdecccbe8730375c11fc4cf400
/src/material/oren_nayar.cpp
ab1e937997f042759c2fbf5d8119a552f6bab9ca
[]
no_license
isikmustafa/glue
3217c93a65db53fbf15a8653b7741a3954197f52
3645eb8a04d83b97eec40ff9e19fd1df88a82592
refs/heads/master
2021-04-15T06:03:14.438470
2019-07-18T18:57:29
2019-07-18T18:57:29
126,844,473
7
1
null
null
null
null
UTF-8
C++
false
false
2,699
cpp
oren_nayar.cpp
#include "oren_nayar.h" #include "../geometry/spherical_coordinate.h" #include "../core/real_sampler.h" #include "../core/math.h" #include "../xml/node.h" #include <glm/gtc/constants.hpp> #include <glm/trigonometric.hpp> namespace glue { namespace material { OrenNayar::Xml::Xml(const xml::Node& node) { kd = texture::Texture::Xml::factory(node.child("Kd", true)); node.parseChildText("Roughness", &roughness); } OrenNayar::Xml::Xml(std::unique_ptr<texture::Texture::Xml> p_kd, float p_roughness) : kd(std::move(p_kd)) , roughness(p_roughness) {} std::unique_ptr<BsdfMaterial> OrenNayar::Xml::create() const { return std::make_unique<OrenNayar>(*this); } OrenNayar::OrenNayar(const OrenNayar::Xml& xml) : m_kd(xml.kd->create()) { auto r2 = xml.roughness * xml.roughness; m_A = 1.0f - r2 / (2.0f * (r2 + 0.33f)); m_B = 0.45f * r2 / (r2 + 0.09f); } std::pair<glm::vec3, glm::vec3> OrenNayar::sampleWi(const glm::vec3& wo_tangent, core::UniformSampler& sampler, const geometry::Intersection& intersection) const { glm::vec3 wi(0.0f); glm::vec3 f(0.0f); if (core::math::cosTheta(wo_tangent) > 0.0f) { wi = core::math::sampleHemisphereCosine(sampler.sample(), sampler.sample()).toCartesianCoordinate(); f = getBsdf(wi, wo_tangent, intersection) * glm::pi<float>(); } return std::make_pair(wi, f); } glm::vec3 OrenNayar::getBsdf(const glm::vec3& wi_tangent, const glm::vec3& wo_tangent, const geometry::Intersection& intersection) const { if (core::math::cosTheta(wi_tangent) > 0.0f && core::math::cosTheta(wo_tangent) > 0.0f) { geometry::SphericalCoordinate wi_ts(wi_tangent); geometry::SphericalCoordinate wo_ts(wo_tangent); return m_kd->fetch(intersection) * glm::one_over_pi<float>() * (m_A + m_B * glm::max(0.0f, glm::cos(wi_ts.phi - wo_ts.phi)) * glm::sin(glm::max(wi_ts.theta, wo_ts.theta)) * glm::tan(glm::min(wi_ts.theta, wo_ts.theta))); } return glm::vec3(0.0f); } float OrenNayar::getPdf(const glm::vec3& wi_tangent, const glm::vec3& wo_tangent, const geometry::Intersection& intersection) const { if (core::math::cosTheta(wi_tangent) > 0.0f && core::math::cosTheta(wo_tangent) > 0.0f) { return core::math::cosTheta(wi_tangent) * glm::one_over_pi<float>(); } return 0.0f; } bool OrenNayar::hasDeltaDistribution(const geometry::Intersection& intersection) const { return false; } bool OrenNayar::useMultipleImportanceSampling(const geometry::Intersection& intersection) const { return false; } bool OrenNayar::isSpecular(const geometry::Intersection& intersection) const { return false; } } }
653dac5fc61f200b51f09d1b08f9f3e386a5f5ec
695097fdaf80653d774fe827e69ffc519c80fa56
/logic.hpp
3f52680b09ea4aebace44dc0442736818d408ef7
[]
no_license
vahabit84/X0
5e7bb22cc9ef47d19cd7a905dcb24deb43eb5fc2
344c209b1642804a1ab678ef22771c8ba7c939cd
refs/heads/main
2023-04-14T19:17:55.052322
2021-05-06T08:45:49
2021-05-06T08:45:49
364,843,088
0
0
null
null
null
null
UTF-8
C++
false
false
2,141
hpp
logic.hpp
#pragma once #include<cstdint> #include<windows.h> enum CellState{Empty,X,O}; typedef enum CellState cell; extern size_t szField; struct Pos{ size_t posX; size_t posY; }; void printField(cell *A){ system("CLS"); for(size_t i=0;i<szField;i++){ std::cout <<"|"; for(size_t j=0;j<szField;j++ ) { if(A[(szField*i)+j]==Empty) std::cout << "_" << "|"; if(A[(szField*i)+j]==X) std::cout << "X" << "|"; if(A[(szField*i)+j]==O) std::cout << "0" << "|"; } std::cout << "\n"; } } bool is_draw(CellState *map) { for (size_t i = 0; i < szField*szField; i++) { if ( map[i] == CellState::Empty) { return false; } } return true; } bool is_win(CellState *map, CellState K){ size_t w=0; //stroki for(size_t i=0; i<szField;i++){ w=0; for(size_t j=0; j<szField;j++){ //std::cout << "stroki\n"; if( K!=map[((i*szField)+j)] ) break; K=map[((i*szField)+j)]; w++; } if(w==(szField)) return true; //stolbchi w=0; for(size_t j=0; j<szField;j++){ if( K!=map[i+(j*szField)]) break; K=map[i+(j*szField)];w++; } if(w==szField) return true; } //dioganal 1 w=0; for(size_t j=0; j<szField;j++){ //std::cout << "dioganaal1\n"; if( K!=map[(szField+1)*j]) break; K=map[(szField+1)*j];w++; } if(w==szField) return true; //dioganal 2 w=0; for(size_t j=0; j<szField;j++){ //std::cout << "diogsnsl2\n"; if( K!=map[(szField-1)*(j+1)]) break; K=map[(szField-1)*(j+1)];w++; } if(w==szField) return true; return false; } //проверка победа-ничья enum Vihod{continium, win,draw}; Vihod Proverka(CellState* map,CellState player){ if(is_win(map,player))return win; if(is_draw(map)){return draw;}; return continium; }
e7929a1e7d1a3e23c4240028d5d7b93462681b22
8b9daac9b2e32015d947f53c8f005685beaae877
/c/c012 10062 - Tell me the frequencies! (2).cpp
ca85937cd2a9fb7bd027edb90e6f8c9b54c03ba5
[]
no_license
NarouMas/ZeroJudge
ffa3b19ec742e47ebbc46cb5eb94eee13bc9a8c8
bed515d77413ddb5595d010c4b912df0207321bd
refs/heads/master
2020-04-11T08:37:23.688246
2018-12-13T14:29:34
2018-12-13T14:29:34
161,650,012
2
1
null
null
null
null
UTF-8
C++
false
false
533
cpp
c012 10062 - Tell me the frequencies! (2).cpp
#include<iostream> #include<algorithm> using namespace std; struct F { int f; int ac; }; bool cmp(F a,F b) { if(a.f!=b.f) return a.f<b.f; else return a.ac>b.ac; } int main() { char a[1001]; int ac[1001],n; while(cin.getline(a,1001)) { F ans[1001]; for(int i=0;i<1001;i++) ac[i]=0; for(int i=0;a[i]!='\0';i++) ac[int(a[i])]++; n=0; for(int i=0;i<1001;i++) if(ac[i]!=0) ans[n].ac=i,ans[n].f=ac[i],n++; sort(ans,ans+n,cmp); for(int i=0;i<n;i++) cout<<ans[i].ac<<" "<<ans[i].f<<endl; } }
083d2493417434f8e4fd0738379d63f687f2556c
6c70c1724f561fb4181e83ff46d36d4af2259508
/src/media/image.h
32354b5ad0b1c24fdb8df967a7c39ebecd9e36c5
[ "MIT" ]
permissive
getopenmono/mono_framework
36875f05f57e784e1591e7572a55fc9b6d314615
899a5820ac850a1f5b3b205bfe3892556ae064ca
refs/heads/master
2021-04-09T17:31:46.558731
2017-09-26T09:55:01
2017-09-26T10:22:06
37,125,865
10
1
null
2017-06-26T17:34:30
2015-06-09T10:32:07
C
UTF-8
C++
false
false
2,862
h
image.h
// This software is part of OpenMono, see http://developer.openmono.com // Released under the MIT license, see LICENSE.txt #ifndef displaySimTest_image_h #define displaySimTest_image_h #include <stdio.h> namespace mono { namespace media { /** * Generic image container class, defining generic properties and methods * for all image formats. * * Subclasses of this class implement different image formats, that can be * decoded by mono framework. See @ref BMPImage * * The class is an abstract interface that defines 3 methods for reading the * raw pixel data from the image, these works like file I/O with a read/write * cursor. * * * @ref ReadPixelData Reads individual raw pixels (@ref Color) from the image * * @ref SkipPixelData Skip a number of pixels * * @ref SeekToHLine Jump to a specific horizontal line in the image (Y coordinate) */ class Image { public: virtual ~Image() {} /** * Returns the width of the image in pixels * */ virtual int Width() = 0; /** * Returns the height of the image in pixels */ virtual int Height() = 0; /** * Returns the pixel size in bytes. This is the format pixels are returned * in, by the method @ref ReadPixelData * * @returns Pixel size in bytes */ virtual int PixelByteSize() = 0; /** * Read raw uncompressed pixels from the image. The pixels are read from * the current position (as set by @ref SeekToHLine), and copied to the * `target` position. * * @param target Pointer to the array where pixels are copied to * @param pixelsToRead The number of pixels to read from the image * @returns The number of pixels that was actually read */ virtual int ReadPixelData(void *target, int pixelsToRead) = 0; /** * Like @ref ReadPixelData but will just skip the pixels, not read them. * This method increments the image current position pointer, as it is set * by @ref SeekToHLine. * * @param pixelsToSkip The number of pixels to skip. * @returns The number of pixels thatwas skipped */ virtual int SkipPixelData(int pixelsToSkip) = 0; /** * Changes the current position cursor of the image to a certain line in * the image. * * @param vertPos The horizontal line in the image, the Y-coordinate */ virtual void SeekToHLine(int vertPos) = 0; /** * Returns `true` if image is usable. * @returns `true` if you can actually get a proper image, `false` otherwise */ virtual bool IsValid() = 0; }; } } #endif
727cd2c734789eeefaa5ee30ecdfbb74bba483d8
05a1a5509e90bcd7e17e92e65a4d2f1fa08d9dbe
/cbeginning/src/functors.cpp
2dcf789299497a006e51f9e39e89a3c3c6b5ec77
[]
no_license
tutorua/Atom
1483a52970836700f3e2dde470df58abb897ea75
6250dc2991b10065ac2f68334a499c564bd5e5ef
refs/heads/master
2021-04-30T01:46:20.929354
2018-09-11T10:11:40
2018-09-11T10:11:40
121,490,108
0
0
null
null
null
null
UTF-8
C++
false
false
550
cpp
functors.cpp
/* https://www.youtube.com/watch?v=fD0Sykh3vPs C++ - predicates and functors Bradley Needham */ #include <iostream> #include <algorithm> #include <vector> #include <string> using namespace std; // Functor overload a Function struct isOdd { bool operator()(int x) { return x % 2; } }; bool isEqual(int a, int b) { return a==b; } int main() { cout << "Functorss in C example:" << '\n'; isOdd fn; cout << boolalpha << fn(4) << endl; cout << boolalpha << isEqual(5,5) << endl; //getch(); return 0; }
b868e9195bc22a8fdae13e51ed0196603222f254
bed3ac926beac0f4e0293303d7b2a6031ee476c9
/Modules/ThirdParty/GDCM/src/gdcm/Source/MediaStorageAndFileFormat/gdcmStrictScanner.h
1463607138a82f680cab1468f76fec8068c106a1
[ "IJG", "Zlib", "LicenseRef-scancode-proprietary-license", "SMLNJ", "BSD-3-Clause", "BSD-4.3TAHOE", "LicenseRef-scancode-free-unknown", "Spencer-86", "LicenseRef-scancode-llnl", "FSFUL", "Libpng", "libtiff", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-hdf5", "MIT", "NTP", "LicenseRef-scancode-mit-old-style", "GPL-1.0-or-later", "LicenseRef-scancode-unknown-license-reference", "MPL-2.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
InsightSoftwareConsortium/ITK
ed9dbbc5b8b3f7511f007c0fc0eebb3ad37b88eb
3eb8fd7cdfbc5ac2d0c2e5e776848a4cbab3d7e1
refs/heads/master
2023-08-31T17:21:47.754304
2023-08-31T00:58:51
2023-08-31T14:12:21
800,928
1,229
656
Apache-2.0
2023-09-14T17:54:00
2010-07-27T15:48:04
C++
UTF-8
C++
false
false
6,765
h
gdcmStrictScanner.h
/*========================================================================= Program: GDCM (Grassroots DICOM). A DICOM library Copyright (c) 2006-2011 Mathieu Malaterre All rights reserved. See Copyright.txt or http://gdcm.sourceforge.net/Copyright.html 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. =========================================================================*/ #ifndef GDCMSTRICTSCANNER_H #define GDCMSTRICTSCANNER_H #include "gdcmDirectory.h" #include "gdcmSubject.h" #include "gdcmTag.h" #include "gdcmPrivateTag.h" #include "gdcmSmartPointer.h" #include <map> #include <set> #include <string> #include <string.h> // strcmp namespace gdcm { class StringFilter; /** * \brief StrictScanner * \details This filter is meant for quickly browsing a FileSet (a set of files on * disk). Special consideration are taken so as to read the minimum amount of * information in each file in order to retrieve the user specified set of * DICOM Attribute. * * This filter is dealing with both VRASCII and VRBINARY element, thanks to the * help of StringFilter * * \warning IMPORTANT In case of file where tags are not ordered (illegal as * per DICOM specification), the output will be missing information * * \note implementation details. All values are stored in a std::set of * std::string. Then the address of the cstring underlying the std::string is * used in the std::map. * * This class implement the Subject/Observer pattern trigger the following events: * \li ProgressEvent * \li StartEvent * \li EndEvent */ class GDCM_EXPORT StrictScanner : public Subject { friend std::ostream& operator<<(std::ostream &_os, const StrictScanner &s); public: StrictScanner():Values(),Filenames(),Mappings() {} ~StrictScanner() override; /// struct to map a filename to a value /// Implementation note: /// all std::map in this class will be using const char * and not std::string /// since we are pointing to existing std::string (hold in a std::vector) /// this avoid an extra copy of the byte array. /// Tag are used as Tag class since sizeof(tag) <= sizeof(pointer) typedef std::map<Tag, const char*> TagToValue; //typedef std::map<Tag, ConstCharWrapper> TagToValue; //StringMap; //typedef TagToStringMap TagToValue; typedef TagToValue::value_type TagToValueValueType; /// Add a tag that will need to be read. Those are root level skip tags void AddTag( Tag const & t ); void ClearTags(); // Work in progress do not use: void AddPrivateTag( PrivateTag const & t ); /// Add a tag that will need to be skipped. Those are root level skip tags void AddSkipTag( Tag const & t ); void ClearSkipTags(); /// Start the scan ! bool Scan( Directory::FilenamesType const & filenames ); Directory::FilenamesType const &GetFilenames() const { return Filenames; } /// Print result void Print( std::ostream & os ) const override; void PrintTable( std::ostream & os ) const; /// Check if filename is a key in the Mapping table. /// returns true only of file can be found, which means /// the file was indeed a DICOM file that could be processed bool IsKey( const char * filename ) const; /// Return the list of filename that are key in the internal map, /// which means those filename were properly parsed Directory::FilenamesType GetKeys() const; // struct to store all the values found: typedef std::set< std::string > ValuesType; /// Get all the values found (in lexicographic order) ValuesType const & GetValues() const { return Values; } /// Get all the values found (in lexicographic order) associated with Tag 't' ValuesType GetValues(Tag const &t) const; /// Get all the values found (in a vector) associated with Tag 't' /// This function is identical to GetValues, but is accessible from the wrapped /// layer (python, C#, java) Directory::FilenamesType GetOrderedValues(Tag const &t) const; /* ltstr is CRITICAL, otherwise pointers value are used to do the key comparison */ struct ltstr { bool operator()(const char* s1, const char* s2) const { assert( s1 && s2 ); return strcmp(s1, s2) < 0; } }; typedef std::map<const char *,TagToValue, ltstr> MappingType; typedef MappingType::const_iterator ConstIterator; ConstIterator Begin() const { return Mappings.begin(); } ConstIterator End() const { return Mappings.end(); } /// Mappings are the mapping from a particular tag to the map, mapping filename to value: MappingType const & GetMappings() const { return Mappings; } /// Get the std::map mapping filenames to value for file 'filename' TagToValue const & GetMapping(const char *filename) const; /// Will loop over all files and return the first file where value match the reference value /// 'valueref' const char *GetFilenameFromTagToValue(Tag const &t, const char *valueref) const; /// Will loop over all files and return a vector of std::strings of filenames /// where value match the reference value 'valueref' Directory::FilenamesType GetAllFilenamesFromTagToValue(Tag const &t, const char *valueref) const; /// See GetFilenameFromTagToValue(). This is simply GetFilenameFromTagToValue followed // by a call to GetMapping() TagToValue const & GetMappingFromTagToValue(Tag const &t, const char *value) const; /// Retrieve the value found for tag: t associated with file: filename /// This is meant for a single short call. If multiple calls (multiple tags) /// should be done, prefer the GetMapping function, and then reuse the TagToValue /// hash table. /// \warning Tag 't' should have been added via AddTag() prior to the Scan() call ! const char* GetValue(const char *filename, Tag const &t) const; /// for wrapped language: instantiate a reference counted object static SmartPointer<StrictScanner> New() { return new StrictScanner; } protected: void ProcessPublicTag(StringFilter &sf, const char *filename); private: // struct to store all uniq tags in ascending order: typedef std::set< Tag > TagsType; typedef std::set< PrivateTag > PrivateTagsType; std::set< Tag > Tags; std::set< PrivateTag > PrivateTags; std::set< Tag > SkipTags; ValuesType Values; Directory::FilenamesType Filenames; // Main struct that will hold all mapping: MappingType Mappings; double Progress; }; //----------------------------------------------------------------------------- inline std::ostream& operator<<(std::ostream &os, const StrictScanner &s) { s.Print( os ); return os; } } // end namespace gdcm #endif //GDCMSTRICTSCANNER_H
686a5719368772950f8ff9bbe812c4a060075bee
39a6672a9e6dfde55381a0b23bb40e9d736e5c8a
/ProjetoHidro/janelasobre.h
7ba57ddc53d547e52dfbaa9affdb66121152ade8
[]
no_license
rodolfo53821/ReBuild
749fa33f64b2424ab397a056a41b9c94d14d4a4c
f96f9230ddec09c806781b3ed232be0547cf002e
refs/heads/master
2016-08-04T02:42:36.994023
2012-10-02T13:39:06
2012-10-02T13:39:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
295
h
janelasobre.h
#ifndef JANELASOBRE_H #define JANELASOBRE_H #include <QDialog> namespace Ui { class janelasobre; } class janelasobre : public QDialog { Q_OBJECT public: explicit janelasobre(QWidget *parent = 0); ~janelasobre(); private: Ui::janelasobre *ui; }; #endif // JANELASOBRE_H
7babe907111acd5722a49b95cfece728b78c64ed
4474aa3f06ce4832bfa25a55d46dde26f16877b1
/extensions/FunctionLib/source/TTCrossFadeOutFunction.cpp
a80cdaa1d5b3b174566524f8851f3545013f3d25
[ "BSD-3-Clause" ]
permissive
RWelsh/JamomaDSP
3e392fe59e0c6d074e3c4f055d0c3f011815ccef
81183644a074e9750f0e1c0f44beb6206eb6ba6e
refs/heads/master
2016-09-06T15:05:25.103104
2012-11-16T23:09:17
2012-11-16T23:09:17
20,038,760
0
1
null
null
null
null
UTF-8
C++
false
false
934
cpp
TTCrossFadeOutFunction.cpp
/* * TTCrossFadeOutFunction Unit for Jamoms DSP * Originally written for the Jamoma FunctionLib * Copyright © 2012 by Trond Lossius * * License: This code is licensed under the terms of the "New BSD License" * http://creativecommons.org/licenses/BSD/ */ #include "TTCrossFadeOutFunction.h" #include <math.h> #define thisTTClass TTCrossFadeOutFunction #define thisTTClassName "crossFadeOut" #define thisTTClassTags "audio, processor, function" TT_AUDIO_CONSTRUCTOR { setProcessMethod(processAudio); setCalculateMethod(calculateValue); } TTCrossFadeOutFunction::~TTCrossFadeOutFunction() { ; } TTErr TTCrossFadeOutFunction::calculateValue(const TTFloat64& x, TTFloat64& y, TTPtrSizedInt data) { y = 1.0 - sin((1.0-x) * kTTPi * 0.5); return kTTErrNone; } TTErr TTCrossFadeOutFunction::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs) { TT_WRAP_CALCULATE_METHOD(calculateValue); }
36415b9b3ef0fcfd7e1199583cb3b83f4a7e6b5e
92947e9833b94814612d14a65d1e3772bda10553
/DeepSee_Stars/DeepSee_Stars/SceneManager/Scene/GameScene/Player/UI/RetentionMissionItem.cpp
7a64cc137df092bb18afcc3a6b7164fcda3a5a59
[]
no_license
human-osaka-game-2018/DeepSee-Stars
db68ee2f834e8f187fed653ea45177f2cc12b85b
6e4c65ee0f328a7489850304c936f80616780f65
refs/heads/master
2020-04-30T21:34:03.248483
2019-05-31T10:52:07
2019-05-31T10:57:05
177,096,457
0
0
null
2019-06-12T05:27:01
2019-03-22T07:57:06
C++
UTF-8
C++
false
false
542
cpp
RetentionMissionItem.cpp
#include "RetentionMissionItem.h" namespace deepseestars { void RetentionMissionItem::Update() { m_missionItem = min(max(m_missionItem, 0), 4); } void RetentionMissionItem::Render() { D3DXVECTOR2 pos = { 1210.f, 650.f }; D3DXVECTOR2 scale = { 70.f , 70.f }; m_vertices.SetPos(pos); m_vertices.SetScale(scale); m_rGameBaseMaker.Render(m_vertices, m_rGameBaseMaker.GetTex(m_MissionItemUITextureKey[0])); m_rGameBaseMaker.Render(m_vertices, m_rGameBaseMaker.GetTex(m_MissionItemUITextureKey[m_missionItem + 1])); } }
d0d5cf79cd120e8b012270d3a2dbd73a9d35de60
619941b532c6d2987c0f4e92b73549c6c945c7e5
/Include/Nuclex/Config.h
40b69d503082f194c6d96cef85d442ae1338916d
[]
no_license
dzw/stellarengine
2b70ddefc2827be4f44ec6082201c955788a8a16
2a0a7db2e43c7c3519e79afa56db247f9708bc26
refs/heads/master
2016-09-01T21:12:36.888921
2008-12-12T12:40:37
2008-12-12T12:40:37
36,939,169
0
0
null
null
null
null
UTF-8
C++
false
false
2,275
h
Config.h
//  // // # # ### # # -= Nuclex Library =-  // // ## # # # ## ## Config.h - Build configuration  // // ### # # ###  // // # ### # ### Contains various #defines for configuring  // // # ## # # ## ## the Nuclex build process  // // # # ### # # R1 (C)2002-2004 Markus Ewald -> License.txt  // //  // #ifndef NUCLEX_CONFIG_H #define NUCLEX_CONFIG_H #ifndef __cplusplus #error Nuclex requires C++ #endif // #include "MemoryTracker/MemoryTracker.h" // Defines the current version of nuclex. Can be used by // applications to identify compatibility issues // #define NUCLEX_VERSION 0x050 // Platform recognition // #if defined(WIN32) || defined(_WIN32) #define NUCLEX_WIN32 #else #define NUCLEX_LINUX #endif // The following block will decide whether symbols are imported from a // dll (client app) or exported to a dll (nuclex library). The NUCLEX_EXPORTS symbol // should only be used for compiling the nuclex library and nowhere else. // #ifdef NUCLEX_EXPORTS #define NUCLEX_API __declspec(dllexport) #else #define NUCLEX_API //__declspec(dllimport) #endif #include <cstddef> #include <numeric> namespace Nuclex { // Import size_t from std into the nuclex namespace using std::size_t; // These are only used for some special hardware-dependant operations // such as interfacing with the graphics adapter or writing image files #ifdef _MSC_VER #pragma warning(disable:4786) // Warning: Debug symbol truncated to 255 characters typedef unsigned __int8 unsigned_8; typedef unsigned __int16 unsigned_16; typedef unsigned __int32 unsigned_32; const size_t BitsPerByte = 8; #else #pragma warning("Unknown byte size for current platform. Assuming x86 layout") typedef unsigned char unsigned_8; typedef unsigned short unsigned_16; typedef unsigned long unsigned_32; const size_t BitsPerByte = 8; #endif } // namespace Nuclex #endif // NUCLEX_CONFIG_H
a9b5b41e671fb39d92ded8f15fd0e5eef99dc47a
5d7786b4a467b5ad7a48a1780f5e79174bbebebe
/src/settings/BoolMetadata.h
71f84706bbad826dadf972e1cf2a69310c9fce4f
[ "MIT" ]
permissive
rexMingla/-deprecated-clippy-cpp
ef2b8925ee71bf08899c779156af63d70128454c
dc1bb5e77a37e217d62c751a72caf16f5d7ec254
refs/heads/master
2021-03-27T19:17:30.579602
2015-02-22T06:33:36
2015-02-22T06:33:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
483
h
BoolMetadata.h
/* See the file "LICENSE.md" for the full license governing this code. */ #ifndef BOOL_METADATA_H #define BOOL_METADATA_H #include "SettingMetadata.h" /** * @brief Metadata that always returns true (added for consistency rather than having a null Metadata) */ class BoolMetadata : public SettingMetadata { public: explicit BoolMetadata(const QVariant& defaultValue); ~BoolMetadata(); bool isValid(const QVariant&value, QString& error) const; }; #endif // BOOL_METADATA_H
045c3b8259df8b958c9a4f6bdf7a2348538f496d
8a87f5b889a9ce7d81421515f06d9c9cbf6ce64a
/3rdParty/boost/1.78.0/boost/python/object/inheritance.hpp
90e56f0c1d6731d3c01ee30f1ea2a796e1fdae99
[ "BSL-1.0", "Apache-2.0", "BSD-3-Clause", "ICU", "Zlib", "GPL-1.0-or-later", "OpenSSL", "ISC", "LicenseRef-scancode-gutenberg-2020", "MIT", "GPL-2.0-only", "CC0-1.0", "LicenseRef-scancode-autoconf-simple-exception", "LicenseRef-scancode-pcre", "Bison-exception-2.2", "LicenseRef-scancode-public-domain", "JSON", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference", "Unlicense", "BSD-4-Clause", "Python-2.0", "LGPL-2.1-or-later" ]
permissive
arangodb/arangodb
0980625e76c56a2449d90dcb8d8f2c485e28a83b
43c40535cee37fc7349a21793dc33b1833735af5
refs/heads/devel
2023-08-31T09:34:47.451950
2023-08-31T07:25:02
2023-08-31T07:25:02
2,649,214
13,385
982
Apache-2.0
2023-09-14T17:02:16
2011-10-26T06:42:00
C++
UTF-8
C++
false
false
3,542
hpp
inheritance.hpp
// Copyright David Abrahams 2002. // 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 INHERITANCE_DWA200216_HPP # define INHERITANCE_DWA200216_HPP # include <boost/python/type_id.hpp> # include <boost/shared_ptr.hpp> # include <boost/mpl/if.hpp> # include <boost/detail/workaround.hpp> # include <boost/python/detail/type_traits.hpp> namespace boost { namespace python { namespace objects { typedef type_info class_id; using python::type_id; // Types used to get address and id of most derived type typedef std::pair<void*,class_id> dynamic_id_t; typedef dynamic_id_t (*dynamic_id_function)(void*); BOOST_PYTHON_DECL void register_dynamic_id_aux( class_id static_id, dynamic_id_function get_dynamic_id); BOOST_PYTHON_DECL void add_cast( class_id src_t, class_id dst_t, void* (*cast)(void*), bool is_downcast); // // a generator with an execute() function which, given a source type // and a pointer to an object of that type, returns its most-derived // /reachable/ type identifier and object pointer. // // first, the case where T has virtual functions template <class T> struct polymorphic_id_generator { static dynamic_id_t execute(void* p_) { T* p = static_cast<T*>(p_); return std::make_pair(dynamic_cast<void*>(p), class_id(typeid(*p))); } }; // now, the non-polymorphic case. template <class T> struct non_polymorphic_id_generator { static dynamic_id_t execute(void* p_) { return std::make_pair(p_, python::type_id<T>()); } }; // Now the generalized selector template <class T> struct dynamic_id_generator : mpl::if_< boost::python::detail::is_polymorphic<T> , boost::python::objects::polymorphic_id_generator<T> , boost::python::objects::non_polymorphic_id_generator<T> > {}; // Register the dynamic id function for T with the type-conversion // system. template <class T> void register_dynamic_id(T* = 0) { typedef typename dynamic_id_generator<T>::type generator; register_dynamic_id_aux( python::type_id<T>(), &generator::execute); } // // a generator with an execute() function which, given a void* // pointing to an object of type Source will attempt to convert it to // an object of type Target. // template <class Source, class Target> struct dynamic_cast_generator { static void* execute(void* source) { return dynamic_cast<Target*>( static_cast<Source*>(source)); } }; template <class Source, class Target> struct implicit_cast_generator { static void* execute(void* source) { Target* result = static_cast<Source*>(source); return result; } }; template <class Source, class Target> struct cast_generator : mpl::if_< boost::python::detail::is_base_and_derived<Target,Source> , implicit_cast_generator<Source,Target> , dynamic_cast_generator<Source,Target> > { }; template <class Source, class Target> inline void register_conversion( bool is_downcast = ::boost::is_base_and_derived<Source,Target>::value // These parameters shouldn't be used; they're an MSVC bug workaround , Source* = 0, Target* = 0) { typedef typename cast_generator<Source,Target>::type generator; add_cast( python::type_id<Source>() , python::type_id<Target>() , &generator::execute , is_downcast ); } }}} // namespace boost::python::object #endif // INHERITANCE_DWA200216_HPP
5ebbce86ab544d9be138dae40bae4c08dbbb5526
9ecbc437bd1db137d8f6e83b7b4173eb328f60a9
/gcc-build/i686-pc-linux-gnu/libjava/javax/realtime/AbsoluteTime.h
b3ae18e4b5d7e24809b4637791cc854bb59b1da0
[]
no_license
giraffe/jrate
7eabe07e79e7633caae6522e9b78c975e7515fe9
764bbf973d1de4e38f93ba9b9c7be566f1541e16
refs/heads/master
2021-01-10T18:25:37.819466
2013-07-20T12:28:23
2013-07-20T12:28:23
11,545,290
1
0
null
null
null
null
UTF-8
C++
false
false
1,607
h
AbsoluteTime.h
// DO NOT EDIT THIS FILE - it is machine generated -*- c++ -*- #ifndef __javax_realtime_AbsoluteTime__ #define __javax_realtime_AbsoluteTime__ #pragma interface #include <javax/realtime/HighResolutionTime.h> extern "Java" { namespace javax { namespace realtime { class Clock; class RelativeTime; class AbsoluteTime; } } }; class ::javax::realtime::AbsoluteTime : public ::javax::realtime::HighResolutionTime { public: AbsoluteTime (); AbsoluteTime (jlong, jint); AbsoluteTime (::javax::realtime::AbsoluteTime *); AbsoluteTime (::java::util::Date *); virtual ::javax::realtime::AbsoluteTime *add (jlong, jint); virtual void add (jlong, jint, ::javax::realtime::AbsoluteTime *); ::javax::realtime::AbsoluteTime *add (::javax::realtime::RelativeTime *); void add (::javax::realtime::RelativeTime *, ::javax::realtime::AbsoluteTime *); virtual void increment (::javax::realtime::RelativeTime *); virtual void decrement (::javax::realtime::RelativeTime *); virtual ::java::util::Date *getDate (); virtual ::javax::realtime::RelativeTime *relative (::javax::realtime::Clock *); ::javax::realtime::RelativeTime *subtract (::javax::realtime::AbsoluteTime *); void subtract (::javax::realtime::AbsoluteTime *, ::javax::realtime::RelativeTime *); ::javax::realtime::AbsoluteTime *subtract (::javax::realtime::RelativeTime *); void subtract (::javax::realtime::RelativeTime *, ::javax::realtime::AbsoluteTime *); virtual ::java::lang::String *toString (); static ::java::lang::Class class$; }; #endif /* __javax_realtime_AbsoluteTime__ */
2f8f8ead87bfc9f42c005e4cd4c969eda522aaee
2b249938e504350adc7967b58312af50a7925a37
/Client.h
9f80655af0e4451f93ab935f0994715730ee0cfe
[]
no_license
hanaa-abdelgawad/DesignPattern_ObserverDP_CPP_WeatherStationSubscribers
6241f115b1a7e0560e7b937a1120f99b5c16e543
e168bf7d79b6016cbdd22d8b821a16e306682fa6
refs/heads/master
2020-09-12T20:16:40.486963
2019-11-18T20:41:24
2019-11-18T20:41:24
222,540,598
0
0
null
null
null
null
UTF-8
C++
false
false
357
h
Client.h
#ifndef OBSERVER_PATTERN_CLIENT_H #define OBSERVER_PATTERN_CLIENT_H #include <iostream> #include "Observer.h" /** * a client that implements the Observer interface */ class Client : public Observer { int id; public: Client(int id); virtual void update(float temp, float humidity, float pressure) override; }; #endif //OBSERVER_PATTERN_CLIENT_H
b8bd7565bdb9e7d957a57cbf6d0a0a2c97185936
eb039fcb8dccfef9cec68dd97bdc3fa63d420845
/kifaru.old/audio.h
8df8c0f08142dbd7768704764f30133a40114d5c
[]
no_license
BackupTheBerlios/kifaru
8fead5b2de6a838aee9cfb0c3c869caaffc35038
b694dffbd4e85c07689d35af5198f1ed1c415f5f
refs/heads/master
2020-12-02T16:00:17.331679
2006-06-28T18:22:20
2006-06-28T18:22:20
40,044,599
0
0
null
null
null
null
UTF-8
C++
false
false
315
h
audio.h
#include <SDL/SDL.h> #include <SDL/SDL_mixer.h> namespace ephidrena { class Audio { private: int Rate,Channels,Buffers; Uint16 Format; Mix_Music *musikk; public: Audio(); ~Audio(); void InitOgg(const char[]); void PlayOgg(); Uint32 OggPosition(); }; };
0594fe9c305a3c3d8ac55f582947821eb4e30c45
b46f65355d9a79e8d7ea7bd473a7d559ee601a1b
/src/aggregators/mk/season.hpp
1bd7bee6f4255e55a6e8347fe44c891ea7188d46
[]
no_license
ekuiter/bsdl
8c50eba05f43a789fc58c2e92aa3cd0a6d62d52b
1f9d9cf5f1f55dab3480023456e244001a6a9eae
refs/heads/master
2020-04-05T15:16:29.337225
2018-10-16T19:40:46
2018-10-16T19:40:46
68,543,822
0
0
null
null
null
null
UTF-8
C++
false
false
814
hpp
season.hpp
#pragma once #include <iostream> #include <map> #include <memory> #include "exception.hpp" #include "episode.hpp" #include "../../http/client.hpp" #include "../aggregator.hpp" using namespace std; namespace aggregators { namespace mk { class season : public aggregators::season { private: map<int, http::request> episode_requests; void load(const http::response& response) const override; public: season(const string& _series_title, const int _number, const map<int, http::request>& _episode_requests): aggregators::season(_series_title, _number, http::request::idle) { episode_requests = _episode_requests; } virtual ostream& print(ostream& stream) const override; }; } }
9546d7509ab3f7896acd2d1fcf709b81e9e819bd
acfdc76c8fbddf2ab4ed668016ab04884c38dd6f
/colourextract.cpp
d742718f421b2cbf1d13b31fd13a4c38b9054cf0
[]
no_license
Balaji-Udayagiri/system-files
b820c85426eaf0f5caf971d512be0ed6e113b398
0deb50f21c0e19c11e12606c2b0b37ef682fa10c
refs/heads/master
2020-04-29T07:29:37.904545
2019-03-16T10:04:44
2019-03-16T10:04:44
175,954,879
0
1
null
null
null
null
UTF-8
C++
false
false
858
cpp
colourextract.cpp
#include"opencv2/core/core.hpp" #include"opencv2/highgui/highgui.hpp" #include"opencv2/imgproc/imgproc.hpp" #include<iostream> using namespace std; using namespace cv; void nokku (int a,void* b) { for(int i=0;i<img1.rows;i++) for(int j=0;j<img1.cols;j++) { if(img1.at<uchar>(j,i)>th) img2.at<uchar>(j,i)=255; else img2.at<uchar>(j,i)=0; } imshow ("win",img2); } int main() { Mat img1=imread("joker.jpg",1); Mat img2(img1.rows,img1.cols,CV_8UC3,Scalar(0,0,0)); namedWindow("win",1); int th=100; createTrackbar("colcola","win",&th,255,nokku); createTrackbar("pepsi","win",&th,255,nokku); createTrackbar("balayya babu","win",&th,255,nokku); for(int i=0;i<img1.rows;i++) for(int j=0;j<img1.cols;j++) { if(img1.at<uchar>(j,i)>th) img2.at<uchar>(j,i)=255; else img2.at<uchar>(j,i)=0; } waitKey (0); return 0; }