hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
dd05284c102ac99a75464f29ae7e8320f1abbc9a
430
hpp
C++
development/CppDB/libCppDb/include/CppDb/details/CrcTypes.hpp
AntonPoturaev/CppDB
034d7feafc438fc585441742472bf4b5ef637eb2
[ "Unlicense" ]
null
null
null
development/CppDB/libCppDb/include/CppDb/details/CrcTypes.hpp
AntonPoturaev/CppDB
034d7feafc438fc585441742472bf4b5ef637eb2
[ "Unlicense" ]
null
null
null
development/CppDB/libCppDb/include/CppDb/details/CrcTypes.hpp
AntonPoturaev/CppDB
034d7feafc438fc585441742472bf4b5ef637eb2
[ "Unlicense" ]
null
null
null
#if !defined(__CPP_ABSTRACT_DATA_BASE_DETAILS_CRC_TYPES_HPP__) # define __CPP_ABSTRACT_DATA_BASE_DETAILS_CRC_TYPES_HPP__ #include <boost/crc.hpp> namespace CppAbstractDataBase { namespace Details { typedef boost::crc_32_type tCrcAlgorithm; } /// end namespace Details typedef Details::tCrcAlgorithm::value_type tCrcValue; } /// end namespace CppAbstractDataBase #endif /// !__CPP_ABSTRACT_DATA_BASE_DETAILS_CRC_TYPES_HPP__
33.076923
62
0.832558
AntonPoturaev
dd08d346ce941191c315e37a554d85af48b33e05
32,801
cpp
C++
tracer/src/Datadog.Trace.ClrProfiler.Native/always_on_profiler.cpp
Kielek/signalfx-dotnet-tracing
80c65ca936748788629287472401fa9f31b79410
[ "Apache-2.0" ]
null
null
null
tracer/src/Datadog.Trace.ClrProfiler.Native/always_on_profiler.cpp
Kielek/signalfx-dotnet-tracing
80c65ca936748788629287472401fa9f31b79410
[ "Apache-2.0" ]
2
2022-02-10T06:13:13.000Z
2022-02-17T01:31:15.000Z
tracer/src/Datadog.Trace.ClrProfiler.Native/always_on_profiler.cpp
Kielek/signalfx-dotnet-tracing
80c65ca936748788629287472401fa9f31b79410
[ "Apache-2.0" ]
null
null
null
// We want to use std::min, not the windows.h macro #define NOMINMAX #include "always_on_profiler.h" #include "logger.h" #include <chrono> #include <map> #include <algorithm> #ifndef _WIN32 #include <pthread.h> #include <codecvt> #endif constexpr auto kMaxStringLength = 512UL; constexpr auto kMaxCodesPerBuffer = 10 * 1000; // If you change this, consider ThreadSampler.cs too constexpr auto kSamplesBufferMaximumSize = 200 * 1024; constexpr auto kSamplesBufferDefaultSize = 20 * 1024; // If you change these, change ThreadSampler.cs too constexpr auto kDefaultSamplePeriod = 10000; constexpr auto kMinimumSamplePeriod = 1000; // FIXME make configurable (hidden)? // These numbers were chosen to keep total overhead under 1 MB of RAM in typical cases (name lengths being the biggest // variable) constexpr auto kMaxFunctionNameCacheSize = 7000; constexpr auto kParamNameMaxLen = 260; constexpr auto kGenericParamsMaxLen = 20; constexpr auto kUnknown = WStr("Unknown"); constexpr auto kParamsSeparator = WStr(", "); constexpr auto kGenericParamsOpeningBrace = WStr("["); constexpr auto kGenericParamsClosingBrace = WStr("]"); constexpr auto kFunctionParamsOpeningBrace = WStr("("); constexpr auto kFunctionParamsClosingBrace = WStr(")"); // If you squint you can make out that the original bones of this came from sample code provided by the dotnet project: // https://github.com/dotnet/samples/blob/2cf486af936261b04a438ea44779cdc26c613f98/core/profiling/stacksampling/src/sampler.cpp // That stack sampling project is worth reading for a simpler (though higher overhead) take on thread sampling. static std::mutex buffer_lock = std::mutex(); static std::vector<unsigned char>* buffer_a; static std::vector<unsigned char>* buffer_b; static std::mutex thread_span_context_lock; static std::unordered_map<ThreadID, trace::thread_span_context> thread_span_context_map; static ICorProfilerInfo10* profiler_info; // After feature sets settle down, perhaps this should be refactored and have a single static instance of ThreadSampler // Dirt-simple back pressure system to save overhead if managed code is not reading fast enough bool ThreadSamplingShouldProduceThreadSample() { std::lock_guard<std::mutex> guard(buffer_lock); return buffer_a == nullptr || buffer_b == nullptr; } void ThreadSamplingRecordProducedThreadSample(std::vector<unsigned char>* buf) { std::lock_guard<std::mutex> guard(buffer_lock); if (buffer_a == nullptr) { buffer_a = buf; } else if (buffer_b == nullptr) { buffer_b = buf; } else { trace::Logger::Warn("Unexpected buffer drop in ThreadSampling_RecordProducedThreadSample"); delete buf; // needs to be dropped now } } // Can return 0 if none are pending int32_t ThreadSamplingConsumeOneThreadSample(int32_t len, unsigned char* buf) { if (len <= 0 || buf == nullptr) { trace::Logger::Warn("Unexpected 0/null buffer to ThreadSampling_ConsumeOneThreadSample"); return 0; } std::vector<unsigned char>* to_use = nullptr; { std::lock_guard<std::mutex> guard(buffer_lock); if (buffer_a != nullptr) { to_use = buffer_a; buffer_a = nullptr; } else if (buffer_b != nullptr) { to_use = buffer_b; buffer_b = nullptr; } } if (to_use == nullptr) { return 0; } const size_t to_use_len = static_cast<int>(std::min(to_use->size(), static_cast<size_t>(len))); memcpy(buf, to_use->data(), to_use_len); delete to_use; return static_cast<int32_t>(to_use_len); } namespace trace { /* * The thread samples buffer format is optimized for single-pass and efficient writing by the native sampling thread (which * has paused the CLR) * * It uses a simple byte-opcode format with fairly standard binary encoding of values. It is entirely positional but is at least versioned * so that mismatched components (native writer and managed reader) will not emit nonsense. * * ints, shorts, and 64-bit longs are written in big-endian format; strings are written as 2-byte-length-prefixed standard windows utf-16 strings * * I would write out the "spec" for this format here, but it essentially maps to the code * (e.g., 0x01 is StartBatch, which is followed by an int versionNumber and a long captureStartTimeInMillis) * * The bulk of the data is an (unknown length) array of frame strings, which are represented as coded strings in each buffer. * Each used string is given a code (starting at 1) - using an old old inline trick, codes are introduced by writing the code as a * negative number followed by the definition of the string (length-prefixed) that maps to that code. Later uses of the code * simply use the 2-byte (positive) code, meaning frequently used strings will take only 2 bytes apiece. 0 is reserved for "end of list" * since the number of frames is not known up-front. * * Each buffer can be parsed/decoded independently; the codes and the LRU NameCache are not related. */ // defined op codes constexpr auto kThreadSamplesStartBatch = 0x01; constexpr auto kThreadSamplesStartSample = 0x02; constexpr auto kThreadSamplesEndBatch = 0x06; constexpr auto kThreadSamplesFinalStats = 0x07; constexpr auto kCurrentThreadSamplesBufferVersion = 1; ThreadSamplesBuffer::ThreadSamplesBuffer(std::vector<unsigned char>* buf) : buffer_(buf) { } ThreadSamplesBuffer ::~ThreadSamplesBuffer() { buffer_ = nullptr; // specifically don't delete as this is done by RecordProduced/ConsumeOneThreadSample } #define CHECK_SAMPLES_BUFFER_LENGTH() { if (buffer_->size() >= kSamplesBufferMaximumSize) { return; } } void ThreadSamplesBuffer::StartBatch() const { CHECK_SAMPLES_BUFFER_LENGTH() WriteByte(kThreadSamplesStartBatch); WriteInt(kCurrentThreadSamplesBufferVersion); const auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()); WriteUInt64(ms.count()); } void ThreadSamplesBuffer::StartSample(ThreadID id, const ThreadState* state, const thread_span_context& span_context) const { CHECK_SAMPLES_BUFFER_LENGTH() WriteByte(kThreadSamplesStartSample); WriteInt(span_context.managed_thread_id_); WriteInt(static_cast<int32_t>(state->native_id_)); WriteString(state->thread_name_); WriteUInt64(span_context.trace_id_high_); WriteUInt64(span_context.trace_id_low_); WriteUInt64(span_context.span_id_); // Feature possibilities: (managed/native) thread priority, cpu/wait times, etc. } void ThreadSamplesBuffer::RecordFrame(FunctionID fid, const shared::WSTRING& frame) { CHECK_SAMPLES_BUFFER_LENGTH() WriteCodedFrameString(fid, frame); } void ThreadSamplesBuffer::EndSample() const { CHECK_SAMPLES_BUFFER_LENGTH() WriteShort(0); } void ThreadSamplesBuffer::EndBatch() const { CHECK_SAMPLES_BUFFER_LENGTH() WriteByte(kThreadSamplesEndBatch); } void ThreadSamplesBuffer::WriteFinalStats(const SamplingStatistics& stats) const { CHECK_SAMPLES_BUFFER_LENGTH() WriteByte(kThreadSamplesFinalStats); WriteInt(stats.micros_suspended); WriteInt(stats.num_threads); WriteInt(stats.total_frames); WriteInt(stats.name_cache_misses); } void ThreadSamplesBuffer::WriteCodedFrameString(FunctionID fid, const shared::WSTRING& str) { const auto found = codes_.find(fid); if (found != codes_.end()) { WriteShort(static_cast<int16_t>(found->second)); } else { const int code = static_cast<int>(codes_.size()) + 1; if (codes_.size() + 1 < kMaxCodesPerBuffer) { codes_[fid] = code; } WriteShort(static_cast<int16_t>(-code)); // note negative sign indicating definition of code WriteString(str); } } void ThreadSamplesBuffer::WriteShort(int16_t val) const { buffer_->push_back(((val >> 8) & 0xFF)); buffer_->push_back(val & 0xFF); } void ThreadSamplesBuffer::WriteInt(int32_t val) const { buffer_->push_back(((val >> 24) & 0xFF)); buffer_->push_back(((val >> 16) & 0xFF)); buffer_->push_back(((val >> 8) & 0xFF)); buffer_->push_back(val & 0xFF); } void ThreadSamplesBuffer::WriteString(const shared::WSTRING& str) const { // limit strings to a max length overall; this prevents (e.g.) thread names or // any other miscellaneous strings that come along from blowing things out const short used_len = static_cast<short>(std::min(str.length(), static_cast<size_t>(kMaxStringLength))); WriteShort(used_len); // odd bit of casting since we're copying bytes, not wchars const auto str_begin = reinterpret_cast<const unsigned char*>(&str.c_str()[0]); // possible endian-ness assumption here; unclear how the managed layer would decode on big endian platforms buffer_->insert(buffer_->end(), str_begin, str_begin + used_len * 2); } void ThreadSamplesBuffer::WriteByte(unsigned char b) const { buffer_->push_back(b); } void ThreadSamplesBuffer::WriteUInt64(uint64_t val) const { buffer_->push_back(((val >> 56) & 0xFF)); buffer_->push_back(((val >> 48) & 0xFF)); buffer_->push_back(((val >> 40) & 0xFF)); buffer_->push_back(((val >> 32) & 0xFF)); buffer_->push_back(((val >> 24) & 0xFF)); buffer_->push_back(((val >> 16) & 0xFF)); buffer_->push_back(((val >> 8) & 0xFF)); buffer_->push_back(val & 0xFF); } class SamplingHelper { public: // These are permanent parts of the helper object ICorProfilerInfo10* info10_ = nullptr; NameCache function_name_cache_; // These cycle every sample and/or are owned externally ThreadSamplesBuffer* cur_writer_ = nullptr; std::vector<unsigned char>* cur_buffer_ = nullptr; SamplingStatistics stats_; SamplingHelper() : function_name_cache_(kMaxFunctionNameCacheSize) { } bool AllocateBuffer() { const bool should = ThreadSamplingShouldProduceThreadSample(); if (!should) { return should; } stats_ = SamplingStatistics(); cur_buffer_ = new std::vector<unsigned char>(); cur_buffer_->reserve(kSamplesBufferDefaultSize); cur_writer_ = new ThreadSamplesBuffer(cur_buffer_); return should; } void PublishBuffer() { ThreadSamplingRecordProducedThreadSample(cur_buffer_); delete cur_writer_; cur_writer_ = nullptr; cur_buffer_ = nullptr; stats_ = SamplingStatistics(); } private: [[nodiscard]] FunctionIdentifier GetFunctionIdentifier(const FunctionID func_id, const COR_PRF_FRAME_INFO frame_info) const { if (func_id == 0) { constexpr auto zero_valid_function_identifier = FunctionIdentifier{0, 0, true}; return zero_valid_function_identifier; } ModuleID module_id = 0; mdToken function_token = 0; // theoretically there is a possibility to use GetFunctionInfo method, but it does not support generic methods const HRESULT hr = info10_->GetFunctionInfo2(func_id, frame_info, nullptr, &module_id, &function_token, 0, nullptr, nullptr); if (FAILED(hr)) { Logger::Debug("GetFunctionInfo2 failed. HRESULT=0x", std::setfill('0'), std::setw(8), std::hex, hr); constexpr auto zero_invalid_function_identifier = FunctionIdentifier{0, 0, false}; return zero_invalid_function_identifier; } return FunctionIdentifier{function_token, module_id, true}; } void GetFunctionName(FunctionIdentifier function_identifier, shared::WSTRING& result) { constexpr auto unknown_list_of_arguments = WStr("(unknown)"); constexpr auto unknown_function_name = WStr("Unknown(unknown)"); constexpr auto name_separator = WStr("."); if (!function_identifier.is_valid) { result.append(unknown_function_name); return; } if (function_identifier.function_token == 0) { constexpr auto unknown_native_function_name = WStr("Unknown_Native_Function(unknown)"); result.append(unknown_native_function_name); return; } ComPtr<IMetaDataImport2> metadata_import; HRESULT hr = info10_->GetModuleMetaData(function_identifier.module_id, ofRead, IID_IMetaDataImport2, reinterpret_cast<IUnknown**>(&metadata_import)); if (FAILED(hr)) { Logger::Debug("GetModuleMetaData failed. HRESULT=0x", std::setfill('0'), std::setw(8), std::hex, hr); result.append(unknown_function_name); return; } const auto function_info = GetFunctionInfo(metadata_import, function_identifier.function_token); if (!function_info.IsValid()) { Logger::Debug("GetFunctionInfo failed. HRESULT=0x", std::setfill('0'), std::setw(8), std::hex, hr); result.append(unknown_function_name); return; } if (function_info.type.parent_type != nullptr) { // parent class is available only for internal classes. // See the class in the test application: My.Custom.Test.Namespace.ClassA.InternalClassB.DoubleInternalClassB.TripleInternalClassB std::shared_ptr<TypeInfo> parent_type = function_info.type.parent_type; shared::WSTRING prefix = parent_type->name; while (parent_type->parent_type != nullptr) { // TODO splunk: address warning prefix = parent_type->parent_type->name + name_separator + prefix; parent_type = parent_type->parent_type; } result.append(prefix); result.append(name_separator); } result.append(function_info.type.name); result.append(name_separator); result.append(function_info.name); HCORENUM function_gen_params_enum = nullptr; HCORENUM class_gen_params_enum = nullptr; mdGenericParam function_generic_params[kGenericParamsMaxLen]{}; mdGenericParam class_generic_params[kGenericParamsMaxLen]{}; ULONG function_gen_params_count = 0; ULONG class_gen_params_count = 0; mdTypeDef class_token = function_info.type.id; hr = metadata_import->EnumGenericParams(&class_gen_params_enum, class_token, class_generic_params, kGenericParamsMaxLen, &class_gen_params_count); metadata_import->CloseEnum(class_gen_params_enum); if (FAILED(hr)) { Logger::Debug("Class generic parameters enumeration failed. HRESULT=0x", std::setfill('0'), std::setw(8), std::hex, hr); result.append(unknown_list_of_arguments); return; } hr = metadata_import->EnumGenericParams(&function_gen_params_enum, function_identifier.function_token, function_generic_params, kGenericParamsMaxLen, &function_gen_params_count); metadata_import->CloseEnum(function_gen_params_enum); if (FAILED(hr)) { Logger::Debug("Method generic parameters enumeration failed. HRESULT=0x", std::setfill('0'), std::setw(8), std::hex, hr); result.append(unknown_list_of_arguments); return; } if (function_gen_params_count > 0) { result.append(kGenericParamsOpeningBrace); for (ULONG i = 0; i < function_gen_params_count; ++i) { if (i != 0) { result.append(kParamsSeparator); } WCHAR param_type_name[kParamNameMaxLen]{}; ULONG pch_name = 0; hr = metadata_import->GetGenericParamProps(function_generic_params[i], nullptr, nullptr, nullptr, nullptr, param_type_name, kParamNameMaxLen, &pch_name); if (FAILED(hr)) { Logger::Debug("GetGenericParamProps failed. HRESULT=0x", std::setfill('0'), std::setw(8), std::hex, hr); result.append(kUnknown); } else { result.append(param_type_name); } } result.append(kGenericParamsClosingBrace); } // try to list arguments type FunctionMethodSignature function_method_signature = function_info.method_signature; hr = function_method_signature.TryParse(); if (FAILED(hr)) { result.append(unknown_list_of_arguments); Logger::Debug("FunctionMethodSignature parsing failed. HRESULT=0x", std::setfill('0'), std::setw(8),std::hex, hr); } else { const auto& arguments = function_method_signature.GetMethodArguments(); result.append(kFunctionParamsOpeningBrace); for (ULONG i = 0; i < arguments.size(); i++) { if (i != 0) { result.append(kParamsSeparator); } auto& current_arg = arguments[i]; PCCOR_SIGNATURE pbCur = &current_arg.pbBase[current_arg.offset]; result.append(GetSigTypeTokName(pbCur, metadata_import, class_generic_params, function_generic_params)); } result.append(kFunctionParamsClosingBrace); } } shared::WSTRING ExtractParameterName(PCCOR_SIGNATURE& pb_cur, const ComPtr<IMetaDataImport2>& metadata_import, const mdGenericParam* generic_parameters) const { pb_cur++; ULONG num = 0; pb_cur += CorSigUncompressData(pb_cur, &num); if (num >= kGenericParamsMaxLen) { return kUnknown; } WCHAR param_type_name[kParamNameMaxLen]{}; ULONG pch_name = 0; const auto hr = metadata_import->GetGenericParamProps(generic_parameters[num], nullptr, nullptr, nullptr, nullptr, param_type_name, kParamNameMaxLen, &pch_name); if (FAILED(hr)) { Logger::Debug("GetGenericParamProps failed. HRESULT=0x", std::setfill('0'), std::setw(8), std::hex, hr); return kUnknown; } return param_type_name; } shared::WSTRING GetSigTypeTokName(PCCOR_SIGNATURE& pb_cur, const ComPtr<IMetaDataImport2>& metadata_import, mdGenericParam class_params[], mdGenericParam method_params[]) { shared::WSTRING token_name = shared::EmptyWStr; bool ref_flag = false; if (*pb_cur == ELEMENT_TYPE_BYREF) { pb_cur++; ref_flag = true; } switch (*pb_cur) { case ELEMENT_TYPE_BOOLEAN: token_name = SystemBoolean; pb_cur++; break; case ELEMENT_TYPE_CHAR: token_name = SystemChar; pb_cur++; break; case ELEMENT_TYPE_I1: token_name = SystemSByte; pb_cur++; break; case ELEMENT_TYPE_U1: token_name = SystemByte; pb_cur++; break; case ELEMENT_TYPE_U2: token_name = SystemUInt16; pb_cur++; break; case ELEMENT_TYPE_I2: token_name = SystemInt16; pb_cur++; break; case ELEMENT_TYPE_I4: token_name = SystemInt32; pb_cur++; break; case ELEMENT_TYPE_U4: token_name = SystemUInt32; pb_cur++; break; case ELEMENT_TYPE_I8: token_name = SystemInt64; pb_cur++; break; case ELEMENT_TYPE_U8: token_name = SystemUInt64; pb_cur++; break; case ELEMENT_TYPE_R4: token_name = SystemSingle; pb_cur++; break; case ELEMENT_TYPE_R8: token_name = SystemDouble; pb_cur++; break; case ELEMENT_TYPE_I: token_name = SystemIntPtr; pb_cur++; break; case ELEMENT_TYPE_U: token_name = SystemUIntPtr; pb_cur++; break; case ELEMENT_TYPE_STRING: token_name = SystemString; pb_cur++; break; case ELEMENT_TYPE_OBJECT: token_name = SystemObject; pb_cur++; break; case ELEMENT_TYPE_CLASS: case ELEMENT_TYPE_VALUETYPE: { pb_cur++; mdToken token; pb_cur += CorSigUncompressToken(pb_cur, &token); token_name = GetTypeInfo(metadata_import, token).name; break; } case ELEMENT_TYPE_SZARRAY: { pb_cur++; token_name = GetSigTypeTokName(pb_cur, metadata_import, class_params, method_params) + WStr("[]"); break; } case ELEMENT_TYPE_GENERICINST: { pb_cur++; token_name = GetSigTypeTokName(pb_cur, metadata_import, class_params, method_params); token_name += kGenericParamsOpeningBrace; ULONG num = 0; pb_cur += CorSigUncompressData(pb_cur, &num); for (ULONG i = 0; i < num; i++) { token_name += GetSigTypeTokName(pb_cur, metadata_import, class_params, method_params); if (i != num - 1) { token_name += kParamsSeparator; } } token_name += kGenericParamsClosingBrace; break; } case ELEMENT_TYPE_MVAR: { token_name += ExtractParameterName(pb_cur, metadata_import, method_params); break; } case ELEMENT_TYPE_VAR: { token_name += ExtractParameterName(pb_cur, metadata_import, class_params); break; } default: break; } if (ref_flag) { token_name += WStr("&"); } return token_name; } public: shared::WSTRING* Lookup(FunctionID fid, COR_PRF_FRAME_INFO frame) { const auto function_identifier = this->GetFunctionIdentifier(fid, frame); // TODO Splunk: consider two layers cache. Based on FunctionID while CLR is suspended. // The second one based on Function token (mdToken) and ModuleID - it can susrvive multiple CLR suspensions. shared::WSTRING* answer = function_name_cache_.Get(function_identifier); if (answer != nullptr) { return answer; } stats_.name_cache_misses++; answer = new shared::WSTRING(); this->GetFunctionName(function_identifier, *answer); function_name_cache_.Put(function_identifier, answer); return answer; } }; HRESULT __stdcall FrameCallback(_In_ FunctionID func_id, _In_ UINT_PTR ip, _In_ COR_PRF_FRAME_INFO frame_info, _In_ ULONG32 context_size, _In_ BYTE context[], _In_ void* client_data) { const auto helper = static_cast<SamplingHelper*>(client_data); helper->stats_.total_frames++; const shared::WSTRING* name = helper->Lookup(func_id, frame_info); // This is where line numbers could be calculated helper->cur_writer_->RecordFrame(func_id, *name); return S_OK; } // Factored out from the loop to a separate function for easier auditing and control of the thread state lock void CaptureSamples(ThreadSampler* ts, ICorProfilerInfo10* info10, SamplingHelper& helper) { ICorProfilerThreadEnum* thread_enum = nullptr; HRESULT hr = info10->EnumThreads(&thread_enum); if (FAILED(hr)) { Logger::Debug("Could not EnumThreads. HRESULT=0x", std::setfill('0'), std::setw(8), std::hex, hr); return; } ThreadID thread_id; ULONG num_returned = 0; helper.cur_writer_->StartBatch(); while ((hr = thread_enum->Next(1, &thread_id, &num_returned)) == S_OK) { helper.stats_.num_threads++; thread_span_context spanContext = thread_span_context_map[thread_id]; auto found = ts->managed_tid_to_state_.find(thread_id); if (found != ts->managed_tid_to_state_.end() && found->second != nullptr) { helper.cur_writer_->StartSample(thread_id, found->second, spanContext); } else { auto unknown = ThreadState(); helper.cur_writer_->StartSample(thread_id, &unknown, spanContext); } // Don't reuse the hr being used for the thread enum, especially since a failed snapshot isn't fatal HRESULT snapshotHr = info10->DoStackSnapshot(thread_id, &FrameCallback, COR_PRF_SNAPSHOT_DEFAULT, &helper, nullptr, 0); if (FAILED(snapshotHr)) { Logger::Debug("DoStackSnapshot failed. HRESULT=0x", std::setfill('0'), std::setw(8), std::hex, snapshotHr); } helper.cur_writer_->EndSample(); } helper.cur_writer_->EndBatch(); } int GetSamplingPeriod() { const shared::WSTRING val = shared::GetEnvironmentValue(environment::thread_sampling_period); if (val.empty()) { return kDefaultSamplePeriod; } try { #ifdef _WIN32 const int parsedValue = std::stoi(val); #else std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> convert; std::string str = convert.to_bytes(val); int parsedValue = std::stoi(str); #endif return (int) std::max(kMinimumSamplePeriod, parsedValue); } catch (...) { return kDefaultSamplePeriod; } } void PauseClrAndCaptureSamples(ThreadSampler* ts, ICorProfilerInfo10* info10, SamplingHelper & helper) { // These locks are in use by managed threads; Acquire locks before suspending the runtime to prevent deadlock std::lock_guard<std::mutex> thread_state_guard(ts->thread_state_lock_); std::lock_guard<std::mutex> span_context_guard(thread_span_context_lock); const auto start = std::chrono::steady_clock::now(); HRESULT hr = info10->SuspendRuntime(); if (FAILED(hr)) { Logger::Warn("Could not suspend runtime to sample threads. HRESULT=0x", std::setfill('0'), std::setw(8), std::hex, hr); } else { try { CaptureSamples(ts, info10, helper); } catch (const std::exception& e) { Logger::Warn("Could not capture thread samples: ", e.what()); } catch (...) { Logger::Warn("Could not capture thread sample for unknown reasons"); } } // I don't have any proof but I sure hope that if suspending fails then it's still ok to ask to resume, with no // ill effects hr = info10->ResumeRuntime(); if (FAILED(hr)) { Logger::Error("Could not resume runtime? HRESULT=0x", std::setfill('0'), std::setw(8), std::hex, hr); } const auto end = std::chrono::steady_clock::now(); const auto elapsed_micros = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count(); helper.stats_.micros_suspended = static_cast<int>(elapsed_micros); helper.cur_writer_->WriteFinalStats(helper.stats_); Logger::Debug("Threads sampled in ", elapsed_micros, " micros. threads=", helper.stats_.num_threads, " frames=", helper.stats_.total_frames, " misses=", helper.stats_.name_cache_misses); helper.PublishBuffer(); } void SleepMillis(int millis) { #ifdef _WIN32 Sleep(millis); #else usleep(millis * 1000); // micros #endif } DWORD WINAPI SamplingThreadMain(_In_ LPVOID param) { const int sleep_millis = GetSamplingPeriod(); const auto ts = static_cast<ThreadSampler*>(param); ICorProfilerInfo10* info10 = ts->info10; SamplingHelper helper; helper.info10_ = info10; info10->InitializeCurrentThread(); while (true) { SleepMillis(sleep_millis); const bool shouldSample = helper.AllocateBuffer(); if (!shouldSample) { Logger::Warn("Skipping a thread sample period, buffers are full. ** THIS WILL RESULT IN LOSS OF PROFILING DATA **"); } else { PauseClrAndCaptureSamples(ts, info10, helper); } } } void ThreadSampler::StartSampling(ICorProfilerInfo10* cor_profiler_info10) { Logger::Info("ThreadSampler::StartSampling"); profiler_info = cor_profiler_info10; this->info10 = cor_profiler_info10; #ifdef _WIN32 CreateThread(nullptr, 0, &SamplingThreadMain, this, 0, nullptr); #else pthread_t thr; pthread_create(&thr, NULL, (void *(*)(void *)) &SamplingThreadMain, this); #endif } void ThreadSampler::ThreadCreated(ThreadID thread_id) { // So it seems the Thread* items can be/are called out of order. ThreadCreated doesn't carry any valuable // ThreadState information so this is a deliberate nop. The other methods will fault in ThreadStates // as needed. // Hopefully the destroyed event is not called out of order with the others... if so, the worst that happens // is we get an empty name string and a 0 in the native ID column } void ThreadSampler::ThreadDestroyed(ThreadID thread_id) { { std::lock_guard<std::mutex> guard(thread_state_lock_); const ThreadState* state = managed_tid_to_state_[thread_id]; delete state; managed_tid_to_state_.erase(thread_id); } { std::lock_guard<std::mutex> guard(thread_span_context_lock); thread_span_context_map.erase(thread_id); } } void ThreadSampler::ThreadAssignedToOsThread(ThreadID thread_id, DWORD os_thread_id) { std::lock_guard<std::mutex> guard(thread_state_lock_); ThreadState* state = managed_tid_to_state_[thread_id]; if (state == nullptr) { state = new ThreadState(); managed_tid_to_state_[thread_id] = state; } state->native_id_ = os_thread_id; } void ThreadSampler::ThreadNameChanged(ThreadID thread_id, ULONG cch_name, WCHAR name[]) { std::lock_guard<std::mutex> guard(thread_state_lock_); ThreadState* state = managed_tid_to_state_[thread_id]; if (state == nullptr) { state = new ThreadState(); managed_tid_to_state_[thread_id] = state; } state->thread_name_.clear(); state->thread_name_.append(name, cch_name); } NameCache::NameCache(const size_t maximum_size) : max_size_(maximum_size) { } shared::WSTRING* NameCache::Get(FunctionIdentifier key) { const auto found = map_.find(key); if (found == map_.end()) { return nullptr; } // This voodoo moves the single item in the iterator to the front of the list // (as it is now the most-recently-used) list_.splice(list_.begin(), list_, found->second); return found->second->second; } void NameCache::Put(FunctionIdentifier key, shared::WSTRING* val) { const auto pair = std::pair(key, val); list_.push_front(pair); map_[key] = list_.begin(); if (map_.size() > max_size_) { const auto &lru = list_.back(); delete lru.second; // FIXME consider using WSTRING directly instead of WSTRING* map_.erase(lru.first); list_.pop_back(); } } } // namespace trace extern "C" { EXPORTTHIS int32_t SignalFxReadThreadSamples(int32_t len, unsigned char* buf) { return ThreadSamplingConsumeOneThreadSample(len, buf); } EXPORTTHIS void SignalFxSetNativeContext(uint64_t traceIdHigh, uint64_t traceIdLow, uint64_t spanId, int32_t managedThreadId) { ThreadID threadId; const HRESULT hr = profiler_info->GetCurrentThreadID(&threadId); if (FAILED(hr)) { trace::Logger::Debug("GetCurrentThreadID failed. HRESULT=0x", std::setfill('0'), std::setw(8), std::hex, hr); return; } std::lock_guard<std::mutex> guard(thread_span_context_lock); thread_span_context_map[threadId] = trace::thread_span_context(traceIdHigh, traceIdLow, spanId, managedThreadId); } }
36.649162
161
0.637176
Kielek
dd094ffbce2847e2b78b31337b526a123f35b8f3
183
hpp
C++
include/net/http/client/curl_native.hpp
francisfsjiang/libjstack
2ffdd7f953f30edf6755cc53260e744ca0fad451
[ "MIT" ]
10
2015-03-19T04:41:21.000Z
2016-03-24T13:58:15.000Z
include/net/http/client/curl_native.hpp
francisfsjiang/Abathur
2ffdd7f953f30edf6755cc53260e744ca0fad451
[ "MIT" ]
2
2021-08-07T11:47:07.000Z
2021-09-05T04:35:37.000Z
include/net/http/client/curl_native.hpp
francisfsjiang/Abathur
2ffdd7f953f30edf6755cc53260e744ca0fad451
[ "MIT" ]
3
2015-03-20T11:57:16.000Z
2017-01-24T03:47:50.000Z
#ifndef LIBJSTACK_CURL_NATIVE_HPP #define LIBJSTACK_CURL_NATIVE_HPP namespace libjstack::net::http::curl_native { #include <curl/curl.h> } #endif //LIBJSTACK_CURL_NATIVE_HPP
15.25
45
0.786885
francisfsjiang
dd0bd28ad4978de4a81b7644bb52f95d53aa12d6
429
cpp
C++
Codeforces/262A-Roma and Lucky Numbers/262A-Roma and Lucky Numbers.cpp
alielsokary/Competitive-programming
7dffaa334e18c61c8a7985f5bbb64e3613d1008b
[ "MIT" ]
null
null
null
Codeforces/262A-Roma and Lucky Numbers/262A-Roma and Lucky Numbers.cpp
alielsokary/Competitive-programming
7dffaa334e18c61c8a7985f5bbb64e3613d1008b
[ "MIT" ]
null
null
null
Codeforces/262A-Roma and Lucky Numbers/262A-Roma and Lucky Numbers.cpp
alielsokary/Competitive-programming
7dffaa334e18c61c8a7985f5bbb64e3613d1008b
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int n, k,a[100000], b[100000], x, cnt,cnt2; int main() { cin>>n>>k; for (int i = 0; i < n; i++) { cin>>a[i]; x = a[i]; while(x>0){ int tmp = x%10; x/= 10; if(tmp == 7 || tmp == 4) cnt++; } b[i] = cnt; cnt = 0; } for (int i = 0; i < n; i++) { if (b[i]<=k) { cnt2++; } } cout<<cnt2<<endl; return 0; }
13
43
0.398601
alielsokary
dd10ec2db2b80310b1733d3f2daaad6d0308a38d
1,104
hpp
C++
MLPP/BernoulliNB/BernoulliNB.hpp
KangLin/MLPP
abd2dba6076c98aa2e1c29fb3198b74a3f28f8fe
[ "MIT" ]
927
2021-12-03T07:02:25.000Z
2022-03-30T07:37:23.000Z
MLPP/BernoulliNB/BernoulliNB.hpp
DJofOUC/MLPP
6940fc1fbcb1bc16fe910c90a32d9e4db52e264f
[ "MIT" ]
7
2022-02-13T22:38:08.000Z
2022-03-07T01:00:32.000Z
MLPP/BernoulliNB/BernoulliNB.hpp
DJofOUC/MLPP
6940fc1fbcb1bc16fe910c90a32d9e4db52e264f
[ "MIT" ]
132
2022-01-13T02:19:04.000Z
2022-03-23T19:23:56.000Z
// // BernoulliNB.hpp // // Created by Marc Melikyan on 1/17/21. // #ifndef BernoulliNB_hpp #define BernoulliNB_hpp #include <vector> #include <map> namespace MLPP{ class BernoulliNB{ public: BernoulliNB(std::vector<std::vector<double>> inputSet, std::vector<double> outputSet); std::vector<double> modelSetTest(std::vector<std::vector<double>> X); double modelTest(std::vector<double> x); double score(); private: void computeVocab(); void computeTheta(); void Evaluate(); // Model Params double prior_1 = 0; double prior_0 = 0; std::vector<std::map<double, int>> theta; std::vector<double> vocab; int class_num; // Datasets std::vector<std::vector<double>> inputSet; std::vector<double> outputSet; std::vector<double> y_hat; }; #endif /* BernoulliNB_hpp */ }
23.489362
98
0.505435
KangLin
dd130a931a0c27414f70b43818c607c5e21b315d
503
cpp
C++
src/qwelk.cpp
raincheque/qwelk
e78ee0ccf7a7f1af91d823d0563b0af360933237
[ "MIT" ]
25
2017-11-22T13:48:05.000Z
2021-12-29T05:49:01.000Z
src/qwelk.cpp
netboy3/qwelk-vcvrack-plugins
e78ee0ccf7a7f1af91d823d0563b0af360933237
[ "MIT" ]
12
2017-11-20T20:45:27.000Z
2021-12-08T20:35:06.000Z
src/qwelk.cpp
netboy3/qwelk-vcvrack-plugins
e78ee0ccf7a7f1af91d823d0563b0af360933237
[ "MIT" ]
4
2018-01-11T21:02:12.000Z
2019-09-29T12:32:50.000Z
#include "qwelk.hpp" Plugin *pluginInstance; void init(rack::Plugin *p) { pluginInstance = p; p->addModel(modelAutomaton); p->addModel(modelByte); p->addModel(modelChaos); p->addModel(modelColumn); p->addModel(modelGate); p->addModel(modelOr); p->addModel(modelNot); p->addModel(modelXor); p->addModel(modelMix); p->addModel(modelNews); p->addModel(modelScaler); p->addModel(modelWrap); p->addModel(modelXFade); p->addModel(modelIndra); }
21.869565
32
0.652087
raincheque
dd1390f4214bcff6805ff06e973499feb4bc1223
4,040
cpp
C++
modules/core/src/MetaObject/core/detail/Time.cpp
dtmoodie/MetaObject
8238d143d578ff9c0c6506e7e627eca15e42369e
[ "MIT" ]
2
2017-10-26T04:41:49.000Z
2018-02-09T05:12:19.000Z
modules/core/src/MetaObject/core/detail/Time.cpp
dtmoodie/MetaObject
8238d143d578ff9c0c6506e7e627eca15e42369e
[ "MIT" ]
null
null
null
modules/core/src/MetaObject/core/detail/Time.cpp
dtmoodie/MetaObject
8238d143d578ff9c0c6506e7e627eca15e42369e
[ "MIT" ]
3
2017-01-08T21:09:48.000Z
2018-02-10T04:27:32.000Z
#include "Time.hpp" #include <iomanip> #include <sstream> namespace mo { static Time::GetTime_f time_source = nullptr; Time Time::now() { if (time_source) { return time_source(); } return std::chrono::high_resolution_clock::now(); } void Time::setTimeSource(Time::GetTime_f timefunc) { time_source = timefunc; } Time::Time(const std::chrono::high_resolution_clock::time_point& t) : std::chrono::high_resolution_clock::time_point(t) { } Time::Time(const Duration& d) : std::chrono::high_resolution_clock::time_point(d) { } Time::Time(const double sec) { fromSeconds(sec); } std::string Time::print() const { std::stringstream ss; print(ss); return ss.str(); } using Days = std::chrono::duration<int, std::ratio<86400>>; void Time::print(std::ostream& ss, const bool print_days, const bool hours, const bool minutes, const bool seconds, const bool nanoseconds) const { ss.fill('0'); auto ns = *this; auto d = std::chrono::duration_cast<Days>(ns.time_since_epoch()); ns -= d; auto h = std::chrono::duration_cast<std::chrono::hours>(ns.time_since_epoch()); ns -= h; auto m = std::chrono::duration_cast<std::chrono::minutes>(ns.time_since_epoch()); ns -= m; auto s = std::chrono::duration_cast<std::chrono::seconds>(ns.time_since_epoch()); ns -= s; if (print_days) { ss << std::setw(2) << d.count(); ss << ':'; } if (hours) { if (print_days) { ss << ':'; } ss << std::setw(2) << h.count(); } if (minutes) { if (hours || print_days) { ss << ':'; } ss << std::setw(2) << m.count(); } if (seconds) { if (minutes) { ss << ':'; } ss << std::setw(2) << s.count(); } if (nanoseconds) { if (seconds) { ss << '.'; } ss << std::setw(4) << ns.time_since_epoch().count(); } } double Time::seconds() const { auto ns = *this; auto d = std::chrono::duration_cast<Days>(ns.time_since_epoch()); ns -= d; auto h = std::chrono::duration_cast<std::chrono::hours>(ns.time_since_epoch()); ns -= h; auto m = std::chrono::duration_cast<std::chrono::minutes>(ns.time_since_epoch()); ns -= m; auto s = std::chrono::duration_cast<std::chrono::seconds>(ns.time_since_epoch()); ns -= s; auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(ns.time_since_epoch()); return s.count() + (ms.count() / 1000.0); } void Time::fromSeconds(const double val) { // TODO } FrameNumber::FrameNumber(const uint64_t v) : val(v) { } uint64_t FrameNumber::max() { return std::numeric_limits<uint64_t>::max(); } bool FrameNumber::valid() const { return val != max(); } FrameNumber::operator uint64_t&() { return val; } FrameNumber::operator uint64_t() const { return val; } FrameNumber& FrameNumber::operator=(const uint64_t v) { val = v; return *this; } /*bool FrameNumber::operator==(const FrameNumber& v) const { return val == v.val; }*/ /*bool FrameNumber::operator==(const uint64_t v) const { return val == v; }*/ } namespace std { std::ostream& operator<<(std::ostream& lhs, const mo::Time& rhs) { rhs.print(lhs, false, false, true, true, true); return lhs; } }
23.352601
95
0.490594
dtmoodie
dd169e862e5831092be13e9aa1a2b62c61c269be
2,859
cpp
C++
src/disp/Module.cpp
LegalizeAdulthood/cimple
5ec70784f2ee3e455a2258f82b07c0dacccb4093
[ "MIT" ]
4
2015-12-16T06:43:14.000Z
2020-01-24T06:05:47.000Z
src/disp/Module.cpp
LegalizeAdulthood/cimple
5ec70784f2ee3e455a2258f82b07c0dacccb4093
[ "MIT" ]
null
null
null
src/disp/Module.cpp
LegalizeAdulthood/cimple
5ec70784f2ee3e455a2258f82b07c0dacccb4093
[ "MIT" ]
null
null
null
/* **============================================================================== ** ** Copyright (c) 2003, 2004, 2005, 2006, Michael Brasher, Karl Schopmeyer ** ** 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 <dlfcn.h> #include "Module.h" #include <cimple/Error.h> #include <cimple/Strings.h> #include "Envelope.h" CIMPLE_NAMESPACE_BEGIN typedef Registration* (*Module_Proc)(); Module::Module(void* handle, Module_Proc proc) : _handle(handle), _providers_loaded(false) { _registration = proc(); } Module::~Module() { if (_providers_loaded) unload_providers(); dlclose(_handle); } void Module::load_providers() { if (_providers_loaded) return; // ATTN: call cimple_module_load() here! // Load all providers in this module: for (Registration* p = _registration; p; p = p->next) { Envelope* env = new Envelope(p); env->load(); _envelopes.append(env); } // Mark as providers_loaded: _providers_loaded = true; } void Module::unload_providers() { if (!_providers_loaded) return; // ATTN: call cimple_module_unload() here! // Unload the providers first: for (List_Elem* p = _envelopes.head; p; p = p->next) { Envelope* env = (Envelope*)p; env->unload(); delete env; } // Clear the list: _envelopes.clear(); // Mark as unproviders_loaded: _providers_loaded = false; } Envelope* Module::find_provider(const char* class_name) { for (List_Elem* p = _envelopes.head; p; p = p->next) { Envelope* env = (Envelope*)p; if (eqi(env->class_name(), class_name)) return env; } // Not found: return 0; } CIMPLE_NAMESPACE_END
25.526786
80
0.637636
LegalizeAdulthood
dd1985b492652c976d8a4d3e6f07cc0be30b3ed4
1,799
cpp
C++
tree/medium/145.BinaryTreePostorderTraversal.cpp
XiaotaoGuo/Leetcode-Solution-In-Cpp
8e01e35c742a7afb0c8cdd228a6a5e564375434e
[ "Apache-2.0" ]
null
null
null
tree/medium/145.BinaryTreePostorderTraversal.cpp
XiaotaoGuo/Leetcode-Solution-In-Cpp
8e01e35c742a7afb0c8cdd228a6a5e564375434e
[ "Apache-2.0" ]
null
null
null
tree/medium/145.BinaryTreePostorderTraversal.cpp
XiaotaoGuo/Leetcode-Solution-In-Cpp
8e01e35c742a7afb0c8cdd228a6a5e564375434e
[ "Apache-2.0" ]
null
null
null
/* * @lc app=leetcode id=145 lang=cpp * * [145] Binary Tree Postorder Traversal * * https://leetcode.com/problems/binary-tree-postorder-traversal/description/ * * algorithms * Medium (55.73%) * Likes: 2082 * Dislikes: 104 * Total Accepted: 415.3K * Total Submissions: 742.6K * Testcase Example: '[1,null,2,3]' * * Given the root of a binary tree, return the postorder traversal of its * nodes' values. * * * Example 1: * * * Input: root = [1,null,2,3] * Output: [3,2,1] * * * Example 2: * * * Input: root = [] * Output: [] * * * Example 3: * * * Input: root = [1] * Output: [1] * * * Example 4: * * * Input: root = [1,2] * Output: [2,1] * * * Example 5: * * * Input: root = [1,null,2] * Output: [2,1] * * * * Constraints: * * * The number of the nodes in the tree is in the range [0, 100]. * -100 <= Node.val <= 100 * * * * * Follow up: * * Recursive solution is trivial, could you do it iteratively? * * * */ // @lc code=start /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), * right(right) {} * }; */ #include <stack> #include <vector> class Solution { public: std::vector<int> postorderTraversal(TreeNode* root) { std::vector<int> result; dfs(root, result); return result; } private: void dfs(TreeNode* root, std::vector<int>& result) { if (!root) return; dfs(root->left, result); dfs(root->right, result); result.push_back(root->val); } }; // @lc code=end
16.657407
77
0.566982
XiaotaoGuo
dd1a7e577104f752756106fe37dbb18b33216096
15,684
cpp
C++
kwm/axlib/application.cpp
a-morales/kwm
2ee8078616d5a37287aeb7c5b20f0dba982b19ed
[ "MIT" ]
13
2020-06-30T09:48:28.000Z
2022-03-29T04:42:54.000Z
kwm/axlib/application.cpp
a-morales/kwm
2ee8078616d5a37287aeb7c5b20f0dba982b19ed
[ "MIT" ]
null
null
null
kwm/axlib/application.cpp
a-morales/kwm
2ee8078616d5a37287aeb7c5b20f0dba982b19ed
[ "MIT" ]
3
2020-02-16T00:57:05.000Z
2022-03-13T23:50:08.000Z
#include "application.h" #include "element.h" #include "sharedworkspace.h" #include "event.h" #include "display.h" #include "axlib.h" #define internal static #define local_persist static enum ax_application_notifications { AXApplication_Notification_WindowCreated, AXApplication_Notification_WindowFocused, AXApplication_Notification_WindowMoved, AXApplication_Notification_WindowResized, AXApplication_Notification_WindowTitle, AXApplication_Notification_Count }; internal CFStringRef AXNotificationFromEnum(int Type) { switch(Type) { case AXApplication_Notification_WindowCreated: { return kAXWindowCreatedNotification; } break; case AXApplication_Notification_WindowFocused: { return kAXFocusedWindowChangedNotification; } break; case AXApplication_Notification_WindowMoved: { return kAXWindowMovedNotification; } break; case AXApplication_Notification_WindowResized: { return kAXWindowResizedNotification; } break; case AXApplication_Notification_WindowTitle: { return kAXTitleChangedNotification; } break; default: { return NULL; /* NOTE(koekeishiya): Should never happen */ } break; } } internal inline ax_window * AXLibGetWindowByRef(ax_application *Application, AXUIElementRef WindowRef) { uint32_t WID = AXLibGetWindowID(WindowRef); return AXLibFindApplicationWindow(Application, WID); } internal inline void AXLibUpdateApplicationWindowTitle(ax_application *Application, AXUIElementRef WindowRef) { ax_window *Window = AXLibGetWindowByRef(Application, WindowRef); if(Window) { if(Window->Name) { free(Window->Name); Window->Name = NULL; } Window->Name = AXLibGetWindowTitle(WindowRef); } } internal inline void AXLibDestroyInvalidWindow(ax_window *Window) { AXLibRemoveObserverNotification(&Window->Application->Observer, Window->Ref, kAXUIElementDestroyedNotification); AXLibDestroyWindow(Window); } OBSERVER_CALLBACK(AXApplicationCallback) { ax_application *Application = (ax_application *) Reference; if(CFEqual(Notification, kAXWindowCreatedNotification)) { /* NOTE(koekeishiya): Construct ax_window struct for the newly created window */ ax_window *Window = AXLibConstructWindow(Application, Element); if(AXLibAddObserverNotification(&Application->Observer, Window->Ref, kAXUIElementDestroyedNotification, Window) == kAXErrorSuccess) { AXLibAddApplicationWindow(Application, Window); /* NOTE(koekeishiya): Triggers an AXEvent_WindowCreated and passes a pointer to the new ax_window */ AXLibConstructEvent(AXEvent_WindowCreated, Window, false); /* NOTE(koekeishiya): When a new window is created, we incorrectly receive the kAXFocusedWindowChangedNotification first, for some reason. We discard that notification and restore it when we have the window to work with. */ AXApplicationCallback(Observer, Window->Ref, kAXFocusedWindowChangedNotification, Application); } else { /* NOTE(koekeishiya): This element is not destructible and cannot be an application window (?) */ AXLibDestroyInvalidWindow(Window); } } else if(CFEqual(Notification, kAXUIElementDestroyedNotification)) { /* NOTE(koekeishiya): If the destroyed UIElement is a window, remove it from the list. */ ax_window *Window = (ax_window *) Reference; if(Window) { AXLibRemoveApplicationWindow(Window->Application, Window->ID); Window->Application->Focus = AXLibGetFocusedWindow(Window->Application); /* NOTE(koekeishiya): The callback is responsible for calling AXLibDestroyWindow(Window); */ AXLibConstructEvent(AXEvent_WindowDestroyed, Window, false); } } else if(CFEqual(Notification, kAXFocusedWindowChangedNotification)) { /* NOTE(koekeishiya): This notification could be received before the window itself is created. Make sure that the window actually exists before we notify our callback. */ ax_window *Window = AXLibGetWindowByRef(Application, Element); if(Window) { /* NOTE(koekeishiya): When a window is deminimized, we receive a FocusedWindowChanged notification before the window is visible. Only notify our callback when we know that we can interact with the window in question. */ if(!AXLibHasFlags(Window, AXWindow_Minimized)) { AXLibConstructEvent(AXEvent_WindowFocused, Window, false); } /* NOTE(koekeishiya): If the application corresponding to this window is flagged for activation and the window is visible to the user, this should be the focused application. */ if(AXLibHasFlags(Window->Application, AXApplication_Activate)) { AXLibClearFlags(Window->Application, AXApplication_Activate); if(!AXLibHasFlags(Window, AXWindow_Minimized)) AXLibConstructEvent(AXEvent_ApplicationActivated, Window->Application, false); } } } else if(CFEqual(Notification, kAXWindowMiniaturizedNotification)) { /* NOTE(koekeishiya): Triggers an AXEvent_WindowMinimized and passes a pointer to the ax_window */ ax_window *Window = (ax_window *) Reference; if(Window) { AXLibAddFlags(Window, AXWindow_Minimized); AXLibConstructEvent(AXEvent_WindowMinimized, Window, false); } } else if(CFEqual(Notification, kAXWindowDeminiaturizedNotification)) { /* NOTE(koekeishiya): Triggers an AXEvent_WindowDeminimized and passes a pointer to the ax_window */ ax_window *Window = (ax_window *) Reference; if(Window) { /* NOTE(koekeishiya): If a window was minimized before AXLib is initialized, the WindowID is reported as 0. We check if this window is one of these, update the WindowID and place it in our managed window list. */ if(Window->ID == 0) { for(int Index = 0; Index < Window->Application->NullWindows.size(); ++Index) { if(Window->Application->NullWindows[Index] == Window) Window->Application->NullWindows.erase(Window->Application->NullWindows.begin() + Index); } Window->ID = AXLibGetWindowID(Window->Ref); Window->Application->Windows[Window->ID] = Window; } /* NOTE(koekeishiya): kAXWindowDeminiaturized is sent before didActiveSpaceChange, when a deminimized window pulls you to the space of that window. If the active space of the display is not equal to the space of the window, we should ignore this event and schedule a new one to happen after the next space changed event. */ ax_display *Display = AXLibWindowDisplay(Window); if(AXLibSpaceHasWindow(Window, Display->Space->ID)) { AXLibConstructEvent(AXEvent_WindowDeminimized, Window, false); } else { AXLibAddFlags(Display->Space, AXSpace_DeminimizedTransition); } } } else if(CFEqual(Notification, kAXWindowMovedNotification)) { /* NOTE(koekeishiya): Triggers an AXEvent_WindowMoved and passes a pointer to the ax_window */ ax_window *Window = AXLibGetWindowByRef(Application, Element); if(Window) { Window->Position = AXLibGetWindowPosition(Window->Ref); AXLibConstructEvent(AXEvent_WindowMoved, Window, AXLibHasFlags(Window, AXWindow_MoveIntrinsic)); AXLibClearFlags(Window, AXWindow_MoveIntrinsic); } } else if(CFEqual(Notification, kAXWindowResizedNotification)) { /* NOTE(koekeishiya): Triggers an AXEvent_WindowResized and passes a pointer to the ax_window */ ax_window *Window = AXLibGetWindowByRef(Application, Element); if(Window) { Window->Position = AXLibGetWindowPosition(Window->Ref); Window->Size = AXLibGetWindowSize(Window->Ref); AXLibConstructEvent(AXEvent_WindowResized, Window, AXLibHasFlags(Window, AXWindow_SizeIntrinsic)); AXLibClearFlags(Window, AXWindow_SizeIntrinsic); } } else if(CFEqual(Notification, kAXTitleChangedNotification)) { AXLibUpdateApplicationWindowTitle(Application, Element); } } ax_application AXLibConstructApplication(pid_t PID, std::string Name) { ax_application Application = {}; Application.Ref = AXUIElementCreateApplication(PID); GetProcessForPID(PID, &Application.PSN); Application.Name = Name; Application.PID = PID; return Application; } void AXLibInitializeApplication(ax_application *Application) { AXLibAddApplicationObserver(Application); AXLibAddApplicationWindows(Application); Application->Focus = AXLibGetFocusedWindow(Application); } /* NOTE(koekeishiya): This function will try to reinitialize the application that failed during creation. */ void AXLibAddApplicationObserverNotificationFallback(ax_application *Application) { AXLibRemoveApplicationWindows(Application); AXLibRemoveApplicationObserver(Application); Application->Focus = NULL; AXLibInitializeApplication(Application); AXLibConstructEvent(AXEvent_ApplicationLaunched, Application, false); } bool AXLibHasApplicationObserverNotification(ax_application *Application) { for(int Notification = AXApplication_Notification_WindowCreated; Notification < AXApplication_Notification_Count; ++Notification) { if(!(Application->Notifications & (1 << Notification))) { return false; } } return true; } void AXLibAddApplicationObserver(ax_application *Application) { AXLibConstructObserver(Application, AXApplicationCallback); if(Application->Observer.Valid) { for(int Notification = AXApplication_Notification_WindowCreated; Notification < AXApplication_Notification_Count; ++Notification) { int Attempts = 10; while((--Attempts > 0) && (AXLibAddObserverNotification(&Application->Observer, Application->Ref, AXNotificationFromEnum(Notification), Application) != kAXErrorSuccess)) { /* NOTE(koekeishiya): Could not add notification because the application has not finishied initializing yet. Sleep for a short while and try again. We limit the number of tries to prevent a deadlock. */ usleep(10000); } /* NOTE(koekeishiya): Mark the notification as successful. */ if(Attempts != 0) { Application->Notifications |= (1 << Notification); } } AXLibStartObserver(&Application->Observer); } } void AXLibRemoveApplicationObserver(ax_application *Application) { if(Application->Observer.Valid) { AXLibStopObserver(&Application->Observer); for(int Notification = AXApplication_Notification_WindowCreated; Notification < AXApplication_Notification_Count; ++Notification) { AXLibRemoveObserverNotification(&Application->Observer, Application->Ref, AXNotificationFromEnum(Notification)); } AXLibDestroyObserver(&Application->Observer); } } void AXLibAddApplicationWindows(ax_application *Application) { CFArrayRef Windows = (CFArrayRef) AXLibGetWindowProperty(Application->Ref, kAXWindowsAttribute); if(Windows) { CFIndex Count = CFArrayGetCount(Windows); for(CFIndex Index = 0; Index < Count; ++Index) { AXUIElementRef Ref = (AXUIElementRef) CFArrayGetValueAtIndex(Windows, Index); if(!AXLibGetWindowByRef(Application, Ref)) { ax_window *Window = AXLibConstructWindow(Application, Ref); if(AXLibAddObserverNotification(&Application->Observer, Window->Ref, kAXUIElementDestroyedNotification, Window) == kAXErrorSuccess) { AXLibAddApplicationWindow(Application, Window); } else { AXLibDestroyWindow(Window); } } } CFRelease(Windows); } } void AXLibRemoveApplicationWindows(ax_application *Application) { std::map<uint32_t, ax_window*>::iterator It; for(It = Application->Windows.begin(); It != Application->Windows.end(); ++It) { ax_window *Window = It->second; AXLibRemoveObserverNotification(&Window->Application->Observer, Window->Ref, kAXUIElementDestroyedNotification); AXLibRemoveObserverNotification(&Window->Application->Observer, Window->Ref, kAXWindowMiniaturizedNotification); AXLibRemoveObserverNotification(&Window->Application->Observer, Window->Ref, kAXWindowDeminiaturizedNotification); AXLibDestroyWindow(Window); } Application->Windows.clear(); } ax_window *AXLibFindApplicationWindow(ax_application *Application, uint32_t WID) { std::map<uint32_t, ax_window*>::iterator It; It = Application->Windows.find(WID); if(It != Application->Windows.end()) return It->second; else return NULL; } void AXLibAddApplicationWindow(ax_application *Application, ax_window *Window) { if(!AXLibFindApplicationWindow(Application, Window->ID)) { AXLibAddObserverNotification(&Application->Observer, Window->Ref, kAXWindowMiniaturizedNotification, Window); AXLibAddObserverNotification(&Application->Observer, Window->Ref, kAXWindowDeminiaturizedNotification, Window); if(Window->ID == 0) Application->NullWindows.push_back(Window); else Application->Windows[Window->ID] = Window; } } void AXLibRemoveApplicationWindow(ax_application *Application, uint32_t WID) { ax_window *Window = AXLibFindApplicationWindow(Application, WID); if(Window) { AXLibRemoveObserverNotification(&Window->Application->Observer, Window->Ref, kAXUIElementDestroyedNotification); AXLibRemoveObserverNotification(&Window->Application->Observer, Window->Ref, kAXWindowMiniaturizedNotification); AXLibRemoveObserverNotification(&Window->Application->Observer, Window->Ref, kAXWindowDeminiaturizedNotification); Application->Windows.erase(WID); } } void AXLibActivateApplication(ax_application *Application) { SharedWorkspaceActivateApplication(Application->PID); } bool AXLibIsApplicationActive(ax_application *Application) { return SharedWorkspaceIsApplicationActive(Application->PID); } bool AXLibIsApplicationHidden(ax_application *Application) { return SharedWorkspaceIsApplicationHidden(Application->PID); } void AXLibDestroyApplication(ax_application *Application) { AXLibRemoveApplicationWindows(Application); AXLibRemoveApplicationObserver(Application); CFRelease(Application->Ref); Application->Ref = NULL; }
38.253659
161
0.672533
a-morales
dd1b4f199dfec33ec5d15fefe4cfa47258fe1744
925
cpp
C++
ConsoleApplication1/ConsoleApplication1/ConsoleApplication1.cpp
Mogikan/OpenMP
7fa130159dfb32a9885c31b2c4e36de4ef36fa44
[ "Apache-2.0" ]
null
null
null
ConsoleApplication1/ConsoleApplication1/ConsoleApplication1.cpp
Mogikan/OpenMP
7fa130159dfb32a9885c31b2c4e36de4ef36fa44
[ "Apache-2.0" ]
null
null
null
ConsoleApplication1/ConsoleApplication1/ConsoleApplication1.cpp
Mogikan/OpenMP
7fa130159dfb32a9885c31b2c4e36de4ef36fa44
[ "Apache-2.0" ]
null
null
null
// ConsoleApplication1.cpp : Defines the entry point for the console application. // #pragma once; #include "stdafx.h" #include <list> #include <iostream> using namespace std; int main() { std::list<int> intlist; for (int i = 0; i < 10; i++) { intlist.push_back(i); } std::list<int>::iterator iterator,iteratorCopy; for (iterator = intlist.begin(); iterator != intlist.end(); ++iterator) { std::cout << *iterator; } bool breakIteration = false; for (iterator = intlist.begin(); iterator != intlist.end(); (breakIteration)?iterator:iterator++) { breakIteration = false; if ((*iterator) == 0) { breakIteration = true; iteratorCopy = iterator; if (iterator == intlist.begin()) { iteratorCopy++; } else { iteratorCopy--; } intlist.splice(intlist.end(), intlist, iterator); iterator = iteratorCopy; } std::cout << *iterator; } std::cin.ignore(); }
18.877551
101
0.632432
Mogikan
dd1f71ee6a148aa7a853aad610459efc653d3a84
2,428
cpp
C++
src/token.cpp
JevinJ/ConnectFour
3e131c9ff957c3ca108b6f79e8940ba3ae40e8d4
[ "MIT" ]
null
null
null
src/token.cpp
JevinJ/ConnectFour
3e131c9ff957c3ca108b6f79e8940ba3ae40e8d4
[ "MIT" ]
null
null
null
src/token.cpp
JevinJ/ConnectFour
3e131c9ff957c3ca108b6f79e8940ba3ae40e8d4
[ "MIT" ]
null
null
null
/* * token.cpp * * Created on: Dec 24, 2017 * Author: Jevin */ #include <iostream> #include "config.hpp" #include "token.hpp" #include "resourcemanager.hpp" Token::Token() : x_pos(0), y_pos(0) { model.setRadius(TOKEN_RADIUS); model.setTexture(&resource_manager.textures[Textures::TokenTexture]); model.setFillColor(sf::Color::Cyan); } Token::Token(sf::Color token_color) : x_pos(0), y_pos(0) { model.setRadius(TOKEN_RADIUS); model.setTexture(&resource_manager.textures[Textures::TokenTexture]); model.setFillColor(token_color); } //Copy constructor so we don't lose the token texture when it is invalidated. Token::Token(const Token& original) { x_pos = original.x_pos; y_pos = original.y_pos; model = original.model; model.setTexture(&resource_manager.textures[Textures::TokenTexture]); } sf::Color Token::get_fill_color() const { return model.getFillColor(); } float Token::get_radius() const { return model.getRadius(); } /* * description: * Sets the token model's position in pixels for use in drawing the model. */ void Token::set_pixel_position(const int x_pos_in_wall, const int y_pos_in_wall) { if(x_pos_in_wall < TOKEN_WALL_WIDTH and y_pos_in_wall <= TOKEN_WALL_HEIGHT+1) { x_pos = x_pos_in_wall; y_pos = y_pos_in_wall; const float token_diameter = TOKEN_RADIUS * 2; const unsigned int x_pos_in_pix = token_diameter * x_pos; const unsigned int y_pos_in_pix = (MAIN_WINDOW_HEIGHT-token_diameter) - (token_diameter*(y_pos-1)); model.setPosition(x_pos_in_pix, y_pos_in_pix); } } /* * description: * Sets the x position in as it is the token wall. * WARNING: this is not the same as pixel position used to draw the model. */ void Token::set_x_position(const int x) { if(x >= 0 and x <= TOKEN_WALL_WIDTH) { x_pos = x; } } int Token::get_x_position() const { return x_pos; } /* * description: * Sets the y position in as it is the token wall. * WARNING: this is not the same as pixel position used to draw the model. */ void Token::set_y_position(const int y) { if(y >= 0 and y <= TOKEN_WALL_HEIGHT) { y_pos = y; } } int Token::get_y_position() const { return y_pos; } void Token::draw(sf::RenderTarget& target, sf::RenderStates states) const { target.draw(model, states); }
24.039604
107
0.669275
JevinJ
dd22ffc5f1053df295a6743345308994cf239cd1
26,682
cpp
C++
src/app/GameView.cpp
Daivuk/ggj16
0ba896f3b6ece32ed3a6e190825e53e88f666d5e
[ "MIT" ]
null
null
null
src/app/GameView.cpp
Daivuk/ggj16
0ba896f3b6ece32ed3a6e190825e53e88f666d5e
[ "MIT" ]
null
null
null
src/app/GameView.cpp
Daivuk/ggj16
0ba896f3b6ece32ed3a6e190825e53e88f666d5e
[ "MIT" ]
1
2019-10-19T04:49:33.000Z
2019-10-19T04:49:33.000Z
#include "GameView.h" #include "Player.h" #include "TiledMapNode.h" #include "Fireplace.h" #include "DanceSequence.h" #include "LightLayer.h" #include "Tree.h" #include "Rock.h" #include "MusicEmitter.h" #include "DancePedestral.h" #include "Monster.h" #include "BloodLayer.h" #include "Stockpile.h" #include "Stone.h" #include "Scarecrow.h" #define TREE_DENSITY 50 #define ROCK_DENSITY 30 int g_daysSurvived = 0; const Vector2 g_playerSpawn[] = { {14.5f, 14.5f}, {18.5f, 18.5f}, {14.5f, 18.5f}, {18.5f, 14.5f}, }; static float lerpf(float from, float to, float t) { return from + (to - from) * t; } GameView* g_gameView = nullptr; GameView::GameView() { g_gameView = this; OUI->add(OLoadUI("../../assets/uis/game.json")); m_storeAnim = OFindUI("store")->rect.size.x; OFindUI("store")->rect.position.x = 140; } GameView::~GameView() { if (m_pBloodLayer) { delete m_pBloodLayer; } if (m_pTiles) { delete[] m_pTiles; } if (m_pFireplace) { delete m_pFireplace; } if (m_pPather) { delete m_pPather; } } void GameView::OnShow() { m_gameover = false; InitPhysics(Vector2::Zero, 1.f); // Create the main game node. Map + objects go in there and are affected by light m_pGameLayer = CreateLightLayer(); m_pGameLayer->SetAmbient(Color(.10f, .15f, .2f, 1)); // Set that so something cool jason will decide on AddNode(m_pGameLayer); // spawn players from the lobby data, for now assume one CreateMusic(); CreateTileMap(); GenerateMap(); CreateEntities(); CenterCamera(); SpawnPlayers(); CreatePathFinder(); m_fadeQuad = CreateSprite("healthGaugeFill.png"); m_fadeQuad->GetColorAnim().start(Color(0.f, 0.f, 0.f, 1.f), Color(0.f, 0.f, 0.f, 0.f), 3.f); m_fadeQuad->SetFilter(onut::SpriteBatch::eFiltering::Nearest); m_fadeQuad->SetScale(Vector2(100, 100)); AddNode(m_fadeQuad); } void GameView::OnHide() { DeleteNode(m_pBloodLayer); m_pBloodLayer = nullptr; delete m_pPather; m_pPather = nullptr; KillAllEntities(); m_entities.clear(); m_players.clear(); m_pedestrals.clear(); m_previousTimeOfDay = TimeOfDay::INVALID; m_dayTime = NOON; m_day = 1; m_monsterSpawnTime = 0; m_activeDanceSequence = nullptr; m_pMusic = nullptr; } void GameView::CreatePathFinder() { m_pPather = new micropather::MicroPather(this); } void GameView::CreateMusic() { m_pMusic = CreateMusicEmitter(); AddNode(m_pMusic); } void GameView::OnUpdate() { if (m_gameover) { if (!m_fadeQuad->GetColorAnim().isPlaying()) { // we are done SendCommand(seed::eAppCommand::SWITCH_VIEW, "GameOverView"); return; } UpdateCamera(); UpdateUIs(); return; } else { if (!m_fadeQuad->GetColorAnim().isPlaying()) { m_fadeQuad->SetVisible(false); } } UpdateTime(); UpdateDanceSequence(); UpdateMonsterSpawning(); UpdateEntities(); UpdateCamera(); UpdateUIs(); // check if we are game over if (AllPlayersAreDead()) { OnGameOver(); } ClearEntities(); } static std::unordered_map<StoreItemType, StoreItem> store = { {StoreItemType::Scarecrow, {StoreItemType::Scarecrow, {{DropType::Wood, 2}}, "scarecrow", OYBtn}}, {StoreItemType::Stone, {StoreItemType::Stone, {{DropType::Rock, 3}}, "stone", OXBtn}} }; void GameView::UpdateUIs() { OFindUI("store")->rect.position.x = m_storeAnim; for (auto& storeItem : store) { bool canAfford = true; for (auto& kv : storeItem.second.cost) { if (m_pStockpile->resources[kv.first] < kv.second) { canAfford = false; break; } } OFindUI(storeItem.second.ui)->isVisible = canAfford; } } Entity* GameView::Buy(StoreItemType item) { auto &storeItem = store[item]; // Check if we can afford bool canAfford = true; for (auto& kv : storeItem.cost) { if (m_pStockpile->resources[kv.first] < kv.second) { canAfford = false; break; } } if (!canAfford) return nullptr; // Deplete resources for (auto& kv : storeItem.cost) { m_pStockpile->resources[kv.first] -= kv.second; } m_pStockpile->UpdateTexts(); // Create a new entity, give it to player switch (item) { case StoreItemType::Scarecrow: return new Scarecrow(this); break; case StoreItemType::Stone: return new Stone(this); break; } return nullptr; } void GameView::UpdateMonsterSpawning() { if (GetTimeOfDay() != TimeOfDay::Night) return; float spawnRate = GetMonsterSpawnRate(); m_monsterSpawnTime -= ODT; if (m_monsterSpawnTime <= 0.f) { m_monsterSpawnTime = spawnRate; SpawnMonster(); } } vector<Entity*> GameView::GetEntitiesInRadius(const Vector2& in_pos, float in_radius) { vector<Entity*> res; Tile* tile = GetTileAt(in_pos); if (tile) { FillVectorWithEntitiesInRadius(tile, in_pos, in_radius, res); } // get all the tiles around it tile = GetTileAt(in_pos + Vector2(-1,0)); if (tile) { FillVectorWithEntitiesInRadius(tile, in_pos, in_radius, res); } tile = GetTileAt(in_pos + Vector2(-1, -1)); if (tile) { FillVectorWithEntitiesInRadius(tile, in_pos, in_radius, res); } tile = GetTileAt(in_pos + Vector2(0, -1)); if (tile) { FillVectorWithEntitiesInRadius(tile, in_pos, in_radius, res); } tile = GetTileAt(in_pos + Vector2(1, -1)); if (tile) { FillVectorWithEntitiesInRadius(tile, in_pos, in_radius, res); } tile = GetTileAt(in_pos + Vector2(1, 0)); if (tile) { FillVectorWithEntitiesInRadius(tile, in_pos, in_radius, res); } tile = GetTileAt(in_pos + Vector2(1, 1)); if (tile) { FillVectorWithEntitiesInRadius(tile, in_pos, in_radius, res); } tile = GetTileAt(in_pos + Vector2(0, 1)); if (tile) { FillVectorWithEntitiesInRadius(tile, in_pos, in_radius, res); } tile = GetTileAt(in_pos + Vector2(-1, 1)); if (tile) { FillVectorWithEntitiesInRadius(tile, in_pos, in_radius, res); } return res; } void GameView::FillVectorWithEntitiesInRadius(Tile* in_tile, const Vector2& in_pos, float in_radius, vector<Entity*>& inOut_result) { for (auto entity = in_tile->pEntities->Head(); entity; entity = in_tile->pEntities->Next(entity)) { if ((entity->GetPosition() - in_pos).LengthSquared() < in_radius * in_radius) { inOut_result.push_back(entity); } } } void GameView::UpdateEntities() { for (auto pEntity : m_entities) { pEntity->UpdateEntity(); } } void GameView::UpdateCamera() { bool bAnooneAline = false; for (Player* p : m_players) { if (p->IsAlive()) { bAnooneAline = true; break; } } if (bAnooneAline) { // Fit players in view Vector2 minPlayer((float)m_pTilemap->getWidth(), (float)m_pTilemap->getHeight()); Vector2 maxPlayer(0.f); for (auto pPlayer : m_players) { minPlayer.x = onut::min(pPlayer->GetPosition().x, minPlayer.x); minPlayer.y = onut::min(pPlayer->GetPosition().y, minPlayer.y); maxPlayer.x = onut::max(pPlayer->GetPosition().x, maxPlayer.x); maxPlayer.y = onut::max(pPlayer->GetPosition().y, maxPlayer.y); } minPlayer.x -= 3; minPlayer.y -= 3; maxPlayer.x += 3; maxPlayer.y += 3; m_camera = (minPlayer + maxPlayer) * .5f; float playerViewHeight = maxPlayer.y - minPlayer.y; float zoomH = OScreenHf / playerViewHeight; if (zoomH > 64.f) zoomH = 64.f; float playerViewWidth = maxPlayer.x - minPlayer.x; float zoomW = OScreenWf / playerViewWidth; if (zoomW > 64.f) zoomW = 64.f; m_zoom = onut::min(zoomW, zoomH); } // Animate to target position m_cameraReal = Vector2::Lerp(m_cameraReal, m_camera, ODT * 1.5f); m_zoomReal = lerpf(m_zoomReal, m_zoom, ODT * 4.f); // Update camera based on the players position GetRootNode()->SetScale(Vector2(m_zoomReal)); GetRootNode()->SetPosition(-m_cameraReal * m_zoomReal + OScreenf * .5f); } void GameView::UpdateTime() { m_dayTime += ODT; if (m_dayTime >= DAY_TOTAL_DURATION) { m_dayTime -= DAY_TOTAL_DURATION; } static const Color dayAmbient(1, 1, 1, 1); static const Color nightAmbient = Color(.10f, .15f, .2f, 1); static const Color dawnAmbient(1, .75f, 0, 1); static const Color duskAmbient(.75f, .35f, .55f, 1); auto timeOfDay = GetTimeOfDay(); switch (timeOfDay) { case TimeOfDay::Day: m_pGameLayer->SetAmbient(dayAmbient); break; case TimeOfDay::Night: m_pGameLayer->SetAmbient(nightAmbient); break; case TimeOfDay::Dawn: { const float fullStart = DAWN_START + (DAWN_END - DAWN_START) * .3f; const float fullEnd = DAWN_START + (DAWN_END - DAWN_START) * .6f; if (m_dayTime >= fullStart && m_dayTime <= fullEnd) m_pGameLayer->SetAmbient(dawnAmbient); else if (m_dayTime < fullStart) { float dawnPercent = (m_dayTime - DAWN_START) / (fullStart - DAWN_START); m_pGameLayer->SetAmbient(Color::Lerp(nightAmbient, dawnAmbient, dawnPercent)); } else { float dawnPercent = (DAWN_END - m_dayTime) / (DAWN_END - fullEnd); m_pGameLayer->SetAmbient(Color::Lerp(dayAmbient, dawnAmbient, dawnPercent)); } break; } case TimeOfDay::Dusk: { const float fullStart = DUSK_START + (DUSK_END - DUSK_START) * .3f; const float fullEnd = DUSK_START + (DUSK_END - DUSK_START) * .6f; if (m_dayTime >= fullStart && m_dayTime <= fullEnd) m_pGameLayer->SetAmbient(duskAmbient); else if (m_dayTime < fullStart) { float duskPercent = (m_dayTime - DUSK_START) / (fullStart - DUSK_START); m_pGameLayer->SetAmbient(Color::Lerp(dayAmbient, duskAmbient, duskPercent)); } else { float duskPercent = (DUSK_END - m_dayTime) / (DUSK_END - fullEnd); m_pGameLayer->SetAmbient(Color::Lerp(nightAmbient, duskAmbient, duskPercent)); } break; } } if (timeOfDay != m_previousTimeOfDay) { m_previousTimeOfDay = timeOfDay; OnTimeOfDayChanged(m_previousTimeOfDay); } } void GameView::OnTimeOfDayChanged(TimeOfDay timeOfDay) { switch (timeOfDay) { case TimeOfDay::Night: StartDanceSequence(); m_monsterSpawnTime = 0.f; break; case TimeOfDay::Day: PlayRandomDayMusic(); break; case TimeOfDay::Dusk: // soir commence m_pMusic->Play("RitualMusicAmbient.mp3", 1.f, 2.f); break; case TimeOfDay::Dawn: // matin commence KillAllMonsters(); m_pMusic->Stop(3.f); StopDanceSequence(); m_day++; break; } } void GameView::PlayRandomDayMusic() { int musicIndex = onut::randi(1, 5); string music = "RitualSFX_DaytimeAmbience0" + to_string(musicIndex) + ".mp3"; m_pMusic->Play(music, 1, 2); } void GameView::KillAllEntities() { m_entitiesToKill = m_entities; ClearEntities(); } void GameView::KillEntity( Entity* in_toKill ) { for (auto pEntity : m_entitiesToKill) if (pEntity == in_toKill) return; m_entitiesToKill.push_back(in_toKill); } void GameView::ClearEntities() { for (size_t i = 0; i < m_entitiesToKill.size(); ++i) { for (auto it = m_scarecrows.begin(); it != m_scarecrows.end();) { if ((*it) == m_entitiesToKill[i]) { it = m_scarecrows.erase(it); break; } else { ++it; } } for (auto it = m_entities.begin(); it != m_entities.end();) { if ((*it) == m_entitiesToKill[i]) { it = m_entities.erase(it); DeleteNode(m_entitiesToKill[i]); break; } else { ++it; } } } m_entitiesToKill.clear(); for (auto pEntity : m_entitiesToAdd) { m_pGameLayer->Attach(pEntity, (int)(pEntity->GetPosition().y * 16.f)); m_entities.push_back(pEntity); auto pTile = GetTileAt(pEntity->GetPosition()); if (pTile) { pTile->RegisterEntity(pEntity); } if (dynamic_cast<Scarecrow*>(pEntity)) { m_scarecrows.push_back(pEntity); } } m_entitiesToAdd.clear(); } void GameView::KillAllMonsters() { for (auto it = m_entities.begin(); it != m_entities.end(); ++it ) { auto pMonster = dynamic_cast<Monster*>(*it); if (pMonster) { KillEntity(pMonster); } } } float GameView::GetDayTimeHour() const { return (m_dayTime / DAY_TOTAL_DURATION) * 24.f; } float GameView::GetNightPercent() const { if (m_dayTime < DAWN_START) { return ((DAY_TOTAL_DURATION - DUSK_END) + m_dayTime) / NIGHT_DURATION; } else { return (m_dayTime - DUSK_END) / NIGHT_DURATION; } } float GameView::GetMonsterSpawnRate() const { float nightPercent = GetNightPercent(); float ratePercent = 1.f; if (nightPercent < .5f) { ratePercent = lerpf(.25f, 1.f, nightPercent * 2.f); } else { ratePercent = lerpf(1.f, .25f, (nightPercent * 2.f) - 1.f); } return 1.f / ((ratePercent) * (float)m_day * .5f); } TimeOfDay GameView::GetTimeOfDay() const { if (m_dayTime >= DAWN_END && m_dayTime <= DUSK_START) return TimeOfDay::Day; if (m_dayTime >= DUSK_START && m_dayTime <= DUSK_END) return TimeOfDay::Dusk; if (m_dayTime >= DAWN_START && m_dayTime <= DAWN_END) return TimeOfDay::Dawn; return TimeOfDay::Night; } void GameView::OnRender() { if (m_gameover) return; #if defined(_DEBUG) auto pFont = OGetBMFont("font.fnt"); pFont->draw("Time: " + std::to_string(GetDayTimeHour()), Vector2::Zero); switch (GetTimeOfDay()) { case TimeOfDay::Night: pFont->draw("Night", Vector2(0, 20)); break; case TimeOfDay::Dawn: pFont->draw("Dawn", Vector2(0, 20)); break; case TimeOfDay::Day: pFont->draw("Day", Vector2(0, 20)); break; case TimeOfDay::Dusk: pFont->draw("Dusk", Vector2(0, 20)); break; } pFont->draw("Monster spawn Rate: " + std::to_string(GetMonsterSpawnRate()), Vector2(0, 40)); pFont->draw("Monster count: " + std::to_string(Monster::count), Vector2(0, 60)); pFont->draw("Day: " + std::to_string(m_day), Vector2(0, 80)); #if 0 // Show path OSB->end(); for (auto pEntity : m_entities) { auto pMonster = dynamic_cast<Monster*>(pEntity); if (pMonster) { OPB->begin(onut::ePrimitiveType::LINE_STRIP, nullptr, GetRootNode()->GetTransform()); for (auto& p : pMonster->m_path) { OPB->draw(p); } OPB->end(); } } OSB->begin(); #endif #endif } void GameView::SpawnPlayers() { for (int i = 0; i < 4; ++i) { if (g_activePlayer[i]) { Player* player = new Player(); // todo pass in what "skin" used player->Init(g_playerSpawn[i], this, i); m_players.push_back(player); AddEntity(player); } } } void GameView::StartDanceSequence() { // activate pods for (DancePedestral* d : m_pedestrals) { d->StartEnabledFX(); } m_activeDanceSequence = new DanceSequence(); m_activeDanceSequence->Init(m_day, m_pFireplace, this); } void GameView::StopDanceSequence() { if (m_activeDanceSequence) { delete m_activeDanceSequence; m_activeDanceSequence = nullptr; } for (Player* p : m_players) { p->OnPedestralLockCancel(); } // activate pods for (DancePedestral* d : m_pedestrals) { d->StopFXes(); } } void GameView::UpdateDanceSequence() { if (m_activeDanceSequence) { // gather each player inputs for (Player* p : m_players) { if (m_activeDanceSequence->PlayerNeedsToComplete(p->GetControllerIndex())) { if (m_activeDanceSequence->IsNailed(p->GetInputSequence(), p->GetControllerIndex())) { // yay p->OnDanceSequenceSuccess(); // grow the fire GrowFire(); } } //else //{ // m_activeDanceSequence->Skip(); //} } if (m_activeDanceSequence->Update()) { for (Player* p : m_players) { p->ResetInputSequence(); } } } } void GameView::CreateTileMap() { auto pTileMapNode = CreateTiledMapNode("maptemplate.tmx"); m_pGameLayer->Attach(pTileMapNode, -10); m_pTilemap = pTileMapNode->GetTiledMap(); m_pBackgroundLayer = (onut::TiledMap::sTileLayer*)m_pTilemap->getLayer("backgrounds"); m_pTileLayer = (onut::TiledMap::sTileLayer*)m_pTilemap->getLayer("tiles"); pTileMapNode->SetScale(Vector2(1.f / m_pTilemap->getTileWidth())); m_pTiles = new Tile[m_pTilemap->getWidth() * m_pTilemap->getHeight()]; m_pGameLayer->Attach(m_pBloodLayer = new BloodLayer(m_pTilemap->getWidth(), m_pTilemap->getHeight()), -11); } void GameView::CenterCamera() { m_cameraReal = m_camera = Vector2((float)m_pTilemap->getWidth() * .5f, (float)m_pTilemap->getHeight() * .5f); } void GameView::GenerateMap() { Vector2 mapCenter((float)m_pTilemap->getWidth() * .5f, (float)m_pTilemap->getHeight() * .5f); m_pStockpile = new Stockpile(this, m_pTilemap->getWidth() / 2 + 1, m_pTilemap->getHeight() / 2 - 4); AddEntity(m_pStockpile); // Spawn a bunch of trees for (int i = 0; i < TREE_DENSITY; ++i) { auto center = onut::rand2f(Vector2::Zero, Vector2((float)m_pTilemap->getWidth(), (float)m_pTilemap->getHeight())); int count = onut::randi(2, 12); for (int j = 0; j < count; ++j) { auto pos = center += onut::rand2f(Vector2(-3), Vector2(3)); pos.x = std::round(pos.x) + .5f; pos.y = std::round(pos.y) + .5f; if (pos.x >= mapCenter.x - 3 && pos.y >= mapCenter.y - 3 && pos.x <= mapCenter.x + 3 && pos.y <= mapCenter.y + 3) continue; if (pos.x < 1.f || pos.y < 1.f || pos.x >(float)m_pTilemap->getWidth() - 1.f || pos.y >(float)m_pTilemap->getHeight() - 1.f) continue; auto pTile = GetTileAt(pos); if (!pTile) continue; if (pTile->isOccupied) continue; pTile->isOccupied = true; auto pTree = new Tree(this, pos); AddEntity(pTree); } } // Spawn a bunch of rockz for (int i = 0; i < ROCK_DENSITY; ++i) { auto center = onut::rand2f(Vector2::Zero, Vector2((float)m_pTilemap->getWidth(), (float)m_pTilemap->getHeight())); int count = onut::randi(2, 6); for (int j = 0; j < count; ++j) { auto pos = center += onut::rand2f(Vector2(-3), Vector2(3)); pos.x = std::round(pos.x) + .5f; pos.y = std::round(pos.y) + .5f; if (pos.x >= mapCenter.x - 3 && pos.y >= mapCenter.y - 3 && pos.x <= mapCenter.x + 3 && pos.y <= mapCenter.y + 3) continue; if (pos.x < 1.f || pos.y < 1.f || pos.x >(float)m_pTilemap->getWidth() - 1.f || pos.y >(float)m_pTilemap->getHeight() - 1.f) continue; auto pTile = GetTileAt(pos); if (!pTile) continue; if (pTile->isOccupied) continue; pTile->isOccupied = true; auto pRock = new Rock(this, pos); AddEntity(pRock); } } for (int i = 0; i < m_pTilemap->getWidth(); ++i) { GetTileAt(i, 0)->isOccupied = true; GetTileAt(0, i)->isOccupied = true; GetTileAt(i, m_pTilemap->getHeight() - 1)->isOccupied = true; GetTileAt(m_pTilemap->getWidth() - 1, i)->isOccupied = true; } } void GameView::SpawnMonster() { if (Monster::count >= MAX_MONSTER_COUNT) return; for (int tries = 0; tries < 10; ++tries) { int side = onut::randi() % 4; Vector2 spawnPos; switch (side) { case 0: spawnPos = onut::rand2f(Vector2::Zero, Vector2((float)m_pTilemap->getWidth(), 2.5f)); break; case 1: spawnPos = onut::rand2f(Vector2::Zero, Vector2(2.5f, (float)m_pTilemap->getHeight())); break; case 2: spawnPos = onut::rand2f(Vector2((float)m_pTilemap->getWidth() - 2.5f, 0.f), Vector2(Vector2((float)m_pTilemap->getWidth(), (float)m_pTilemap->getHeight()))); break; case 3: spawnPos = onut::rand2f(Vector2(0.f, (float)m_pTilemap->getHeight() - 2.5f), Vector2(Vector2((float)m_pTilemap->getWidth(), (float)m_pTilemap->getHeight()))); break; } spawnPos.x = std::round(spawnPos.x) + .5f; spawnPos.y = std::round(spawnPos.y) + .5f; auto pTile = GetTileAt(spawnPos); if (!pTile) continue; if (!pTile->isOccupied) { auto pMonster = new Monster(MonsterType::CRAWLER, this, spawnPos); AddEntity(pMonster); break; } } } eTile GameView::GetTileIdAt(const Vector2& position) const { return (eTile)m_pTilemap->getTileAt(m_pTileLayer, (int)position.x, (int)position.y); } void GameView::SetTileIdAt(const Vector2& position, eTile tileId) { m_pTilemap->setTileAt(m_pTileLayer, (int)position.x, (int)position.y, (int)tileId); } Tile *GameView::GetTileAt(const Vector2& position) const { auto x = (int)position.x; auto y = (int)position.y; return GetTileAt(x, y); } Tile* GameView::GetTileAt(int x, int y) const { if (x < 0 || y < 0 || x >= m_pTilemap->getWidth() || y >= m_pTilemap->getHeight()) return nullptr; return m_pTiles + (y * m_pTilemap->getWidth() + x); } Vector2 GameView::GetMapCenter() const { return Vector2((float)m_pTilemap->getWidth() * .5f, (float)m_pTilemap->getHeight() * .5f); } void GameView::CreateEntities() { m_pFireplace = new Fireplace(this, GetMapCenter()); AddEntity(m_pFireplace); // 4 dance pedestral for (int i = 0; i < 4; ++i) { Vector2 pedOffset; if (i == 0) pedOffset = Vector2(-2, -2); if (i == 1) pedOffset = Vector2(2, -2); if (i == 2) pedOffset = Vector2(2, 2); if (i == 3) pedOffset = Vector2(-2, 2); DancePedestral* pedes = new DancePedestral(this, GetMapCenter() + pedOffset, i); m_pedestrals.push_back(pedes); AddEntity(pedes); } } void GameView::AddEntity(Entity* pEntity) { m_entitiesToAdd.push_back(pEntity); } void GameView::OnEntityMoved(Entity* pEntity) { m_pGameLayer->Detach(pEntity); m_pGameLayer->Attach(pEntity, (int)(pEntity->GetPosition().y * 16.f)); auto pTile = GetTileAt(pEntity->GetPosition()); if (pTile) { pTile->RegisterEntity(pEntity); } } void GameView::GrowFire() { m_pFireplace->Grow(); } void GameView::OnGameOver() { g_daysSurvived = m_day - 1; StopDanceSequence(); m_gameover = true; const float fadeTime = 5.f; // start fading the quad anim m_fadeQuad->GetColorAnim().start(Color(0.f, 0.f, 0.f, 0.f), Color(0.f, 0.f, 0.f, 1.f), fadeTime); m_fadeQuad->SetVisible(true); m_pMusic->Stop(fadeTime); m_pFireplace->OnGameOver(); } bool GameView::AllPlayersAreDead() { for (Player* p : m_players) { if (p->IsAlive()) return false; } return true; } int GameView::GetAlivePlayerCount() { int nb = 0; for (auto pPlayer : m_players) { if (pPlayer->IsAlive()) { nb++; } } return nb; } Player* GameView::GetClosestPlayer(const Vector2& position) const { float closestDist = 100000.f; Player* pRet = nullptr; for (auto pPlayer : m_players) { if (!pPlayer->IsAlive()) continue; float dist = Vector2::DistanceSquared(pPlayer->GetPosition(), position); if (dist < closestDist) { closestDist = dist; pRet = pPlayer; } } return pRet; } Entity* GameView::GetClosestPlayerAsSeenByMonster(const Vector2& position) const { float closestDist = 100000.f; Entity* pRet = nullptr; for (auto pPlayer : m_players) { if (!pPlayer->IsAlive()) continue; float dist = Vector2::DistanceSquared(pPlayer->GetPosition(), position); if (dist < closestDist) { closestDist = dist; pRet = pPlayer; } } for (auto pPlayer : m_scarecrows) { float dist = Vector2::DistanceSquared(pPlayer->GetPosition(), position); if (dist < closestDist) { closestDist = dist; pRet = pPlayer; } } return pRet; } void GameView::ShowStore() { m_storeAnim.stop(false); m_storeAnim.startFromCurrent(0.f, .25f, OSpringOut); } void GameView::HideStore() { m_storeAnim.stop(false); m_storeAnim.startFromCurrent(OFindUI("store")->rect.size.x, .25f, OEaseIn); } void GameView::OnPlayerSacrifice(Player* in_player) { for (Player* p : m_players) { if (p != in_player && p->IsAlive()) { p->RestoreFullHealth(); } } KillAllMonsters(); m_pFireplace->GrowToMax(); } void GameView::SplatGore(const Vector2& pos) { m_pBloodLayer->SplatGore(pos); }
26.602193
174
0.574395
Daivuk
dd292d6b7460b7bfbd4c2503f5f32bd4bfff325f
8,898
cpp
C++
AVSGatewayManager/test/AVSGatewayManagerTest.cpp
rysmith0315/avs-device-sdk
f0fa55856af9e33d0889ac14820efbb807341f17
[ "Apache-2.0" ]
null
null
null
AVSGatewayManager/test/AVSGatewayManagerTest.cpp
rysmith0315/avs-device-sdk
f0fa55856af9e33d0889ac14820efbb807341f17
[ "Apache-2.0" ]
null
null
null
AVSGatewayManager/test/AVSGatewayManagerTest.cpp
rysmith0315/avs-device-sdk
f0fa55856af9e33d0889ac14820efbb807341f17
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <fstream> #include <string> #include <gmock/gmock.h> #include <AVSGatewayManager/AVSGatewayManager.h> #include <AVSCommon/SDKInterfaces/MockAVSGatewayAssigner.h> #include <AVSCommon/Utils/Configuration/ConfigurationNode.h> #include <RegistrationManager/CustomerDataManager.h> namespace alexaClientSDK { namespace avsGatewayManager { namespace test { using namespace avsCommon::sdkInterfaces::test; using namespace avsCommon::utils::configuration; using namespace ::testing; /// Test AVS Gateway static const std::string TEST_AVS_GATEWAY = "www.test-avs-gateway.com"; /// Default AVS Gateway static const std::string DEFAULT_AVS_GATEWAY = "https://alexa.na.gateway.devices.a2z.com"; /// Stored AVS Gateway static const std::string STORED_AVS_GATEWAY = "www.avs-gatewa-from-storage.com"; // clang-format off static const std::string AVS_GATEWAY_MANAGER_JSON = R"( { "avsGatewayManager" : { "avsGateway":")" + TEST_AVS_GATEWAY + R"(" } } )"; // clang-format on // clang-format off static const std::string AVS_GATEWAY_MANAGER_JSON_NO_GATEWAY = R"( { "avsGatewayManager" : { } } )"; // clang-format on // clang-format off static const std::string AVS_GATEWAY_MANAGER_JSON_EMPTY_GATEWAY = R"( { "avsGatewayManager" : { "avsGateway":"" } } )"; // clang-format on class MockAVSGatewayManagerStorage : public storage::AVSGatewayManagerStorageInterface { public: MOCK_METHOD0(init, bool()); MOCK_METHOD1(loadState, bool(GatewayVerifyState*)); MOCK_METHOD1(saveState, bool(const GatewayVerifyState&)); MOCK_METHOD0(clear, void()); }; /** * Test harness for @c AVSGatewayManager class. */ class AVSGatewayManagerTest : public Test { public: /// Setup the test harness for running the test. void SetUp() override; /// Clean up the test harness after running the test. void TearDown() override; protected: /// Initializes the @c ConfigurationRoot. void initializeConfigRoot(const std::string& configJson); /// Creates the @c AVSGatewayManager used in the tests. void createAVSGatewayManager(); /// The @c CustomerDataManager. std::shared_ptr<registrationManager::CustomerDataManager> m_customerDataManager; /// The mock @c AVSGatewayAssigner. std::shared_ptr<MockAVSGatewayAssigner> m_mockAvsGatewayAssigner; /// The mock @c AVSGatewayManagerStorageInterface. std::shared_ptr<MockAVSGatewayManagerStorage> m_mockAVSGatewayManagerStorage; /// The instance of the @c AVSGatewayManagerStorage that will be used in the tests. std::shared_ptr<AVSGatewayManager> m_avsGatewayManager; }; void AVSGatewayManagerTest::SetUp() { m_mockAVSGatewayManagerStorage = std::make_shared<NiceMock<MockAVSGatewayManagerStorage>>(); m_mockAvsGatewayAssigner = std::make_shared<NiceMock<MockAVSGatewayAssigner>>(); m_customerDataManager = std::make_shared<registrationManager::CustomerDataManager>(); } void AVSGatewayManagerTest::TearDown() { ConfigurationNode::uninitialize(); } void AVSGatewayManagerTest::initializeConfigRoot(const std::string& configJson) { auto json = std::shared_ptr<std::stringstream>(new std::stringstream()); *json << configJson; std::vector<std::shared_ptr<std::istream>> jsonStream; jsonStream.push_back(json); ASSERT_TRUE(ConfigurationNode::initialize(jsonStream)); } void AVSGatewayManagerTest::createAVSGatewayManager() { EXPECT_CALL(*m_mockAVSGatewayManagerStorage, init()).Times(1).WillOnce(Return(true)); EXPECT_CALL(*m_mockAVSGatewayManagerStorage, loadState(_)).Times(1).WillOnce(Return(true)); m_avsGatewayManager = AVSGatewayManager::create(m_mockAVSGatewayManagerStorage, m_customerDataManager, ConfigurationNode::getRoot()); ASSERT_NE(m_avsGatewayManager, nullptr); } TEST_F(AVSGatewayManagerTest, test_createAVSGatewayManagerWithInvalidParameters) { auto instance = AVSGatewayManager::create(nullptr, m_customerDataManager, ConfigurationNode::getRoot()); ASSERT_EQ(instance, nullptr); instance = AVSGatewayManager::create(m_mockAVSGatewayManagerStorage, nullptr, ConfigurationNode::getRoot()); ASSERT_EQ(instance, nullptr); } /** * Test if a call to setAVSGatewayAssigner uses the gateway URL from the configuration file. */ TEST_F(AVSGatewayManagerTest, test_defaultAVSGatewayFromConfigFile) { initializeConfigRoot(AVS_GATEWAY_MANAGER_JSON); createAVSGatewayManager(); EXPECT_CALL(*m_mockAvsGatewayAssigner, setAVSGateway(_)).WillOnce(Invoke([](const std::string& gatewayURL) { ASSERT_EQ(gatewayURL, TEST_AVS_GATEWAY); })); m_avsGatewayManager->setAVSGatewayAssigner(m_mockAvsGatewayAssigner); } /** * Test if a call to setAVSGatewayAssigner uses the default gateway URL if configuration is not specified. */ TEST_F(AVSGatewayManagerTest, test_defaultAVSGatewayFromConfigFileWithNoGateway) { initializeConfigRoot(AVS_GATEWAY_MANAGER_JSON_NO_GATEWAY); createAVSGatewayManager(); EXPECT_CALL(*m_mockAvsGatewayAssigner, setAVSGateway(_)).WillOnce(Invoke([](const std::string& gatewayURL) { ASSERT_EQ(gatewayURL, DEFAULT_AVS_GATEWAY); })); m_avsGatewayManager->setAVSGatewayAssigner(m_mockAvsGatewayAssigner); } /** * Test if a call to setAVSGatewayAssigner uses the default gateway URL if avsGateway in configuration is empty. */ TEST_F(AVSGatewayManagerTest, test_defaultAVSGatewayFromConfigFileWithEmptyGateway) { initializeConfigRoot(AVS_GATEWAY_MANAGER_JSON_EMPTY_GATEWAY); createAVSGatewayManager(); EXPECT_CALL(*m_mockAvsGatewayAssigner, setAVSGateway(_)).WillOnce(Invoke([](const std::string& gatewayURL) { ASSERT_EQ(gatewayURL, DEFAULT_AVS_GATEWAY); })); m_avsGatewayManager->setAVSGatewayAssigner(m_mockAvsGatewayAssigner); } /** * Test if a call to setAVSGatewayAssigner uses the gateway URL from storage. */ TEST_F(AVSGatewayManagerTest, test_avsGatewayFromStorage) { initializeConfigRoot(AVS_GATEWAY_MANAGER_JSON); EXPECT_CALL(*m_mockAVSGatewayManagerStorage, init()).Times(1).WillOnce(Return(true)); EXPECT_CALL(*m_mockAVSGatewayManagerStorage, loadState(_)).WillOnce(Invoke([](GatewayVerifyState* state) { state->avsGatewayURL = STORED_AVS_GATEWAY; state->isVerified = true; return true; })); m_avsGatewayManager = AVSGatewayManager::create(m_mockAVSGatewayManagerStorage, m_customerDataManager, ConfigurationNode::getRoot()); ASSERT_NE(m_avsGatewayManager, nullptr); EXPECT_CALL(*m_mockAvsGatewayAssigner, setAVSGateway(_)).WillOnce(Invoke([](const std::string& gatewayURL) { ASSERT_EQ(gatewayURL, STORED_AVS_GATEWAY); })); m_avsGatewayManager->setAVSGatewayAssigner(m_mockAvsGatewayAssigner); } /** * Test if a call to setGatewayURL() with a new URL calls the setAVSGateway() method on @c AVSGatewayAssigner and calls * storeState() on @c AVSGatewayManagerStorage. */ TEST_F(AVSGatewayManagerTest, test_setAVSGatewayURLWithNewURL) { initializeConfigRoot(AVS_GATEWAY_MANAGER_JSON); createAVSGatewayManager(); EXPECT_CALL(*m_mockAvsGatewayAssigner, setAVSGateway(_)).Times(2); EXPECT_CALL(*m_mockAVSGatewayManagerStorage, saveState(_)).Times(1); m_avsGatewayManager->setAVSGatewayAssigner(m_mockAvsGatewayAssigner); m_avsGatewayManager->setGatewayURL(DEFAULT_AVS_GATEWAY); } /** * Test if a call to setGatewayURL with the same URL does not trigger calls to @c AVSGatewayAssigner and @c * AVSGatewayManagerStorage. */ TEST_F(AVSGatewayManagerTest, test_setAVSGatewayURLWithSameURL) { initializeConfigRoot(AVS_GATEWAY_MANAGER_JSON); createAVSGatewayManager(); EXPECT_CALL(*m_mockAvsGatewayAssigner, setAVSGateway(_)).Times(1); EXPECT_CALL(*m_mockAVSGatewayManagerStorage, saveState(_)).Times(0); m_avsGatewayManager->setAVSGatewayAssigner(m_mockAvsGatewayAssigner); m_avsGatewayManager->setGatewayURL(TEST_AVS_GATEWAY); } /** * Test if a call to clearData() invokes call to clear() on the storage. */ TEST_F(AVSGatewayManagerTest, test_clearData) { initializeConfigRoot(AVS_GATEWAY_MANAGER_JSON); createAVSGatewayManager(); EXPECT_CALL(*m_mockAVSGatewayManagerStorage, clear()).Times(1); m_avsGatewayManager->clearData(); } } // namespace test } // namespace avsGatewayManager } // namespace alexaClientSDK
35.73494
119
0.764329
rysmith0315
dd2b3a0606d4f086cfcdd028231cd9711e51406e
1,496
cpp
C++
Breakout/laser.cpp
henry9836/Space-Invaders
75a3c530589c3a0b6f207e6fd2bbcaad9c9f6c98
[ "MIT" ]
null
null
null
Breakout/laser.cpp
henry9836/Space-Invaders
75a3c530589c3a0b6f207e6fd2bbcaad9c9f6c98
[ "MIT" ]
null
null
null
Breakout/laser.cpp
henry9836/Space-Invaders
75a3c530589c3a0b6f207e6fd2bbcaad9c9f6c98
[ "MIT" ]
null
null
null
// // Bachelor of Software Engineering // Media Design School // Auckland // New Zealand // // (c) 2018 Media Design School. // // File Name : laser.cpp // Description : controls lasers // Author : Henry Oliver // Mail : henry.oliver@mediadesign.school.nz // // Library Includes // Local Includes #include "resource.h" #include "utils.h" // This Includes #include "laser.h" // Static Variables // Static Function Prototypes // Implementation CLaser::CLaser() :m_fVelocityY(0.0f), m_fVelocityX(0.0f) { } CLaser::~CLaser() { } bool CLaser::Initialise(float _fPosX, float _fPosY, float _fVelocityY) { VALIDATE(CEntity::Initialise(IDB_BITMAP7, IDB_BITMAP8)); m_fX = _fPosX; m_fY = _fPosY; m_fVelocityX = 0; m_fVelocityY = _fVelocityY; return (true); } void CLaser::Draw() { CEntity::Draw(); } void CLaser::Process(float _fDeltaTick, CLaser* me) { m_fX += m_fVelocityX * _fDeltaTick; m_fY += m_fVelocityY * _fDeltaTick; CEntity::Process(_fDeltaTick); } float CLaser::GetVelocityX() const { return (m_fVelocityX); } float CLaser::GetVelocityY() const { return (m_fVelocityY); } void CLaser::SetVelocityX(float _fX) { m_fVelocityX = _fX; } void CLaser::SetVelocityY(float _fY) { m_fVelocityY = _fY; } void CLaser::amBady() { amBadGuy = true; } bool CLaser::getBad() { return amBadGuy; } float CLaser::GetRadius() const { return (GetWidth() / 2.0f); }
13.724771
66
0.645053
henry9836
dd2d3aa721bd507c5401bafa86e2ff70669e61da
3,478
cpp
C++
source/launch.cpp
mvandevander/SpechtCMDLauncher
692c6acec43f6c91a63edce8094be8c18ad677ab
[ "MIT" ]
1
2022-02-09T01:14:25.000Z
2022-02-09T01:14:25.000Z
source/launch.cpp
mvandevander/SpechtCMDLauncher
692c6acec43f6c91a63edce8094be8c18ad677ab
[ "MIT" ]
null
null
null
source/launch.cpp
mvandevander/SpechtCMDLauncher
692c6acec43f6c91a63edce8094be8c18ad677ab
[ "MIT" ]
null
null
null
// Launch.cpp is a command line utilitiy for launching Applications without // a .bat script from a config file // TODO: Write my own token parsing, and compare #include <cstdio> #include <stdlib.h> #include "SpechtStringLib.cpp" #define internal static #define local_persist static #define global_variable static struct AppPathPair { char *application; char *path; }; // TODO: Dynamicly store these so we don't have a hard limit and so we don't // have to many global_variable AppPathPair ParsingApps[100] = {}; internal AppPathPair SplitLineToAppPathPair(char *str, char delim = '=') { AppPathPair curProccessingApp = {}; //just a place to save the rest of the line after the delim char *saveptr = ((char*)calloc(getStringLength(str)+1, sizeof(char))); char *tempStr = str; char *token = SplitString(tempStr, delim, saveptr); //TODO: Make this less janky // This also assumes there is only 2 parts a application name and a // application path if(token) { printf("\nDEBUG | Application -> %s", token); curProccessingApp.application = token; free(token); //token = SplitString(NULL, delim, saveptr); if(token) { // temp until splitString is fixed to take null printf("\nDEBUG | Path -> %s", saveptr); curProccessingApp.path = saveptr; //free(token); } } else { printf_s("\nInvalid Token: %s", token); free(token); } free(saveptr); return curProccessingApp; } internal int CLConfigParser(char *configFile) { // following if the current line in the config.cfg that I am trying to read // openTTD="C:\Program Files (x86)\OpenTTD\openttd.exe" // though when I debug the currentLine is only openTTD=\ FILE *cfg = fopen(configFile, "r"); // open the config file read-only if (cfg) { char currentLine[256] = {}; int validLineCount = 0; while(fgets(currentLine, 256, cfg)) { ParsingApps[validLineCount] = SplitLineToAppPathPair((char *)&currentLine); validLineCount++; } fclose(cfg); return validLineCount; } else { printf_s("\nThe config file was not found, please check the name : %s", configFile); fclose(cfg); return 0; } } internal void CLArgsParser(char *arg, int validAppCount) { if(compareString(arg,"-h") || compareString(arg,"--help") || compareString(arg,"/?")) { printf("\n%s\n", arg); printf("THIS IS HELP\n"); //TODO: Actually print some help for the end user } else { for(int i = 0; i < validAppCount; i++) { if(compareString(arg, ParsingApps[i].application)) { //printf("\nPATH -> %s\n", ParsingApps[i].path); // String work to get everything in 1 string so system() can work char *buffer = CatString("call ", ParsingApps[i].path); system(buffer); } } } } int main(int argc, char *argv[]) { if (argc >= 1) { int validApplicationCount = CLConfigParser("config.cfg"); if(validApplicationCount > 0) { char *cmdArg = argv[1]; CLArgsParser(cmdArg, validApplicationCount); } } else { printf("\ninvalid argument count: must have 1 arg\n"); } return 0; }
25.021583
92
0.591432
mvandevander
dd306cf223ff136818dd3c8b1a7dc37e82d3d7cc
8,356
cc
C++
testing/mystrlen_test_multi_event.cc
jasonspencer/CPP_LPE_wrap
b4b20b730cb04d91c665314aa805cfce4f3ddf35
[ "Apache-2.0" ]
1
2020-08-10T21:35:14.000Z
2020-08-10T21:35:14.000Z
testing/mystrlen_test_multi_event.cc
jasonspencer/CPP_LPE_wrap
b4b20b730cb04d91c665314aa805cfce4f3ddf35
[ "Apache-2.0" ]
null
null
null
testing/mystrlen_test_multi_event.cc
jasonspencer/CPP_LPE_wrap
b4b20b730cb04d91c665314aa805cfce4f3ddf35
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <sstream> #include <cstring> // std strlen #include <functional> #include <memory> #include <jsplib/perf/PerfEventCount.hh> #include <jsplib/perf/ScopedEventTrigger.hh> #include <jsplib/perf/WallTimeEvent.hh> #ifndef TOTALSTRINGLENGTH #define TOTALSTRINGLENGTH (1<<30) #endif // g++ -O3 -Wall -Wextra ScopedPerfEventCounter_mystrlen_test_multi_event.cc -std=c++0x -DUSELONGWORDS && ./a.out size_t mystrlen ( const char * str ) { size_t len = 0; while(*str++) ++len; return len; } int main() { std::unique_ptr<char []> str (new char[TOTALSTRINGLENGTH]); // deliberately not aligned - and the strings within the array will mostly be unaligned anyway. std::fill( str.get(), str.get()+TOTALSTRINGLENGTH, 'a' ); for(unsigned j = 1, i = 1 ; i < TOTALSTRINGLENGTH ; ++j ) { str[i] = '\0'; #ifdef USELONGWORDS i += 64+(j%64); #else i += 2+(j%8); #endif } str[TOTALSTRINGLENGTH-1] = '\0'; using pehs = jsplib::perf::linux_perf_event_counter_t::HWSW_EVENT_T; using pehcev = jsplib::perf::linux_perf_event_counter_t::HWCACHE_EVENT_T; using pehcopid = jsplib::perf::linux_perf_event_counter_t::HWCACHE_OPID_EVENT_T; using pehcopre = jsplib::perf::linux_perf_event_counter_t::HWCACHE_OPRESULT_EVENT_T; { jsplib::perf::PerfEventCount pc1{ pehs::HW_CACHE_REFERENCES, pehs::HW_CACHE_MISSES, pehs::HW_BRANCH_INSTRUCTIONS, pehs::HW_BRANCH_MISSES, pehs::HW_REF_CPU_CYCLES }; jsplib::perf::WallTimeEvent timer; std::cout << ">>> 1 group of 5 performance events." << std::endl; uintmax_t sum = 0; { jsplib::perf::ScopedEventTrigger trig2 { &timer }; jsplib::perf::ScopedEventTrigger trig1 { &pc1 }; unsigned j = 0; size_t len = 1; while( j < TOTALSTRINGLENGTH ) { len = mystrlen ( str.get() + j ); sum += len; j += (len+1); } } std::cout << "mystrlen took: " << timer.getDuration() << '\n'; std::cout << "sum : " << sum << '\n'; std::cout << "HW_CACHE_REFERENCES: " << pc1.getValue( 0 ) << "\tHW_CACHE_MISSES: " << pc1.getValue( 1 ) << "\tratio: " << 100.0 * pc1.getRatio( 1, 0 ) << " %\n"; std::cout << "HW_BRANCH_INSTRUCTIONS: " << pc1.getValue( 2 ) << "\tHW_BRANCH_MISSES: " << pc1.getValue( 3 ) << "\tratio: " << 100.0 * pc1.getRatio( 3, 2 ) << " %\n"; std::cout << "HW_REF_CPU_CYCLES: " << pc1.getValue( 4 ) << '\n'; std::cout << "Multiplexing scaling factor: " << pc1.getLastScaling() << "\n\n"; } { jsplib::perf::PerfEventCount pc1{ pehs::HW_CACHE_REFERENCES, pehs::HW_CACHE_MISSES, pehs::HW_BRANCH_INSTRUCTIONS, pehs::HW_BRANCH_MISSES, {pehcev::HW_CACHE_L1D,pehcopid::HW_CACHE_OP_PREFETCH,pehcopre::HW_CACHE_RESULT_MISS} }; jsplib::perf::WallTimeEvent timer; std::cout << ">>> 1 group of 5 performance events, swapping HW_REF_CPU_CYCLES for a cache event." << std::endl; uintmax_t sum = 0; { jsplib::perf::ScopedEventTrigger trig { &pc1, &timer }; unsigned j = 0; size_t len = 1; while( j < TOTALSTRINGLENGTH ) { len = mystrlen ( str.get() + j ); sum += len; j += (len+1); } } std::cout << "mystrlen took: " << timer.getDuration() << '\n'; std::cout << "sum : " << sum << '\n'; std::cout << "HW_CACHE_REFERENCES: " << pc1.getValue( 0 ) << "\tHW_CACHE_MISSES: " << pc1.getValue( 1 ) << "\tratio: " << 100.0 * pc1.getRatio( 1, 0 ) << " %\n"; std::cout << "HW_BRANCH_INSTRUCTIONS: " << pc1.getValue( 2 ) << "\tHW_BRANCH_MISSES: " << pc1.getValue( 3 ) << "\tratio: " << 100.0 * pc1.getRatio( 3, 2 ) << " %\n"; std::cout << "L1D_PREFETCH_MISSES: " << pc1.getValue( 4 ) << '\n'; std::cout << "Multiplexing scaling factor: " << pc1.getLastScaling() << "\n\n"; } { jsplib::perf::PerfEventCount pc1{ pehs::HW_CACHE_REFERENCES, pehs::HW_CACHE_MISSES, {pehcev::HW_CACHE_L1D,pehcopid::HW_CACHE_OP_PREFETCH,pehcopre::HW_CACHE_RESULT_MISS} }; jsplib::perf::PerfEventCount pc2{ pehs::HW_BRANCH_INSTRUCTIONS, pehs::HW_BRANCH_MISSES, pehs::HW_REF_CPU_CYCLES }; jsplib::perf::WallTimeEvent timer; std::cout << ">>> 2 groups of 3 and 3 performance events, including the cache event and HW_REF_CPU_CYCLES. Triggered by two ScopedEventTriggers." << std::endl; uintmax_t sum = 0; { jsplib::perf::ScopedEventTrigger trig1 { &pc1 }; jsplib::perf::ScopedEventTrigger trig2 { &pc2 }; jsplib::perf::ScopedEventTrigger trig3 { &timer }; unsigned j = 0; size_t len = 1; while( j < TOTALSTRINGLENGTH ) { len = mystrlen ( str.get() + j ); sum += len; j += (len+1); } } std::cout << "mystrlen took: " << timer.getDuration() << '\n'; std::cout << "sum : " << sum << '\n'; std::cout << "HW_CACHE_REFERENCES: " << pc1.getValue( 0 ) << "\tHW_CACHE_MISSES: " << pc1.getValue( 1 ) << "\tratio: " << 100.0 * pc1.getRatio( 1, 0 ) << " %\n"; std::cout << "HW_BRANCH_INSTRUCTIONS: " << pc2.getValue( 0 ) << "\tHW_BRANCH_MISSES: " << pc2.getValue( 1 ) << "\tratio: " << 100.0 * pc2.getRatio( 1, 0 ) << " %\n"; std::cout << "L1D_PREFETCH_MISSES: " << pc2.getValue( 0 ) << '\n'; std::cout << "HW_REF_CPU_CYCLES: " << pc2.getValue( 1 ) << '\n'; std::cout << "Multiplexing scaling factor for pc1: " << pc1.getLastScaling() << '\n'; std::cout << "Multiplexing scaling factor for pc2: " << pc2.getLastScaling() << "\n\n"; } { jsplib::perf::PerfEventCount pc1{ pehs::HW_CACHE_REFERENCES, pehs::HW_CACHE_MISSES, {pehcev::HW_CACHE_L1D,pehcopid::HW_CACHE_OP_PREFETCH,pehcopre::HW_CACHE_RESULT_MISS} }; jsplib::perf::PerfEventCount pc2{ pehs::HW_BRANCH_INSTRUCTIONS, pehs::HW_BRANCH_MISSES, pehs::HW_REF_CPU_CYCLES }; jsplib::perf::WallTimeEvent timer; std::cout << ">>> 2 groups of 3 and 3 performance events, including the cache event and HW_REF_CPU_CYCLES. Triggered by a single ScopedEventTrigger." << std::endl; uintmax_t sum = 0; { jsplib::perf::ScopedEventTrigger trig1 { &timer, &pc1, &pc2 }; unsigned j = 0; size_t len = 1; while( j < TOTALSTRINGLENGTH ) { len = mystrlen ( str.get() + j ); sum += len; j += (len+1); } } std::cout << "mystrlen took: " << timer.getDuration() << '\n'; std::cout << "sum : " << sum << '\n'; std::cout << "HW_CACHE_REFERENCES: " << pc1.getValue( 0 ) << "\tHW_CACHE_MISSES: " << pc1.getValue( 1 ) << "\tratio: " << 100.0 * pc1.getRatio( 1, 0 ) << " %\n"; std::cout << "HW_BRANCH_INSTRUCTIONS: " << pc2.getValue( 0 ) << "\tHW_BRANCH_MISSES: " << pc2.getValue( 1 ) << "\tratio: " << 100.0 * pc2.getRatio( 1, 0 ) << " %\n"; std::cout << "L1D_PREFETCH_MISSES: " << pc2.getValue( 0 ) << '\n'; std::cout << "HW_REF_CPU_CYCLES: " << pc2.getValue( 1 ) << '\n'; std::cout << "Multiplexing scaling factor for pc1: " << pc1.getLastScaling() << '\n'; std::cout << "Multiplexing scaling factor for pc2: " << pc2.getLastScaling() << "\n\n"; } { jsplib::perf::PerfEventCount pc1{ pehs::HW_CACHE_REFERENCES, pehs::HW_CACHE_MISSES, {pehcev::HW_CACHE_L1D,pehcopid::HW_CACHE_OP_PREFETCH,pehcopre::HW_CACHE_RESULT_MISS} }; jsplib::perf::PerfEventCount pc2{ pehs::HW_BRANCH_INSTRUCTIONS, pehs::HW_BRANCH_MISSES, pehs::HW_REF_CPU_CYCLES }; jsplib::perf::WallTimeEvent timer; std::cout << ">>> 2 groups of 3 and 3 performance events, including the cache event and HW_REF_CPU_CYCLES. ." << std::endl; uintmax_t sum = 0; { jsplib::perf::ScopedEventTrigger trig1 { &timer, &pc1 }; unsigned j = 0; size_t len = 1; while( j < TOTALSTRINGLENGTH ) { len = mystrlen ( str.get() + j ); sum += len; j += (len+1); } } std::cout << "mystrlen took: " << timer.getDuration() << '\n'; timer.reset(); std::cout << "sum : " << sum << '\n'; sum = 0; { jsplib::perf::ScopedEventTrigger trig1 { &timer, &pc2 }; unsigned j = 0; size_t len = 1; while( j < TOTALSTRINGLENGTH ) { len = mystrlen ( str.get() + j ); sum += len; j += (len+1); } } std::cout << "mystrlen took: " << timer.getDuration() << '\n'; std::cout << "sum : " << sum << '\n'; std::cout << "HW_CACHE_REFERENCES: " << pc1.getValue( 0 ) << "\tHW_CACHE_MISSES: " << pc1.getValue( 1 ) << "\tratio: " << 100.0 * pc1.getRatio( 1, 0 ) << " %\n"; std::cout << "HW_BRANCH_INSTRUCTIONS: " << pc2.getValue( 0 ) << "\tHW_BRANCH_MISSES: " << pc2.getValue( 1 ) << "\tratio: " << 100.0 * pc2.getRatio( 1, 0 ) << " %\n"; std::cout << "L1D_PREFETCH_MISSES: " << pc2.getValue( 0 ) << '\n'; std::cout << "HW_REF_CPU_CYCLES: " << pc2.getValue( 1 ) << '\n'; std::cout << "Multiplexing scaling factor for pc1: " << pc1.getLastScaling() << '\n'; std::cout << "Multiplexing scaling factor for pc2: " << pc2.getLastScaling() << "\n\n"; } }
43.978947
226
0.640618
jasonspencer
dd30ba1707c087832ab694c9fc294b4c3a359ab5
1,353
cpp
C++
线性表/顺序实现大题/P19.5.cpp
Ruvikm/Wangdao-Data-Structures
e00494f40c0be9d81229062bf69fe1e12e340773
[ "MIT" ]
103
2021-01-07T13:03:57.000Z
2022-03-31T03:10:35.000Z
线性表/顺序实现大题/P19.5.cpp
fu123567/Wangdao-Data-Structures
e00494f40c0be9d81229062bf69fe1e12e340773
[ "MIT" ]
null
null
null
线性表/顺序实现大题/P19.5.cpp
fu123567/Wangdao-Data-Structures
e00494f40c0be9d81229062bf69fe1e12e340773
[ "MIT" ]
23
2021-04-10T07:53:03.000Z
2022-03-31T00:33:05.000Z
#include <cstdio> #include <iostream> #include <algorithm> using namespace std; #pragma region 建立顺序存储的线性表 #define MAX 30 #define _for(i,a,b) for( int i=(a); i<(b); ++i) #define _rep(i,a,b) for( int i=(a); i<=(b); ++i) typedef struct { int data[MAX]; int length; }List; void swap(int& a, int& b) { int t; t = a; a = b; b = t; } //给定一个List,传入List的大小,要逆转的起始位置 void Reserve(List& list, int start, int end, int size) { if (end <= start || end >= size) { return; } int mid = (start + end) / 2; _rep(i, 0, mid - start) { swap(list.data[start + i], list.data[end - i]); } } void PrintList(List list) { _for(i, 0, list.length) { cout << list.data[i] << " "; } cout << endl; } #pragma endregion //P19.5 //从顺序表中删除其值在给定值s与t之间(包含s和t, 要求s < t)的所有元素, //如果s或t不合理或顺序表为空, 则显示出错信息并退出运行 void DeleteS_T(List& list, int S, int T) { if (S >= T || !list.length) return; for (int i = 0; i < list.length; i++) { if (list.data[i] >= S && list.data[i] <= T) { for (int j = i + 1; j < list.length; j++) { list.data[j - 1] = list.data[j]; } //要重新回退一个位置,重新检测,否则会跳过某些数字 if (i) i -= 1; list.length -= 1; } } } int main() { List list; list.length = 9; int Data[] = { 2,4,9,5,11,5,24,14,44 }; for (int i = 0; i < list.length; i++) list.data[i] = Data[i]; PrintList(list); DeleteS_T(list, 4, 11); PrintList(list); }
17.802632
56
0.574279
Ruvikm
dd400b2b4d4bd9ccb7aac503d7135a31cfdc8598
3,046
cpp
C++
PareidoliaCL/pattern.cpp
cpkt9762/PareidoliaTriggerbot
fdd98d4fc31fa6dec60176c87264705ddff8a3e8
[ "MIT" ]
21
2019-11-05T10:21:39.000Z
2022-03-27T09:07:26.000Z
PareidoliaCL/pattern.cpp
blackhades00/PareidoliaTriggerbot
fdd98d4fc31fa6dec60176c87264705ddff8a3e8
[ "MIT" ]
null
null
null
PareidoliaCL/pattern.cpp
blackhades00/PareidoliaTriggerbot
fdd98d4fc31fa6dec60176c87264705ddff8a3e8
[ "MIT" ]
18
2019-11-03T13:55:50.000Z
2022-03-27T09:07:27.000Z
/*++ Copyright (c) 2019 changeofpace. All rights reserved. Use of this source code is governed by the MIT license. See the 'LICENSE' file for more information. --*/ #include "pattern.h" #include "log.h" #include "ntdll.h" _Use_decl_annotations_ BOOL PtnFindPatternUnique( PVOID pBaseAddress, SIZE_T cbSearchSize, PCHAR pszPattern, PCHAR pszMask, SIZE_T cchPattern, CHAR Wildcard, PULONG_PTR pAddress ) /*++ Description: Search the specified region of memory for a unique series of bytes which match the specified pattern and mask. Parameters: pBaseAddress - The base address of the region of memory to be searched. cbSearchSize - The size of the region of memory to be searched. pszPattern - A null-terminated string representing the desired series of bytes to be matched. pszMask - A null-terminated string that specifies the indices of the wildcard characters in the pattern string. cchPattern - The number of characters, including the null-terminator, in the pattern string and the mask string. WildCard - The wildcard character used in the mask string. pAddress - Returns the address of the matched series of bytes. Remarks: This routine returns FALSE if multiple matches are found. --*/ { SIZE_T cchCompare = 0; PCHAR pCursor = NULL; PCHAR pEndAddress = NULL; SIZE_T i = 0; PVOID pCandidate = NULL; BOOL status = TRUE; // // Zero out parameters. // *pAddress = 0; DBG_PRINT("Searching for unique pattern. (Address = %p, Size = 0x%IX)", pBaseAddress, cbSearchSize); // // We do not match the null-terminator when searching. // cchCompare = cchPattern - 1; if (!cchCompare || MAXSIZE_T == cchCompare) { ERR_PRINT("Invalid pattern length."); status = FALSE; goto exit; } pEndAddress = (PCHAR)((ULONG_PTR)pBaseAddress + cbSearchSize); for (pCursor = (PCHAR)pBaseAddress; (ULONG_PTR)pCursor + cchCompare <= (ULONG_PTR)pEndAddress; pCursor++) { for (i = 0; i < cchCompare; i++) { if (pszMask[i] == Wildcard) { continue; } if (pCursor[i] != pszPattern[i]) { break; } } // if (i != cchCompare) { continue; } // // Verify that we only find one match in the search region. // if (pCandidate) { ERR_PRINT("Pattern collision. (%p, %p)", pCandidate, pCursor); status = FALSE; goto exit; } // // Set the current address as our candidate. // pCandidate = pCursor; } // if (!pCandidate) { ERR_PRINT("Failed to find pattern."); status = FALSE; goto exit; } // // Set out parameters. // *pAddress = (ULONG_PTR)pCandidate; exit: return status; }
21.602837
78
0.587656
cpkt9762
dd45fb34e2674257c2cc5f5bb9b285324a86752b
2,562
cc
C++
tests&old_stuff/old tests/learning by doing/cache - Copy.cc
reiss-josh/RESTful_memcache
40a21020cd3830c9e11b075039cb7a3b760ac0ad
[ "MIT" ]
1
2019-05-02T21:47:15.000Z
2019-05-02T21:47:15.000Z
tests&old_stuff/old tests/learning by doing/cache - Copy.cc
reiss-josh/RESTful_memcache
40a21020cd3830c9e11b075039cb7a3b760ac0ad
[ "MIT" ]
null
null
null
tests&old_stuff/old tests/learning by doing/cache - Copy.cc
reiss-josh/RESTful_memcache
40a21020cd3830c9e11b075039cb7a3b760ac0ad
[ "MIT" ]
1
2018-10-08T06:04:44.000Z
2018-10-08T06:04:44.000Z
#include <cache.hh> #include <iostream> struct Cache::Impl { private: index_type memused_; evictor_type evictor_; hash_func hasher_; index_type maxmem_; public: /*Impl(index_type maxmem, evictor_type evictor, hash_func hasher) : maxmem_(maxmem), evictor_(evictor), hasher_(hasher), memused_(0) { } ~Impl() = default;*/ void set(key_type key, val_type val, index_type size) { hash_func hasher = std::hash<std::string>(); size_t hashed = hasher(key); //put key,val pair into array. wtf is size?? } val_type get(key_type key, index_type& val_size) const { hash_func hasher = std::hash<std::string>(); size_t hashed = hasher(key); //return a pointer to key in array } void del(key_type key) { printf("god help us\n"); hash_func hasher = std::hash<std::string>(); size_t hashed = hasher(key); //if there's anything at hashed in array, delete it n } index_type space_used() const { return memused_; } }; // Create a new cache object with a given maximum memory capacity. Cache::Cache(index_type maxmem, evictor_type evictor, hash_func hasher) : pImpl_(new Impl) {} Cache::~Cache() = default; // Add a <key, value> pair to the cache. // If key already exists, it will overwrite the old value. // Both the key and the value are to be deep-copied (not just pointer copied). // If maxmem capacity is exceeded, sufficient values will be removed // from the cache to accomodate the new value. void Cache::set(key_type key, val_type val, index_type size) { pImpl_ ->set(key,val,size); } // Retrieve a pointer to the value associated with key in the cache, // or NULL if not found. // Sets the actual size of the returned value (in bytes) in val_size. Cache::val_type Cache::get(key_type key, index_type& val_size) const { return pImpl_ ->get(key, val_size); } // Delete an object from the cache, if it's still there void Cache::del(key_type key) { pImpl_ ->del(key); } // Compute the total amount of memory used up by all cache values (not keys) Cache::index_type Cache::space_used() const { return pImpl_ ->space_used(); } int main() { Cache test_cache(10); std::cout << test_cache.space_used() << std::endl; test_cache.del("help"); Cache::val_type x = "grape"; Cache::index_type y = 10; test_cache.set("apple",x,y); } //boop /* unordered_map<std::string, void*, hash_func> my_table(0, hasher_; hash_func hasher; hash_vale = hasher(); std::hash<std::string> h; h(); struct Cache::Impl { unordered_map<std::string, void*, hash_func> data_; ... Impl(maxmem, hasher, evictor) : data_(0, hasher) } */
22.875
78
0.703357
reiss-josh
dd493e03d27603d239c22a07eed05f382237c86c
2,357
hpp
C++
queue.hpp
praktikum-tiunpad-2021/tugas-08a-AriqHakim
8e0fdb0e61830928704aeb4756c8fc4413674e1a
[ "MIT" ]
null
null
null
queue.hpp
praktikum-tiunpad-2021/tugas-08a-AriqHakim
8e0fdb0e61830928704aeb4756c8fc4413674e1a
[ "MIT" ]
null
null
null
queue.hpp
praktikum-tiunpad-2021/tugas-08a-AriqHakim
8e0fdb0e61830928704aeb4756c8fc4413674e1a
[ "MIT" ]
null
null
null
#pragma once namespace strukdat { namespace priority_queue { /** * @brief Implementasi struct untuk elemen, harus ada isi dan prioritas elemen. */ template <typename T> struct Element { T data; int priority; Element* next; }; template <typename T> using ElementPtr = Element<T> *; /** * @brief implemetasi struct untuk queue. */ template <typename T> struct Queue { ElementPtr<T> head; ElementPtr<T> tail; }; /** * @brief membuat queue baru * * @return queue kosong */ template <typename T> Queue<T> new_queue() { Queue<T> Q; Q.head = nullptr; Q.tail = nullptr; return Q; } /** * @brief memasukan data sesuai priority elemen. * * @param q queue yang dipakai. * @param value isi dari elemen. * @param priority prioritas elemen yang menentukan urutan. */ template <typename T> void enqueue(Queue<T> &q, const T &value, int priority) { ElementPtr<T> pNew = new Element<T>; pNew -> data = value; pNew -> priority = priority; pNew -> next = nullptr; if(q.head == nullptr && q.tail == nullptr){ q.head = pNew; q.tail = pNew; } else { ElementPtr<T> pHelp = q.head; ElementPtr<T> prev = nullptr; while(pNew -> priority <= pHelp -> priority){ if(pHelp -> next == nullptr) break; prev = pHelp; pHelp = pHelp -> next; } if(pHelp == q.head && pNew -> priority > pHelp -> priority){ pNew -> next = pHelp; q.head = pNew; } else if(pHelp == q.tail && pNew -> priority < pHelp -> priority){ pHelp -> next = pNew; q.tail = pNew; } else { pNew -> next = pHelp; prev -> next = pNew; } } } /** * @brief mengembalikan isi dari elemen head. * * @param q queue yang dipakai. * @return isi dari elemen head. */ template <typename T> T top(const Queue<T> &q) { return q.head -> data; } /** * @brief menghapus elemen head queue (First in first out). * * @param q queue yang dipakai. */ template <typename T> void dequeue(Queue<T> &q) { ElementPtr<T> curr; if(q.head == nullptr && q.tail == nullptr){ curr = nullptr; } else if (q.head -> next == nullptr){ curr = q.head; q.head = nullptr; q.tail = nullptr; } else { curr = q.head; q.head = q.head -> next; curr -> next = nullptr; } delete curr; } } // namespace priority_queue } // namespace strukdat
20.318966
79
0.600764
praktikum-tiunpad-2021
dd506a0fa0bac06cc2667e0cb814f0f8d55a42fa
4,039
cpp
C++
src/GeneralSettingsPage.cpp
lingnand/Helium
d1f8fab6eb5d60e35b3287f6ea35cd1fae71f816
[ "BSD-3-Clause" ]
8
2021-04-16T02:05:54.000Z
2022-03-16T13:56:23.000Z
src/GeneralSettingsPage.cpp
lingnand/Helium
d1f8fab6eb5d60e35b3287f6ea35cd1fae71f816
[ "BSD-3-Clause" ]
null
null
null
src/GeneralSettingsPage.cpp
lingnand/Helium
d1f8fab6eb5d60e35b3287f6ea35cd1fae71f816
[ "BSD-3-Clause" ]
2
2021-04-17T10:49:58.000Z
2021-07-21T20:39:52.000Z
/* * GeneralSettingsPage.cpp * * Created on: May 25, 2015 * Author: lingnan */ #include <bb/cascades/TitleBar> #include <bb/cascades/Picker> #include <bb/cascades/Label> #include <bb/cascades/DropDown> #include <bb/cascades/Option> #include <bb/cascades/Divider> #include <bb/cascades/ScrollView> #include <bb/cascades/pickers/FilePicker> #include <GeneralSettingsPage.h> #include <GeneralSettings.h> #include <NumberPicker.h> #include <Segment.h> #include <Utility.h> #include <Defaults.h> using namespace bb::cascades; GeneralSettingsPage::GeneralSettingsPage(GeneralSettings *generalSettings): _settings(generalSettings), _highlightRangePicker(new NumberPicker(0, 40)), _highlightRangeHelp(Label::create().multiline(true) .textStyle(Defaults::helpText())), _chooseDefaultProjectDirOption(Option::create()), _currentDefaultProjectDirOption(Option::create()), _defaultProjectDirSelect(DropDown::create() .add(_chooseDefaultProjectDirOption) .add(_currentDefaultProjectDirOption)), _defaultProjectDirHelp(Label::create().multiline(true) .textStyle(Defaults::helpText())), _fpicker(NULL) { setTitleBar(TitleBar::create()); _highlightRangePicker->setSelectedNumber(_settings->highlightRange()); conn(_highlightRangePicker, SIGNAL(selectedNumberChanged(int)), _settings, SLOT(setHighlightRange(int))); conn(_settings, SIGNAL(highlightRangeChanged(int)), _highlightRangePicker, SLOT(setSelectedNumber(int))); resetDefaultProjectDirSelection(); conn(_chooseDefaultProjectDirOption, SIGNAL(selectedChanged(bool)), this, SLOT(onChooseDefaultProjectDirSelectedChanged(bool))); onDefaultProjectDirectoryChanged(_settings->defaultProjectDirectory()); conn(_settings, SIGNAL(defaultProjectDirectoryChanged(const QString&)), this, SLOT(onDefaultProjectDirectoryChanged(const QString&))); setContent(ScrollView::create(Segment::create().section() .add(Segment::create().subsection().add(_highlightRangePicker)) .add(Segment::create().subsection().add(_highlightRangeHelp)) .add(Divider::create()) .add(Segment::create().subsection().add(_defaultProjectDirSelect)) .add(Segment::create().subsection().add(_defaultProjectDirHelp))) .scrollMode(ScrollMode::Vertical)); onTranslatorChanged(); } void GeneralSettingsPage::onChooseDefaultProjectDirSelectedChanged(bool selected) { if (selected) { if (!_fpicker) { _fpicker = new pickers::FilePicker(this); _fpicker->setMode(pickers::FilePickerMode::SaverMultiple); conn(_fpicker, SIGNAL(fileSelected(const QStringList&)), this, SLOT(onDefaultProjectDirSelected(const QStringList&))); conn(_fpicker, SIGNAL(pickerClosed()), this, SLOT(resetDefaultProjectDirSelection())); } _fpicker->open(); } } void GeneralSettingsPage::resetDefaultProjectDirSelection() { _defaultProjectDirSelect->setSelectedOption(_currentDefaultProjectDirOption); } void GeneralSettingsPage::onDefaultProjectDirSelected(const QStringList &list) { _settings->setDefaultProjectDirectory(list[0]); } void GeneralSettingsPage::onDefaultProjectDirectoryChanged(const QString &directory) { _currentDefaultProjectDirOption->setText(directory); } void GeneralSettingsPage::onTranslatorChanged() { PushablePage::onTranslatorChanged(); titleBar()->setTitle(tr("General Settings")); _highlightRangePicker->setTitle(tr("Highlight Range")); _highlightRangeHelp->setText(tr("Highlight range controls the number of lines to be highlighted on each side of the cursor. " "Adjusting this value down will improve performance and vice versa.")); _defaultProjectDirSelect->setTitle(tr("Default Project Directory")); _chooseDefaultProjectDirOption->setText(tr("<Choose a Directory>")); _defaultProjectDirHelp->setText(tr("The default directory for a new project")); }
38.103774
129
0.732359
lingnand
dd53cab832213078acd8b3f185a44673d7be4aa8
1,213
cpp
C++
src/gasdev.cpp
atyre2/HABITAT
bbf231fcfe48cb11b27117266bfc85f427225414
[ "MIT" ]
null
null
null
src/gasdev.cpp
atyre2/HABITAT
bbf231fcfe48cb11b27117266bfc85f427225414
[ "MIT" ]
2
2019-03-29T22:15:17.000Z
2019-03-29T22:15:50.000Z
src/gasdev.cpp
atyre2/HABITAT
bbf231fcfe48cb11b27117266bfc85f427225414
[ "MIT" ]
null
null
null
#include <math.h> #include "mt19937.h" #include "util2019.h" #include "gasdev.h" //--------------------------------------------------------------------------- /* Returns a normally distributed deviate with zero mean and unit variance, using ran1(idum) as the source of uniform deviates. Taken from numerical recipes book in c, p.289 */ float gasdev(void) { /* float ran3(long *idum); */ static int iset=0; static float gset; float fac, rsq, v1, v2, temp; /* We don't have an extra deviate handy, so pick 2 uniform numbers in the square extending from -1 to +1 in each direction, see if they are in the unit circle, and if they are not, try again.*/ if (iset == 0){ do{ v1 = 2.0*rand0to1()-1.0; v2 = 2.0*rand0to1()-1.0; rsq=v1*v1+v2*v2; }while (rsq >= 1.0 ||rsq == 0.0); temp = -2.0*log(rsq)/rsq; if (temp >= 0.0) fac = sqrt(temp); else { fac = 0; } /* Now make the Box-Muller transformation to get 2 normal deviates. Return one and save the other for the next time. */ gset = v1*fac; iset=1; /*set flag */ return v2*fac; } else{ /* We have an extra deviate handy, so unset the flag, and return it.*/ iset = 0; return gset; } }
25.270833
77
0.589448
atyre2
dd560ca786c1e4570e39164b58b3757dc29a169f
8,459
hpp
C++
include/rabbit/graphics/graphics.hpp
demurzasty/rabb
f980fd18332f7846cd22b502f1075d224938379c
[ "MIT" ]
8
2020-11-21T17:59:09.000Z
2022-02-13T05:14:40.000Z
include/rabbit/graphics/graphics.hpp
demurzasty/rabb
f980fd18332f7846cd22b502f1075d224938379c
[ "MIT" ]
null
null
null
include/rabbit/graphics/graphics.hpp
demurzasty/rabb
f980fd18332f7846cd22b502f1075d224938379c
[ "MIT" ]
1
2020-11-23T23:01:14.000Z
2020-11-23T23:01:14.000Z
#pragma once #include "viewport.hpp" #include "environment.hpp" #include "texture.hpp" #include "material.hpp" #include "mesh.hpp" #include "../components/transform.hpp" #include "../components/camera.hpp" #include "../components/geometry.hpp" #include "../components/light.hpp" #include <memory> namespace rb { enum class graphics_backend { vulkan }; struct graphics_limits { static constexpr std::size_t max_lights{ 1024 }; static constexpr std::size_t brdf_map_size{ 512 }; static constexpr std::size_t irradiance_map_size{ 64 }; static constexpr std::size_t prefilter_map_size{ 128 }; static constexpr std::size_t shadow_map_size{ 1024 }; static constexpr std::size_t max_shadow_cascades{ 4 }; static constexpr std::size_t ssao_image_reduction{ 4 }; }; class graphics_impl { public: virtual ~graphics_impl() = default; virtual std::shared_ptr<viewport> make_viewport(const viewport_desc& desc) = 0; virtual std::shared_ptr<texture> make_texture(const texture_desc& desc) = 0; virtual std::shared_ptr<environment> make_environment(const environment_desc& desc) = 0; virtual std::shared_ptr<material> make_material(const material_desc& desc) = 0; virtual std::shared_ptr<mesh> make_mesh(const mesh_desc& desc) = 0; virtual void begin() = 0; virtual void set_camera(const mat4f& projection, const mat4f& view, const mat4f& world, const std::shared_ptr<environment>& environment) = 0; virtual void begin_depth_pass(const std::shared_ptr<viewport>& viewport) = 0; virtual void draw_depth(const std::shared_ptr<viewport>& viewport, const mat4f& world, const std::shared_ptr<mesh>& mesh, std::size_t mesh_lod_index) = 0; virtual void end_depth_pass(const std::shared_ptr<viewport>& viewport) = 0; virtual void begin_shadow_pass(const transform& transform, const light& light, const directional_light& directional_light, std::size_t cascade) = 0; virtual void draw_shadow(const mat4f& world, const geometry& geometry, std::size_t cascade) = 0; virtual void end_shadow_pass() = 0; virtual void begin_light_pass(const std::shared_ptr<viewport>& viewport) = 0; virtual void add_point_light(const std::shared_ptr<viewport>& viewport, const transform& transform, const light& light, const point_light& point_light) = 0; virtual void add_directional_light(const std::shared_ptr<viewport>& viewport, const transform& transform, const light& light, const directional_light& directional_light, bool use_shadow) = 0; virtual void end_light_pass(const std::shared_ptr<viewport>& viewport) = 0; virtual void begin_forward_pass(const std::shared_ptr<viewport>& viewport) = 0; virtual void draw_skybox(const std::shared_ptr<viewport>& viewport) = 0; virtual void draw_forward(const std::shared_ptr<viewport>& viewport, const mat4f& world, const std::shared_ptr<mesh>& mesh, const std::shared_ptr<material>& material, std::size_t mesh_lod_index) = 0; virtual void end_forward_pass(const std::shared_ptr<viewport>& viewport) = 0; virtual void pre_draw_ssao(const std::shared_ptr<viewport>& viewport) = 0; virtual void begin_fill_pass(const std::shared_ptr<viewport>& viewport) = 0; virtual void draw_fill(const std::shared_ptr<viewport>& viewport, const transform& transform, const geometry& geometry) = 0; virtual void end_fill_pass(const std::shared_ptr<viewport>& viewport) = 0; virtual void begin_postprocess_pass(const std::shared_ptr<viewport>& viewport) = 0; virtual void next_postprocess_pass(const std::shared_ptr<viewport>& viewport) = 0; virtual void draw_ssao(const std::shared_ptr<viewport>& viewport) = 0; virtual void draw_fxaa(const std::shared_ptr<viewport>& viewport) = 0; virtual void draw_blur(const std::shared_ptr<viewport>& viewport, int strength) = 0; virtual void draw_sharpen(const std::shared_ptr<viewport>& viewport, float strength) = 0; virtual void draw_motion_blur(const std::shared_ptr<viewport>& viewport) = 0; virtual void draw_outline(const std::shared_ptr<viewport>& viewport) = 0; virtual void end_postprocess_pass(const std::shared_ptr<viewport>& viewport) = 0; virtual void begin_immediate_pass() = 0; virtual void draw_immediate_color(const span<const vertex>& vertices, const color& color) = 0; virtual void draw_immediate_textured(const span<const vertex>& vertices, const std::shared_ptr<texture>& texture) = 0; virtual void end_immediate_pass() = 0; virtual void present(const std::shared_ptr<viewport>& viewport) = 0; virtual void end() = 0; virtual void swap_buffers() = 0; virtual void flush() = 0; }; class graphics { public: static void init(); static void release(); static std::shared_ptr<viewport> make_viewport(const viewport_desc& desc); static std::shared_ptr<texture> make_texture(const texture_desc& desc); static std::shared_ptr<environment> make_environment(const environment_desc& desc); static std::shared_ptr<material> make_material(const material_desc& desc); static std::shared_ptr<mesh> make_mesh(const mesh_desc& desc); static void begin(); static void set_camera(const mat4f& projection, const mat4f& view, const mat4f& world, const std::shared_ptr<environment>& environment); static void begin_depth_pass(const std::shared_ptr<viewport>& viewport); static void draw_depth(const std::shared_ptr<viewport>& viewport, const mat4f& world, const std::shared_ptr<mesh>& mesh, std::size_t mesh_lod_index); static void end_depth_pass(const std::shared_ptr<viewport>& viewport); static void begin_shadow_pass(const transform& transform, const light& light, const directional_light& directional_light, std::size_t cascade); static void draw_shadow(const mat4f& world, const geometry& geometry, std::size_t cascade); static void end_shadow_pass(); static void begin_light_pass(const std::shared_ptr<viewport>& viewport); static void add_point_light(const std::shared_ptr<viewport>& viewport, const transform& transform, const light& light, const point_light& point_light); static void add_directional_light(const std::shared_ptr<viewport>& viewport, const transform& transform, const light& light, const directional_light& directional_light, bool use_shadow); static void end_light_pass(const std::shared_ptr<viewport>& viewport); static void begin_forward_pass(const std::shared_ptr<viewport>& viewport); static void draw_skybox(const std::shared_ptr<viewport>& viewport); static void draw_forward(const std::shared_ptr<viewport>& viewport, const mat4f& world, const std::shared_ptr<mesh>& mesh, const std::shared_ptr<material>& material, std::size_t mesh_lod_index); static void end_forward_pass(const std::shared_ptr<viewport>& viewport); static void pre_draw_ssao(const std::shared_ptr<viewport>& viewport); static void begin_fill_pass(const std::shared_ptr<viewport>& viewport); static void draw_fill(const std::shared_ptr<viewport>& viewport, const transform& transform, const geometry& geometry); static void end_fill_pass(const std::shared_ptr<viewport>& viewport); static void begin_postprocess_pass(const std::shared_ptr<viewport>& viewport); static void next_postprocess_pass(const std::shared_ptr<viewport>& viewport); static void draw_ssao(const std::shared_ptr<viewport>& viewport); static void draw_fxaa(const std::shared_ptr<viewport>& viewport); static void draw_blur(const std::shared_ptr<viewport>& viewport, int strength); static void draw_sharpen(const std::shared_ptr<viewport>& viewport, float strength); static void draw_motion_blur(const std::shared_ptr<viewport>& viewport); static void draw_outline(const std::shared_ptr<viewport>& viewport); static void end_postprocess_pass(const std::shared_ptr<viewport>& viewport); static void begin_immediate_pass(); static void draw_immediate_color(const span<const vertex>& vertices, const color& color); static void draw_immediate_textured(const span<const vertex>& vertices, const std::shared_ptr<texture>& texture); static void end_immediate_pass(); static void present(const std::shared_ptr<viewport>& viewport); static void end(); static void swap_buffers(); static void flush(); private: static std::shared_ptr<graphics_impl> _impl; }; }
39.713615
202
0.747488
demurzasty
dd581e2a7cdf51648dd61510b5f7a625d1cf573f
1,076
cpp
C++
games/jungle_chess/impl/jungle_chess.cpp
JacobFischer/Joueur.cpp
673fce574ca80fb8f02777e610884a1c9808501d
[ "MIT" ]
1
2015-08-09T01:29:34.000Z
2015-08-09T01:29:34.000Z
games/jungle_chess/impl/jungle_chess.cpp
JacobFischer/Joueur.cpp
673fce574ca80fb8f02777e610884a1c9808501d
[ "MIT" ]
null
null
null
games/jungle_chess/impl/jungle_chess.cpp
JacobFischer/Joueur.cpp
673fce574ca80fb8f02777e610884a1c9808501d
[ "MIT" ]
null
null
null
// DO NOT MODIFY THIS FILE // Never try to directly create an instance of this class, or modify its member variables. // This contains implementation details, written by code, and only useful to code #include "jungle_chess.hpp" #include "../../../joueur/src/register.hpp" #include "../../../joueur/src/exceptions.hpp" namespace cpp_client { namespace jungle_chess { //register the game Game_registry registration("Jungle_chess", "0f0b85b33f03a669a391b36c90daa195d028dd1f21f8d4b601adfcf39b23eee2", std::unique_ptr<Jungle_chess>(new Jungle_chess)); std::unique_ptr<Base_ai> Jungle_chess::generate_ai() { return std::unique_ptr<Base_ai>(new AI); } std::shared_ptr<Base_object> Jungle_chess::generate_object(const std::string& type) { if(type == "GameObject") { return std::make_shared<Game_object_>(); } else if(type == "Player") { return std::make_shared<Player_>(); } throw Unknown_type("Unknown type " + type + " encountered."); } } // jungle_chess } // cpp_client
25.619048
94
0.67658
JacobFischer
e57b35cd99acac58fcd73cc73f21a74700c4d32b
26,109
cpp
C++
src/pmp/algorithms/SurfaceRemeshing.cpp
choyfung/pmp-library
4a72c918494dac92f5e77545b71c7a327dafe71e
[ "BSD-3-Clause" ]
1
2020-05-21T04:15:44.000Z
2020-05-21T04:15:44.000Z
src/pmp/algorithms/SurfaceRemeshing.cpp
choyfung/pmp-library
4a72c918494dac92f5e77545b71c7a327dafe71e
[ "BSD-3-Clause" ]
null
null
null
src/pmp/algorithms/SurfaceRemeshing.cpp
choyfung/pmp-library
4a72c918494dac92f5e77545b71c7a327dafe71e
[ "BSD-3-Clause" ]
1
2020-05-21T04:15:52.000Z
2020-05-21T04:15:52.000Z
//============================================================================= // Copyright (C) 2011-2018 The pmp-library developers // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. //============================================================================= #include <pmp/algorithms/SurfaceRemeshing.h> #include <pmp/algorithms/distancePointTriangle.h> #include <pmp/algorithms/SurfaceCurvature.h> #include <pmp/algorithms/SurfaceNormals.h> #include <pmp/algorithms/barycentricCoordinates.h> #include <cfloat> #include <cmath> #include <algorithm> //============================================================================= namespace pmp { //============================================================================= SurfaceRemeshing::SurfaceRemeshing(SurfaceMesh& mesh) : m_mesh(mesh), m_refmesh(nullptr), m_kDTree(nullptr) { m_points = m_mesh.vertexProperty<Point>("v:point"); SurfaceNormals::computeVertexNormals(m_mesh); m_vnormal = m_mesh.vertexProperty<Point>("v:normal"); } //----------------------------------------------------------------------------- SurfaceRemeshing::~SurfaceRemeshing() = default; //----------------------------------------------------------------------------- void SurfaceRemeshing::uniformRemeshing(Scalar edgeLength, unsigned int iterations, bool useProjection) { if (!m_mesh.isTriangleMesh()) { std::cerr << "Not a triangle mesh!" << std::endl; return; } m_uniform = true; m_useProjection = useProjection; m_targetEdgeLength = edgeLength; preprocessing(); for (unsigned int i = 0; i < iterations; ++i) { splitLongEdges(); SurfaceNormals::computeVertexNormals(m_mesh); collapseShortEdges(); flipEdges(); tangentialSmoothing(5); } removeCaps(); postprocessing(); } //----------------------------------------------------------------------------- void SurfaceRemeshing::adaptiveRemeshing(Scalar minEdgeLength, Scalar maxEdgeLength, Scalar approxError, unsigned int iterations, bool useProjection) { if (!m_mesh.isTriangleMesh()) { std::cerr << "Not a triangle mesh!" << std::endl; return; } m_uniform = false; m_minEdgeLength = minEdgeLength; m_maxEdgeLength = maxEdgeLength; m_approxError = approxError; m_useProjection = useProjection; preprocessing(); for (unsigned int i = 0; i < iterations; ++i) { splitLongEdges(); SurfaceNormals::computeVertexNormals(m_mesh); collapseShortEdges(); flipEdges(); tangentialSmoothing(5); } removeCaps(); postprocessing(); } //----------------------------------------------------------------------------- void SurfaceRemeshing::preprocessing() { // properties m_vfeature = m_mesh.vertexProperty<bool>("v:feature", false); m_efeature = m_mesh.edgeProperty<bool>("e:feature", false); m_vlocked = m_mesh.addVertexProperty<bool>("v:locked", false); m_elocked = m_mesh.addEdgeProperty<bool>("e:locked", false); m_vsizing = m_mesh.getVertexProperty<Scalar>("v:sizing"); // re-use an existing sizing field. used for remeshing a cage in the // adaptive refinement benchmark. bool useSizingField(false); if (m_vsizing) useSizingField = true; else m_vsizing = m_mesh.addVertexProperty<Scalar>("v:sizing"); // lock unselected vertices if some vertices are selected SurfaceMesh::VertexProperty<bool> vselected = m_mesh.getVertexProperty<bool>("v:selected"); if (vselected) { bool hasSelection = false; for (auto v : m_mesh.vertices()) { if (vselected[v]) { hasSelection = true; break; } } if (hasSelection) { for (auto v : m_mesh.vertices()) { m_vlocked[v] = !vselected[v]; } // lock an edge if one of its vertices is locked for (auto e : m_mesh.edges()) { m_elocked[e] = (m_vlocked[m_mesh.vertex(e, 0)] || m_vlocked[m_mesh.vertex(e, 1)]); } } } // lock feature corners for (auto v : m_mesh.vertices()) { if (m_vfeature[v]) { int c = 0; for (auto h : m_mesh.halfedges(v)) if (m_efeature[m_mesh.edge(h)]) ++c; if (c != 2) m_vlocked[v] = true; } } // compute sizing field if (m_uniform) { for (auto v : m_mesh.vertices()) { m_vsizing[v] = m_targetEdgeLength; } } else if (!useSizingField) { // compute curvature for all mesh vertices, using cotan or Cohen-Steiner // do 2 post-smoothing steps to get a smoother sizing field SurfaceCurvature curv(m_mesh); //curv.analyze(1); curv.analyzeTensor(1, true); for (auto v : m_mesh.vertices()) { // maximum absolute curvature Scalar c = curv.maxAbsCurvature(v); // curvature of feature vertices: average of non-feature neighbors if (m_vfeature[v]) { SurfaceMesh::Vertex vv; Scalar w, ww = 0.0; c = 0.0; for (auto h : m_mesh.halfedges(v)) { vv = m_mesh.toVertex(h); if (!m_vfeature[vv]) { w = std::max(0.0, cotanWeight(m_mesh, m_mesh.edge(h))); ww += w; c += w * curv.maxAbsCurvature(vv); } } c /= ww; } // get edge length from curvature const Scalar r = 1.0 / c; const Scalar e = m_approxError; Scalar h; if (e < r) { // see mathworld: "circle segment" and "equilateral triangle" //h = sqrt(2.0*r*e-e*e) * 3.0 / sqrt(3.0); h = sqrt(6.0 * e * r - 3.0 * e * e); // simplified... } else { // this does not really make sense h = e * 3.0 / sqrt(3.0); } // clamp to min. and max. edge length if (h < m_minEdgeLength) h = m_minEdgeLength; else if (h > m_maxEdgeLength) h = m_maxEdgeLength; // store target edge length m_vsizing[v] = h; } } if (m_useProjection) { // build reference mesh m_refmesh = new SurfaceMesh(); m_refmesh->assign(m_mesh); SurfaceNormals::computeVertexNormals(*m_refmesh); m_refpoints = m_refmesh->vertexProperty<Point>("v:point"); m_refnormals = m_refmesh->vertexProperty<Point>("v:normal"); // copy sizing field from m_mesh m_refsizing = m_refmesh->addVertexProperty<Scalar>("v:sizing"); for (auto v : m_refmesh->vertices()) { m_refsizing[v] = m_vsizing[v]; } // build kd-tree m_kDTree = new TriangleKdTree(*m_refmesh, 0); } } //----------------------------------------------------------------------------- void SurfaceRemeshing::postprocessing() { // delete kd-tree and reference mesh if (m_useProjection) { delete m_kDTree; delete m_refmesh; } // remove properties m_mesh.removeVertexProperty(m_vlocked); m_mesh.removeEdgeProperty(m_elocked); m_mesh.removeVertexProperty(m_vsizing); } //----------------------------------------------------------------------------- void SurfaceRemeshing::projectToReference(SurfaceMesh::Vertex v) { if (!m_useProjection) { return; } // find closest triangle of reference mesh TriangleKdTree::NearestNeighbor nn = m_kDTree->nearest(m_points[v]); const Point p = nn.nearest; const SurfaceMesh::Face f = nn.face; // get face data SurfaceMesh::VertexAroundFaceCirculator fvIt = m_refmesh->vertices(f); const Point p0 = m_refpoints[*fvIt]; const Point n0 = m_refnormals[*fvIt]; const Scalar s0 = m_refsizing[*fvIt]; ++fvIt; const Point p1 = m_refpoints[*fvIt]; const Point n1 = m_refnormals[*fvIt]; const Scalar s1 = m_refsizing[*fvIt]; ++fvIt; const Point p2 = m_refpoints[*fvIt]; const Point n2 = m_refnormals[*fvIt]; const Scalar s2 = m_refsizing[*fvIt]; // get barycentric coordinates Point b = barycentricCoordinates(p, p0, p1, p2); // interpolate normal Point n; n = (n0 * b[0]); n += (n1 * b[1]); n += (n2 * b[2]); n.normalize(); assert(!std::isnan(n[0])); // interpolate sizing field Scalar s; s = (s0 * b[0]); s += (s1 * b[1]); s += (s2 * b[2]); // set result m_points[v] = p; m_vnormal[v] = n; m_vsizing[v] = s; } //----------------------------------------------------------------------------- void SurfaceRemeshing::splitLongEdges() { SurfaceMesh::Vertex vnew, v0, v1; SurfaceMesh::Edge enew, e0, e1; SurfaceMesh::Face f0, f1, f2, f3; bool ok, isFeature, isSurfaceBoundary; int i; for (ok = false, i = 0; !ok && i < 10; ++i) { ok = true; for (auto e : m_mesh.edges()) { v0 = m_mesh.vertex(e, 0); v1 = m_mesh.vertex(e, 1); if (!m_elocked[e] && isTooLong(v0, v1)) { const Point& p0 = m_points[v0]; const Point& p1 = m_points[v1]; isFeature = m_efeature[e]; isSurfaceBoundary = m_mesh.isSurfaceBoundary(e); vnew = m_mesh.addVertex((p0 + p1) * 0.5f); m_mesh.split(e, vnew); // need normal or sizing for adaptive refinement m_vnormal[vnew] = SurfaceNormals::computeVertexNormal(m_mesh, vnew); m_vsizing[vnew] = 0.5f * (m_vsizing[v0] + m_vsizing[v1]); if (isFeature) { enew = isSurfaceBoundary ? SurfaceMesh::Edge(m_mesh.nEdges() - 2) : SurfaceMesh::Edge(m_mesh.nEdges() - 3); m_efeature[enew] = true; m_vfeature[vnew] = true; } else { projectToReference(vnew); } ok = false; } } } } //----------------------------------------------------------------------------- void SurfaceRemeshing::collapseShortEdges() { SurfaceMesh::VertexAroundVertexCirculator vvIt, vvEnd; SurfaceMesh::Vertex v0, v1; SurfaceMesh::Halfedge h0, h1, h01, h10; bool ok, b0, b1, l0, l1, f0, f1; int i; bool hcol01, hcol10; for (ok = false, i = 0; !ok && i < 10; ++i) { ok = true; for (auto e : m_mesh.edges()) { if (!m_mesh.isDeleted(e) && !m_elocked[e]) { h10 = m_mesh.halfedge(e, 0); h01 = m_mesh.halfedge(e, 1); v0 = m_mesh.toVertex(h10); v1 = m_mesh.toVertex(h01); if (isTooShort(v0, v1)) { // get status b0 = m_mesh.isSurfaceBoundary(v0); b1 = m_mesh.isSurfaceBoundary(v1); l0 = m_vlocked[v0]; l1 = m_vlocked[v1]; f0 = m_vfeature[v0]; f1 = m_vfeature[v1]; hcol01 = hcol10 = true; // boundary rules if (b0 && b1) { if (!m_mesh.isSurfaceBoundary(e)) continue; } else if (b0) hcol01 = false; else if (b1) hcol10 = false; // locked rules if (l0 && l1) continue; else if (l0) hcol01 = false; else if (l1) hcol10 = false; // feature rules if (f0 && f1) { // edge must be feature if (!m_efeature[e]) continue; // the other two edges removed by collapse must not be features h0 = m_mesh.prevHalfedge(h01); h1 = m_mesh.nextHalfedge(h10); if (m_efeature[m_mesh.edge(h0)] || m_efeature[m_mesh.edge(h1)]) hcol01 = false; // the other two edges removed by collapse must not be features h0 = m_mesh.prevHalfedge(h10); h1 = m_mesh.nextHalfedge(h01); if (m_efeature[m_mesh.edge(h0)] || m_efeature[m_mesh.edge(h1)]) hcol10 = false; } else if (f0) hcol01 = false; else if (f1) hcol10 = false; // topological rules bool collapseOk = m_mesh.isCollapseOk(h01); if (hcol01) hcol01 = collapseOk; if (hcol10) hcol10 = collapseOk; // both collapses possible: collapse into vertex w/ higher valence if (hcol01 && hcol10) { if (m_mesh.valence(v0) < m_mesh.valence(v1)) hcol10 = false; else hcol01 = false; } // try v1 -> v0 if (hcol10) { // don't create too long edges for (auto vv : m_mesh.vertices(v1)) { if (isTooLong(v0, vv)) { hcol10 = false; break; } } if (hcol10) { m_mesh.collapse(h10); ok = false; } } // try v0 -> v1 else if (hcol01) { // don't create too long edges for (auto vv : m_mesh.vertices(v0)) { if (isTooLong(v1, vv)) { hcol01 = false; break; } } if (hcol01) { m_mesh.collapse(h01); ok = false; } } } } } } m_mesh.garbageCollection(); } //----------------------------------------------------------------------------- void SurfaceRemeshing::flipEdges() { SurfaceMesh::Vertex v0, v1, v2, v3; SurfaceMesh::Halfedge h; int val0, val1, val2, val3; int valOpt0, valOpt1, valOpt2, valOpt3; int ve0, ve1, ve2, ve3, veBefore, veAfter; bool ok; int i; // precompute valences SurfaceMesh::VertexProperty<int> valence = m_mesh.addVertexProperty<int>("valence"); for (auto v : m_mesh.vertices()) { valence[v] = m_mesh.valence(v); } for (ok = false, i = 0; !ok && i < 10; ++i) { ok = true; for (auto e : m_mesh.edges()) { if (!m_elocked[e] && !m_efeature[e]) { h = m_mesh.halfedge(e, 0); v0 = m_mesh.toVertex(h); v2 = m_mesh.toVertex(m_mesh.nextHalfedge(h)); h = m_mesh.halfedge(e, 1); v1 = m_mesh.toVertex(h); v3 = m_mesh.toVertex(m_mesh.nextHalfedge(h)); if (!m_vlocked[v0] && !m_vlocked[v1] && !m_vlocked[v2] && !m_vlocked[v3]) { val0 = valence[v0]; val1 = valence[v1]; val2 = valence[v2]; val3 = valence[v3]; valOpt0 = (m_mesh.isSurfaceBoundary(v0) ? 4 : 6); valOpt1 = (m_mesh.isSurfaceBoundary(v1) ? 4 : 6); valOpt2 = (m_mesh.isSurfaceBoundary(v2) ? 4 : 6); valOpt3 = (m_mesh.isSurfaceBoundary(v3) ? 4 : 6); ve0 = (val0 - valOpt0); ve1 = (val1 - valOpt1); ve2 = (val2 - valOpt2); ve3 = (val3 - valOpt3); ve0 *= ve0; ve1 *= ve1; ve2 *= ve2; ve3 *= ve3; veBefore = ve0 + ve1 + ve2 + ve3; --val0; --val1; ++val2; ++val3; ve0 = (val0 - valOpt0); ve1 = (val1 - valOpt1); ve2 = (val2 - valOpt2); ve3 = (val3 - valOpt3); ve0 *= ve0; ve1 *= ve1; ve2 *= ve2; ve3 *= ve3; veAfter = ve0 + ve1 + ve2 + ve3; if (veBefore > veAfter && m_mesh.isFlipOk(e)) { m_mesh.flip(e); --valence[v0]; --valence[v1]; ++valence[v2]; ++valence[v3]; ok = false; } } } } } m_mesh.removeVertexProperty(valence); } //----------------------------------------------------------------------------- void SurfaceRemeshing::tangentialSmoothing(unsigned int iterations) { SurfaceMesh::Vertex v1, v2, v3, vv; SurfaceMesh::Edge e; Scalar w, ww, area; Point u, n, t, b; // add property SurfaceMesh::VertexProperty<Point> update = m_mesh.addVertexProperty<Point>("v:update"); // project at the beginning to get valid sizing values and normal vectors // for vertices introduced by splitting if (m_useProjection) { for (auto v : m_mesh.vertices()) { if (!m_mesh.isSurfaceBoundary(v) && !m_vlocked[v]) { projectToReference(v); } } } for (unsigned int iters = 0; iters < iterations; ++iters) { for (auto v : m_mesh.vertices()) { if (!m_mesh.isSurfaceBoundary(v) && !m_vlocked[v]) { if (m_vfeature[v]) { u = Point(0.0); t = Point(0.0); ww = 0; int c = 0; for (auto h : m_mesh.halfedges(v)) { if (m_efeature[m_mesh.edge(h)]) { vv = m_mesh.toVertex(h); b = m_points[v]; b += m_points[vv]; b *= 0.5; w = distance(m_points[v], m_points[vv]) / (0.5 * (m_vsizing[v] + m_vsizing[vv])); ww += w; u += w * b; if (c == 0) { t += normalize(m_points[vv] - m_points[v]); ++c; } else { ++c; t -= normalize(m_points[vv] - m_points[v]); } } } assert(c == 2); u *= (1.0 / ww); u -= m_points[v]; t = normalize(t); u = t * dot(u, t); update[v] = u; // who deleted this line??? } else { u = Point(0.0); t = Point(0.0); ww = 0; for (auto h : m_mesh.halfedges(v)) { v1 = v; v2 = m_mesh.toVertex(h); v3 = m_mesh.toVertex(m_mesh.nextHalfedge(h)); b = m_points[v1]; b += m_points[v2]; b += m_points[v3]; b *= (1.0 / 3.0); area = norm(cross(m_points[v2] - m_points[v1], m_points[v3] - m_points[v1])); w = area / pow((m_vsizing[v1] + m_vsizing[v2] + m_vsizing[v3]) / 3.0, 2.0); u += w * b; ww += w; } u /= ww; u -= m_points[v]; n = m_vnormal[v]; u -= n * dot(u, n); update[v] = u; } } } // update vertex positions for (auto v : m_mesh.vertices()) { if (!m_mesh.isSurfaceBoundary(v) && !m_vlocked[v]) { m_points[v] += update[v]; } } // update normal vectors (if not done so through projection) SurfaceNormals::computeVertexNormals(m_mesh); } // project at the end if (m_useProjection) { for (auto v : m_mesh.vertices()) { if (!m_mesh.isSurfaceBoundary(v) && !m_vlocked[v]) { projectToReference(v); } } } // remove property m_mesh.removeVertexProperty(update); } //----------------------------------------------------------------------------- void SurfaceRemeshing::removeCaps() { SurfaceMesh::Halfedge h; SurfaceMesh::Vertex v, vb, vd; SurfaceMesh::Face fb, fd; Scalar a0, a1, amin, aa(::cos(170.0 * M_PI / 180.0)); Point a, b, c, d; for (auto e : m_mesh.edges()) { if (!m_elocked[e] && m_mesh.isFlipOk(e)) { h = m_mesh.halfedge(e, 0); a = m_points[m_mesh.toVertex(h)]; h = m_mesh.nextHalfedge(h); b = m_points[vb = m_mesh.toVertex(h)]; h = m_mesh.halfedge(e, 1); c = m_points[m_mesh.toVertex(h)]; h = m_mesh.nextHalfedge(h); d = m_points[vd = m_mesh.toVertex(h)]; a0 = dot(normalize(a - b), normalize(c - b)); a1 = dot(normalize(a - d), normalize(c - d)); if (a0 < a1) { amin = a0; v = vb; } else { amin = a1; v = vd; } // is it a cap? if (amin < aa) { // feature edge and feature vertex -> seems to be intended if (m_efeature[e] && m_vfeature[v]) continue; // project v onto feature edge if (m_efeature[e]) m_points[v] = (a + c) * 0.5f; // flip m_mesh.flip(e); } } } } //============================================================================= } // namespace pmp //=============================================================================
30.608441
87
0.423724
choyfung
e57d51693282e2a2a352ae9e8b9c07fe816cb123
1,889
cpp
C++
src/earconverter.cpp
jodavaho/earth_coords
f964f5e85749eb3a0ab5170bd6b15a871ecf6b27
[ "MIT" ]
null
null
null
src/earconverter.cpp
jodavaho/earth_coords
f964f5e85749eb3a0ab5170bd6b15a871ecf6b27
[ "MIT" ]
null
null
null
src/earconverter.cpp
jodavaho/earth_coords
f964f5e85749eb3a0ab5170bd6b15a871ecf6b27
[ "MIT" ]
null
null
null
/* * earconverter.cpp * * Created on: Mar 26, 2011 * Author: joshua */ #include <EarthCoords/EarthCoords.h> #include <stdio.h> #include <stdlib.h> using namespace RSN; int main(int argc, char** argv){ if (argc==1){ } EarthCoords e; double x,y; for (int i=1;i<argc;i+=2){ if (strcmp("-h",argv[i])==0){ e.setHome(atof(argv[i+1]),atof(argv[i+2])); i=i+1; } e.getLocalCords(atof(argv[i]),atof(argv[i+1]),x,y); printf("%0.3f,%0.3f\n",x,y); } // e.getLocalCords(,,x,y); // printf("tag la: %f, tag lo: %f",x,y); //44.97426,-93.22765 /* * 44.974299, -93.227918 * 44.974279, -93.227968 * 44.974263, -93.227955 * 44.974266, -93.227974 * 44.974266, -93.227916 * 44.974266, -93.227920 * */ /* e.setHome(44.974299, -93.227918); e.getLocalCords(44.974387,-93.2277421,x,y); printf("tag x: %f, tag y: %f\n",x,y); e.setHome(44.974279, -93.227968); e.getLocalCords(44.974387,-93.2277421,x,y); printf("tag x: %f, tag y: %f\n",x,y); e.setHome(44.974263, -93.227955); e.getLocalCords(44.974387,-93.2277421,x,y); printf("tag x: %f, tag y: %f\n",x,y); e.setHome(44.974266, -93.227974); e.getLocalCords(44.974387,-93.2277421,x,y); printf("tag x: %f, tag y: %f\n",x,y); e.setHome(44.974266, -93.227916); e.getLocalCords(44.974387,-93.2277421,x,y); printf("tag x: %f, tag y: %f\n",x,y); e.setHome(44.974266, -93.227920); e.getLocalCords(44.974387,-93.2277421,x,y); printf("tag x: %f, tag y: %f\n",x,y); */ // //44.97403,-93.22778 // // e.setHome(44.974195511,-93.227734676); // e.getLocalCords(44.97403,-93.22778,x,y); // printf("before last tag x: %f, tag y: %f\n",x,y); // // e.setHome(44.974011691,-93.227595842); // e.getLocalCords(44.97403,-93.22778,x,y); // printf("last tag x: %f, tag y: %f\n",x,y); // // e.setHome(44.974019999,-93.227595842); // e.getLocalCords(44.97401,-93.22759,x,y); // printf("err x: %f, err y: %f\n",x,y); }
25.527027
53
0.60667
jodavaho
e585a602837d0026215acd3613baf037690a2eba
15,276
cc
C++
util.cc
jkominek/fdbfs
0a347cc63f99428ff37348486a29b11ea13d9292
[ "0BSD" ]
12
2019-09-11T09:32:31.000Z
2022-01-14T05:26:38.000Z
util.cc
jkominek/fdbfs
0a347cc63f99428ff37348486a29b11ea13d9292
[ "0BSD" ]
18
2019-12-17T22:32:01.000Z
2022-03-14T06:03:15.000Z
util.cc
jkominek/fdbfs
0a347cc63f99428ff37348486a29b11ea13d9292
[ "0BSD" ]
null
null
null
#include "util.h" #include <strings.h> #include <stdio.h> #include <time.h> #include <ctype.h> #ifdef LZ4_BLOCK_COMPRESSION #include <lz4.h> #endif #ifdef ZSTD_BLOCK_COMPRESSION #include <zstd.h> #endif #include "values.pb.h" struct fdbfs_filehandle **extract_fdbfs_filehandle(struct fuse_file_info *fi) { static_assert(sizeof(fi->fh) >= sizeof(struct fdbfs_filehandle *), "FUSE File handle can't hold a pointer to our structure"); return reinterpret_cast<struct fdbfs_filehandle **>(&(fi->fh)); } std::vector<uint8_t> inode_use_identifier; // tracks kernel cache of lookups, so we can avoid fdb // calls except when we're going from zero to not-zero // TODO if the FDB networking became multithreaded, or // we could otherwise process responses in a multithreaded // fashion, we'd need locking. std::unordered_map<fuse_ino_t, uint64_t> lookup_counts; // if this returns true, the caller is obligated to // insert a record adjacent to the inode to keep it alive bool increment_lookup_count(fuse_ino_t ino) { auto it = lookup_counts.find(ino); if(it != lookup_counts.end()) { // present it->second += 1; return false; } else { // not present lookup_counts[ino] = 1; return true; } } // if this returns true, the caller is obligated to // remove the inode adjacent record that keeps it alive bool decrement_lookup_count(fuse_ino_t ino, uint64_t count) { auto it = lookup_counts.find(ino); if(it == lookup_counts.end()) { // well. oops. kernel knew about something that isn't there. return false; } else { it->second -= count; if(it->second > 0) { // still cached, nothing to do. return false; } else { // we're forgetting about this inode, drop it lookup_counts.erase(ino); return true; } } } // will be filled out before operation begins std::vector<uint8_t> key_prefix; fuse_ino_t generate_inode() { // TODO everything that uses this will need to check that // it isn't trampling an existing inode. struct timespec tp; clock_gettime(CLOCK_REALTIME, &tp); // we get 30 bits from the nanoseconds. we'll move // those up to the high end of what will be the key. // the low 34 bit of the seconds will be moved to // the low end of the key. uint64_t l = (tp.tv_sec & 0x3FFFFFFFF); uint64_t h = (tp.tv_nsec & 0x3FFFFFFF) << 34; // returning MAX_UINT64 would probably be bad, because i'm // not convinced we've correctly covered all of the edge // cases around that. but considering our generation method, // i don't think it'll be a concern return (h | l); } int inode_key_length; std::vector<uint8_t> pack_inode_key(fuse_ino_t ino, char prefix) { std::vector<uint8_t> key = key_prefix; key.push_back(prefix); fuse_ino_t tmp = htobe64(ino); uint8_t *tmpp = reinterpret_cast<uint8_t *>(&tmp); key.insert(key.end(), tmpp, tmpp + sizeof(fuse_ino_t)); return key; } std::vector<uint8_t> pack_garbage_key(fuse_ino_t ino) { std::vector<uint8_t> key = key_prefix; key.push_back(GARBAGE_PREFIX); fuse_ino_t tmp = htobe64(ino); uint8_t *tmpp = reinterpret_cast<uint8_t *>(&tmp); key.insert(key.end(), tmpp, tmpp + sizeof(fuse_ino_t)); return key; } std::vector<uint8_t> pack_inode_use_key(fuse_ino_t ino) { auto key = pack_inode_key(ino); key.push_back(INODE_USE_PREFIX); key.insert(key.end(), inode_use_identifier.begin(), inode_use_identifier.end()); return key; } int fileblock_prefix_length; int fileblock_key_length; std::vector<uint8_t> pack_fileblock_key(fuse_ino_t ino, uint64_t block) { auto key = pack_inode_key(ino, DATA_PREFIX); // TODO this is fast on our end, but every file block key now has 64 // bits in it, where most of those 64 bits will be 0, most of the // time. which are stored redundantly and moved back and forth across // the network on a regular basis. // most OSes are going to limit us to 64 bit files anyways. so we // really only need to go up to (64 - BLOCKBITS) here. // so we should consider switching over to a variable length representation // of the block number. we could even imagine replacing the DATA_PREFIX // 'f' with the values 0xF8 through 0xFF, and then taking the lowest // three bits as representing the number of bytes in the block number // representation. (because 2^3 bytes for representing an integer is // plenty.) block = htobe64(block); uint8_t *tmpp = reinterpret_cast<uint8_t *>(&block); key.insert(key.end(), tmpp, tmpp + sizeof(uint64_t)); return key; } int dirent_prefix_length; std::vector<uint8_t> pack_dentry_key(fuse_ino_t ino, const std::string &name) { auto key = pack_inode_key(ino, DENTRY_PREFIX); key.insert(key.end(), name.begin(), name.end()); return key; } std::vector<uint8_t> pack_xattr_key(fuse_ino_t ino, const std::string &name) { auto key = pack_inode_key(ino, XATTR_NODE_PREFIX); if(!name.empty()) key.insert(key.end(), name.begin(), name.end()); return key; } std::vector<uint8_t> pack_xattr_data_key(fuse_ino_t ino, const std::string &name) { auto key = pack_inode_key(ino, XATTR_DATA_PREFIX); if(!name.empty()) key.insert(key.end(), name.begin(), name.end()); return key; } void print_key(std::vector<uint8_t> v) { printf("%zu ", v.size()); for (std::vector<uint8_t>::const_iterator i = v.begin(); i != v.end(); ++i) if(isprint(*i)) printf("%c", *i); else printf("\\x%02x", *i); printf("\n"); } void pack_inode_record_into_stat(INodeRecord *inode, struct stat *attr) { if(inode == NULL) { printf("got bad inode to repack into attr\n"); } bzero(attr, sizeof(struct stat)); attr->st_ino = inode->inode(); attr->st_dev = 0; attr->st_mode = inode->mode() | inode->type(); attr->st_nlink = inode->nlinks(); if(inode->has_uid()) attr->st_uid = inode->uid(); else attr->st_uid = 0; if(inode->has_gid()) attr->st_gid = inode->gid(); else attr->st_gid = 0; if(inode->has_size()) attr->st_size = inode->size(); else attr->st_size = 0; if(inode->has_atime()) { attr->st_atim.tv_sec = inode->atime().sec(); attr->st_atim.tv_nsec = inode->atime().nsec(); } if(inode->has_mtime()) { attr->st_mtim.tv_sec = inode->mtime().sec(); attr->st_mtim.tv_nsec = inode->mtime().nsec(); } if(inode->has_ctime()) { attr->st_ctim.tv_sec = inode->ctime().sec(); attr->st_ctim.tv_nsec = inode->ctime().nsec(); } attr->st_blksize = BLOCKSIZE; attr->st_blocks = (attr->st_size / 512) + 1; /* printf("stat struct\n"); printf(" dev: %li\n", attr->st_dev); printf(" ino: %li\n", attr->st_ino); printf(" mode: %o\n", attr->st_mode); printf("nlink: %li\n", attr->st_nlink); printf(" uid: %i\n", attr->st_uid); printf(" gid: %i\n", attr->st_gid); */ } range_keys offset_size_to_range_keys(fuse_ino_t ino, size_t off, size_t size) { uint64_t start_block = off >> BLOCKBITS; uint64_t stop_block = ((off + size - 1) >> BLOCKBITS); auto start = pack_fileblock_key(ino, start_block); auto stop = pack_fileblock_key(ino, stop_block); stop.push_back(0xff); return std::pair(start, stop); } bool filename_length_check(fuse_req_t req, const char *name, size_t maxlength) { if(strnlen(name, maxlength+1)>maxlength) { fuse_reply_err(req, ENAMETOOLONG); return true; } return false; } void update_atime(INodeRecord *inode, struct timespec *tv) { Timespec *atime = inode->mutable_atime(); atime->set_sec(tv->tv_sec); atime->set_nsec(tv->tv_nsec); } void update_ctime(INodeRecord *inode, struct timespec *tv) { Timespec *ctime = inode->mutable_ctime(); ctime->set_sec(tv->tv_sec); ctime->set_nsec(tv->tv_nsec); update_atime(inode, tv); } void update_mtime(INodeRecord *inode, struct timespec *tv) { Timespec *mtime = inode->mutable_mtime(); mtime->set_sec(tv->tv_sec); mtime->set_nsec(tv->tv_nsec); update_ctime(inode, tv); } void update_directory_times(FDBTransaction *transaction, INodeRecord &inode) { struct timespec tp; clock_gettime(CLOCK_REALTIME, &tp); inode.mutable_ctime()->set_sec(tp.tv_sec); inode.mutable_ctime()->set_nsec(tp.tv_nsec); inode.mutable_mtime()->set_sec(tp.tv_sec); inode.mutable_mtime()->set_nsec(tp.tv_nsec); auto key = pack_inode_key(inode.inode()); int inode_size = inode.ByteSize(); uint8_t inode_buffer[inode_size]; inode.SerializeToArray(inode_buffer, inode_size); fdb_transaction_set(transaction, key.data(), key.size(), inode_buffer, inode_size); } void erase_inode(FDBTransaction *transaction, fuse_ino_t ino) { // inode data auto key_start = pack_inode_key(ino); auto key_stop = key_start; key_stop.push_back('\xff'); fdb_transaction_clear_range(transaction, key_start.data(), key_start.size(), key_stop.data(), key_stop.size()); // TODO be clever and only isse these clears based on inode type // file data key_start = pack_fileblock_key(ino, 0); key_stop = pack_fileblock_key(ino, UINT64_MAX); key_stop.push_back('\xff'); fdb_transaction_clear_range(transaction, key_start.data(), key_start.size(), key_stop.data(), key_stop.size()); // directory listing key_start = pack_dentry_key(ino, ""); key_stop = pack_dentry_key(ino, "\xff"); fdb_transaction_clear_range(transaction, key_start.data(), key_start.size(), key_stop.data(), key_stop.size()); // xattr nodes key_start = pack_xattr_key(ino, ""); key_stop = pack_xattr_key(ino, "\xff"); fdb_transaction_clear_range(transaction, key_start.data(), key_start.size(), key_stop.data(), key_stop.size()); // xattr data key_start = pack_xattr_data_key(ino, ""); key_stop = pack_xattr_data_key(ino, "\xff"); fdb_transaction_clear_range(transaction, key_start.data(), key_start.size(), key_stop.data(), key_stop.size()); } inline void sparsify(uint8_t *block, uint64_t *write_size) { // sparsify our writes, by truncating nulls from the end of // blocks, and just clearing away totally null blocks for(; *(write_size)>0; *(write_size)-=1) { if(block[*(write_size)-1] != 0x00) break; } } void set_block(FDBTransaction *transaction, std::vector<uint8_t> key, uint8_t *buffer, uint64_t size, bool write_conflict) { sparsify(buffer, &size); if(size>0) { if(!write_conflict) if(fdb_transaction_set_option(transaction, FDB_TR_OPTION_NEXT_WRITE_NO_WRITE_CONFLICT_RANGE, NULL, 0)) /* it doesn't matter if this fails. semantics will be preserved, there will just be some performance loss. */; // TODO here's where we'd implement the write-side cleverness for our // block encoding schemes. they should all not only be ifdef'd, but // check for whether or not the feature is enabled on the filesystem. #ifdef BLOCK_COMPRESSION if(size>=64) { // considering that these blocks may be stored 3 times, and over // their life may have to be moved repeatedly across WANs between // data centers, we'll accept very small amounts of compression: int acceptable_size = BLOCKSIZE - 16; uint8_t compressed[BLOCKSIZE]; // we're arbitrarily saying blocks should be at least 64 bytes // after sparsification, before we'll attempt to compress them. #ifdef ZSTD_BLOCK_COMPRESSION int ret = ZSTD_compress(reinterpret_cast<char*>(compressed), BLOCKSIZE, reinterpret_cast<char*>(buffer), size, 10); if((!ZSTD_isError(ret)) && (ret <= acceptable_size)) { // ok, we'll take it. key.push_back('z'); // compressed key.push_back(0x01); // 1 byte of arguments key.push_back(0x01); // ZSTD marker fdb_transaction_set(transaction, key.data(), key.size(), compressed, ret); return; } #endif } #endif // we'll fall back to this if none of the compression schemes bail out fdb_transaction_set(transaction, key.data(), key.size(), buffer, size); } else { // storage model allows for sparsity; interprets missing blocks as nulls } } /** * Given a block's KV pair, decode it into output, preferably to targetsize, * but definitely no further than maxsize. * return negative for error; positive for length * * raw value: |ccccccccccccccccccccccccccccccccc| * ^ kv.value_length * decompressed: |ddddddddddddddddddddddddddddddddddddddddddd| * maxsize ^ * target_size v * needed: |--------------------| * ^ value_offset * */ int decode_block(FDBKeyValue *kv, int block_offset, uint8_t *output, int targetsize, int maxsize) { const uint8_t *key = kv->key; const uint8_t *value = kv->value; //printf("decoding block\n"); //print_bytes(value, kv->value_length);printf("\n"); if(kv->key_length == fileblock_key_length) { //printf(" plain.\n"); // plain block. there's no added info after the block key int amount = std::min(kv->value_length - block_offset, maxsize); if(amount>0) { bcopy(value + block_offset, output, amount); return amount; } else { return 0; } } #ifdef SPECIAL_BLOCKS //printf(" not plain!\n"); // ah! not a plain block! there might be something interesting! // ... for now we just support compression int i=fileblock_key_length; #ifdef BLOCK_COMPRESSION if(key[i] == 'z') { //printf(" compressed\n"); int arglen = key[i+1]; if(arglen<=0) { //printf(" no arg\n"); // no argument, but we needed to know compression type return -1; } #ifdef LZ4_BLOCK_COMPRESSION // for now we only know how to interpret a single byte of argument if(key[i+2] == 0x00) { // 0x00 means LZ4 char buffer[BLOCKSIZE]; // we'll only ask that enough be decompressed to satisfy the request int ret = LZ4_decompress_safe_partial(value, buffer, kv->value_length, BLOCKSIZE, BLOCKSIZE); printf("%i\n", ret); if(ret<0) { return ret; } if(ret > block_offset) { // decompression produced at least one byte worth sending back int amount = std::min(ret - block_offset, targetsize); bcopy(buffer + block_offset, output, amount); return amount; } else { // there was less data in the block than necessary to reach the // start of the copy, so we don't have to do anything. return 0; } } #endif #ifdef ZSTD_BLOCK_COMPRESSION if(key[i+2] == 0x01) { // 0x01 means ZSTD uint8_t buffer[BLOCKSIZE]; int ret = ZSTD_decompress(buffer, BLOCKSIZE, value, kv->value_length); if(ZSTD_isError(ret)) { // error return -1; } if(ret > block_offset) { int amount = std::min(ret - block_offset, targetsize); bcopy(buffer + block_offset, output, amount); return amount; } else { // nothing to copy return 0; } } #endif // unrecognized compression algorithm return -1; } #endif #endif // unrecognized block type. return -1; }
30.613226
108
0.661364
jkominek
e5870aeafd1ec110394b6da4a5100249254e5468
3,513
hpp
C++
inc/Alphabet.hpp
esaliya/lbl.pisa
1846075d84021303f3971534b0ea830845b0cb9e
[ "BSD-3-Clause-LBNL" ]
4
2020-08-19T17:48:00.000Z
2021-06-17T14:39:48.000Z
inc/Alphabet.hpp
esaliya/lbl.pisa
1846075d84021303f3971534b0ea830845b0cb9e
[ "BSD-3-Clause-LBNL" ]
4
2020-08-14T16:43:20.000Z
2020-08-21T01:03:01.000Z
inc/Alphabet.hpp
PASSIONLab/PASTIS
1846075d84021303f3971534b0ea830845b0cb9e
[ "BSD-3-Clause-LBNL" ]
null
null
null
// Created by Saliya Ekanayake on 1/22/19. #pragma once #include <cstring> #include <string> namespace pastis { class Alphabet { public: enum type {PROTEIN, DNA}; static const unsigned short capacity = 128; std::string letters; unsigned short size; unsigned short max_char; unsigned char char_to_code[capacity]; unsigned char code_to_char[capacity]; unsigned char al_map[capacity]; static const char *protein; // full superset static const char *dna; Alphabet (Alphabet::type t) { switch (t) { case PROTEIN: for (size_t i = 0; i < strlen(protein); ++i) al_map[protein[i]] = protein[i]; break; case DNA: for (size_t i = 0; i < strlen(dna); ++i) al_map[dna[i]] = dna[i]; break; } } void init (void); char & operator[] (size_t idx) { return letters[idx]; } }; class DefaultProteinAlph : public Alphabet { public: DefaultProteinAlph () : Alphabet(Alphabet::PROTEIN) { letters = "ARNDCQEGHILKMFPSTWYVBZX*J"; size = letters.size(); max_char = 90; init(); } }; class Murphy10ProteinAlph : public Alphabet { public: Murphy10ProteinAlph () : Alphabet(Alphabet::PROTEIN) { letters = "ACDFGHIKSYBZX*J"; al_map['D'] = al_map['E'] = al_map['N'] = al_map['Q'] = 'D'; al_map['F'] = al_map['W'] = al_map['Y'] = 'F'; al_map['I'] = al_map['L'] = al_map['M'] = al_map['V'] = 'I'; al_map['K'] = al_map['R'] = 'K'; al_map['S'] = al_map['T'] = 'S'; size = letters.size(); max_char = 90; init(); } }; class DSSP10ProteinAlph : public Alphabet { public: DSSP10ProteinAlph () : Alphabet(Alphabet::PROTEIN) { letters = "EILFAWHCDGBZX*J"; al_map['E'] = al_map['K'] = al_map['Q'] = al_map['R'] = 'E'; al_map['I'] = al_map['V'] = 'I'; al_map['L'] = al_map['Y'] = 'L'; al_map['A'] = al_map['M'] = 'A'; al_map['H'] = al_map['T'] = 'H'; al_map['D'] = al_map['N'] = al_map['S'] = 'D'; al_map['G'] = al_map['P'] = 'G'; size = letters.size(); max_char = 90; init(); } }; class GBMR10ProteinAlph : public Alphabet { public: GBMR10ProteinAlph () : Alphabet(Alphabet::PROTEIN) { letters = "GDNAYHCTSPBZX*J"; al_map['A'] = al_map['E'] = al_map['F'] = al_map['I'] = al_map['K'] = al_map['L'] = al_map['M'] = al_map['Q'] = al_map['R'] = al_map['V'] = al_map['W'] = 'A'; size = letters.size(); max_char = 90; init(); } }; class TD10ProteinAlph : public Alphabet { public: TD10ProteinAlph () : Alphabet(Alphabet::PROTEIN) { letters = "PGEDTHIWALBZX*J"; al_map['E'] = al_map['K'] = al_map['R'] = al_map['Q'] = 'E'; al_map['D'] = al_map['S'] = al_map['N'] = 'D'; al_map['H'] = al_map['C'] = 'H'; al_map['I'] = al_map['V'] = 'I'; al_map['W'] = al_map['Y'] = al_map['F'] = 'W'; al_map['L'] = al_map['M'] = 'L'; size = letters.size(); max_char = 90; init(); } }; class DiamondProteinAlph : public Alphabet { public: DiamondProteinAlph () : Alphabet(Alphabet::PROTEIN) { letters = "KCGHIMFYWPSBZX*J"; al_map['K'] = al_map['R'] = al_map['E'] = al_map['D'] = al_map['Q'] = al_map['N'] = 'K'; al_map['I'] = al_map['L'] = al_map['V'] = 'I'; al_map['S'] = al_map['T'] = al_map['A'] = 'S'; size = letters.size(); max_char = 90; init(); } }; class DefaultDNAAlph : public Alphabet { DefaultDNAAlph () : Alphabet(Alphabet::DNA) { // std::cout << "DefaultDNAAlph ctor\n"; letters = "ACGT"; size = letters.size(); max_char = 84; init(); } }; }
15.683036
71
0.568745
esaliya
e58b0e4981e854b2a38992b0e1c156da04817a83
2,803
cpp
C++
OcularCore/src/Math/Random/CMWC.cpp
ssell/OcularEngine
c80cc4fcdb7dd7ce48d3af330bd33d05312076b1
[ "Apache-2.0" ]
8
2017-01-27T01:06:06.000Z
2020-11-05T20:23:19.000Z
OcularCore/src/Math/Random/CMWC.cpp
ssell/OcularEngine
c80cc4fcdb7dd7ce48d3af330bd33d05312076b1
[ "Apache-2.0" ]
39
2016-06-03T02:00:36.000Z
2017-03-19T17:47:39.000Z
OcularCore/src/Math/Random/CMWC.cpp
ssell/OcularEngine
c80cc4fcdb7dd7ce48d3af330bd33d05312076b1
[ "Apache-2.0" ]
4
2019-05-22T09:13:36.000Z
2020-12-01T03:17:45.000Z
/** * Copyright 2014-2017 Steven T Sell (ssell@vertexfragment.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "Math/Random/CMWC.hpp" #define M_C 362436UL #define M_QSIZE 4096 #define PHI 0x9e3779b9 //------------------------------------------------------------------------------------------ namespace Ocular { namespace Math { namespace Random { //------------------------------------------------------------------------------ // CONSTRUCTORS //------------------------------------------------------------------------------ CMWC131104::CMWC131104() : ARandom(), m_C(M_C) { m_Q.fill(0); } CMWC131104::~CMWC131104() { } //------------------------------------------------------------------------------ // PUBLIC METHODS //------------------------------------------------------------------------------ void CMWC131104::seed(int64_t seed) { m_SeedCast = static_cast<uint32_t>(seed); m_Q[0] = m_SeedCast; m_Q[1] = m_SeedCast + PHI; m_Q[2] = m_SeedCast + PHI + PHI; for (int i = 3; i < M_QSIZE; i++) { m_Q[i] = m_Q[i - 3] ^ m_Q[i - 2] ^ PHI ^ i; } } uint32_t CMWC131104::next() { static uint32_t i = M_QSIZE - 1; uint64_t t = 18782LL; i = (i + 1) & 4095; t = (18705ULL * m_Q[i]) + m_C; m_C = t >> 32; m_Q[i] = static_cast<uint32_t>(0xfffffffe - t); return m_Q[i]; } //------------------------------------------------------------------------------ // PROTECTED METHODS //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // PRIVATE METHODS //------------------------------------------------------------------------------ } } }
32.218391
92
0.351052
ssell
e5966c7d7338e04d4f35ac22fbc1ffb55193646b
5,159
hpp
C++
lib/include/interlinck/Core/Syntax/SyntaxVariant.hpp
henrikfroehling/polyglot
955fb37c2f54ebbaf933c16bf9e0e4bcca8a4142
[ "MIT" ]
null
null
null
lib/include/interlinck/Core/Syntax/SyntaxVariant.hpp
henrikfroehling/polyglot
955fb37c2f54ebbaf933c16bf9e0e4bcca8a4142
[ "MIT" ]
50
2021-06-30T20:01:50.000Z
2021-11-28T16:21:26.000Z
lib/include/interlinck/Core/Syntax/SyntaxVariant.hpp
henrikfroehling/polyglot
955fb37c2f54ebbaf933c16bf9e0e4bcca8a4142
[ "MIT" ]
null
null
null
#ifndef INTERLINCK_CORE_SYNTAX_SYNTAXVARIANT_H #define INTERLINCK_CORE_SYNTAX_SYNTAXVARIANT_H #include <cassert> #include <bitset> #include "interlinck/interlinck_global.hpp" namespace interlinck::Core::Syntax { class ISyntaxNode; class ISyntaxToken; class ISyntaxTrivia; namespace _detail { constexpr std::bitset<4> mask_empty{0x0}; constexpr std::bitset<4> mask_node{0x1}; constexpr std::bitset<4> mask_token{0x2}; constexpr std::bitset<4> mask_trivia{0x4}; } // end namespace _detail /** * @brief Represents an immutable wrapper for pointer of different syntax types. * * <code>SyntaxVariant</code>s are used at several places in the whole Syntax API. * * An instance can only hold one pointer of the following types: <code>ISyntaxNode</code>, * <code>ISyntaxToken</code> or <code>ISyntaxTrivia</code>. */ class INTERLINCK_API SyntaxVariant final { public: /** * @brief Returns the stored <code>ISyntaxNode</code> pointer if <code>isNode()</code> returns true. * @return The stored <code>ISyntaxNode</code> pointer. */ inline const ISyntaxNode* node() const noexcept { assert(isNode()); return static_cast<const ISyntaxNode*>(_value); } /** * @brief Returns the stored <code>ISyntaxToken</code> pointer if <code>isToken()</code> returns true. * @return The stored <code>ISyntaxToken</code> pointer. */ inline const ISyntaxToken* token() const noexcept { assert(isToken()); return static_cast<const ISyntaxToken*>(_value); } /** * @brief Returns the stored <code>ISyntaxTrivia</code> pointer if <code>isTrivia()</code> returns true. * @return The stored <code>ISyntaxTrivia</code> pointer. */ inline const ISyntaxTrivia* trivia() const noexcept { assert(isTrivia()); return static_cast<const ISyntaxTrivia*>(_value); } /** * @brief Returns whether the stored pointer is of type <code>ISyntaxNode</code>. * @return True, if the stored pointer is of type <code>ISyntaxNode</code>, otherwise false. */ inline bool isNode() const noexcept { return (_type & _detail::mask_node) != 0; } /** * @brief Returns whether the stored pointer is of type <code>ISyntaxToken</code>. * @return True, if the stored pointer is of type <code>ISyntaxToken</code>, otherwise false. */ inline bool isToken() const noexcept { return (_type & _detail::mask_token) != 0; } /** * @brief Returns whether the stored pointer is of type <code>ISyntaxTrivia</code>. * @return True, if the stored pointer is of type <code>ISyntaxTrivia</code>, otherwise false. */ inline bool isTrivia() const noexcept { return (_type & _detail::mask_trivia) != 0; } /** * @brief Returns whether the stored pointer is null. * * An empty <code>SyntaxVariant</code> does not store any pointer. * * @return True, if the stored pointer is null, otherwise false. */ inline bool isEmpty() const noexcept { return _type == _detail::mask_empty; } /** * @brief Creates a <code>SyntaxVariant</code> instance which stores a <code>ISyntaxNode</code> pointer. * @param node The <code>ISyntaxNode</code> pointer which will be stored. * @return A <code>SyntaxVariant</code> instance which stores a <code>ISyntaxNode</code> pointer. */ inline static SyntaxVariant asNode(const ISyntaxNode* node) noexcept { assert(node != nullptr); return SyntaxVariant{node, _detail::mask_node}; } /** * @brief Creates a <code>SyntaxVariant</code> instance which stores a <code>ISyntaxToken</code> pointer. * @param token The <code>ISyntaxToken</code> pointer which will be stored. * @return A <code>SyntaxVariant</code> instance which stores a <code>ISyntaxToken</code> pointer. */ inline static SyntaxVariant asToken(const ISyntaxToken* token) noexcept { assert(token != nullptr); return SyntaxVariant{token, _detail::mask_token}; } /** * @brief Creates a <code>SyntaxVariant</code> instance which stores a <code>ISyntaxTrivia</code> pointer. * @param trivia The <code>ISyntaxTrivia</code> pointer which will be stored. * @return A <code>SyntaxVariant</code> instance which stores a <code>ISyntaxTrivia</code> pointer. */ inline static SyntaxVariant asTrivia(const ISyntaxTrivia* trivia) noexcept { assert(trivia != nullptr); return SyntaxVariant{trivia, _detail::mask_trivia}; } /** * @brief Creates an empty <code>SyntaxVariant</code> instance which does not store any pointer. * @return An empty <code>SyntaxVariant</code> instance which does not store any pointer. */ inline static SyntaxVariant empty() noexcept { return SyntaxVariant{nullptr, _detail::mask_empty}; } private: explicit SyntaxVariant(const void* value, std::bitset<4> type) noexcept : _value{value}, _type{type} {} private: const void* _value; std::bitset<4> _type; }; } // end namespace interlinck::Core::Syntax #endif // INTERLINCK_CORE_SYNTAX_SYNTAXVARIANT_H
35.826389
110
0.680364
henrikfroehling
e5a369b4ae18d3d951e5b1a3df8be196edd99fae
11,443
cpp
C++
src/mesh.cpp
ddrevicky/cpu-renderer
445e467377558e9a42bd32feac74c517e55e60be
[ "MIT" ]
4
2019-03-18T18:44:02.000Z
2022-01-17T17:16:51.000Z
src/mesh.cpp
ddrevicky/cpu-renderer
445e467377558e9a42bd32feac74c517e55e60be
[ "MIT" ]
null
null
null
src/mesh.cpp
ddrevicky/cpu-renderer
445e467377558e9a42bd32feac74c517e55e60be
[ "MIT" ]
1
2019-03-18T18:44:22.000Z
2019-03-18T18:44:22.000Z
#include "mesh.h" #include "common.h" #include "bunny.h" using glm::normalize; using glm::vec2; using glm::vec3; using glm::vec4; #define PI 3.14159265358979323846264338327950f Mesh UtilMesh::MakeBunnyMesh() { Mesh mesh = {}; mesh.isTexturable = false; mesh.vertexCount = 0; mesh.vertices = (Vertex *)malloc(2092 * 3 * sizeof(Vertex)); for (Uint32 i = 0; i < 2092; ++i) { for (Uint32 j = 0; j < 3; ++j) { short index = bunnyIndices[i][j]; BunnyVertex bv = bunnyVertices[index]; Vertex v = {}; v.position = vec4(bv.position[0], bv.position[1], bv.position[2], 1.0f); v.normal = vec3(bv.normal[0], bv.normal[1], bv.normal[2]); v.vsOutColor = vec3(1.0f, 0.0f, 0.0f); mesh.vertices[i * 3 + j] = v; mesh.vertexCount++; } } return mesh; } // Contains lines created as normals of the original mesh (starting at the vertices of the original and going // to the normal direction). Mesh UtilMesh::MakeNormalMesh(Mesh *original, float normalLength) { Mesh normalMesh = {}; normalMesh.vertexCount = 0; normalMesh.vertices = (Vertex*)malloc(2 * original->vertexCount * sizeof(Vertex)); normalMesh.isTexturable = false; for (Uint32 i = 0; i < original->vertexCount; ++i) { Vertex start = {}; start.position = original->vertices[i].position; start.vsOutColor = vec3(1.0f, 1.0f, 0.0f); Vertex end = {}; end.position = start.position + vec4(original->vertices[i].normal, 0.0f) * normalLength; end.vsOutColor = vec3(1.0f, 1.0f, 0.0f); normalMesh.vertices[normalMesh.vertexCount++] = start; normalMesh.vertices[normalMesh.vertexCount++] = end; } return normalMesh; } Mesh UtilMesh::MakeWorldAxesMesh() { Mesh mesh = {}; mesh.vertexCount = 3 * 2; mesh.vertices = (Vertex*)malloc(mesh.vertexCount * sizeof(Vertex)); mesh.isTexturable = false; float axisLength = 3; Vertex center = {}, x = {}, y = {}, z = {}; center.position = vec4(0, 0, 0, 1); x.position = vec4(axisLength, 0, 0, 1); x.vsOutColor = vec3(1, 0, 0); y.position = vec4(0, axisLength, 0, 1); y.vsOutColor = vec3(0, 1, 0); z.position = vec4(0, 0, axisLength, 1); x.vsOutColor = vec3(0, 1, 0); mesh.vertices[0] = center; mesh.vertices[1] = x; mesh.vertices[2] = center; mesh.vertices[3] = y; mesh.vertices[4] = center; mesh.vertices[5] = z; return mesh; } void AddLine(Mesh *mesh, Vertex v0, Vertex v1) { mesh->vertices[mesh->vertexCount++] = v0; mesh->vertices[mesh->vertexCount++] = v1; } // Plane is visualized as a set of lines Mesh UtilMesh::MakePlaneMesh() { Uint32 numberOfLines = 60; float span = 5.0f; Mesh mesh = {}; mesh.vertexCount = 0; mesh.vertices = (Vertex*)malloc(numberOfLines * 2 * sizeof(Vertex)); mesh.isTexturable = false; // The plane is built in the xy plane (z == 0) for (Uint32 i = 0; i < numberOfLines; ++i) { float y = -(span / 2.0f) + i * (span / numberOfLines); float startX = -span / 2.0f; float endX = span / 2.0f; float z = 0.0f; Vertex start = {}, end = {}; start.position = vec4(span / 2.0f, y, 0.0f, 1.0f); end.position = vec4(-span / 2.0f, y, 0.0f, 1.0f); start.vsOutColor = vec3(0, 0, 1); end.vsOutColor = vec3(0, 0, 1); AddLine(&mesh, start, end); } return mesh; } void UtilMesh::AddTriangle(Mesh *mesh, Vertex v0, Vertex v1, Vertex v2) { mesh->vertices[mesh->vertexCount++] = v0; mesh->vertices[mesh->vertexCount++] = v1; mesh->vertices[mesh->vertexCount++] = v2; } // Phi is latitude. Theta longitude. vec4 SphericalToCartesian(float r, float phi, float theta) { vec4 cartesian; cartesian.x = r * sin(theta) * sin(phi); cartesian.y = r * cos(phi); cartesian.z = r * cos(theta) * sin(phi); cartesian.w = 1.0f; return cartesian; } Mesh UtilMesh::MakeUVSphere(Uint32 subdivisions, vec3 color) { Uint32 stacks = subdivisions; Uint32 slices = subdivisions; float r = 1.0f; vec3 c = vec3(0.0f, 0.0f, 0.0f); Mesh mesh = {}; mesh.vertexCount = 0; mesh.vertices = (Vertex*)malloc(3 * (slices * 2 + ((stacks - 2) * slices * 2)) * sizeof(Vertex)); mesh.isTexturable = false; for (Uint32 p = 0; p < stacks; ++p) { float phi1 = (float(p) / stacks)*PI; float phi2 = (float(p + 1) / stacks)*PI; for (Uint32 t = 0; t < slices; ++t) { float theta1 = (float(t) / slices) * 2 * PI; float theta2 = (float(t + 1) / slices) * 2 * PI; Vertex v1 = {}, v2 = {}, v3 = {}, v4 = {}; v1.position = SphericalToCartesian(r, phi1, theta1); v2.position = SphericalToCartesian(r, phi2, theta1); v3.position = SphericalToCartesian(r, phi2, theta2); v4.position = SphericalToCartesian(r, phi1, theta2); v1.normal = normalize(vec3(v1.position) - c); v2.normal = normalize(vec3(v2.position) - c); v3.normal = normalize(vec3(v3.position) - c); v4.normal = normalize(vec3(v4.position) - c); v1.vsOutColor = color; v2.vsOutColor = color; v3.vsOutColor = color; v4.vsOutColor = color; if (p == 0) // First stack AddTriangle(&mesh, v1, v2, v3); else if (p + 1 == stacks) AddTriangle(&mesh, v2, v4, v1); // Last stack else { AddTriangle(&mesh, v1, v2, v3); // Middle stacks AddTriangle(&mesh, v3, v4, v1); } } } return mesh; } Mesh UtilMesh::MakeTriangle() { Mesh mesh = {}; mesh.vertexCount = 3; mesh.vertices = (Vertex*)malloc(mesh.vertexCount * sizeof(Vertex)); mesh.isTexturable = false; Vertex v0 = {}, v1 = {}, v2 = {}; v0.position = vec4(0, 0, -1, 1); v1.position = vec4(-1, 0, 1, 1); v2.position = vec4(0, 0, 1, 1); mesh.vertices[0] = v1; mesh.vertices[1] = v2; mesh.vertices[2] = v0; return mesh; } Mesh UtilMesh::MakeCubeCentered(float edgeSize) { float size = edgeSize; Vertex vertices[] = { // Front Vertex{ vec4(-size / 2, -size / 2, size / 2, 1.0f), vec2(1.5f, 0.0f), vec3(0.0f, 0.0f, 1.0f), vec3(0.5f, 0.0f, 0.0f) }, // LBN, Vertex{ vec4(size / 2, -size / 2, size / 2, 1.0f), vec2(0.0f, 0.0f), vec3(0.0f, 0.0f, 1.0f), vec3(0.0f, 0.5f, 0.0f) }, // RBN, Vertex{ vec4(size / 2, size / 2, size / 2, 1.0f), vec2(0.0f, 1.5f), vec3(0.0f, 0.0f, 1.0f), vec3(0.0f, 0.0f, 0.5f) }, // RTN, Vertex{ vec4(size / 2, size / 2, size / 2, 1.0f), vec2(0.0f, 1.5f), vec3(0.0f, 0.0f, 1.0f), vec3(0.0f, 0.0f, 0.5f) }, // RTN, Vertex{ vec4(-size / 2, size / 2, size / 2, 1.0f), vec2(1.5f, 1.5f), vec3(0.0f, 0.0f, 1.0f), vec3(0.0f, 0.5f, 0.0f) }, // LTN, Vertex{ vec4(-size / 2, -size / 2, size / 2, 1.0f), vec2(1.5f, 0.0f), vec3(0.0f, 0.0f, 1.0f), vec3(0.5f, 0.0f, 0.0f) }, // LBN, // Top Vertex{ vec4(-size / 2, size / 2, size / 2, 1.0f), vec2(0.0f, 0.0f), vec3(0.0f, 1.0f, 0.0f), vec3(0.5f, 0.0f, 0.0f) }, // LTN, Vertex{ vec4(size / 2, size / 2, size / 2, 1.0f), vec2(1.5f, 0.0f), vec3(0.0f, 1.0f, 0.0f), vec3(0.0f, 0.5f, 0.0f) }, // RTN, Vertex{ vec4(size / 2, size / 2, -size / 2, 1.0f), vec2(1.5f, 1.5f), vec3(0.0f, 1.0f, 0.0f), vec3(0.0f, 0.0f, 0.5f) }, // RTF, Vertex{ vec4(size / 2, size / 2, -size / 2, 1.0f), vec2(1.5f, 1.5f), vec3(0.0f, 1.0f, 0.0f), vec3(0.5f, 0.0f, 0.0f) }, // RTF, Vertex{ vec4(-size / 2, size / 2, -size / 2, 1.0f), vec2(0.0f, 1.5f), vec3(0.0f, 1.0f, 0.0f), vec3(0.0f, 0.5f, 0.0f) }, // LTF, Vertex{ vec4(-size / 2, size / 2, size / 2, 1.0f), vec2(0.0f, 0.0f), vec3(0.0f, 1.0f, 0.0f), vec3(0.0f, 0.0f, 0.5f) }, // LTN, // Back Vertex{ vec4(size / 2, -size / 2, -size / 2, 1.0f), vec2(1.5f, 0.0f), vec3(0.0f, 0.0f, -1.0f), vec3(0.0f, 0.0f, 0.5f) }, // RBF, Vertex{ vec4(-size / 2, -size / 2, -size / 2, 1.0f), vec2(0.0f, 0.0f), vec3(0.0f, 0.0f, -1.0f), vec3(0.0f, 0.5f, 0.0f) }, // LBF, Vertex{ vec4(-size / 2, size / 2, -size / 2, 1.0f), vec2(0.0f, 1.5f), vec3(0.0f, 0.0f, -1.0f), vec3(0.0f, 0.0f, 0.5f) }, // LTF, Vertex{ vec4(-size / 2, size / 2, -size / 2, 1.0f), vec2(0.0f, 1.5f), vec3(0.0f, 0.0f, -1.0f), vec3(0.0f, 0.0f, 0.5f) }, // LTF, Vertex{ vec4(size / 2, size / 2, -size / 2, 1.0f), vec2(1.5f, 1.5f), vec3(0.0f, 0.0f, -1.0f), vec3(0.0f, 0.5f, 0.0f) }, // RTF, Vertex{ vec4(size / 2, -size / 2, -size / 2, 1.0f), vec2(1.5f, 0.0f), vec3(0.0f, 0.0f, -1.0f), vec3(0.0f, 0.0f, 0.5f) }, // RBF, // Bottom Vertex{ vec4(-size / 2, -size / 2, -size / 2, 1.0f), vec2(0.0f, 1.5f), vec3(0.0f, -1.0f, 0.0f), vec3(0.5f, 0.0f, 0.0f) }, // LBF, Vertex{ vec4(size / 2, -size / 2, -size / 2, 1.0f), vec2(1.5f, 1.5f), vec3(0.0f, -1.0f, 0.0f), vec3(0.0f, 0.5f, 0.0f) }, // RBF, Vertex{ vec4(size / 2, -size / 2, size / 2, 1.0f), vec2(1.5f, 0.0f), vec3(0.0f, -1.0f, 0.0f), vec3(0.0f, 0.0f, 0.5f) }, // RBN, Vertex{ vec4(size / 2, -size / 2, size / 2, 1.0f), vec2(1.5f, 0.0f), vec3(0.0f, -1.0f, 0.0f), vec3(0.5f, 0.0f, 0.0f) }, // RBN, Vertex{ vec4(-size / 2, -size / 2, size / 2, 1.0f), vec2(0.0f, 0.0f), vec3(0.0f, -1.0f, 0.0f), vec3(0.0f, 0.5f, 0.0f) }, // LBN, Vertex{ vec4(-size / 2, -size / 2, -size / 2, 1.0f), vec2(0.0f, 1.5f), vec3(0.0f, -1.0f, 0.0f), vec3(0.0f, 0.0f, 0.5f) }, // LBF, // Right Vertex{ vec4(size / 2, -size / 2, size / 2, 1.0f), vec2(0.0f, 0.0f), vec3(1.0f, 0.0f, 0.0f), vec3(0.5f, 0.0f, 0.0f) }, // RBN, Vertex{ vec4(size / 2, -size / 2, -size / 2, 1.0f), vec2(1.5f, 0.0f), vec3(1.0f, 0.0f, 0.0f), vec3(0.0f, 0.5f, 0.0f) }, // RBF, Vertex{ vec4(size / 2, size / 2, -size / 2, 1.0f), vec2(1.5f, 1.5f), vec3(1.0f, 0.0f, 0.0f), vec3(0.0f, 0.0f, 0.5f) }, // RTF, Vertex{ vec4(size / 2, size / 2, -size / 2, 1.0f), vec2(1.5f, 1.5f), vec3(1.0f, 0.0f, 0.0f), vec3(0.5f, 0.0f, 0.0f) }, // RTF, Vertex{ vec4(size / 2, size / 2, size / 2, 1.0f), vec2(0.0f, 1.5f), vec3(1.0f, 0.0f, 0.0f), vec3(0.0f, 0.5f, 0.0f) }, // RTN, Vertex{ vec4(size / 2, -size / 2, size / 2, 1.0f), vec2(0.0f, 0.0f), vec3(1.0f, 0.0f, 0.0f), vec3(0.0f, 0.0f, 0.5f) }, // RBN, // Left Vertex{ vec4(-size / 2, -size / 2, -size / 2, 1.0f), vec2(0.0f, 0.0f), vec3(-1.0f, 0.0f, 0.0f), vec3(0.5f, 0.0f, 0.0f) }, // LBF, Vertex{ vec4(-size / 2, -size / 2, size / 2, 1.0f), vec2(1.5f, 0.0f), vec3(-1.0f, 0.0f, 0.0f) , vec3(0.0f, 0.5f, 0.0f) }, // LBN, Vertex{ vec4(-size / 2, size / 2, size / 2, 1.0f), vec2(1.5f, 1.5f), vec3(-1.0f, 0.0f, 0.0f) , vec3(0.0f, 0.0f, 0.5f) }, // LTN, Vertex{ vec4(-size / 2, size / 2, size / 2, 1.0f), vec2(1.5f, 1.5f), vec3(-1.0f, 0.0f, 0.0f) , vec3(0.5f, 0.0f, 0.0f) }, // LTN, Vertex{ vec4(-size / 2, size / 2, -size / 2, 1.0f), vec2(0.0f, 1.5f), vec3(-1.0f, 0.0f, 0.0f) , vec3(0.0f, 0.5f, 0.0f) }, // LTF, Vertex{ vec4(-size / 2, -size / 2, -size / 2, 1.0f), vec2(0.0f, 0.0f), vec3(-1.0f, 0.0f, 0.0f), vec3(0.0f, 0.0f, 0.5f) }, // LBF, }; Mesh mesh = {}; mesh.vertexCount = SDL_arraysize(vertices); mesh.vertices = (Vertex*) malloc(mesh.vertexCount * sizeof(Vertex)); mesh.isTexturable = true; memcpy(mesh.vertices, vertices, sizeof(vertices)); return mesh; } void UtilMesh::Release(Mesh mesh) { free(mesh.vertices); } Mesh UtilMesh::MakeMeshCopy(Mesh *original) { Mesh mesh = {}; mesh.isTexturable = original->isTexturable; mesh.vertexCount = original->vertexCount; mesh.vertices = (Vertex*)malloc(original->vertexCount * sizeof(Vertex)); memcpy(mesh.vertices, original->vertices, original->vertexCount * sizeof(Vertex)); return mesh; } void UtilMesh::UpdateVertices(Mesh *mesh, Vertex *newVertices, Uint32 newVertexCount) { free(mesh->vertices); mesh->vertexCount = newVertexCount; mesh->vertices = (Vertex*)malloc(newVertexCount * sizeof(Vertex)); memcpy(mesh->vertices, newVertices, newVertexCount * sizeof(Vertex)); }
37.273616
138
0.585336
ddrevicky
e5aaeca79a571acefdb4e26a65da167153685c47
1,968
cpp
C++
code archive/CF/734E.cpp
brianbbsu/program
c4505f2b8c0b91010e157db914a63c49638516bc
[ "MIT" ]
4
2018-04-08T08:07:58.000Z
2021-06-07T14:55:24.000Z
code archive/CF/734E.cpp
brianbbsu/program
c4505f2b8c0b91010e157db914a63c49638516bc
[ "MIT" ]
null
null
null
code archive/CF/734E.cpp
brianbbsu/program
c4505f2b8c0b91010e157db914a63c49638516bc
[ "MIT" ]
1
2018-10-29T12:37:25.000Z
2018-10-29T12:37:25.000Z
//{ #include<bits/stdc++.h> using namespace std; typedef long long ll; typedef double lf; typedef pair<ll,ll> ii; #define REP(i,n) for(ll i=0;i<n;i++) #define FILL(i,n) memset(i,n,sizeof i) #define X first #define Y second #define SZ(_a) (int)_a.size() #define ALL(_a) _a.begin(),_a.end() #define pb push_back #ifdef brian #define debug(...) do{\ fprintf(stderr,"%s - %d (%s) = ",__PRETTY_FUNCTION__,__LINE__,#__VA_ARGS__);\ _do(__VA_ARGS__);\ }while(0) template<typename T>void _do(T &&_x){cerr<<_x<<endl;} template<typename T,typename ...S> void _do(T &&_x,S &&..._t){cerr<<_x<<" ,";_do(_t...);} template<typename _a,typename _b> ostream &operator << (ostream &_s,pair<_a,_b> &_p){return _s<<"("<<_p.X<<","<<_p.Y<<")";} template<typename It> ostream& _OUTC(ostream &_s,It _ita,It _itb) { _s<<"{"; for(It _it=_ita;_it!=_itb;_it++) { _s<<(_it==_ita?"":",")<<*_it; } _s<<"}"; return _s; } template<typename _a> ostream &operator << (ostream &_s,vector<_a> &_c){return _OUTC(_s,ALL(_c));} template<typename _a> ostream &operator << (ostream &_s,set<_a> &_c){return _OUTC(_s,ALL(_c));} template<typename _a,typename _b> ostream &operator << (ostream &_s,map<_a,_b> &_c){return _OUTC(_s,ALL(_c));} #else #define debug(...) #define endl '\n' #endif // brian //} const ll MAXn=2e5+5; const ll MOD=1000000007; const ll INF=ll(1e15); ll n; vector<ll> v[MAXn]; bool d[MAXn]; set<ii,greater<ll> > st; ll mn=0; ll dfs(ll now,ll f,bool l) { ii tmp=ii(0,0); for(ll k:v[now]) { if(k==f)continue; ll t=dfs(k,now,d[now]); if(t>tmp.X)swap(t,tmp.X); if(t>tmp.Y)tmp.Y=t; } mn=max(mn,(tmp.X+tmp.Y+1)/2); return (tmp.X+(d[now]!=l)); } int main() { ios_base::sync_with_stdio(0);cin.tie(0); cin>>n; REP(i,n)cin>>d[i]; REP(i,n-1) { ll a,b; cin>>a>>b; a--;b--; v[a].pb(b); v[b].pb(a); } dfs(0,-1,d[0]); cout<<mn<<endl; }
24.296296
123
0.57876
brianbbsu
e5adb9ceed8b97daf62b23a84f53f6e01f287334
479
cpp
C++
question_solution/first_time/1027.cpp
xiaoland/CaiojSolution
a12c505235d70b414071ea894fa72cddbcfabc6d
[ "Apache-2.0" ]
1
2020-09-24T13:35:45.000Z
2020-09-24T13:35:45.000Z
question_solution/first_time/1027.cpp
xiaoland/CaiojSolution
a12c505235d70b414071ea894fa72cddbcfabc6d
[ "Apache-2.0" ]
null
null
null
question_solution/first_time/1027.cpp
xiaoland/CaiojSolution
a12c505235d70b414071ea894fa72cddbcfabc6d
[ "Apache-2.0" ]
null
null
null
#include <cstdio> int a[110], len, s; int pd(int x) { len = 0; int d= x; while(x>0) { len++; a[len] = x%10; x = x/10; } for(int i = 1;i<=len;i++) { s= 0; s = s + a[i]*a[i]*a[i]; } if(s == d) { return 0; } else { return 1; } } int main() { int x, y; scanf("%d%d", &x, &y); for(int i = x; i<=y;i++) { if(pd(i) == 0){ printf("%d\n", i); } } }
15.966667
31
0.323591
xiaoland
e5aef649a03bb14be46c75d5a62ca98388714c65
431
cc
C++
examples/google-code-jam/BryceSandlund/Brattleship.cc
rbenic-fer/progauthfp
d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675
[ "MIT" ]
null
null
null
examples/google-code-jam/BryceSandlund/Brattleship.cc
rbenic-fer/progauthfp
d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675
[ "MIT" ]
null
null
null
examples/google-code-jam/BryceSandlund/Brattleship.cc
rbenic-fer/progauthfp
d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdio> using namespace std; typedef long long ll; int main() { ll T; cin >> T; for (ll cs = 1; cs <= T; ++cs) { ll R, C, W; cin >> R >> C >> W; ll moves = (C / W) * R; if (C % W == 0) { moves += W-1; } else { moves += W; } printf("Case #%lld: %lld\n", cs, moves); } return 0; }
15.392857
48
0.37819
rbenic-fer
e5b421b796abba481ae71cd45ba2c0d4d745a0fa
318
hpp
C++
TGEngine/TGEngine.hpp
ThePixly/TGEngine
aff5d5f42c3094dcc37253f4a3f5e09db560a4eb
[ "Apache-2.0" ]
null
null
null
TGEngine/TGEngine.hpp
ThePixly/TGEngine
aff5d5f42c3094dcc37253f4a3f5e09db560a4eb
[ "Apache-2.0" ]
null
null
null
TGEngine/TGEngine.hpp
ThePixly/TGEngine
aff5d5f42c3094dcc37253f4a3f5e09db560a4eb
[ "Apache-2.0" ]
null
null
null
#pragma once #include "Stdbase.hpp" #include "App.hpp" #include "pipeline/Pipeline.hpp" #include "pipeline/Draw.hpp" #include "game_content/Actor.hpp" #include "game_content/Light.hpp" #include "ui/UI.hpp" SINCE(0, 0, 1) void initTGEngine(Window* window, void(*draw)(IndexBuffer*, VertexBuffer*), void(*init)(void));
26.5
95
0.738994
ThePixly
e5bb03bacfe29c4c281d494bc99258f2a9f09872
1,253
hpp
C++
source/ashes/renderer/GlRenderer/Enum/GlQueryType.hpp
DragonJoker/Ashes
a6ed950b3fd8fb9626c60b4291fbd52ea75ac66e
[ "MIT" ]
227
2018-09-17T16:03:35.000Z
2022-03-19T02:02:45.000Z
source/ashes/renderer/GlRenderer/Enum/GlQueryType.hpp
DragonJoker/RendererLib
0f8ad8edec1b0929ebd10247d3dd0a9ee8f8c91a
[ "MIT" ]
39
2018-02-06T22:22:24.000Z
2018-08-29T07:11:06.000Z
source/ashes/renderer/GlRenderer/Enum/GlQueryType.hpp
DragonJoker/Ashes
a6ed950b3fd8fb9626c60b4291fbd52ea75ac66e
[ "MIT" ]
8
2019-05-04T10:33:32.000Z
2021-04-05T13:19:27.000Z
/* This file belongs to Ashes. See LICENSE file in root folder */ #pragma once #include <vector> namespace ashes::gl { enum GlQueryType : GLenum { GL_QUERY_TYPE_SAMPLES_PASSED = 0x8914, GL_QUERY_TYPE_PRIMITIVES_GENERATED = 0x8C87, GL_QUERY_TYPE_TIMESTAMP = 0x8E28, GL_QUERY_TYPE_VERTICES_SUBMITTED = 0x82EE, GL_QUERY_TYPE_PRIMITIVES_SUBMITTED = 0x82EF, GL_QUERY_TYPE_VERTEX_SHADER_INVOCATIONS = 0x82F0, GL_QUERY_TYPE_TESS_CONTROL_SHADER_PATCHES = 0x82F1, GL_QUERY_TYPE_TESS_EVALUATION_SHADER_INVOCATIONS = 0x82F2, GL_QUERY_TYPE_GEOMETRY_SHADER_INVOCATIONS = 0x887F, GL_QUERY_TYPE_GEOMETRY_SHADER_PRIMITIVES_EMITTED = 0x82F3, GL_QUERY_TYPE_FRAGMENT_SHADER_INVOCATIONS = 0x82F4, GL_QUERY_TYPE_COMPUTE_SHADER_INVOCATIONS = 0x82F5, GL_QUERY_TYPE_CLIPPING_INPUT_PRIMITIVES = 0x82F6, GL_QUERY_TYPE_CLIPPING_OUTPUT_PRIMITIVES = 0x82F7, }; std::string getName( GlQueryType value ); inline std::string toString( GlQueryType value ) { return getName( value ); } /** *\brief * Convertit un VkQueryType en GlQueryType. *\param[in] value * Le VkQueryType. *\return * Le GlQueryType. */ GlQueryType convert( VkQueryType const & value ); std::vector< GlQueryType > getQueryTypes( VkQueryPipelineStatisticFlags value ); }
29.833333
81
0.797287
DragonJoker
e5be320567ef32a0d2335e55d64601e871f424d5
3,101
cpp
C++
src/sysCommon/controller.cpp
doldecomp/pikmin
8c8c20721ecb2a19af8e50a4bdebdba90c9a27ed
[ "Unlicense" ]
27
2021-09-28T00:33:11.000Z
2021-11-18T19:38:40.000Z
src/sysCommon/controller.cpp
doldecomp/pikmin
8c8c20721ecb2a19af8e50a4bdebdba90c9a27ed
[ "Unlicense" ]
null
null
null
src/sysCommon/controller.cpp
doldecomp/pikmin
8c8c20721ecb2a19af8e50a4bdebdba90c9a27ed
[ "Unlicense" ]
null
null
null
#include "types.h" /* * --INFO-- * Address: ........ * Size: 00009C */ void _Error(char*, ...) { // UNUSED FUNCTION } /* * --INFO-- * Address: ........ * Size: 0000F4 */ void _Print(char*, ...) { // UNUSED FUNCTION } struct Controller { u8 unknown00[0x20]; u32 _20; u32 _24; u32 _28; u32 _2C; u32 _30; u32 _34; u32 _38; u32 _3C; u32 _40; bool _44; void reset(unsigned long); void updateCont(unsigned long); void update(); void getMainStickX(); void getMainStickY(); void getSubStickX(); void getSubStickY(); }; /* * --INFO-- * Address: 800409B0 * Size: 000024 */ void Controller::reset(unsigned long arg1) { _3C = -1; _44 = false; _38 = arg1; _40 = 0; _20 = 0; _24 = 0; } /* * --INFO-- * Address: 800409D4 * Size: 00009C */ void Controller::updateCont(unsigned long arg1) { _24 = _20; _20 = 0; if (!_44) { _20 = arg1; } _28 = _20 & ~_24; _20 = _24 & ~_20; if (_40) { _30 = 0; if (!(_34 = _28)) { return; } _40 = 10; } else { if (!(--_40)) { return; } if (!(_30 = _34 & _28)) { return; } _40 = 0; } } /* * --INFO-- * Address: 80040A70 * Size: 00002C */ struct ControllerManager { void updateController(Controller*); }; struct System { u8 data[0x27C]; ControllerManager* m_contManager; }; extern System* gsys; void Controller::update() { gsys->m_contManager->updateController(this); } /* * --INFO-- * Address: 80040A9C * Size: 000038 */ void Controller::getMainStickX() { /* .loc_0x0: stwu r1, -0x18(r1) lis r0, 0x4330 lbz r3, 0x45(r3) lfd f2, -0x7C00(r2) extsb r3, r3 lfs f0, -0x7C08(r2) xoris r3, r3, 0x8000 stw r3, 0x14(r1) stw r0, 0x10(r1) lfd f1, 0x10(r1) fsubs f1, f1, f2 fdivs f1, f1, f0 addi r1, r1, 0x18 blr */ } /* * --INFO-- * Address: 80040AD4 * Size: 000038 */ void Controller::getMainStickY() { /* .loc_0x0: stwu r1, -0x18(r1) lis r0, 0x4330 lbz r3, 0x46(r3) lfd f2, -0x7C00(r2) extsb r3, r3 lfs f0, -0x7C08(r2) xoris r3, r3, 0x8000 stw r3, 0x14(r1) stw r0, 0x10(r1) lfd f1, 0x10(r1) fsubs f1, f1, f2 fdivs f1, f1, f0 addi r1, r1, 0x18 blr */ } /* * --INFO-- * Address: 80040B0C * Size: 000038 */ void Controller::getSubStickX() { /* .loc_0x0: stwu r1, -0x18(r1) lis r0, 0x4330 lbz r3, 0x47(r3) lfd f2, -0x7C00(r2) extsb r3, r3 lfs f0, -0x7C08(r2) xoris r3, r3, 0x8000 stw r3, 0x14(r1) stw r0, 0x10(r1) lfd f1, 0x10(r1) fsubs f1, f1, f2 fdivs f1, f1, f0 addi r1, r1, 0x18 blr */ } /* * --INFO-- * Address: 80040B44 * Size: 000038 */ void Controller::getSubStickY() { /* .loc_0x0: stwu r1, -0x18(r1) lis r0, 0x4330 lbz r3, 0x48(r3) lfd f2, -0x7C00(r2) extsb r3, r3 lfs f0, -0x7C08(r2) xoris r3, r3, 0x8000 stw r3, 0x14(r1) stw r0, 0x10(r1) lfd f1, 0x10(r1) fsubs f1, f1, f2 fdivs f1, f1, f0 addi r1, r1, 0x18 blr */ }
14.159817
74
0.537891
doldecomp
e5c03082b68d39e51789eef9b772f44eecc96c0c
12,068
hpp
C++
join/network/include/join/protocol.hpp
mrabine/join
63c6193f2cc229328c36748d7f9ef8aca915bec3
[ "MIT" ]
1
2021-09-14T13:53:07.000Z
2021-09-14T13:53:07.000Z
join/network/include/join/protocol.hpp
joinframework/join
63c6193f2cc229328c36748d7f9ef8aca915bec3
[ "MIT" ]
15
2021-08-09T23:55:02.000Z
2021-11-22T11:05:41.000Z
join/network/include/join/protocol.hpp
mrabine/join
63c6193f2cc229328c36748d7f9ef8aca915bec3
[ "MIT" ]
null
null
null
/** * MIT License * * Copyright (c) 2021 Mathieu Rabine * * 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. */ #ifndef __JOIN_PROTOCOL_HPP__ #define __JOIN_PROTOCOL_HPP__ // libjoin. #include <join/endpoint.hpp> // C. #include <net/ethernet.h> namespace join { template <class Protocol> class BasicResolver; template <class Protocol> class BasicSocket; template <class Protocol> class BasicDatagramSocket; template <class Protocol> class BasicStreamSocket; template <class Protocol> class BasicTlsSocket; template <class Protocol> class BasicStreamAcceptor; template <class Protocol> class BasicTlsAcceptor; /** * @brief unix datagram protocol class. */ class UnixDgram { public: using Endpoint = BasicUnixEndpoint <UnixDgram>; using Socket = BasicDatagramSocket <UnixDgram>; /** * @brief construct the unix datagram protocol instance by default. */ constexpr UnixDgram () noexcept = default; /** * @brief get the protocol ip address family. * @return the protocol ip address family. */ constexpr int family () const noexcept { return AF_UNIX; } /** * @brief get the protocol communication semantic. * @return the protocol communication semantic. */ constexpr int type () const noexcept { return SOCK_DGRAM; } /** * @brief get the protocol type. * @return the protocol type. */ constexpr int protocol () const noexcept { return 0; } }; /** * @brief unix stream protocol class. */ class UnixStream { public: using Endpoint = BasicUnixEndpoint <UnixStream>; using Socket = BasicStreamSocket <UnixStream>; using Acceptor = BasicStreamAcceptor <UnixStream>; /** * @brief construct the unix stream protocol instance by default. */ constexpr UnixStream () noexcept = default; /** * @brief get the protocol ip address family. * @return the protocol ip address family. */ constexpr int family () const noexcept { return AF_UNIX; } /** * @brief get the protocol communication semantic. * @return the protocol communication semantic. */ constexpr int type () const noexcept { return SOCK_STREAM; } /** * @brief get the protocol type. * @return the protocol type. */ constexpr int protocol () const noexcept { return 0; } }; /** * @brief RAW protocol class. */ class Raw { public: using Endpoint = BasicLinkLayerEndpoint <Raw>; using Socket = BasicSocket <Raw>; /** * @brief default constructor. */ constexpr Raw () noexcept = default; /** * @brief get the protocol ip address family. * @return the protocol ip address family. */ constexpr int family () const noexcept { return AF_PACKET; } /** * @brief get the protocol communication semantic. * @return the protocol communication semantic. */ constexpr int type () const noexcept { return SOCK_RAW; } /** * @brief get the protocol type. * @return the protocol type. */ constexpr int protocol () const noexcept { if (BYTE_ORDER == LITTLE_ENDIAN) { return (ETH_P_ALL >> 8) | (ETH_P_ALL << 8); } return ETH_P_ALL; } }; /** * @brief UDP protocol class. */ class Udp { public: using Endpoint = BasicInternetEndpoint <Udp>; using Resolver = BasicResolver <Udp>; using Socket = BasicDatagramSocket <Udp>; /** * @brief construct the udp protocol instance. * @param family IP address family. */ constexpr Udp (int family = AF_INET) noexcept : _family (family) { } /** * @brief get protocol suitable for IPv4 address family. * @return an IPv4 address family suitable protocol. */ static inline Udp& v4 () noexcept { static Udp udpv4 (AF_INET); return udpv4; } /** * @brief get protocol suitable for IPv6 address family. * @return an IPv6 address family suitable protocol. */ static inline Udp& v6 () noexcept { static Udp udpv6 (AF_INET6); return udpv6; } /** * @brief get the protocol IP address family. * @return the protocol IP address family. */ constexpr int family () const noexcept { return _family; } /** * @brief get the protocol communication semantic. * @return the protocol communication semantic. */ constexpr int type () const noexcept { return SOCK_DGRAM; } /** * @brief get the protocol type. * @return the protocol type. */ constexpr int protocol () const noexcept { return IPPROTO_UDP; } private: /// IP address family. int _family; }; /** * @brief check if equals. * @param a protocol to check. * @param b protocol to check. * @return true if equals. */ constexpr bool operator== (const Udp& a, const Udp& b) noexcept { return a.family () == b.family (); } /** * @brief check if not equals. * @param a protocol to check. * @param b protocol to check. * @return true if not equals. */ constexpr bool operator!= (const Udp& a, const Udp& b) noexcept { return !(a == b); } /** * @brief ICMP protocol class. */ class Icmp { public: using Endpoint = BasicInternetEndpoint <Icmp>; using Resolver = BasicResolver <Icmp>; using Socket = BasicDatagramSocket <Icmp>; /** * @brief create the icmp protocol instance. * @param family IP address family. */ constexpr Icmp (int family = AF_INET) noexcept : _family (family) { } /** * @brief get protocol suitable for IPv4 address family. * @return an IPv4 address family suitable protocol. */ static inline Icmp& v4 () noexcept { static Icmp icmpv4 (AF_INET); return icmpv4; } /** * @brief get protocol suitable for IPv6 address family. * @return an IPv6 address family suitable protocol. */ static inline Icmp& v6 () noexcept { static Icmp icmpv6 (AF_INET6); return icmpv6; } /** * @brief get the protocol IP address family. * @return the protocol IP address family. */ constexpr int family () const noexcept { return _family; } /** * @brief get the protocol communication semantic. * @return the protocol communication semantic. */ constexpr int type () const noexcept { return SOCK_RAW; } /** * @brief get the protocol type. * @return the protocol type. */ constexpr int protocol () const noexcept { if (family () == AF_INET6) { return int (IPPROTO_ICMPV6); } return IPPROTO_ICMP; } private: /// IP address family. int _family; }; /** * @brief check if equal. * @param a protocol to compare. * @param b protocol to compare to. * @return true if equal. */ constexpr bool operator== (const Icmp& a, const Icmp& b) noexcept { return a.family () == b.family (); } /** * @brief check if not equal. * @param a protocol to compare. * @param b protocol to compare to. * @return true if not equal. */ constexpr bool operator!= (const Icmp& a, const Icmp& b) noexcept { return !(a == b); } /** * @brief TCP protocol class. */ class Tcp { public: using Endpoint = BasicInternetEndpoint <Tcp>; using Resolver = BasicResolver <Tcp>; using Socket = BasicStreamSocket <Tcp>; using TlsSocket = BasicTlsSocket <Tcp>; using Acceptor = BasicStreamAcceptor <Tcp>; using TlsAcceptor = BasicTlsAcceptor <Tcp>; /** * @brief create the tcp protocol instance. * @param family IP address family. */ constexpr Tcp (int family = AF_INET) noexcept : _family (family) { } /** * @brief get protocol suitable for IPv4 address family. * @return an IPv4 address family suitable protocol. */ static inline Tcp& v4 () noexcept { static Tcp tcpv4 (AF_INET); return tcpv4; } /** * @brief get protocol suitable for IPv6 address family. * @return an IPv6 address family suitable protocol. */ static inline Tcp& v6 () noexcept { static Tcp tcpv6 (AF_INET6); return tcpv6; } /** * @brief get the protocol IP address family. * @return the protocol IP address family. */ constexpr int family () const noexcept { return _family; } /** * @brief get the protocol communication semantic. * @return the protocol communication semantic. */ constexpr int type () const noexcept { return SOCK_STREAM; } /** * @brief get the protocol type. * @return the protocol type. */ constexpr int protocol () const noexcept { return IPPROTO_TCP; } private: /// IP address family. int _family; }; /** * @brief Check if equals. * @param a protocol to check. * @param b protocol to check. * @return true if equals. */ constexpr bool operator== (const Tcp& a, const Tcp& b) noexcept { return a.family () == b.family (); } /** * @brief Check if not equals. * @param a protocol to check. * @param b protocol to check. * @return true if not equals. */ constexpr bool operator!= (const Tcp& a, const Tcp& b) noexcept { return !(a == b); } } #endif
25.896996
81
0.545409
mrabine
e5c208de8521f1f39ff879baf31058d17db8e27c
3,757
cpp
C++
board.cpp
marifdemirtas/minesweeper
4e49692a4af8edf75673d6e53f8dfa5b8c715a8c
[ "MIT" ]
null
null
null
board.cpp
marifdemirtas/minesweeper
4e49692a4af8edf75673d6e53f8dfa5b8c715a8c
[ "MIT" ]
null
null
null
board.cpp
marifdemirtas/minesweeper
4e49692a4af8edf75673d6e53f8dfa5b8c715a8c
[ "MIT" ]
null
null
null
#include <iostream> #include "board.h" using namespace std; /** * Constructor */ Board::Board(int row_count, int col_count) { board = new int*[row_count]; for (int i = 0; i < row_count; i++){ board[i] = new int[col_count]; for (int j = 0; j < col_count; j++){ board[i][j] = 0; } } mask = new char*[row_count]; for (int i = 0; i < row_count; i++){ mask[i] = new char[col_count]; for (int j = 0; j < col_count; j++){ mask[i][j] = '-'; } } this->row_count = row_count; this->col_count = col_count; this->safe_squares = row_count * col_count; } Board::~Board() { for (int i = 0; i < row_count; i++) { delete[] board[i]; delete[] mask[i]; } delete[] board; delete[] mask; } /** * Shows the board under the mask. * Shows value of square if mask is opened, else the symbol on the mask. */ void Board::showBoard(bool bombs) { for (int i = 0; i < row_count; i++){ for (int j = 0; j < col_count; j++){ if (mask[i][j] == '.'){ cout << board[i][j] << " "; } else { if (board[i][j] == 9 && bombs){ cout << board[i][j] << " "; } else { cout << mask[i][j] << " "; } } } cout << endl; } } /** * Places bomb at given coordinate * */ void Board::placeBomb(int x, int y) { if (x >= row_count || y >= col_count || x < 0 || y < 0){ throw out_of_range("Given coordinate is out of board"); } if (board[x][y] == 9){ throw domain_error("Already placed a bomb there"); } board[x][y] = 9; safe_squares--; incrementCell(x-1, y-1); incrementCell(x , y-1); incrementCell(x+1, y-1); incrementCell(x-1, y ); incrementCell(x+1, y ); incrementCell(x-1, y+1); incrementCell(x , y+1); incrementCell(x+1, y+1); } void Board::incrementCell(int x, int y){ if (x < row_count && y < col_count && (x >= 0 && y >= 0) && board[x][y] < 8){ board[x][y]++; } } bool Board::revealClick(int x, int y){ if (x >= row_count || y >= col_count || x < 0 || y < 0){ throw out_of_range("Given coordinate is out of board"); } if (mask[x][y] != '-'){ throw domain_error("Given coordinate is already revealed"); } if (board[x][y] == 9){ return true; } else { mask[x][y] = '.'; safe_squares--; if (board[x][y] == 0){ reveal(x-1, y-1); reveal(x , y-1); reveal(x+1, y-1); reveal(x-1, y ); reveal(x+1, y ); reveal(x-1, y+1); reveal(x , y+1); reveal(x+1, y+1); } return false; } } void Board::reveal(int x, int y){ if ((x < row_count && y < col_count) && (x >= 0 && y >= 0)){ if (mask[x][y] == '-'){ mask[x][y] = '.'; safe_squares--; if (board[x][y] == 0){ reveal(x-1, y-1); reveal(x , y-1); reveal(x+1, y-1); reveal(x-1, y ); reveal(x+1, y ); reveal(x-1, y+1); reveal(x , y+1); reveal(x+1, y+1); } } } } void Board::markBomb(int x, int y){ if (x >= row_count || y >= col_count || x < 0 || y < 0){ throw out_of_range("Given coordinate is out of board"); } if (mask[x][y] != '-'){ throw domain_error("Given coordinate is not hidden"); } if (mask[x][y] == '!') { mask[x][y] == '-'; } else { mask[x][y] = '!'; } }
23.929936
85
0.438914
marifdemirtas
e5c6aa0df0c94138ef97000c6627cd6ee4f8501d
1,259
hpp
C++
wrapper/stupid_iterator.hpp
TooBiased/growt
8b6bb4052763351b8799c392f0573da3efdd1e34
[ "BSD-2-Clause" ]
79
2016-10-13T17:42:53.000Z
2022-03-10T07:04:03.000Z
wrapper/stupid_iterator.hpp
TooBiased/growt
8b6bb4052763351b8799c392f0573da3efdd1e34
[ "BSD-2-Clause" ]
8
2016-10-07T14:03:50.000Z
2021-06-09T08:09:07.000Z
wrapper/stupid_iterator.hpp
TooBiased/growt
8b6bb4052763351b8799c392f0573da3efdd1e34
[ "BSD-2-Clause" ]
11
2018-09-29T11:32:13.000Z
2022-03-10T07:04:05.000Z
/******************************************************************************* * wrapper/junction_wrapper.h * * Wrapper to use junction's junction::ConcurrentMap_... in our benchmarks * use #define JUNCTION_TYPE junction::ConcurrentMap_Leapfrog to chose the table * * Part of Project growt - https://github.com/TooBiased/growt.git * * Copyright (C) 2015-2016 Tobias Maier <t.maier@kit.edu> * * All rights reserved. Published under the BSD-2 license in the LICENSE file. ******************************************************************************/ #pragma once #include <tuple> template <class K, class D> class StupidIterator { private: std::pair<K, D> pair; public: using key_type = K; using mapped_type = D; using value_type = std::pair<K, D>; using reference = value_type&; StupidIterator(const key_type& k = key_type(), const mapped_type& d = mapped_type()) : pair(k, d) { } const std::pair<K, D>& operator*() { return pair; } inline bool operator==(const StupidIterator& r) const { return pair.first == r.pair.first; } inline bool operator!=(const StupidIterator& r) const { return pair.first != r.pair.first; } };
27.369565
80
0.559174
TooBiased
e5c717fff21c427d9df41750f33789951afb75cb
4,427
cpp
C++
src/serial_port.cpp
NaokiTakahashi12/wit901c_rs485
a78e724145e9f8267d60f17336b5f69296529fa9
[ "MIT" ]
null
null
null
src/serial_port.cpp
NaokiTakahashi12/wit901c_rs485
a78e724145e9f8267d60f17336b5f69296529fa9
[ "MIT" ]
null
null
null
src/serial_port.cpp
NaokiTakahashi12/wit901c_rs485
a78e724145e9f8267d60f17336b5f69296529fa9
[ "MIT" ]
null
null
null
#include <wit901c_rs485/serial_port.hpp> #include <thread> #include <chrono> #include <Eigen/Dense> #include <boost/system/error_code.hpp> #include <boost/asio/io_service.hpp> #include <boost/asio/serial_port.hpp> #include <boost/asio/read.hpp> #include <boost/asio/write.hpp> namespace wit901c_rs485 { class SerialPort::Implementation { public : Implementation(const SerialPortOptions &options) { if(!options.port_name.empty()) { port_name = options.port_name; } else { port_name = "/dev/ttyUSB0"; } if(options.baud_rate != 0) { baud_rate = options.baud_rate; } else { baud_rate = 115200; } }; ~Implementation() { if(!serial_port && serial_port->is_open()) { serial_port->close(); } } Implementation(boost::asio::io_service &io_service, const SerialPortOptions &options) : Implementation(options) { serial_port = std::make_unique<boost::asio::serial_port>(io_service); } bool openSerialPort(const std::string &overwrite_port_name, const unsigned int &overwrite_baud_rate) { if(!serial_port) { throw std::runtime_error("serial_port is nullptr"); } boost::system::error_code ec; serial_port->open(overwrite_port_name, ec); std::this_thread::sleep_for(std::chrono::milliseconds(10)); if(ec) { return true; } serial_port->set_option(boost::asio::serial_port_base::baud_rate(overwrite_baud_rate)); return false; } void writeSerial(const std::string &wrt_msg) { if(!serial_port) { throw std::runtime_error("serial_port is nullptr"); } if(!serial_port->is_open()) { throw std::runtime_error("Serial port is not open"); } boost::asio::write( *serial_port, boost::asio::buffer( wrt_msg.data(), wrt_msg.size() ) ); } const std::string &readSerial(const unsigned int &packet_length) { static std::string read_msg; if(!serial_port) { throw std::runtime_error("serial_port is nullptr"); } if(!serial_port->is_open()) { throw std::runtime_error("Serial port is not open"); } uint8_t byte = 0; unsigned int counter = 0; read_msg.clear(); while(true) { boost::asio::read(*serial_port, boost::asio::buffer(&byte, 1)); read_msg += static_cast<char>(byte); counter ++; byte = 0; if(counter >= packet_length) { break; } } return read_msg; } std::string port_name; unsigned int baud_rate; static constexpr float gravity = 9.798; private : std::unique_ptr<boost::asio::serial_port> serial_port; }; SerialPort::SerialPort(const SerialPortOptions &options) { pimpl = std::make_unique<Implementation>(options); } SerialPort::SerialPort(boost::asio::io_service &io_service, const SerialPortOptions &options) { pimpl = std::make_unique<Implementation>(io_service, options); } SerialPort::~SerialPort() { } bool SerialPort::open() { return pimpl->openSerialPort(pimpl->port_name, pimpl->baud_rate); } bool SerialPort::open(const std::string &port_name, const unsigned int &baud_rate) { return pimpl->openSerialPort(port_name, baud_rate); } void SerialPort::write(const std::string &msg) { pimpl->writeSerial(msg); } std::string SerialPort::read(const unsigned int &packet_length) { return pimpl->readSerial(packet_length); } }
31.621429
114
0.510052
NaokiTakahashi12
e5c9444cde58149a53a5b2afd4155a8f065c0f25
707
cpp
C++
Baekjoon/13023.cpp
Twinparadox/AlgorithmProblem
0190d17555306600cfd439ad5d02a77e663c9a4e
[ "MIT" ]
null
null
null
Baekjoon/13023.cpp
Twinparadox/AlgorithmProblem
0190d17555306600cfd439ad5d02a77e663c9a4e
[ "MIT" ]
null
null
null
Baekjoon/13023.cpp
Twinparadox/AlgorithmProblem
0190d17555306600cfd439ad5d02a77e663c9a4e
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; vector<vector<int> > adj; vector<bool> check; int N, M, flag = 0; void dfs(int cur, int cnt) { if (cnt == 4) { flag = 1; return; } check[cur] = true; int size = adj[cur].size(); for (int i = 0; i < size; i++) { int next = adj[cur][i]; if (!check[next]) dfs(next, cnt + 1); if (flag) return; } check[cur] = false; } int main(void) { cin.tie(0); cout.tie(0); ios_base::sync_with_stdio(false); cin >> N >> M; adj.resize(N); check.resize(N, false); int s, e; for (int i = 0; i < M; i++) { cin >> s >> e; adj[s].push_back(e); adj[e].push_back(s); } for (int i = 0; i < N; i++) dfs(i, 0); cout << flag; }
14.428571
34
0.547383
Twinparadox
e5d5e5f4b98658eac0cf2f141408f4f74f8db09a
435
cpp
C++
src/OneKey/OneKey/HeroTask.cpp
xylsxyls/xueyelingshuan
61eb1c7c4f76c3eaf4cf26e4b2b37b6ed2abc5b9
[ "MIT" ]
3
2019-11-26T05:33:47.000Z
2020-05-18T06:49:41.000Z
src/OneKey/OneKey/HeroTask.cpp
xylsxyls/xueyelingshuan
61eb1c7c4f76c3eaf4cf26e4b2b37b6ed2abc5b9
[ "MIT" ]
null
null
null
src/OneKey/OneKey/HeroTask.cpp
xylsxyls/xueyelingshuan
61eb1c7c4f76c3eaf4cf26e4b2b37b6ed2abc5b9
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "HeroTask.h" #include "CKeyBoard/CKeyboardAPI.h" #include "D:\\SendToMessageTest.h" HeroTask::HeroTask(): m_code1(0), m_code2(0) { } void HeroTask::DoTask() { if (m_code1 != 0) { CKeyboard::KeyPress(m_code1, 0); } if (m_code2 != 0) { CKeyboard::KeyPress(m_code2, 0); } } void HeroTask::setParam(int32_t code1, int32_t code2) { m_code1 = code1; m_code2 = code2; }
15
54
0.627586
xylsxyls
e5dfd1ad9efbc76565f94871afa3f79f020134bf
914
hpp
C++
src/core/template.hpp
RamchandraApte/OmniTemplate
f150f451871b0ab43ac39a798186278106da1527
[ "MIT" ]
14
2019-04-23T21:44:12.000Z
2022-03-04T22:48:59.000Z
src/core/template.hpp
RamchandraApte/OmniTemplate
f150f451871b0ab43ac39a798186278106da1527
[ "MIT" ]
3
2019-04-25T10:45:32.000Z
2020-08-05T22:40:39.000Z
src/core/template.hpp
RamchandraApte/OmniTemplate
f150f451871b0ab43ac39a798186278106da1527
[ "MIT" ]
1
2020-07-16T22:16:33.000Z
2020-07-16T22:16:33.000Z
#pragma once #include "algebra/big_integer.hpp" #include "algebra/fft.hpp" #include "algebra/linear_algebra.hpp" #include "algebra/polynomial.hpp" #include "combinatorics/combinatorics.hpp" #include "combinatorics/permutation.hpp" #include "core/all.hpp" #include "core/main.hpp" #include "core/time.hpp" #include "ds/bit.hpp" #include "ds/cht.hpp" #include "ds/dsu.hpp" #include "ds/persistent.hpp" #include "ds/queue.hpp" #include "ds/segment_tree.hpp" #include "ds/sparse_table.hpp" #include "ds/splay_tree.hpp" #include "ds/treap.hpp" #include "graph/2sat.hpp" #include "graph/all.hpp" #include "graph/tree/hld.hpp" #include "graph/tree/link_cut.hpp" #include "graph/tree/tree.hpp" #include "number_theory/modulo.hpp" #include "number_theory/number_theory.hpp" #include "string/string.hpp" #include "utility.hpp" #include "utility/abbrev.hpp" #include "utility/coroutine.hpp" #include "utility/graph_draw.hpp"
28.5625
42
0.76477
RamchandraApte
e5f049beca1fb78b70071000c1a814969e9b54a8
1,881
cc
C++
dohboy/src/settings.cc
connectiblutz/dohboy
78601bf314e77bcb11970f8922cdc67f66857665
[ "MIT" ]
null
null
null
dohboy/src/settings.cc
connectiblutz/dohboy
78601bf314e77bcb11970f8922cdc67f66857665
[ "MIT" ]
null
null
null
dohboy/src/settings.cc
connectiblutz/dohboy
78601bf314e77bcb11970f8922cdc67f66857665
[ "MIT" ]
null
null
null
#include "settings.h" #include <bcl/fileutil.h> namespace dohboy { Settings Settings::instance; void Settings::load(std::string& target, cJSON* config, const std::string& name) { if (cJSON_HasObjectItem(config, name.c_str())) { cJSON* tmp = cJSON_GetObjectItem(config, name.c_str()); if (tmp && cJSON_IsString(tmp)) { target=cJSON_GetStringValue(tmp); } } } void Settings::load(bool& target, cJSON* config, const std::string& name) { if (cJSON_HasObjectItem(config, name.c_str())) { cJSON* tmp = cJSON_GetObjectItem(config, name.c_str()); if (tmp && cJSON_IsBool(tmp)) { target=cJSON_IsTrue(tmp); } } } void Settings::load(bcl::SocketAddress& target, cJSON* config, const std::string& name) { if (cJSON_HasObjectItem(config, name.c_str())) { cJSON* tmp = cJSON_GetObjectItem(config, name.c_str()); if (tmp && cJSON_IsString(tmp)) { target=bcl::SocketAddress(cJSON_GetStringValue(tmp)); } } } void Settings::load(bcl::IPAddress& target, cJSON* config, const std::string& name) { if (cJSON_HasObjectItem(config, name.c_str())) { cJSON* tmp = cJSON_GetObjectItem(config, name.c_str()); if (tmp && cJSON_IsString(tmp)) { target=bcl::IPAddress(cJSON_GetStringValue(tmp)); } } } void Settings::Set(const std::filesystem::path& file) { (void)(file); std::string configStr = bcl::FileUtil::FileToString(file); cJSON* configJson = cJSON_Parse(configStr.c_str()); Settings::load(instance.bindAddress,configJson,"bindAddress"); Settings::load(instance.domain,configJson,"domain"); Settings::load(instance.domainIP,configJson,"bindAddress"); Settings::load(instance.forceSingleThread,configJson,"forceSingleThread"); Settings::load(instance.localDomain,configJson,"localDomain"); Settings::load(instance.dhcpLeases,configJson,"dhcpLeases"); cJSON_free(configJson); } }
32.431034
91
0.699628
connectiblutz
e5f4468cbcdbf312f931dbaf6546bf5c3ce130b0
10,144
cc
C++
dfs/img_gzfile.cc
jamesyoungman/beebtools
3780a6f7fba9cdb18e1522720508ecc9a5efd1b6
[ "Apache-2.0" ]
4
2020-07-17T19:01:59.000Z
2020-07-19T21:36:41.000Z
dfs/img_gzfile.cc
jamesyoungman/beebtools
3780a6f7fba9cdb18e1522720508ecc9a5efd1b6
[ "Apache-2.0" ]
null
null
null
dfs/img_gzfile.cc
jamesyoungman/beebtools
3780a6f7fba9cdb18e1522720508ecc9a5efd1b6
[ "Apache-2.0" ]
1
2022-02-19T20:31:29.000Z
2022-02-19T20:31:29.000Z
// // Copyright 2020 James Youngman // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "media.h" // for make_decompressed_file #include <exception> // for exception #include <errno.h> // for errno #include <stdio.h> // for fread, FILE, fclose, ferror, fopen, fseek #include <stdlib.h> // for free #include <string.h> // for memset, strdup #include <zconf.h> // for MAX_WBITS #include <zlib.h> // for z_stream, Z_NULL, Z_STREAM_END, gz_header #include <functional> // for function #include <limits> // for numeric_limits #include <memory> // for make_unique, unique_ptr #include <string> // for string, allocator, operator+ #include <vector> // for vector #include "abstractio.h" // for FileAccess, SectorBuffer #include "cleanup.h" // for cleanup #include "dfstypes.h" // for byte #include "exceptions.h" // for FileIOError, NonFileOsError namespace { using std::numeric_limits; using DFS::DataAccess; using DFS::SectorBuffer; using DFS::NonFileOsError; using DFS::FileIOError; class FixedDecompressionError : public std::exception { public: explicit FixedDecompressionError(const char *msg) : msg_(strdup(msg)) { } ~FixedDecompressionError() { free(msg_); } const char *what() const noexcept { return msg_; } private: char *msg_; }; class OutOfMemoryError : public std::exception { public: OutOfMemoryError() {} const char *what() const noexcept { return "not enough available memory"; } }; const OutOfMemoryError out_of_memory; class DecompressionError : public std::exception { public: explicit DecompressionError(gzFile f) : msg_(get_err(f)) { } static std::string get_err(gzFile f) { int dummy; return std::string(gzerror(f, &dummy)); } const char *what() const noexcept { return msg_.c_str(); } private: std::string msg_; }; void check_zlib_error_code(int zerr) { switch (zerr) { case Z_OK: return; case Z_STREAM_END: // We should never see this case, because the loop in which // we call inflate should terminate when we see Z_STREAM_END // without callign check_zlib_error_code(). throw FixedDecompressionError("reached end of comressed data"); case Z_NEED_DICT: // I don't think this occurs in gzip-formatted inputs, // which is all we support. throw FixedDecompressionError("a pre-set zlib dictionary is required " "to decompress this data"); case Z_ERRNO: // This is not a file I/O error because zlib isn't performing the // file I/O. throw DFS::NonFileOsError(errno); case Z_STREAM_ERROR: // This generally means that the data in the z_stream struct // is inconsistent with the data in the incoming stream, or // bad parameters were passed to a zlib gunction. It seems // hard to reproduce these problems in a correct program. throw FixedDecompressionError("invalid compressed data stream or " "inconsistent program state (i.e. bug)"); case Z_DATA_ERROR: throw FixedDecompressionError("input data was corrupted, " "are you sure it was created with gzip?"); case Z_MEM_ERROR: throw out_of_memory; // avoids allocation case Z_BUF_ERROR: throw FixedDecompressionError("compressed input is incomplete"); case Z_VERSION_ERROR: throw FixedDecompressionError("incompatible version of zlib"); default: throw FixedDecompressionError("unknown decompression error"); } } void write_decompressed_data(const std::string& name, FILE* fout) { errno = 0; // We use both a local buffer for zlib and a stdio buffer here. // See the comment at input_buf_size for an explanation. Before // moving this declaration, note that this must live longer than // the FILE object which references it. std::vector<char> readbuf(32768, '\0'); FILE *f = fopen(name.c_str(), "rb"); if (0 == f) { throw DFS::FileIOError(name, errno); } // NOTE: We rely on C++ destroying |closer| (which closes f) // before destroying |readbuf| (which f holds a pointer to). // Section 6.6 [stmt.jump] of the ISO C++ 2003 standard specifies // that objects with automatic storage duration are destroyed in // reverse order of their declaration. // // NOTE: the capture for readbuf in the lambda used by closer is // there so that we get a compiler error if the declaration (and // thus destruction) order becomes incorrect. cleanup closer([&f, &name, &readbuf]() { (void)readbuf; // see NOTE above errno = 0; if (EOF == fclose(f)) { throw DFS::FileIOError(name, errno); } }); setbuffer(f, readbuf.data(), readbuf.size()); gz_header header; memset(&header, 0, sizeof(header)); z_stream stream; memset(&stream, 0, sizeof(stream)); stream.zalloc = Z_NULL; stream.zfree = Z_NULL; stream.opaque = Z_NULL; stream.avail_in = 0; stream.next_in = Z_NULL; // We're decompressing a foo.gz file, so permit only gzip-compressed streams // by passing 16+MAX_WBITS as the second arg to inflateInit2. int zerr = inflateInit2(&stream, 16+MAX_WBITS); check_zlib_error_code(zerr); cleanup de_init([&stream]() { check_zlib_error_code(inflateEnd(&stream)); }); // Signal that we want zlib to check for and extract the gzip // header. header.done = 0; check_zlib_error_code(inflateGetHeader(&stream, &header)); // If input_buf_size (and the stdio buffer size) is too small, we // perform too many read operations. But keeping input_buf_size // low ensures that we handle all the various cases around buffer // filling and emptying. Therefore to avoid input_buf_size // causing I/O read performance problems, we use a large stdio // buffer. const int input_buf_size = 512; // If output_buf_size is too small, we just call inflate() too // many times. const int output_buf_size = 1024; unsigned char input_buffer[input_buf_size]; // zlib's inflate() requires to be able to write to a contiguous // buffer, so we have to provide one. unsigned char output_buffer[output_buf_size]; // These static assertions ensure that the static casts within the // loop are safe. typedef decltype(stream.avail_in) avail_in_type; static_assert(input_buf_size <= std::numeric_limits<decltype(stream.avail_in)>::max()); static_assert(output_buf_size <= std::numeric_limits<decltype(stream.avail_out)>::max()); zerr = Z_OK; while (zerr != Z_STREAM_END) { errno = 0; auto got = stream.avail_in = static_cast<avail_in_type>(fread(input_buffer, 1, input_buf_size, f)); if (ferror(f)) { throw DFS::FileIOError(name, errno); } // We rely on zlib to detect the end of the input stream. If // there is no more input here we will pass avail_in=0 to // inflate() which tells it there is no more input. If that // means the input is incomplete, it will return zerr != Z_OK // and we will issue a diagnostic. However, if we were // reading a file compressed with compress(1) (e.g. foo.ssd.Z) // then we might have to recognise the end of the input stream // with physical EOF. I don't think it's possible to identify // when a foo.Z file has been truncated. stream.next_in = input_buffer; do // decompress some data from the input buffer. { stream.next_out = output_buffer; stream.avail_out = output_buf_size; zerr = inflate(&stream, Z_NO_FLUSH); const size_t bytes_to_write = output_buf_size - stream.avail_out; errno = 0; const size_t bytes_written = fwrite(output_buffer, 1, bytes_to_write, fout); if (bytes_written != bytes_to_write) throw DFS::FileIOError(name, errno); if (zerr == Z_BUF_ERROR && got) { // Want more input data. break; } if (zerr != Z_STREAM_END) check_zlib_error_code(zerr); } while (stream.avail_out == 0); } } FILE* open_temporary_file() { errno = 0; return tmpfile(); } class DecompressedFile : public DFS::FileAccess { public: explicit DecompressedFile(const std::string& name); virtual ~DecompressedFile(); std::vector<DFS::byte> read(unsigned long pos, unsigned long len) override; private: FILE *f_; std::string name_; }; DecompressedFile::DecompressedFile(const std::string& name) : f_(open_temporary_file()), name_(std::string("decompressed version of " + name)) { if (0 == f_) throw new NonFileOsError(errno); write_decompressed_data(name, f_); } DecompressedFile::~DecompressedFile() { } std::vector<DFS::byte> DecompressedFile::read(unsigned long pos, unsigned long len) { auto fail = [this]() -> std::vector<DFS::byte> { if (errno) throw FileIOError(name_, errno); else return std::vector<DFS::byte>(); }; errno = 0; if (0 != fseek(f_, pos, SEEK_SET)) return fail(); std::vector<DFS::byte> buf; buf.resize(len); const size_t bytes_read = fread(buf.data(), 1, buf.size(), f_); if (bytes_read == 0) return fail(); buf.resize(bytes_read); return buf; } } // namespace namespace DFS { std::unique_ptr<FileAccess> make_decompressed_file(const std::string& name) { return std::make_unique<DecompressedFile>(name); } } // namespace DFS
31.116564
100
0.661869
jamesyoungman
f901c2418c65937bb4727d46b735e344b541b490
3,976
cpp
C++
genetics/shared/geometry/ObjShape.cpp
crest01/ShapeGenetics
7321f6484be668317ad763c0ca5e4d6cbfef8cd1
[ "MIT" ]
18
2017-04-26T13:53:43.000Z
2021-05-29T03:55:27.000Z
genetics/shared/geometry/ObjShape.cpp
crest01/ShapeGenetics
7321f6484be668317ad763c0ca5e4d6cbfef8cd1
[ "MIT" ]
null
null
null
genetics/shared/geometry/ObjShape.cpp
crest01/ShapeGenetics
7321f6484be668317ad763c0ca5e4d6cbfef8cd1
[ "MIT" ]
2
2017-10-17T10:32:01.000Z
2019-11-11T07:23:54.000Z
#include "ObjShape.h" #include <fstream> #include <iostream> namespace PGA { void ObjShape::normalizeShape() { if (v.size() == 0) { return; } math::float3 center; math::float3 min; math::float3 max; center = v[0]; min = center; max = center; for (int i = 1; i < v.size(); ++i) { center += v[i]; if (min.x > v[i].x) { min.x = v[i].x; } if (min.y > v[i].y) { min.y = v[i].y; } if (min.z > v[i].z) { min.z = v[i].z; } if (max.x < v[i].x) { max.x = v[i].x; } if (max.y < v[i].y) { max.y = v[i].y; } if (max.z < v[i].z) { max.z = v[i].z; } } center = center / v.size(); math::float4x4 transform = math::identity<math::float4x4>(); transform._14 = center.x * -1.0f; transform._24 = center.y * -1.0f; transform._34 = center.z * -1.0f; math::float3 size(max - min); math::float3 scale(1.0f/size.x, 1.0f/size.y, 1.0f/size.z); transform._11 = transform._11 * scale.x; transform._22 = transform._22 * scale.y; transform._33 = transform._33 * scale.z; for (int i = 0; i < v.size(); ++i) { math::float4 p(v[i].x, v[i].y, v[i].z, 1.0f); p = transform * p; v[i] = math::float3(p.x/p.w, p.y/p.w, p.z/p.w); } // todo: update the normals as well? } void ObjShape::applyMatrixToObj(const math::float3x4& m) { for (int i = 0; i < v.size(); ++i) { v[i] = m*math::float4(v[i], 1.0f); } for (int i = 0; i < vn.size(); ++i) { vn[i] = normalize(m*math::float4(vn[i], 0.0f)); } } int ObjShape::writeVertsToFile(std::ofstream& out) { for (int i = 0; i < v.size(); ++i) { out << "v " << v[i].x << " " << v[i].y << " " << v[i].z << std::endl; } return v.size(); } int ObjShape::writeNormToFile(std::ofstream& out) { for (int i = 0; i < vn.size(); ++i) { out << "vn " << vn[i].x << " " << vn[i].y << " " << vn[i].z << std::endl; } return vn.size(); } int ObjShape::writeTexToFile(std::ofstream& out) { for (int i = 0; i < vt.size(); ++i) { out << "vt " << vt[i].x << " " << vt[i].y << std::endl; } return vt.size(); } int ObjShape::writeFaceToFile(std::ofstream& out) { for (int i = 0; i < f.size(); ++i) { out << "f "; for (int j = 0; j < 3; ++j) { out << f[i].v[j] + v_off << "/" << f[i].t[j] + t_off << "/" << f[i].n[j] + n_off << " "; } out << std::endl; } return f.size(); } void ObjShape::createVerticesForOpenGL() { for (int face = 0; face < f.size(); ++face) { GeneratedVertex verts[3]; for (int i = 0; i < 3; ++i) { verts[i] = GeneratedVertex(v[f[face].v[i] - 1], vn[f[face].n[i] - 1], vt[f[face].t[i] - 1]); } math::float3 obj_n = (verts[0].n + verts[1].n + verts[2].n) / 3.0f; float direction = dot(cross(verts[0].p - verts[1].p, verts[0].p - verts[2].p),obj_n); if (direction > 0) { for (int i = 2; i >= 0; --i) { vertices.push_back(verts[i]); } } else { for (int i = 0; i <= 2; ++i) { vertices.push_back(verts[i]); } } } } bool ObjShape::readFromFile(const std::string& filename) { std::ifstream file(filename); if (!file) { std::cout << "unable to open mesh file '" << filename << "'" << std::endl; return false; } std::cout << "reading from file " << filename << std::endl; std::string cmd; while (file >> cmd) { if (cmd[0] == '#') { while (file && file.get() != '\n'); } else if (cmd == "v") { math::float3 p; file >> p.x >> p.y >> p.z; v.push_back(p); } else if (cmd == "vn") { math::float3 n; file >> n.x >> n.y >> n.z; vn.push_back(n); } else if (cmd == "vt") { math::float2 t; file >> t.x >> t.y; vt.push_back(t); } else if (cmd == "f") { Face face; for (int i = 0; i < 3; ++i) { int indices[3]; // TODO: this only works if the file has verts/texture/norms for each face vertex for (int j = 0; j < 3; ++j) { file >> indices[j]; file.get(); } face.v[i] = indices[0]; face.t[i] = indices[1]; face.n[i] = indices[2]; } f.push_back(face); } } return true; } } // namespace PGA
20.080808
95
0.51333
crest01
f902e446e98e7b31e63ee30763abca9fb7640976
1,541
hpp
C++
src/dam/matrix4f.hpp
delveam/chess
2c1e8582b73cb59d71e14a50f671d4ccbac34b95
[ "MIT" ]
null
null
null
src/dam/matrix4f.hpp
delveam/chess
2c1e8582b73cb59d71e14a50f671d4ccbac34b95
[ "MIT" ]
1
2021-07-25T15:54:27.000Z
2021-07-25T15:54:27.000Z
src/dam/matrix4f.hpp
delveam/chess
2c1e8582b73cb59d71e14a50f671d4ccbac34b95
[ "MIT" ]
null
null
null
#ifndef DAM_MATRIX4_HPP #define DAM_MATRIX4_HPP #include <array> namespace dam { class Matrix4F; } class dam::Matrix4F { public: Matrix4F() = default; Matrix4F(std::array<float, 16> data) : m_data(data) { } unsigned int rows() const { return m_rows; } unsigned int columns() const { return m_columns; } const std::array<float, 16>& data() const { return m_data; } float get(unsigned int x, unsigned int y) const; void set(unsigned int x, unsigned int y, float value); void set_data(std::array<float, 16>); void debug(); static Matrix4F identity(); static Matrix4F transpose(Matrix4F matrix); static Matrix4F add(Matrix4F a, Matrix4F b); static Matrix4F subtract(Matrix4F a, Matrix4F b); static Matrix4F multiply(Matrix4F a, Matrix4F b); static Matrix4F add_scalar(Matrix4F matrix, float scalar); static Matrix4F subtract_scalar(Matrix4F matrix, float scalar); static Matrix4F multiply_scalar(Matrix4F matrix, float scalar); static Matrix4F divide_scalar(Matrix4F matrix, float scalar); static Matrix4F create_rotation_x(float angle); static Matrix4F create_rotation_y(float angle); static Matrix4F create_rotation_z(float angle); static Matrix4F create_translation(float x, float y, float z); static Matrix4F create_scale(float x, float y, float z); private: const unsigned int m_rows { 4 }; const unsigned int m_columns { 4 }; std::array<float, 16> m_data; }; #endif
28.018182
67
0.687865
delveam
f9059fc7656e2fd4b795effcc2d844a182e305b0
1,510
cpp
C++
src/main.cpp
saeenyoda/Hash_Table
b014e76c2089a7d4159c1f9ec55442de5ce41511
[ "MIT", "Unlicense" ]
null
null
null
src/main.cpp
saeenyoda/Hash_Table
b014e76c2089a7d4159c1f9ec55442de5ce41511
[ "MIT", "Unlicense" ]
null
null
null
src/main.cpp
saeenyoda/Hash_Table
b014e76c2089a7d4159c1f9ec55442de5ce41511
[ "MIT", "Unlicense" ]
null
null
null
#include "util.h" int main() { HashTable<int, File> table(1000); std::cout << "Welcome to our Repo!\n\n"; int in = 0; bool flag = false; while (!flag) { std::cout << "\n"; menu(); in = input(); system("cls"); switch (in) { default: break; case 1: load_file(table); break; case 2: { int f_id; std::cout << "Input file ID: "; std::cin >> f_id; if (table.insert(f_id, File(f_id))) std::cout << "File inserted!\n"; else std::cout << "File Already exists!\n"; break; } case 3: { int id; std::cout << "Input file ID: "; std::cin >> id; auto val = table[id]; if (!val) std::cout << "File doesn't exist!\n"; else if (val && table[id].value().get().isFree()) { table.remove(id); std::cout << "File has been removed!\n"; } else std::cout << "File is being used!\n"; break; } case 4: access_file(table); break; case 5: { int fid; std::cout << "Input file ID: "; std::cin >> fid; auto val = table[fid]; if (!val) { std::cout << "No such file!\n"; break; } int uid; std::cout << "\nInput user ID: "; std::cin >> uid; bool ac = val.value().get().release_access(uid); if (ac) std::cout << "Released access to File: " << fid << " for User: " << uid << "\n"; else std::cout << "No such User is currently accessing the file!\n"; break; } case 6: table.print(); break; case 7: flag = true; break; } } system("pause"); }
16.413043
84
0.523179
saeenyoda
f907a8a9b57ab0202d85faa7f61207a4dc8d05e7
8,268
hpp
C++
optionals/arcadian/base/config_sound.hpp
JeffPerk/HavocTeam
6fb616c41da4baece79ebac941bac72a78c715f9
[ "MIT" ]
null
null
null
optionals/arcadian/base/config_sound.hpp
JeffPerk/HavocTeam
6fb616c41da4baece79ebac941bac72a78c715f9
[ "MIT" ]
7
2021-11-22T04:36:52.000Z
2021-12-13T18:55:24.000Z
optionals/arcadian/base/config_sound.hpp
JeffPerk/HavocTeam
6fb616c41da4baece79ebac941bac72a78c715f9
[ "MIT" ]
null
null
null
attenuationEffectType = "CarAttenuation"; soundGetIn[] = {"A3\Sounds_F\vehicles2\soft\Mrap_01\Mrap_01_Enter", 0.44, 1}; soundGetOut[] = {"A3\Sounds_F\vehicles2\soft\Mrap_01\Mrap_01_Exit", 0.44, 1, 40}; soundDammage[] = {"", 0.56, 1}; insideSoundCoef = 1; buildCrash0[] = {"A3\Sounds_F\vehicles2\soft\shared\collisions\Vehicle_Soft_Collision_Medium_01", 1.99, 1,75}; buildCrash1[] = {"A3\Sounds_F\vehicles2\soft\shared\collisions\Vehicle_Soft_Collision_Medium_02", 1.99, 1,75}; buildCrash2[] = {"A3\Sounds_F\vehicles2\soft\shared\collisions\Vehicle_Soft_Collision_Medium_03", 1.99, 1,75}; buildCrash3[] = {"A3\Sounds_F\vehicles2\soft\shared\collisions\Vehicle_Soft_Collision_Medium_04", 1.99, 1,75}; buildCrash4[] = {"A3\Sounds_F\vehicles2\soft\shared\collisions\Vehicle_Soft_Collision_Medium_05", 1.99, 1,75}; buildCrash5[] = {"A3\Sounds_F\vehicles2\soft\shared\collisions\Vehicle_Soft_Collision_Medium_06", 1.99, 1,75}; buildCrash6[] = {"A3\Sounds_F\vehicles2\soft\shared\collisions\Vehicle_Soft_Collision_Medium_07", 1.99, 1,75}; buildCrash7[] = {"A3\Sounds_F\vehicles2\soft\shared\collisions\Vehicle_Soft_Collision_Medium_08", 1.99, 1,75}; soundBuildingCrash[] = { "buildCrash0", 0.125, "buildCrash1", 0.125, "buildCrash2", 0.125, "buildCrash3", 0.125, "buildCrash4", 0.125, "buildCrash5", 0.125, "buildCrash6", 0.125, "buildCrash7", 0.125 }; BushCrash1[] = {"A3\Sounds_F\vehicles2\soft\shared\collisions\Vehicle_Soft_Collision_Light_Bush_01", 0.63, 1, 50}; BushCrash2[] = {"A3\Sounds_F\vehicles2\soft\shared\collisions\Vehicle_Soft_Collision_Light_Bush_02", 0.63, 1, 50}; BushCrash3[] = {"A3\Sounds_F\vehicles2\soft\shared\collisions\Vehicle_Soft_Collision_Light_Bush_03", 0.63, 1, 50}; BushCrash4[] = {"A3\Sounds_F\vehicles2\soft\shared\collisions\Vehicle_Soft_Collision_Light_Bush_03", 0.63, 0.8, 50}; soundBushCrash[] = { "BushCrash1", 0.25, "BushCrash2", 0.25, "BushCrash3", 0.25, "BushCrash4", 0.25 }; WoodCrash0[] = {"A3\Sounds_F\vehicles2\soft\shared\collisions\Vehicle_Soft_Collision_Medium_Wood_01", 1.99,1,75}; WoodCrash1[] = {"A3\Sounds_F\vehicles2\soft\shared\collisions\Vehicle_Soft_Collision_Medium_Wood_02", 1.99,1,75}; WoodCrash2[] = {"A3\Sounds_F\vehicles2\soft\shared\collisions\Vehicle_Soft_Collision_Medium_Wood_03", 1.99,1,75}; WoodCrash3[] = {"A3\Sounds_F\vehicles2\soft\shared\collisions\Vehicle_Soft_Collision_Medium_Wood_04", 1.99,1,75}; WoodCrash4[] = {"A3\Sounds_F\vehicles2\soft\shared\collisions\Vehicle_Soft_Collision_Medium_Wood_05", 1.99,1,75}; WoodCrash5[] = {"A3\Sounds_F\vehicles2\soft\shared\collisions\Vehicle_Soft_Collision_Medium_Wood_06", 1.99,1,75}; WoodCrash6[] = {"A3\Sounds_F\vehicles2\soft\shared\collisions\Vehicle_Soft_Collision_Medium_Wood_07", 1.99,1,75}; WoodCrash7[] = {"A3\Sounds_F\vehicles2\soft\shared\collisions\Vehicle_Soft_Collision_Medium_Wood_08", 1.99,1,75}; soundWoodCrash[] = { "woodCrash0", 0.125, "woodCrash1", 0.125, "woodCrash2", 0.125, "woodCrash3", 0.125, "woodCrash4", 0.125, "woodCrash5", 0.125, "woodCrash6", 0.125, "woodCrash7", 0.125 }; armorCrash0[] = {"A3\Sounds_F\vehicles2\soft\shared\collisions\Vehicle_Soft_Collision_Medium_01", 1.99, 1,75}; armorCrash1[] = {"A3\Sounds_F\vehicles2\soft\shared\collisions\Vehicle_Soft_Collision_Medium_02", 1.99, 1,75}; armorCrash2[] = {"A3\Sounds_F\vehicles2\soft\shared\collisions\Vehicle_Soft_Collision_Medium_03", 1.99, 1,75}; armorCrash3[] = {"A3\Sounds_F\vehicles2\soft\shared\collisions\Vehicle_Soft_Collision_Medium_04", 1.99, 1,75}; armorCrash4[] = {"A3\Sounds_F\vehicles2\soft\shared\collisions\Vehicle_Soft_Collision_Medium_05", 1.99, 1,75}; armorCrash5[] = {"A3\Sounds_F\vehicles2\soft\shared\collisions\Vehicle_Soft_Collision_Medium_06", 1.99, 1,75}; armorCrash6[] = {"A3\Sounds_F\vehicles2\soft\shared\collisions\Vehicle_Soft_Collision_Medium_07", 1.99, 1,75}; armorCrash7[] = {"A3\Sounds_F\vehicles2\soft\shared\collisions\Vehicle_Soft_Collision_Medium_08", 1.99, 1,75}; soundArmorCrash[] = { "ArmorCrash0", 0.125, "ArmorCrash1", 0.125, "ArmorCrash2", 0.125, "ArmorCrash3", 0.125, "ArmorCrash4", 0.125, "ArmorCrash5", 0.125, "ArmorCrash6", 0.125, "ArmorCrash7", 0.125 }; Crash0[] = {"A3\Sounds_F\vehicles2\soft\shared\collisions\Vehicle_Soft_Collision_Medium_01", 1.99, 1, 75}; Crash1[] = {"A3\Sounds_F\vehicles2\soft\shared\collisions\Vehicle_Soft_Collision_Medium_02", 1.99, 1, 75}; Crash2[] = {"A3\Sounds_F\vehicles2\soft\shared\collisions\Vehicle_Soft_Collision_Medium_03", 1.99, 1, 75}; Crash3[] = {"A3\Sounds_F\vehicles2\soft\shared\collisions\Vehicle_Soft_Collision_Medium_04", 1.99, 1, 75}; Crash4[] = {"A3\Sounds_F\vehicles2\soft\shared\collisions\Vehicle_Soft_Collision_Medium_05", 1.99, 1, 75}; Crash5[] = {"A3\Sounds_F\vehicles2\soft\shared\collisions\Vehicle_Soft_Collision_Medium_06", 1.99, 1, 75}; Crash6[] = {"A3\Sounds_F\vehicles2\soft\shared\collisions\Vehicle_Soft_Collision_Medium_07", 1.99, 1, 75}; Crash7[] = {"A3\Sounds_F\vehicles2\soft\shared\collisions\Vehicle_Soft_Collision_Medium_08", 1.99, 1, 75}; soundCrashes[] = { "Crash0", 0.125, "Crash1", 0.125, "Crash2", 0.125, "Crash3", 0.125, "Crash4", 0.125, "Crash5", 0.125, "Crash6", 0.125, "Crash7", 0.125 }; // Engine on/off sounds (Source: Vanilla Hunter) soundEngineOnInt[] = {"A3\Sounds_F\vehicles2\soft\Mrap_01\Mrap_01_Engine_Int_Start", 0.63, 1}; soundEngineOnExt[] = {"A3\Sounds_F\vehicles2\soft\Mrap_01\Mrap_01_Engine_Ext_Start", 1.99, 1, 50}; soundEngineOffInt[] = {"A3\Sounds_F\vehicles2\soft\Mrap_01\Mrap_01_Engine_Int_stop", 0.5, 1}; soundEngineOffExt[] = {"A3\Sounds_F\vehicles2\soft\Mrap_01\Mrap_01_Engine_Ext_stop", 1.99, 1, 50}; class Sounds { soundSetsInt[] = { "Offroad_01_Engine_RPM0_INT_SoundSet", "Offroad_01_Engine_RPM1_INT_SoundSet", "Offroad_01_Engine_RPM2_INT_SoundSet", "Offroad_01_Engine_RPM3_INT_SoundSet", "Offroad_01_Engine_RPM4_INT_SoundSet", "Mrap_01_Rattling_INT_SoundSet", "", "Mrap_01_Rain_INT_SoundSet", "Mrap_01_Tires_Rock_Fast_INT_SoundSet", "Mrap_01_Tires_Grass_Fast_INT_SoundSet", "Mrap_01_Tires_Sand_Fast_INT_SoundSet", "Mrap_01_Tires_Gravel_Fast_INT_SoundSet", "Mrap_01_Tires_Mud_Fast_INT_SoundSet", "Mrap_01_Tires_Asphalt_Fast_INT_SoundSet", "Mrap_01_Tires_Water_Fast_INT_SoundSet", "Mrap_01_Tires_Rock_Slow_INT_SoundSet", "Mrap_01_Tires_Grass_Slow_INT_SoundSet", "Mrap_01_Tires_Sand_Slow_INT_SoundSet", "Mrap_01_Tires_Gravel_Slow_INT_SoundSet", "Mrap_01_Tires_Mud_Slow_INT_SoundSet", "Mrap_01_Tires_Asphalt_Slow_INT_SoundSet", "Mrap_01_Tires_Water_Slow_INT_SoundSet", "Mrap_01_Tires_Turn_Hard_INT_SoundSet", "Mrap_01_Tires_Turn_Soft_INT_SoundSet", "Mrap_01_Tires_Brake_Hard_INT_SoundSet", "Mrap_01_Tires_Brake_Soft_INT_SoundSet", "", "Tires_Movement_Dirt_Int_01_SoundSet" }; soundSetsExt[] = { "Offroad_01_Engine_RPM0_EXT_SoundSet", "Offroad_01_Engine_RPM1_EXT_SoundSet", "Offroad_01_Engine_RPM2_EXT_SoundSet", "Offroad_01_Engine_RPM3_EXT_SoundSet", "Offroad_01_Engine_RPM4_EXT_SoundSet", "", "Mrap_01_Rain_EXT_SoundSet", "Mrap_01_Tires_Rock_Fast_EXT_SoundSet", "Mrap_01_Tires_Grass_Fast_EXT_SoundSet", "Mrap_01_Tires_Sand_Fast_EXT_SoundSet", "Mrap_01_Tires_Gravel_Fast_EXT_SoundSet", "Mrap_01_Tires_Mud_Fast_EXT_SoundSet", "Mrap_01_Tires_Asphalt_Fast_EXT_SoundSet", "Mrap_01_Tires_Water_Fast_EXT_SoundSet", "Mrap_01_Tires_Rock_Slow_EXT_SoundSet", "Mrap_01_Tires_Grass_Slow_EXT_SoundSet", "Mrap_01_Tires_Sand_Slow_EXT_SoundSet", "Mrap_01_Tires_Gravel_Slow_EXT_SoundSet", "Mrap_01_Tires_Mud_Slow_EXT_SoundSet", "Mrap_01_Tires_Asphalt_Slow_EXT_SoundSet", "Mrap_01_Tires_Water_Slow_EXT_SoundSet", "Mrap_01_Tires_Turn_Hard_EXT_SoundSet", "Mrap_01_Tires_Turn_Soft_EXT_SoundSet", "Mrap_01_Tires_Brake_Hard_EXT_SoundSet", "Mrap_01_Tires_Brake_Soft_EXT_SoundSet", "", "Tires_Movement_Dirt_Ext_01_SoundSet" }; };
49.214286
116
0.73851
JeffPerk
f9081e05578584029a42cbdd9f3584ac056a9114
8,627
cpp
C++
MonoNative.Tests/mscorlib/System/Reflection/mscorlib_System_Reflection_AssemblyName_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
7
2015-03-10T03:36:16.000Z
2021-11-05T01:16:58.000Z
MonoNative.Tests/mscorlib/System/Reflection/mscorlib_System_Reflection_AssemblyName_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
1
2020-06-23T10:02:33.000Z
2020-06-24T02:05:47.000Z
MonoNative.Tests/mscorlib/System/Reflection/mscorlib_System_Reflection_AssemblyName_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
null
null
null
// Mono Native Fixture // Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // Namespace: System.Reflection // Name: AssemblyName // C++ Typed Name: mscorlib::System::Reflection::AssemblyName #include <gtest/gtest.h> #include <mscorlib/System/Reflection/mscorlib_System_Reflection_AssemblyName.h> #include <mscorlib/System/Globalization/mscorlib_System_Globalization_CultureInfo.h> #include <mscorlib/System/Reflection/mscorlib_System_Reflection_StrongNameKeyPair.h> #include <mscorlib/System/mscorlib_System_Version.h> #include <mscorlib/System/mscorlib_System_Byte.h> #include <mscorlib/System/Runtime/Serialization/mscorlib_System_Runtime_Serialization_SerializationInfo.h> #include <mscorlib/System/Runtime/Serialization/mscorlib_System_Runtime_Serialization_StreamingContext.h> #include <mscorlib/System/mscorlib_System_Type.h> namespace mscorlib { namespace System { namespace Reflection { //Constructors Tests //AssemblyName() TEST(mscorlib_System_Reflection_AssemblyName_Fixture,DefaultConstructor) { mscorlib::System::Reflection::AssemblyName *value = new mscorlib::System::Reflection::AssemblyName(); EXPECT_NE(NULL, value->GetNativeObject()); } //AssemblyName(mscorlib::System::String assemblyName) TEST(mscorlib_System_Reflection_AssemblyName_Fixture,Constructor_2) { mscorlib::System::Reflection::AssemblyName *value = new mscorlib::System::Reflection::AssemblyName(); EXPECT_NE(NULL, value->GetNativeObject()); } //Public Methods Tests // Method ToString // Signature: TEST(mscorlib_System_Reflection_AssemblyName_Fixture,ToString_Test) { } // Method GetPublicKey // Signature: TEST(mscorlib_System_Reflection_AssemblyName_Fixture,GetPublicKey_Test) { } // Method GetPublicKeyToken // Signature: TEST(mscorlib_System_Reflection_AssemblyName_Fixture,GetPublicKeyToken_Test) { } // Method SetPublicKey // Signature: std::vector<mscorlib::System::Byte*> publicKey TEST(mscorlib_System_Reflection_AssemblyName_Fixture,SetPublicKey_Test) { } // Method SetPublicKeyToken // Signature: std::vector<mscorlib::System::Byte*> publicKeyToken TEST(mscorlib_System_Reflection_AssemblyName_Fixture,SetPublicKeyToken_Test) { } // Method GetObjectData // Signature: mscorlib::System::Runtime::Serialization::SerializationInfo info, mscorlib::System::Runtime::Serialization::StreamingContext context TEST(mscorlib_System_Reflection_AssemblyName_Fixture,GetObjectData_Test) { } // Method Clone // Signature: TEST(mscorlib_System_Reflection_AssemblyName_Fixture,Clone_Test) { } // Method OnDeserialization // Signature: mscorlib::System::Object sender TEST(mscorlib_System_Reflection_AssemblyName_Fixture,OnDeserialization_Test) { } //Public Static Methods Tests // Method ReferenceMatchesDefinition // Signature: mscorlib::System::Reflection::AssemblyName reference, mscorlib::System::Reflection::AssemblyName definition TEST(mscorlib_System_Reflection_AssemblyName_Fixture,ReferenceMatchesDefinition_StaticTest) { } // Method GetAssemblyName // Signature: mscorlib::System::String assemblyFile TEST(mscorlib_System_Reflection_AssemblyName_Fixture,GetAssemblyName_StaticTest) { } //Public Properties Tests // Property ProcessorArchitecture // Return Type: mscorlib::System::Reflection::ProcessorArchitecture::__ENUM__ // Property Get Method TEST(mscorlib_System_Reflection_AssemblyName_Fixture,get_ProcessorArchitecture_Test) { } // Property ProcessorArchitecture // Return Type: mscorlib::System::Reflection::ProcessorArchitecture::__ENUM__ // Property Set Method TEST(mscorlib_System_Reflection_AssemblyName_Fixture,set_ProcessorArchitecture_Test) { } // Property Name // Return Type: mscorlib::System::String // Property Get Method TEST(mscorlib_System_Reflection_AssemblyName_Fixture,get_Name_Test) { } // Property Name // Return Type: mscorlib::System::String // Property Set Method TEST(mscorlib_System_Reflection_AssemblyName_Fixture,set_Name_Test) { } // Property CodeBase // Return Type: mscorlib::System::String // Property Get Method TEST(mscorlib_System_Reflection_AssemblyName_Fixture,get_CodeBase_Test) { } // Property CodeBase // Return Type: mscorlib::System::String // Property Set Method TEST(mscorlib_System_Reflection_AssemblyName_Fixture,set_CodeBase_Test) { } // Property EscapedCodeBase // Return Type: mscorlib::System::String // Property Get Method TEST(mscorlib_System_Reflection_AssemblyName_Fixture,get_EscapedCodeBase_Test) { } // Property CultureInfo // Return Type: mscorlib::System::Globalization::CultureInfo // Property Get Method TEST(mscorlib_System_Reflection_AssemblyName_Fixture,get_CultureInfo_Test) { } // Property CultureInfo // Return Type: mscorlib::System::Globalization::CultureInfo // Property Set Method TEST(mscorlib_System_Reflection_AssemblyName_Fixture,set_CultureInfo_Test) { } // Property Flags // Return Type: mscorlib::System::Reflection::AssemblyNameFlags::__ENUM__ // Property Get Method TEST(mscorlib_System_Reflection_AssemblyName_Fixture,get_Flags_Test) { } // Property Flags // Return Type: mscorlib::System::Reflection::AssemblyNameFlags::__ENUM__ // Property Set Method TEST(mscorlib_System_Reflection_AssemblyName_Fixture,set_Flags_Test) { } // Property FullName // Return Type: mscorlib::System::String // Property Get Method TEST(mscorlib_System_Reflection_AssemblyName_Fixture,get_FullName_Test) { } // Property HashAlgorithm // Return Type: mscorlib::System::Configuration::Assemblies::AssemblyHashAlgorithm::__ENUM__ // Property Get Method TEST(mscorlib_System_Reflection_AssemblyName_Fixture,get_HashAlgorithm_Test) { } // Property HashAlgorithm // Return Type: mscorlib::System::Configuration::Assemblies::AssemblyHashAlgorithm::__ENUM__ // Property Set Method TEST(mscorlib_System_Reflection_AssemblyName_Fixture,set_HashAlgorithm_Test) { } // Property KeyPair // Return Type: mscorlib::System::Reflection::StrongNameKeyPair // Property Get Method TEST(mscorlib_System_Reflection_AssemblyName_Fixture,get_KeyPair_Test) { } // Property KeyPair // Return Type: mscorlib::System::Reflection::StrongNameKeyPair // Property Set Method TEST(mscorlib_System_Reflection_AssemblyName_Fixture,set_KeyPair_Test) { } // Property Version // Return Type: mscorlib::System::Version // Property Get Method TEST(mscorlib_System_Reflection_AssemblyName_Fixture,get_Version_Test) { } // Property Version // Return Type: mscorlib::System::Version // Property Set Method TEST(mscorlib_System_Reflection_AssemblyName_Fixture,set_Version_Test) { } // Property VersionCompatibility // Return Type: mscorlib::System::Configuration::Assemblies::AssemblyVersionCompatibility::__ENUM__ // Property Get Method TEST(mscorlib_System_Reflection_AssemblyName_Fixture,get_VersionCompatibility_Test) { } // Property VersionCompatibility // Return Type: mscorlib::System::Configuration::Assemblies::AssemblyVersionCompatibility::__ENUM__ // Property Set Method TEST(mscorlib_System_Reflection_AssemblyName_Fixture,set_VersionCompatibility_Test) { } // Property CultureName // Return Type: mscorlib::System::String // Property Get Method TEST(mscorlib_System_Reflection_AssemblyName_Fixture,get_CultureName_Test) { } // Property ContentType // Return Type: mscorlib::System::Reflection::AssemblyContentType::__ENUM__ // Property Get Method TEST(mscorlib_System_Reflection_AssemblyName_Fixture,get_ContentType_Test) { } // Property ContentType // Return Type: mscorlib::System::Reflection::AssemblyContentType::__ENUM__ // Property Set Method TEST(mscorlib_System_Reflection_AssemblyName_Fixture,set_ContentType_Test) { } } } }
24.933526
150
0.722499
brunolauze
f90a157b484bf7553757f731e5729b3c5e23f30e
961
cpp
C++
737.cpp
zfang399/LeetCode-Problems
4cb25718a3d1361569f5ee6fde7b4a9a4fde2186
[ "MIT" ]
8
2018-10-31T11:00:19.000Z
2020-07-31T05:25:06.000Z
737.cpp
zfang399/LeetCode-Problems
4cb25718a3d1361569f5ee6fde7b4a9a4fde2186
[ "MIT" ]
null
null
null
737.cpp
zfang399/LeetCode-Problems
4cb25718a3d1361569f5ee6fde7b4a9a4fde2186
[ "MIT" ]
2
2018-05-31T11:29:22.000Z
2019-09-11T06:34:40.000Z
class Solution { public: bool areSentencesSimilarTwo(vector<string>& words1, vector<string>& words2, vector<pair<string, string>> pairs) { if (words1.size() != words2.size()) return false; map<string, string> m; for (int i = 0; i < pairs.size(); i++){ string parent1 = find(m, pairs[i].first); string parent2 = find(m, pairs[i].second); if (parent1 != parent2) m[parent1] = parent2; } for (int i = 0; i < words1.size(); i++){ if(words1[i].compare(words2[i]) == 0) continue; if(find(m,words1[i]).compare(find(m,words2[i])) == 0) continue; return false; } return true; } string find(map<string, string>& m, string s){ if(m.count(s)){ if(m[s] == s){ return s; } return find(m, m[s]); }else{ m[s] = s; return s; } } };
30.03125
117
0.480749
zfang399
f90ee2953cf8de6346777a82f96500eeeb535f3b
11,306
hpp
C++
include/worker_thread.hpp
cschreib/ice3
44aa182543d037863fb7726827e688490ac26275
[ "MIT" ]
null
null
null
include/worker_thread.hpp
cschreib/ice3
44aa182543d037863fb7726827e688490ac26275
[ "MIT" ]
null
null
null
include/worker_thread.hpp
cschreib/ice3
44aa182543d037863fb7726827e688490ac26275
[ "MIT" ]
null
null
null
#ifndef WORKER_THREAD_HPP #define WORKER_THREAD_HPP #include <vector> #include "lock_free_queue.hpp" #include "threading_policies.hpp" #include "worker_thread_fwd.hpp" #ifdef NO_STD_THREAD #pragma GCC system_header #include <boost/thread.hpp> #include <boost/functional.hpp> typedef boost::thread thread_t; #else #include <thread> #include <functional> typedef std::thread thread_t; #endif template<typename T, size_t N, typename sleep_policy> class worker_thread_t<T, N, policies::task::with_output, sleep_policy> { typedef typename policies::task::argument_of<T>::type argument; typedef typename policies::task::result_of<T>::type result; lock_free_queue<argument> in[N]; lock_free_queue<result> out; std::atomic<bool> running, waiting; thread_t thread; sleep_policy sleeper; std::unique_ptr<T> worker; public : worker_thread_t() : running(false), waiting(false) {} template<typename ... Args> explicit worker_thread_t(Args&&... args) : running(false), waiting(false), worker(new T(std::forward<Args>(args)...)) {} ~worker_thread_t() { abort(); } // Disable copy worker_thread_t(const worker_thread_t& t) = delete; worker_thread_t& operator = (const worker_thread_t& t) = delete; // Get worker instance T& get_worker() { return *worker; } // Get worker instance const T& get_worker() const { return *worker; } // Get the number of priority queues size_t get_num_queues() const { return N; } // Order a new task void add_task(size_t priority, const argument& data) { in[priority].push(data); } // Retreive result bool consume(result& res) { return out.pop(res); } // Start working void start() { abort(); running = true; #ifdef NO_STD_THREAD thread = boost::thread(boost::bind(&worker_thread_t::work_, this)); #else thread = std::thread(&worker_thread_t::work_, this); #endif } // Start working with new worker template<typename ... Args> void start_new(Args&&... args) { abort(); worker = std::unique_ptr<T>(new T(std::forward<Args>(args)...)); start(); } // Wait for all tasks to complete void wait() { if (thread.joinable()) { waiting = true; thread.join(); } } // Clear the task queue void abort() { if (thread.joinable()) { running = false; thread.join(); } } private : // Do the actual work void work_() { argument data; size_t i; bool empty = true; while (running && !(waiting && empty)) { sleeper.sleep_if(empty); empty = true; for (i = 0; i < N; ++i) { if (in[i].pop(data)) { (*worker)(data); empty = false; break; } } } for (i = 0; i < N; ++i) in[i].clear(); } }; template<typename T, size_t N, typename sleep_policy> class worker_thread_t<T, N, policies::task::no_output, sleep_policy> { typedef typename policies::task::argument_of<T>::type argument; lock_free_queue<argument> in[N]; std::atomic<bool> running, waiting; bool empty; thread_t thread; sleep_policy sleeper; std::unique_ptr<T> worker; public : worker_thread_t() : running(false), waiting(false), empty(true) {} template<typename ... Args> explicit worker_thread_t(Args&&... args) : running(false), waiting(false), empty(true), worker(new T(std::forward<Args>(args)...)) {} ~worker_thread_t() { abort(); } // Disable copy worker_thread_t(const worker_thread_t& t) = delete; worker_thread_t& operator = (const worker_thread_t& t) = delete; // Get the number of priority queues size_t get_num_queues() const { return N; } // Get worker instance T& get_worker() { return *worker; } // Get worker instance const T& get_worker() const { return *worker; } // Order a new task void add_task(size_t priority, const argument& data) { in[priority].push(data); empty = false; } // Start working void start() { abort(); running = true; #ifdef NO_STD_THREAD thread = boost::thread(boost::bind(&worker_thread_t::work_, this)); #else thread = std::thread(&worker_thread_t::work_, this); #endif } // Start working with new task parameters template<typename ... Args> void start_new(Args&&... args) { abort(); worker = std::unique_ptr<T>(new T(std::forward<Args>(args)...)); start(); } // Wait for all tasks to complete void wait() { if (thread.joinable()) { waiting = true; thread.join(); } } // Clear the task queue void abort() { if (thread.joinable()) { running = false; thread.join(); } } private : // Do the actual work void work_() { argument data; size_t i; bool empty = true; while (running && !(waiting && empty)) { sleeper.sleep_if(empty); empty = true; for (i = 0; i < N; ++i) { if (in[i].pop(data)) { (*worker)(data); empty = false; break; } } } for (i = 0; i < N; ++i) in[i].clear(); } }; template<typename sleep_policy> class multitask_worker_thread; class worker_base { template<typename sleep_policy> friend class multitask_worker_thread; protected : public : worker_base() {} virtual ~worker_base() {}; // Disable copy worker_base(const worker_base& w) = delete; worker_base& operator = (const worker_base& w) = delete; protected : virtual void work_(bool& empty) = 0; virtual void clear_() = 0; }; template<typename T, size_t N> class worker_t<T, N, policies::task::with_output> : public worker_base { protected : typedef typename policies::task::argument_of<T>::type argument; typedef typename policies::task::result_of<T>::type result; lock_free_queue<argument> in[N]; lock_free_queue<result> out; std::unique_ptr<T> worker; public : worker_t() = default; ~worker_t() final = default; template <typename ... Args> explicit worker_t(Args&&... args) : worker(new T(std::forward<Args>(args)...)) {} // Get the number of priority queues size_t get_num_queues() const { return N; } // Get worker instance T& get_worker() { return *worker; } // Get worker instance const T& get_worker() const { return *worker; } // Order a new task void add_task(size_t priority, const argument& data) { in[priority].push(data); } // Retreive result bool consume(result& res) { return out.pop(res); } // Start working with new task parameters template<typename ... Args> void start_new(Args&&... args) { worker = std::unique_ptr<T>(new T(std::forward<Args>(args)...)); } protected : void work_(bool& empty) override final { argument data; size_t i; for (i = 0; i < N; ++i) { if (in[i].pop(data)) { out.push((*worker)(data)); empty = false; return; } } } void clear_() override final { for (size_t i = 0; i < N; ++i) in[i].clear(); } }; template<typename T, size_t N> class worker_t<T, N, policies::task::no_output> : public worker_base { protected : typedef typename policies::task::argument_of<T>::type argument; lock_free_queue<argument> in[N]; std::unique_ptr<T> worker; public : worker_t() = default; ~worker_t() final = default; template <typename ... Args> explicit worker_t(Args&&... args) : worker(new T(std::forward<Args>(args)...)) {} // Get the number of priority queues size_t get_num_queues() const { return N; } // Get worker instance T& get_worker() { return *worker; } // Get worker instance const T& get_worker() const { return *worker; } // Order a new task void add_task(size_t priority, const argument& data) { in[priority].push(data); } // Start working with new task parameters template<typename ... Args> void start_new(Args&&... args) { worker = std::unique_ptr<T>(new T(std::forward<Args>(args)...)); } protected : void work_(bool& empty) override final { argument data; size_t i; for (i = 0; i < N; ++i) { if (in[i].pop(data)) { (*worker)(data); empty = false; return; } } } void clear_() override final { for (size_t i = 0; i < N; ++i) in[i].clear(); } }; template<typename sleep_policy = policies::sleep::no_sleep> class multitask_worker_thread { std::vector<worker_base*> workers; std::atomic<bool> running, waiting; thread_t thread; sleep_policy sleeper; public : multitask_worker_thread() : running(false), waiting(false) {} template<typename ... Workers> multitask_worker_thread(Workers&... args) : running(false), waiting(false) { push_worker_(args...); } ~multitask_worker_thread() { abort(); } template<typename ... Workers> void set_workers(Workers&... args) { push_worker_(args...); } void add_worker(worker_base& w) { push_worker_(w); } // Start working void start() { abort(); running = true; #ifdef NO_STD_THREAD thread = boost::thread(boost::bind(&multitask_worker_thread::work_, this)); #else thread = std::thread(&multitask_worker_thread::work_, this); #endif } // Wait for all tasks to complete void wait() { if (thread.joinable()) { waiting = true; thread.join(); } } // Clear the task queue void abort() { if (thread.joinable()) { running = false; thread.join(); } } private : void work_() { bool empty = true; while (running && !(waiting && empty)) { sleeper.sleep_if(empty); empty = true; for (auto w : workers) w->work_(empty); } for (auto w : workers) w->clear_(); } template<typename ... Workers> void push_worker_(worker_base& worker, Workers&... args) { workers.push_back(&worker); push_worker_(args...); } void push_worker_(worker_base& worker) { workers.push_back(&worker); } }; #endif
21.700576
91
0.549266
cschreib
f916751bd2d5b36248cab4599a8f68b59836351b
3,021
cpp
C++
src/eepp/ui/css/propertyspecification.cpp
jayrulez/eepp
09c5c1b6b4c0306bb0a188474778c6949b5df3a7
[ "MIT" ]
37
2020-01-20T06:21:24.000Z
2022-03-21T17:44:50.000Z
src/eepp/ui/css/propertyspecification.cpp
jayrulez/eepp
09c5c1b6b4c0306bb0a188474778c6949b5df3a7
[ "MIT" ]
null
null
null
src/eepp/ui/css/propertyspecification.cpp
jayrulez/eepp
09c5c1b6b4c0306bb0a188474778c6949b5df3a7
[ "MIT" ]
9
2019-03-22T00:33:07.000Z
2022-03-01T01:35:59.000Z
#include <eepp/core/core.hpp> #include <eepp/system/log.hpp> #include <eepp/ui/css/propertyspecification.hpp> namespace EE { namespace UI { namespace CSS { SINGLETON_DECLARE_IMPLEMENTATION( PropertySpecification ) PropertySpecification::~PropertySpecification() {} PropertyDefinition& PropertySpecification::registerProperty( const std::string& propertyVame, const std::string& defaultValue, bool inherited ) { PropertyDefinition* property = const_cast<PropertyDefinition*>( getProperty( propertyVame ) ); if ( nullptr != property ) { Log::warning( "Property %s already registered.", propertyVame.c_str() ); return *property; } PropertyDefinition* propDef = new PropertyDefinition( propertyVame, defaultValue, inherited ); mProperties[propDef->getId()] = std::shared_ptr<PropertyDefinition>( propDef ); for ( auto& sep : {"-", "_"} ) { if ( propDef->getName().find( sep ) != std::string::npos ) { std::string alias( propDef->getName() ); String::replaceAll( alias, sep, "" ); propDef->addAlias( alias ); } } return *propDef; } const PropertyDefinition* PropertySpecification::getProperty( const Uint32& id ) const { auto it = mProperties.find( id ); if ( it != mProperties.end() ) return it->second.get(); return nullptr; } const PropertyDefinition* PropertySpecification::getProperty( const std::string& name ) const { return getProperty( String::hash( name ) ); } ShorthandDefinition& PropertySpecification::registerShorthand( const std::string& name, const std::vector<std::string>& properties, const std::string& shorthandParserName ) { ShorthandDefinition* shorthand = const_cast<ShorthandDefinition*>( getShorthand( name ) ); if ( nullptr != shorthand ) { Log::warning( "Shorthand %s already registered.", name.c_str() ); return *shorthand; } ShorthandDefinition* shorthandDef = new ShorthandDefinition( name, properties, shorthandParserName ); mShorthands[shorthandDef->getId()] = std::shared_ptr<ShorthandDefinition>( shorthandDef ); return *shorthandDef; } const ShorthandDefinition* PropertySpecification::getShorthand( const String::HashType& id ) const { auto it = mShorthands.find( id ); if ( it != mShorthands.end() ) return it->second.get(); return nullptr; } const ShorthandDefinition* PropertySpecification::getShorthand( const std::string& name ) const { return getShorthand( String::hash( name ) ); } bool PropertySpecification::isShorthand( const std::string& name ) const { return getShorthand( name ) != nullptr; } bool PropertySpecification::isShorthand( const Uint32& id ) const { return getShorthand( id ) != nullptr; } const PropertyDefinition* PropertySpecification::addPropertyAlias( Uint32 aliasId, const PropertyDefinition* propDef ) { if ( getProperty( aliasId ) == nullptr ) { auto it = mProperties.find( propDef->getId() ); if ( it != mProperties.end() ) { mProperties[aliasId] = it->second; } } return propDef; } }}} // namespace EE::UI::CSS
29.910891
100
0.714995
jayrulez
f91c1ebbf48fb01f9e37432b0304a0947b024a07
2,435
cpp
C++
00124_binary-tree-maximum-path-sum/200208-1.cpp
yanlinlin82/leetcode
ddcc0b9606d951cff9c08d1f7dfbc202067c8d65
[ "MIT" ]
6
2019-10-23T01:07:29.000Z
2021-12-05T01:51:16.000Z
00124_binary-tree-maximum-path-sum/200208-1.cpp
yanlinlin82/leetcode
ddcc0b9606d951cff9c08d1f7dfbc202067c8d65
[ "MIT" ]
null
null
null
00124_binary-tree-maximum-path-sum/200208-1.cpp
yanlinlin82/leetcode
ddcc0b9606d951cff9c08d1f7dfbc202067c8d65
[ "MIT" ]
1
2021-12-03T06:54:57.000Z
2021-12-03T06:54:57.000Z
// https://leetcode-cn.com/problems/binary-tree-maximum-path-sum/ #include <cstdio> #include <algorithm> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; void release(TreeNode* t) { if (t) { release(t->left); release(t->right); delete t; } } class Solution { public: int maxPathSum(TreeNode* root) { if (!root->left && !root->right) return root->val; int a = maxRootPathSum(root->left); int b = maxRootPathSum(root->right); int s = a + root->val + b; if (s < root->val + a) { s = root->val + a; } if (s < root->val + b) { s = root->val + b; } if (s < root->val) { s = root->val; } if (root->left && s < a) { s = a; } if (root->right && s < b) { s = b; } if (root->left) { a = maxPathSum(root->left); if (s < a) { s = a; } } if (root->right) { b = maxPathSum(root->right); if (s < b) { s = b; } } return s; } private: int maxRootPathSum(TreeNode* t) { // path that starts with root node if (!t) return 0; int a = maxRootPathSum(t->left); int b = maxRootPathSum(t->right); return t->val + max(0, max(a, b)); } }; int main() { Solution s; { TreeNode* t = new TreeNode(1); t->left = new TreeNode(2); t->right = new TreeNode(3); printf("%d\n", s.maxPathSum(t)); // answer: 6 release(t); } { TreeNode* t = new TreeNode(-10); t->left = new TreeNode(9); t->right = new TreeNode(20); t->right->left = new TreeNode(15); t->right->right = new TreeNode(7); printf("%d\n", s.maxPathSum(t)); // answer: 42 release(t); } { TreeNode* t = new TreeNode(-3); printf("%d\n", s.maxPathSum(t)); // answer: -3 release(t); } { TreeNode* t = new TreeNode(-2); t->right = new TreeNode(-1); printf("%d\n", s.maxPathSum(t)); // answer: -1 release(t); } { TreeNode* t = new TreeNode(9); t->left = new TreeNode(6); t->right = new TreeNode(-3); t->right->left = new TreeNode(-6); t->right->right = new TreeNode(2); t->right->right->left = new TreeNode(2); t->right->right->left->left = new TreeNode(-6); t->right->right->left->right = new TreeNode(-6); t->right->right->left->left->left = new TreeNode(-6); /* 9 * / \ * 6 -3 * / \ * -6 2 * / * 2 * / \ * -6 -6 * / * -6 */ printf("%d\n", s.maxPathSum(t)); // answer: 16 release(t); } return 0; }
22.136364
69
0.544969
yanlinlin82
f91d805b7315035dc22746fb046e08442503f6be
425
cpp
C++
CodeForces/841/B - Godsend.cpp
QAQrz/ACM-Code
7f7b6fd315e7d84ed606dd48d666da07fc4d0ae7
[ "Unlicense" ]
2
2018-02-24T06:45:56.000Z
2018-05-29T04:47:39.000Z
CodeForces/841/B - Godsend.cpp
QAQrz/ACM-Code
7f7b6fd315e7d84ed606dd48d666da07fc4d0ae7
[ "Unlicense" ]
null
null
null
CodeForces/841/B - Godsend.cpp
QAQrz/ACM-Code
7f7b6fd315e7d84ed606dd48d666da07fc4d0ae7
[ "Unlicense" ]
2
2018-06-28T09:53:27.000Z
2022-03-23T13:29:57.000Z
#include <bits/stdc++.h> using namespace std; #define db(x) cout<<(x)<<endl #define pb(x) push_back(x) #define mp(x,y) make_pair(x,y) #define ms(x,y) memset(x,y,sizeof x) typedef long long LL; const LL mod=1e9+7,inf=0x3f3f3f3f,maxn=1123456; LL n,sum,a,flag; int main(){ ios::sync_with_stdio(false); cin>>n; for(int i=0;i<n;i++){ cin>>a; sum+=a; if(a%2) flag=1; } db((sum%2||flag)?"First":"Second"); return 0; }
20.238095
47
0.64
QAQrz
f91f517680e5e0dd53b2e3c058af5eac2a6b3ee0
1,120
cpp
C++
src/QtFuzzy/nFuzzySNormFactory.cpp
Vladimir-Lin/QtFuzzy
185869384f3ce9d3a801080b675bae8ed6c5fb12
[ "MIT" ]
null
null
null
src/QtFuzzy/nFuzzySNormFactory.cpp
Vladimir-Lin/QtFuzzy
185869384f3ce9d3a801080b675bae8ed6c5fb12
[ "MIT" ]
null
null
null
src/QtFuzzy/nFuzzySNormFactory.cpp
Vladimir-Lin/QtFuzzy
185869384f3ce9d3a801080b675bae8ed6c5fb12
[ "MIT" ]
null
null
null
#include <qtfuzzy.h> N::Fuzzy::SNormFactory:: SNormFactory(void) { } N::Fuzzy::SNormFactory::~SNormFactory(void) { } N::Fuzzy::SNorm * N::Fuzzy::SNormFactory::create(const QString & zName) const { #define FSNF(CN) if (zName==CN().className()) return new CN() FSNF ( Maximum ) ; FSNF ( AlgebraicSum ) ; FSNF ( BoundedSum ) ; FSNF ( NormalizedSum ) ; FSNF ( DrasticSum ) ; FSNF ( EinsteinSum ) ; FSNF ( HamacherSum ) ; #undef FSNF return NULL ; } QVector<QString> N::Fuzzy::SNormFactory::available(void) const { QVector<QString> result ; #define FSNX(CN) result.push_back(CN().className()) FSNX ( Maximum ) ; FSNX ( AlgebraicSum ) ; FSNX ( BoundedSum ) ; FSNX ( NormalizedSum ) ; FSNX ( DrasticSum ) ; FSNX ( EinsteinSum ) ; FSNX ( HamacherSum ) ; #undef FSNX return result ; }
28.717949
77
0.475893
Vladimir-Lin
f924ed633381bcc5babc06e4f9d3f332bad627b2
2,686
hh
C++
src/ggl/Graph.hh
michaelapeterka/GGL
99e585b773ad8f33e39160d2cbd71c00e036fa37
[ "MIT" ]
20
2017-05-09T15:37:04.000Z
2021-11-24T10:51:02.000Z
src/ggl/Graph.hh
michaelapeterka/GGL
99e585b773ad8f33e39160d2cbd71c00e036fa37
[ "MIT" ]
2
2017-05-24T08:00:25.000Z
2017-05-24T08:01:01.000Z
src/ggl/Graph.hh
michaelapeterka/GGL
99e585b773ad8f33e39160d2cbd71c00e036fa37
[ "MIT" ]
7
2017-05-29T10:55:18.000Z
2020-12-04T14:24:51.000Z
#ifndef GGL_GRAPH_HH_ #define GGL_GRAPH_HH_ #include <boost/graph/properties.hpp> #include <boost/graph/adjacency_list.hpp> #include <iostream> #include <vector> #include <set> #include "sgm/Graph_boost.hh" //! The ggl namespace contains classes needed to specify rules of a graph //! grammar and to apply these rules to graphs. namespace ggl { //! This boost graph property is used to determine the index of a given //! node along the iterator order. typedef boost::vertex_index_t PropNodeIndex; //! Vector of node indices typedef std::vector< PropNodeIndex > NodeIndexVec; //! Set of node indices typedef std::set< PropNodeIndex > NodeIndexSet; //! This boost graph property is used to determine the label of a given //! node. typedef boost::vertex_name_t PropNodeLabel; //! The properties available for the nodes of a Graph //! //! @author Martin Mann (c) 2008 http://www.bioinf.uni-freiburg.de/~mmann/ //! typedef boost::property< PropNodeIndex, size_t , boost::property< PropNodeLabel, std::string > > Graph_NodeProperties; //! This boost graph property is used to determine the label of a given //! edge. typedef boost::edge_name_t PropEdgeLabel; //! The properties available for the edges of a Graph //! //! @author Martin Mann (c) 2008 http://www.bioinf.uni-freiburg.de/~mmann/ //! typedef boost::property< PropEdgeLabel, std::string > Graph_EdgeProperties; //! The definition of undirected graphs that are handled by the graph //! grammar rules of the GGL. //! //! @author Martin Mann (c) 2008 http://www.bioinf.uni-freiburg.de/~mmann/ //! typedef boost::adjacency_list< boost::vecS, // store edges boost::vecS, // store vertices boost::undirectedS, // is an undirected graph Graph_NodeProperties, // (atom symbols etc) Graph_EdgeProperties // (edge symbols etc) > Graph; /*! * Definition of a sgm::Graph_Interface wrapper around a ggl::Graph * object. * * @author Martin Mann (c) 2012 http://www.bioinf.uni-freiburg.de/~mmann/ */ typedef sgm::Graph_boost < Graph \ , PropNodeLabel \ , PropEdgeLabel \ , PropNodeIndex \ > Graph_boost; } // namespace ggl /*! * Writes a ggl::Graph object to stream in GML format * @param out the stream to write to * @param g the graph to be written in GML format * @return the changed input stream out */ std::ostream& operator <<( std::ostream & out, const ggl::Graph& g ); #endif /*GRAPH_HH_*/
27.979167
78
0.642964
michaelapeterka
234e424ee765ce167a5d7a82484fedeabc8e887b
10,711
hpp
C++
src/parser/lexer/string_reader.hpp
alohaeee/-orrosion
7529cf9fb2d15f4d67a45013bd90760bc9c8f579
[ "MIT" ]
null
null
null
src/parser/lexer/string_reader.hpp
alohaeee/-orrosion
7529cf9fb2d15f4d67a45013bd90760bc9c8f579
[ "MIT" ]
null
null
null
src/parser/lexer/string_reader.hpp
alohaeee/-orrosion
7529cf9fb2d15f4d67a45013bd90760bc9c8f579
[ "MIT" ]
null
null
null
#ifndef CORROSION_SRC_PARSER_LEXER_STRING_READER_HPP_ #define CORROSION_SRC_PARSER_LEXER_STRING_READER_HPP_ #include "utility/std_incl.hpp" #include "lexer/lexer.hpp" #include "parser/parse_session.hpp" #include "ast/token.hpp" #include "span/source_file.hpp" #include "span/symbol.hpp" #include "span/span.hpp" #include "error/log.hpp" namespace corrosion { class StringReader { public: StringReader(std::shared_ptr<ParseSession>& parseSession, std::size_t start = 0) : parseSession{ parseSession }, m_start(start) { m_tokenizer = lexer::Tokenizer{ parseSession->file().source() }; } inline void tokenizerLog(const lexer::Token& token) { #ifdef CR_ENABLE_LOG_TOKENIZER Log::getTokenizerLogger()->flush(); CR_LOG_TOKENIZER("[{}] TokenKind: \"{}\" Span: {}-{} {} \n\t\t Source: {}", parseSession->file().path().string(), lexer::Tokenizer::tokenKindPrintable(token.kind), m_start, m_tokenizer.consumed(), lexer::Tokenizer::tokenDataPrintable(token.data), m_tokenizer.text().substr(m_start, token.consumed)); #endif } inline std::string_view strToken() const { return m_tokenizer.text().substr(m_start,m_token.consumed); } inline std::string_view strTo(std::size_t n) { // std::cout << n << ":" << m_start << std::endl; // CR_DEBUG_LOG_TRACE("token:{} data:{}", m_tokenizer.tokenKindPrintable(m_token.kind),m_tokenizer.tokenDataPrintable(m_token.data)); assert(n > m_start); return m_tokenizer.text().substr(m_start, n - m_start); } inline std::string_view strFrom(std::size_t n) { assert(n < m_tokenizer.consumed()); return m_tokenizer.text().substr(n, m_tokenizer.consumed() - n); } inline Span spanToken() const { return { m_start, m_tokenizer.consumed() }; } ast::Token nextToken() { if (m_tokenizer.isEof()) { return ast::Token{ ast::TokenKind::Eof, { 0, 0 }}; } m_token = m_tokenizer.advanceToken(); // Logging into "tokenizer.txt" file if CR_ENABLE_LOG_TOKENIZER was defined. tokenizerLog(m_token); auto ast_token = lexerTokenCook(m_token); auto span = Span(m_start, m_token.consumed); m_start = m_tokenizer.consumed(); return ast_token; } /// Turns simple `lexer::TokenKind` enum into a rich /// `ast::TokenKind`. This turns strings into interned /// symbols and runs additional validation. ast::Token lexerTokenCook(const lexer::Token& token) { ast::TokenData data=ast::data::Empty{}; ast::TokenKind kind; switch (token.kind) { case lexer::TokenKind::LineComment: kind = ast::TokenKind::Comment; break; case lexer::TokenKind::BlockComment: { auto data = std::get<lexer::data::BlockComment>(token.data); if (!data.terminated) { parseSession->criticalSpan(spanToken(), "unterminated block comment"); } kind = ast::TokenKind::Comment; break; } case lexer::TokenKind::Whitespace: kind = ast::TokenKind::Whitespace; break; case lexer::TokenKind::Identifier: { auto sym = Symbol::intern(strToken()); kind = ast::TokenKind::Ident; data = ast::data::Ident{ sym }; break; } case lexer::TokenKind::RawIdentifier: parseSession->errorSpan(spanToken(), "raw identifiers are not implimented."); kind = ast::TokenKind::Unknown; break; case lexer::TokenKind::Literal: { auto lit_data = std::get<lexer::data::LiteralKind>(token.data); data = lexerLiteralCook(lit_data); kind = ast::TokenKind::Literal; break; } case lexer::TokenKind::Lifetime: { auto start_with_number = std::get<lexer::data::Lifetime>(token.data).startWithNumber; if (start_with_number) { parseSession->errorSpan(spanToken(), "lifetimes cannot start with a number"); } auto lifetime_ident = strToken(); lifetime_ident = lifetime_ident.substr(1, lifetime_ident.size()); auto sym = Symbol::intern(lifetime_ident); kind = ast::TokenKind::Lifetime; data = ast::data::Lifetime{ sym }; break; } case lexer::TokenKind::Semi: kind = ast::TokenKind::Semi; break; case lexer::TokenKind::Comma: kind = ast::TokenKind::Comma; break; case lexer::TokenKind::Dot: kind = ast::TokenKind::Dot; break; case lexer::TokenKind::OpenParen: data = ast::data::Delim{ ast::data::Delim::Paren }; kind = ast::TokenKind::OpenDelim; break; case lexer::TokenKind::CloseParen: data = ast::data::Delim{ ast::data::Delim::Paren }; kind = ast::TokenKind::CloseDelim; break; case lexer::TokenKind::OpenBrace: data = ast::data::Delim{ ast::data::Delim::Brace }; kind = ast::TokenKind::OpenDelim; break; case lexer::TokenKind::CloseBrace: data = ast::data::Delim{ ast::data::Delim::Brace }; kind = ast::TokenKind::CloseDelim; break; case lexer::TokenKind::OpenBracket: data = ast::data::Delim{ ast::data::Delim::Bracket }; kind = ast::TokenKind::OpenDelim; break; case lexer::TokenKind::CloseBracket: data = ast::data::Delim{ ast::data::Delim::Bracket }; kind = ast::TokenKind::CloseDelim; break; case lexer::TokenKind::At: kind = ast::TokenKind::At; break; case lexer::TokenKind::Pound: kind = ast::TokenKind::Pound; break; case lexer::TokenKind::Tilde: kind = ast::TokenKind::Tilde; break; case lexer::TokenKind::Question: kind = ast::TokenKind::Question; break; case lexer::TokenKind::Colon: kind = ast::TokenKind::Colon; break; case lexer::TokenKind::Dollar: kind = ast::TokenKind::Dollar; break; case lexer::TokenKind::Eq: kind = ast::TokenKind::Eq; break; case lexer::TokenKind::Not: kind = ast::TokenKind::Not; break; case lexer::TokenKind::Minus: data = ast::data::BinOp{ ast::data::BinOp::Minus }; kind = ast::TokenKind::BinOp; break; case lexer::TokenKind::And: data = ast::data::BinOp{ ast::data::BinOp::And }; kind = ast::TokenKind::BinOp; break; case lexer::TokenKind::Or: data = ast::data::BinOp{ ast::data::BinOp::Or }; kind = ast::TokenKind::BinOp; break; case lexer::TokenKind::Plus: data = ast::data::BinOp{ ast::data::BinOp::Plus }; kind = ast::TokenKind::BinOp; break; case lexer::TokenKind::Star: data = ast::data::BinOp{ ast::data::BinOp::Star }; kind = ast::TokenKind::BinOp; break; case lexer::TokenKind::Slash: data = ast::data::BinOp{ ast::data::BinOp::Slash }; kind = ast::TokenKind::BinOp; break; case lexer::TokenKind::Caret: data = ast::data::BinOp{ ast::data::BinOp::Caret }; kind = ast::TokenKind::BinOp; break; case lexer::TokenKind::Percent: data = ast::data::BinOp{ ast::data::BinOp::Percent }; kind = ast::TokenKind::BinOp; break; case lexer::TokenKind::Gt: kind = ast::TokenKind::Gt; break; case lexer::TokenKind::Lt: kind = ast::TokenKind::Lt; break; default: { parseSession->errorSpan(spanToken(), "unknown start of token"); kind = ast::TokenKind::Unknown; } } return { kind, spanToken(), data }; } ast::data::Literal lexerLiteralCook(const lexer::data::LiteralKind kind) { return std::visit([this](auto&& arg) -> ast::data::Literal { using T = std::decay_t<decltype(arg)>; std::optional<Symbol> suf = std::nullopt; if constexpr(std::is_same_v<T, lexer::literal_types::Char>) { auto content = Symbol::intern(strTo(arg.suffixStart)); if (!arg.terminated) { parseSession->criticalSpan(spanToken(), "unterminated character literal"); } if (arg.suffixStart != m_tokenizer.consumed()) { parseSession->errorSpan(Span(arg.suffixStart,m_tokenizer.consumed()), "suffixes on a string literal are invalid"); suf = Symbol::intern(strFrom(arg.suffixStart)); } return { ast::data::Literal::Char, content, suf }; } else if constexpr(std::is_same_v<T, lexer::literal_types::Str>) { auto content = Symbol::intern(strTo(arg.suffixStart)); if (!arg.terminated) { parseSession->criticalSpan(spanToken(), "unterminated double quote string"); } if (arg.suffixStart != m_tokenizer.consumed()) { parseSession->errorSpan(Span(arg.suffixStart,m_tokenizer.consumed()), "suffixes on a string literal are invalid"); suf = Symbol::intern(strFrom(arg.suffixStart)); } return { ast::data::Literal::Str, content, suf }; } else if constexpr(std::is_same_v<T, lexer::literal_types::Int>) { auto content = Symbol::intern(strTo(arg.suffixStart)); if (arg.emptyInt) { parseSession->errorSpan(spanToken(), "no valid digits found for number"); } if (arg.suffixStart != m_tokenizer.consumed()) { suf = Symbol::intern(strFrom(arg.suffixStart)); } integerValidation(arg.base, strToken()); return { ast::data::Literal::Integer, content, suf }; } else if constexpr(std::is_same_v<T, lexer::literal_types::Float>) { auto content = Symbol::intern(strTo(arg.suffixStart)); if (arg.emptyExponent) { parseSession->errorSpan(spanToken(), "expected at least one digit in exponent"); } if (arg.suffixStart != m_tokenizer.consumed()) { suf = Symbol::intern(strFrom(arg.suffixStart)); } switch (arg.base) { case lexer::Base::Hexadecimal: parseSession->errorSpan(spanToken(), "hexadecimal float literal is not supported"); break; case lexer::Base::Octal: parseSession->errorSpan(spanToken(), "octal float literal is not supported"); break; case lexer::Base::Binary: parseSession->errorSpan(spanToken(), "binary float literal is not supported"); break; default: break; } return { ast::data::Literal::Float, content, suf }; } else { static_assert("Bad visit in coocking ast literal"); } }, kind); } void integerValidation(lexer::Base base, std::string_view number) { uint8_t base_num; if (base == lexer::Base::Binary) { base_num = 2; } else if (base == lexer::Base::Binary) { base_num = 8; } else { return; } number = number.substr(2, number.size()); for (auto& c: number) { if (static_cast<uint8_t>(c - '0') >= base_num) { parseSession->errorSpan(spanToken(), fmt::format("invalid digit for a base {} literal", base)); return; } } } std::shared_ptr<ParseSession> parseSession; protected: lexer::Tokenizer m_tokenizer{}; std::size_t m_start; lexer::Token m_token{}; }; } #endif //CORROSION_SRC_PARSER_LEXER_STRING_READER_HPP_
29.752778
135
0.642424
alohaeee
235065baa317611a019f596d0f90b837f98d8488
606
cpp
C++
Code/2020/Day 3/day3p1.cpp
holllikill/AdventOfCode2019
7ea69ac9cf57ba15196047564f40e63f4d20d996
[ "MIT" ]
1
2020-01-28T00:06:30.000Z
2020-01-28T00:06:30.000Z
Code/2020/Day 3/day3p1.cpp
holllikill/AdventOfCode2019
7ea69ac9cf57ba15196047564f40e63f4d20d996
[ "MIT" ]
null
null
null
Code/2020/Day 3/day3p1.cpp
holllikill/AdventOfCode2019
7ea69ac9cf57ba15196047564f40e63f4d20d996
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> using namespace std; int main () { ifstream infile; infile.open ("input.txt"); string total[500]; int i = 0; if (infile.is_open()) { while (infile.good()) { char c[40]; infile.getline(c, 256); total[i]+=c; i++; } } int trees = 0; int lnSize = total[0].length(); for (int x = 0; x < i; x++) { int loc =(x*3)%lnSize; if (total[x].at(loc) == '#') { trees++; } } cout << "trees: " << trees; return 0; }
16.833333
38
0.429043
holllikill
2353913ff868e3d33d8c912eae7628f289ed2759
5,949
cpp
C++
components/network/tcp/iot_tcp.cpp
lask/esp-iot-solution
40cec135eace36cf11ab72988e27546a2c0d025b
[ "Apache-2.0" ]
8
2021-03-29T16:42:39.000Z
2022-02-18T07:05:00.000Z
components/network/tcp/iot_tcp.cpp
Conanzhou/esp-iot-solution
f2e0a8ee2448b26171fe361add1b6786b7cf43a0
[ "Apache-2.0" ]
27
2019-03-12T10:13:29.000Z
2019-06-07T20:40:56.000Z
components/network/tcp/iot_tcp.cpp
Conanzhou/esp-iot-solution
f2e0a8ee2448b26171fe361add1b6786b7cf43a0
[ "Apache-2.0" ]
3
2020-05-01T06:33:57.000Z
2020-05-13T12:01:25.000Z
// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <string.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_system.h" #include "esp_log.h" #include "lwip/err.h" #include "lwip/sockets.h" #include "lwip/sys.h" #include "lwip/netdb.h" #include "lwip/dns.h" #include "iot_tcp.h" static const char* TAG = "tcp_connection"; static const char* TAG_SERVER = "tcp_server"; CTcpConn::CTcpConn(int sock) { tout = 0; sockfd = sock; } CTcpConn::~CTcpConn() { close(sockfd); sockfd = -1; } int CTcpConn::Connect(const char* ip, uint16_t port) { if (sockfd < 0) { sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { ESP_LOGE(TAG, "... Failed to allocate socket."); } ESP_LOGI(TAG, "... allocated socket"); } int ret = 0; struct sockaddr_in servaddr; memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(port); ret = inet_pton(AF_INET, ip, &servaddr.sin_addr); if (ret <= 0) { ESP_LOGE(TAG, "inet_pton error for %s\n", ip); return ret; } ret = connect(sockfd, (struct sockaddr* )&servaddr, sizeof(servaddr)); if (ret < 0) { ESP_LOGE(TAG, "connect error: %s(%d)\n", ip, port); close(sockfd); sockfd = -1; } return ret; } int CTcpConn::Connect(uint32_t ip, uint16_t port) { if (sockfd < 0) { sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { ESP_LOGE(TAG, "... Failed to allocate socket."); } ESP_LOGD(TAG, "... allocated socket"); } int ret = 0; struct sockaddr_in servaddr; memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(port); struct in_addr ip_addr; ip_addr.s_addr = ip; servaddr.sin_addr = ip_addr; ret = connect(sockfd, (struct sockaddr* )&servaddr, sizeof(servaddr)); if (ret < 0) { ESP_LOGE(TAG, "connect error: %d.%d.%d.%d(%d)\n", ((uint8_t* )&ip)[0], ((uint8_t* )&ip)[1], ((uint8_t* )&ip)[2], ((uint8_t* )&ip)[3], port); close(sockfd); sockfd = -1; } return ret; } int CTcpConn::SetTimeout(int timeout) { int ret = 0; if (sockfd < 0) { return -1; } tout = timeout; struct timeval receiving_timeout; receiving_timeout.tv_sec = timeout; receiving_timeout.tv_usec = 0; ret = setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &receiving_timeout, sizeof(receiving_timeout)); if (ret < 0) { ESP_LOGE(TAG, "... failed to set socket receiving timeout"); close(sockfd); sockfd = -1; } return ret; } int CTcpConn::Read(uint8_t* data, int length, int timeout) { int ret; if (sockfd < 0) { return -1; } if (timeout > 0) { ret = SetTimeout(timeout); if (ret < 0) { return ret; } } ret = recv(sockfd, data, length, 0); return ret; } int CTcpConn::Write(const void *data, int length) { if (sockfd < 0) { ESP_LOGE(TAG, "... socket error"); return -1; } int ret = send(sockfd, data, length, 0); if (ret < 0) { ESP_LOGE(TAG, "... socket send failed"); close(sockfd); sockfd = -1; } return ret; } int CTcpConn::Disconnect() { int ret = close(sockfd); sockfd = -1; return ret; } //---------- TCP Server -------------- CTcpServer::CTcpServer() { tout = 0; sockfd = -1; } CTcpServer::~CTcpServer() { Stop(); } int CTcpServer::Listen(uint16_t port, int max_connection) { struct sockaddr_in server_addr; int ret = -1; /* Construct local address structure */ memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; /* Internet address family */ server_addr.sin_addr.s_addr = INADDR_ANY; /* Any incoming interface */ server_addr.sin_len = sizeof(server_addr); server_addr.sin_port = htons(port); /* Local port */ /* Create socket for incoming connections */ if (sockfd < 0) { sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { ESP_LOGE(TAG_SERVER, "C > user_webserver_task failed to create sock!"); return -1; } } /* Bind to the local address */ ret = bind(sockfd, (struct sockaddr * )&server_addr, sizeof(server_addr)); if (ret != 0) { ESP_LOGE(TAG_SERVER, "C > user_webserver_task failed to bind sock!"); close(sockfd); sockfd = -1; return -1; } /* Listen to the local connection */ ret = listen(sockfd, max_connection); if (ret != 0) { ESP_LOGE(TAG_SERVER, "C > user_webserver_task failed to set listen queue!"); close(sockfd); sockfd = -1; return -1; } return 0; } CTcpConn* CTcpServer::Accept() { if (sockfd < 0) { ESP_LOGE(TAG_SERVER, "TCP server socket error"); return NULL; } int connect_fd = -1; connect_fd = accept(sockfd, (struct sockaddr*) NULL, NULL); if (connect_fd == -1) { ESP_LOGE(TAG_SERVER, "accept socket error: %s(errno: %d)", strerror(errno), errno); return NULL; } CTcpConn* tcp_conn = new CTcpConn(connect_fd); return tcp_conn; } void CTcpServer::Stop() { if (sockfd > 0) { close(sockfd); } }
25.642241
120
0.597411
lask
23555e12d8d2541b45abfc5e9eb42037e5b9d8a5
1,545
cp
C++
MacOS/Sources/Support/CClockEventHandler.cp
mulberry-mail/mulberry4-client
cdaae15c51dd759110b4fbdb2063d0e3d5202103
[ "ECL-2.0", "Apache-2.0" ]
12
2015-04-21T16:10:43.000Z
2021-11-05T13:41:46.000Z
MacOS/Sources/Support/CClockEventHandler.cp
mulberry-mail/mulberry4-client
cdaae15c51dd759110b4fbdb2063d0e3d5202103
[ "ECL-2.0", "Apache-2.0" ]
2
2015-11-02T13:32:11.000Z
2019-07-10T21:11:21.000Z
MacOS/Sources/Support/CClockEventHandler.cp
mulberry-mail/mulberry4-client
cdaae15c51dd759110b4fbdb2063d0e3d5202103
[ "ECL-2.0", "Apache-2.0" ]
6
2015-01-12T08:49:12.000Z
2021-03-27T09:11:10.000Z
/* Copyright (c) 2007 Cyrus Daboo. 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. */ // Source for CClockEventHandler class #include "CClockEventHandler.h" #include "LClock.h" void CClockEventHandler::InstallMLTEEventHandler(EventTargetRef inTarget) { EventTypeSpec events[] = { { kEventClassKeyboard, kEventRawKeyDown } }; mHandler.Install(inTarget, 1, events, this, &CClockEventHandler::HandleEvent); } // Special draw OSStatus CClockEventHandler::HandleEvent(EventHandlerCallRef inCallRef, EventRef inEventRef) { OSStatus result = eventNotHandledErr; UInt32 eclass = GetEventClass(inEventRef); UInt32 ekind = GetEventKind(inEventRef); if ((eclass == kEventClassKeyboard) && (ekind == kEventRawKeyDown)) { // Look for MLTE target LClock* clock = dynamic_cast<LClock*>(LCommander::GetTarget()); if (clock != NULL) { clock->FocusDraw(); // Do pre-process, then do post-process result = ::CallNextEventHandler(inCallRef, inEventRef); } } return result; }
29.150943
92
0.732039
mulberry-mail
235bab4fddd1c645d87cf3164c014efe2abeece2
299
hpp
C++
src/tool.hpp
Montag55/gl-playground
7501718726f8933e7550abfacaeff9708a4ab270
[ "MIT" ]
null
null
null
src/tool.hpp
Montag55/gl-playground
7501718726f8933e7550abfacaeff9708a4ab270
[ "MIT" ]
null
null
null
src/tool.hpp
Montag55/gl-playground
7501718726f8933e7550abfacaeff9708a4ab270
[ "MIT" ]
null
null
null
#pragma once #include <memory> // assure compile class will be there class GraphApp; class Tool { public: Tool(GraphApp* app); virtual bool draw() const = 0; virtual bool registerTool() = 0; void setPriority(int prio); protected: GraphApp* m_linkedApp; int m_priotity; };
17.588235
38
0.67893
Montag55
235ccc2ae0a2b5fe5b4f3268928091154f4cc7f8
14,458
hpp
C++
src/libs/optframe/src/OptFrame/MultiObjValue.hpp
fellipessanha/LMRRC-Team-AIDA
8076599427df0e35890caa7301972a53ae327edb
[ "MIT" ]
1
2021-08-19T13:31:29.000Z
2021-08-19T13:31:29.000Z
src/libs/optframe/src/OptFrame/MultiObjValue.hpp
fellipessanha/LMRRC-Team-AIDA
8076599427df0e35890caa7301972a53ae327edb
[ "MIT" ]
null
null
null
src/libs/optframe/src/OptFrame/MultiObjValue.hpp
fellipessanha/LMRRC-Team-AIDA
8076599427df0e35890caa7301972a53ae327edb
[ "MIT" ]
null
null
null
#ifndef OPTFRAME_MULTI_OBJ_VALUE_HPP #define OPTFRAME_MULTI_OBJ_VALUE_HPP #include <assert.h> #include <iostream> #include <sstream> #include <tuple> #include "SingleObjValue.hpp" // must re-use some structures #include "myconcepts.h" //#include <OptFrame/printable/printable.h> namespace optframe { // Struct to handle comparison values for two MultiObjValue // It could be a triple of ints... but too many tuples already on code below!! (largely complex) // for simplicity, decided to create a struct to name each field struct MOVCompare { int lt{ 0 }; // count (<=>) -1 int eq{ 0 }; // count (<=>) 0 int gt{ 0 }; // count (<=>) +1 void add(const MOVCompare& other) { lt += other.lt; eq += other.eq; gt += other.gt; } friend std::ostream& operator<<(std::ostream& os, const MOVCompare& me) { os << "MOVCompare(lt=" << me.lt << ";eq=" << me.eq << ";gt=" << me.gt << ")"; return os; } }; // typically, template parameter packs are: template<class... Params> // here, parameter pack requires 'totally_ordered' elements (by concepts) // IMPORTANT: it may be good to already require 'basic_arithmetics' on types (+,-) (and perhaps * in next phase...) which are historically useful // if this is a bad decision, we can revert it some day :) // basic arithmetics are useful to compute 'MoveCosts', infeasibility weights and many other things template<optframe::basic_arithmetics... AllObjTypes> //template<optframe::totally_ordered... AllObjTypes> class MultiObjValue { //protected: // should be public, to make it easier is_zero verifications public: std::tuple<AllObjTypes...> objValues; public: explicit MultiObjValue(std::tuple<AllObjTypes...> allObjValues) : objValues(allObjValues) { static_assert(optframe::basic_arithmetics<MultiObjValue<AllObjTypes...>>); } template<class... Args> explicit MultiObjValue(Args&&... allObjValues) : objValues(std::forward<Args>(allObjValues)...) // does it help? //: objValues(allObjValues...) { } protected: // compare tuples and return "spaceship" comparison (-1,0,+1) to each value // magic solution adapted from: https://stackoverflow.com/questions/1198260/how-can-you-iterate-over-the-elements-of-an-stdtuple // base: I = 0 template<std::size_t I = 0> inline typename std::enable_if<I == sizeof...(AllObjTypes), MOVCompare>::type comparet(const std::tuple<AllObjTypes...>& tOther) const { return MOVCompare(); // empty comparison struct MOVCompare } // continues.. I > 0 template<std::size_t I = 0> inline typename std::enable_if < I<sizeof...(AllObjTypes), MOVCompare>::type comparet(const std::tuple<AllObjTypes...>& tOther) const { MOVCompare movc; // beware that '==', '<' and '>' may not be completely consistent, must sum individually if (std::get<I>(this->objValues) == std::get<I>(tOther)) movc.eq += 1; // equals '0' if (std::get<I>(this->objValues) < std::get<I>(tOther)) movc.lt += 1; // less '-1' if (std::get<I>(this->objValues) > std::get<I>(tOther)) movc.gt += 1; // greater '+1' // get next recursive (TODO: may pass by reference or move) MOVCompare movc2 = comparet<I + 1>(tOther); // aggregate information movc.add(movc2); // TODO: may get directly from method as 'move &&' and drop return movc; } public: // too bad, no spaceship operator widely available (yet) to depend on (example: for basic types like int, double, etc) // will create a 'compare' helper here, for other methods // -1 less, 0 equals, 1 greater, -2 different // (not that 'different' means 'uncomparable' here in general sense.. for Pareto implementations we solve this in other manner) virtual int compare(const MultiObjValue& c) const { // get number of objectives (compile-time) constexpr int N = sizeof...(AllObjTypes); MOVCompare movc = comparet(c.objValues); // do not use 'comparev' here, will lose precious time if (movc.eq == N) return 0; // all equals if (movc.lt == N) return -1; // all less if (movc.gt == N) return +1; // all greater return -2; // different/uncomparable (needs some Pareto-based or other specific rule to decide) } // comparev just "safely" exposes comparet // TODO: maybe this method may become 'constexpr'.. hard to unroll all loops and aggregate struct MOVCompare ?? MOVCompare comparev(const MultiObjValue& c) const { // c++17 fold expression std::apply could be perhaps used here, with some indexing technique (TODO) return comparet(c.objValues); } bool operator==(const MultiObjValue& c) const { return (compare(c) == 0); } bool operator!=(const MultiObjValue& c) const { // consistency return !this->operator==(c); } bool operator>(const MultiObjValue& c) const { return (compare(c) == 1); } bool operator>=(const MultiObjValue& c) const { // do NOT make it !operator<, because it may break consistency... ensure it's REALLY >= return (compare(c) >= 0); } bool operator<(const MultiObjValue& c) const { return (compare(c) == -1); } bool operator<=(const MultiObjValue& c) const { // do NOT make it !operator<, because it may break consistency... ensure it's REALLY >= int comp = compare(c); // beware that comp may be -2 return (comp == -1) || (comp == 0); } // now, going to arithmetic operators protected: // using same technique as 'comparet' // to simplify, 'operate_t' will operate over myself with += , -= and *= template<char OP, std::size_t I = 0> inline typename std::enable_if<I == sizeof...(AllObjTypes), void>::type operatet(const std::tuple<AllObjTypes...>& tOther) { // nothing to do (no objetives to compute with I==sizeof out of boundaries) } // continues.. I > 0 template<char OP, std::size_t I = 0> inline typename std::enable_if < I<sizeof...(AllObjTypes), void>::type operatet(const std::tuple<AllObjTypes...>& tOther) { // TODO: use 'OP' as consexpr to directly evaluate desired operation (will perform on compile-time) // WARNING: doing this on runtime (compiler may be smart and help us!). It would very likely... if (OP == '+') std::get<I>(this->objValues) += std::get<I>(tOther); if (OP == '-') std::get<I>(this->objValues) -= std::get<I>(tOther); // useful, but not supporting scalar multiplication yet!! by int, double.. on practice, we cannot do 'weights' yet, too hard.. //if(OP == '*') // std::get<I>(this->objValues) *= std::get<I>(tOther); } public: MultiObjValue& operator+=(const MultiObjValue& c) { operatet<'+'>(c.objValues); return *this; } MultiObjValue& operator-=(const MultiObjValue& c) { operatet<'-'>(c.objValues); return *this; } // dropping now to avoid scalar mult support //MultiObjValue& operator*=(const MultiObjValue& c) //{ // operatet<'*'>(c.objValues); // return *this; //} // division is not required! MultiObjValue operator+(const MultiObjValue& c) const { return MultiObjValue(*this) += c; } MultiObjValue operator-(const MultiObjValue& c) const { return MultiObjValue(*this) -= c; } //MultiObjValue operator*(const MultiObjValue& c) const //{ // return MultiObjValue(*this) *= c; //} // finally, must ensure this class is printable std::string toString() const { std::stringstream ss; // c++17 fold expression std::apply (helps a lot!). TODO: capture last value to avoid semi-colon ss << "MultiObjValue:("; std::apply([&](auto&&... args) { ((ss << args << ';'), ...); }, this->objValues); ss << ")"; return ss.str(); } friend std::ostream& operator<<(std::ostream& os, const MultiObjValue& me) { os << me.toString(); return os; } // this has some scope issue, if we want it to be in optframe:: only... must let access protected free /* friend inline bool numeric_is_zero(const MultiObjValue<AllObjTypes...>& tOther) { //return compare_zero<Args...>(tOther); // c++17 fold apply return std::apply([](auto... v) { return (optframe::numeric_is_zero(v) && ...); }, tOther.objValues); } */ }; /* // ================================================== // define when a MultiObjValue may be considered zero // base: I = 0 template<class... AllObjTypes, std::size_t I = 0> inline typename std::enable_if<I == sizeof...(AllObjTypes), bool>::type compare_zero(const std::tuple<AllObjTypes...>& tOther) { return true; // empty I out of bounds ust be true } // continues.. I > 0 template<class... AllObjTypes, std::size_t I = 0> inline typename std::enable_if < I<sizeof...(AllObjTypes), bool>::type compare_zero(const std::tuple<AllObjTypes...>& tOther) { // every element must be zero if (!optframe::numeric_is_zero(std::get<I>(tOther))) return false; // get next recursive (TODO: may try to short-circuit with AND &&) return compare_zero<AllObjTypes..., I + 1>(tOther); } //template<class T, class... Args> //inline typename std::enable_if<std::is_same<T, MultiObjValue<Args...>>::value, bool>::type //numeric_is_zero(const MultiObjValue<Args...>& tOther) //{ // return compare_zero<Args...>(tOther); //} */ //template<optframe::basic_arithmetics... Args, class T = optframe::MultiObjValue<Args...>> template<optframe::basic_arithmetics... Args> inline bool //inline typename std::enable_if<std::is_same<std::remove_reference_t<T>, optframe::MultiObjValue<Args...>>::value, bool>::type numeric_is_zero(const optframe::MultiObjValue<Args...>& tOther) //numeric_is_zero(const T& tOther) { //return compare_zero<Args...>(tOther); // c++17 fold apply return std::apply([](auto... v) { return (optframe::numeric_is_zero(v) && ...); }, tOther.objValues); // only issue is PROTECTED info. let it PUBLIC for now } // TODO: find a better way to capture like this! /* template<optframe::basic_arithmetics... Args, class T = MultiObjValue<Args...>> //inline const T inline typename std::enable_if<std::is_same<std::remove_reference_t<T>, optframe::MultiObjValue<Args...>>::value, T>::type numeric_zero() { std::tuple<Args...> tdef; // default values (TODO: iterate to define zero) return T(tdef); } // This conflicts with double definition and MultiObjValue<double> ... don't know how to solve it, without passing as parameter value (to avoid ambiguity!) */ /* template<optframe::basic_arithmetics... Args, class T = MultiObjValue<Args...>> //inline const T inline typename std::enable_if<std::is_same<std::remove_reference_t<T>, optframe::MultiObjValue<Args...>>::value, void>::type numeric_zero(MultiObjValue<Args...>& t) { std::tuple<Args...> tdef; // default values (TODO: iterate to define zero) t.objValues = tdef; } */ template< template<typename...> class T, typename... Args2 > inline typename std::enable_if< std::is_same< T<Args2...>, MultiObjValue<Args2...> >::value, void >::type numeric_zero(T<Args2...>& t) { std::tuple<Args2...> tdef; // default values (TODO: iterate to define zero) t.objValues = tdef; } // ----------------- template<optframe::basic_arithmetics T> inline T get_numeric_zero() { T t; optframe::numeric_zero<T>(t); return t; } // --------------------------------- // Compile-tests (validate concepts) // => Disable these with NDEBUG <= // --------------------------------- // IMPORTANT: these are different from Unit Tests, because // these help compile "to break" in advance, and if it progresses further, // something else will break in perhaps an unexplicable way... good old C++ :) // We still need to ensure proper unit testing on tests/ folder, for other reasons. #ifndef NDEBUG // TestTArithMO_is_zero should be an XEvaluation type template<optframe::basic_arithmetics ObjType> class TestTArithMO_is_zero { public: using objType = ObjType; // exporting 'objType' type, based on 'ObjType' // ObjType infMeasureX; bool outdated; // required for XEvaluation bool estimated; // required for XEvaluation bool betterStrict(const TestTArithMO_is_zero<ObjType>& e); // required bool betterNonStrict(const TestTArithMO_is_zero<ObjType>& e); // required bool equals(const TestTArithMO_is_zero<ObjType>& e); // required bool isStrictImprovement(); bool isNonStrictImprovement(); void update(TestTArithMO_is_zero<ObjType>& e); // required TestTArithMO_is_zero<ObjType> diff(const TestTArithMO_is_zero<ObjType>& e); // required void f() { assert(optframe::numeric_is_zero(infMeasureX)); } std::string toString() const { return ""; } TestTArithMO_is_zero& clone() { return *this; } ObjType evaluation() const { ObjType t; return t; } friend std::ostream& operator<<(std::ostream& os, const TestTArithMO_is_zero& me) { os << me.toString(); return os; } }; struct optframe_debug_example_test_mov { struct s_empty {}; void f() { //std::tuple<int, char> foo(10, 'x'); // C++20 'char' may not allow this... //MultiObjValue<int, char> testMOV1(foo); // C++20 'char' may not allow this... //MultiObjValue<int, char> testMOV2(20, 'y'); // C++20 'char' may not allow this... MultiObjValue<int, double> testMOV3(0, 0.000001); assert(optframe::numeric_is_zero(testMOV3)); // should be zero! MultiObjValue<int, double> num0; //optframe::numeric_zero<int, double>(num0); optframe::numeric_zero(num0); assert(optframe::numeric_is_zero(num0)); // should be zero! TestTArithMO_is_zero<MultiObjValue<int, double>> Tmo; //MultiObjValue<s_empty, char> testMOV2(s_empty(), 'y'); // ERROR: breaks 'totally_ordered' requirement }; }; // TODO: create unit tests to validate simple comparisons between MultiObjValue objects #endif } // namespace optframe #endif // OPTFRAME_MULTI_OBJ_VALUE_HPP
33.236782
155
0.634389
fellipessanha
2360bd309419075ba38cb55f88873bc1911fbde4
972
cpp
C++
src/simulator.cpp
RicoAntonioFelix/TELEVISION-SIMULATOR
318862b3a3e0a30dbcc34e9e6fb364d8ed1a4f38
[ "Apache-2.0" ]
null
null
null
src/simulator.cpp
RicoAntonioFelix/TELEVISION-SIMULATOR
318862b3a3e0a30dbcc34e9e6fb364d8ed1a4f38
[ "Apache-2.0" ]
null
null
null
src/simulator.cpp
RicoAntonioFelix/TELEVISION-SIMULATOR
318862b3a3e0a30dbcc34e9e6fb364d8ed1a4f38
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2014-2015 Rico Antonio Felix * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * @author Rico Antonio Felix <ricoantoniofelix@yahoo.com> */ /* * Local Dependency */ #include "tv.hpp" int main(int argc, char **argv) { namespace CSP = compuSUAVE_Professional; CSP::TV bedroom; CSP::Remote::toggle_mode(bedroom); CSP::Remote::change_channel(bedroom, 40); CSP::Remote::display_settings(bedroom); return 0; }
25.578947
75
0.709877
RicoAntonioFelix
236394ec20600a21bdcb7a74a3118867e877c422
144
hpp
C++
include/cgla/cgla.hpp
Blodangan/cgla
48e3418c3fbe7c2e01ec0b107f1fb862de8f48e0
[ "MIT" ]
1
2020-07-09T19:50:09.000Z
2020-07-09T19:50:09.000Z
include/cgla/cgla.hpp
Blodangan/cgla
48e3418c3fbe7c2e01ec0b107f1fb862de8f48e0
[ "MIT" ]
null
null
null
include/cgla/cgla.hpp
Blodangan/cgla
48e3418c3fbe7c2e01ec0b107f1fb862de8f48e0
[ "MIT" ]
null
null
null
#ifndef CGLA_CGLA_HPP #define CGLA_CGLA_HPP #include "config.hpp" #include "vector.hpp" #include "matrix.hpp" #include "transform.hpp" #endif
14.4
24
0.763889
Blodangan
2374a4a78a7c28009d58df9962397dfd618c6436
1,218
cpp
C++
src/test/tst4.cpp
TING2938/Gmx2020PostAnalysis
0859383946c05c7424adb1ffa72fd2f8066ce850
[ "MIT" ]
4
2021-11-23T15:02:13.000Z
2022-03-21T16:32:09.000Z
src/test/tst4.cpp
jianghuili/Gmx2020PostAnalysis
0859383946c05c7424adb1ffa72fd2f8066ce850
[ "MIT" ]
null
null
null
src/test/tst4.cpp
jianghuili/Gmx2020PostAnalysis
0859383946c05c7424adb1ffa72fd2f8066ce850
[ "MIT" ]
1
2021-11-23T15:01:49.000Z
2021-11-23T15:01:49.000Z
#include <itp/core> #include <format> #include <map> #include <vector> #define Print(...) std::cout << std::format(__VA_ARGS__) std::vector<std::string> splitString(const std::string& str) { std::vector<std::string> result; std::string::const_iterator currPos = str.begin(); const std::string::const_iterator end = str.end(); while (currPos != end) { while (currPos != end && std::isspace(*currPos)) { ++currPos; } const std::string::const_iterator startPos = currPos; while (currPos != end && !std::isspace(*currPos)) { ++currPos; } if (startPos != end) { result.emplace_back(startPos, currPos); } } return result; } int main() { Eigen::Vector3d vec(1, 3, 5); std::cout << vec << std::endl; std::cout << std::format("a is {}\n", 42); Print("b is {} {}\n", 43, 42); std::map<std::string, std::vector<std::string>> map; auto ret = splitString("Value 32 65"); map[ret[0]] = std::vector<std::string>(ret.begin()+1, ret.end()); std::vector<int> va = { 1, 2, 3 }; va.clear(); va.push_back(2); va.clear(); va.push_back(3); va.push_back(6); }
23.882353
69
0.554187
TING2938
237a2bf739070b77f847360e67b4b390ece00c8b
609
cpp
C++
201403/1.cpp
YiqinXiong/CSP_Practice
b5840117175f0370d4c1fbcc3c6ffd1fd337a04c
[ "MIT" ]
null
null
null
201403/1.cpp
YiqinXiong/CSP_Practice
b5840117175f0370d4c1fbcc3c6ffd1fd337a04c
[ "MIT" ]
null
null
null
201403/1.cpp
YiqinXiong/CSP_Practice
b5840117175f0370d4c1fbcc3c6ffd1fd337a04c
[ "MIT" ]
null
null
null
/* * 用时 10分 * 得分 100分 */ #include <cstdio> #include <iostream> using namespace std; const int MAX_N = 2005; bool arr[MAX_N]; int N; int main() { int ans = 0; fill(begin(arr), end(arr), false); cin >> N; for (int i = 0; i < N; i++) { int num; cin >> num; //把数字范围调整为[0,2000] num += 1000; arr[num] = true; } //检索相反数 int base = 0 + 1000; for (int offset = 1; offset <= 1000; offset++) { if (arr[base - offset] && arr[base + offset]) { ans++; } } cout << ans << endl; return 0; }
16.459459
53
0.456486
YiqinXiong
237b40b10cccd5bfd935e1c28b2f669e41669b0d
1,376
hpp
C++
libs/input/include/sge/input/processor.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/input/include/sge/input/processor.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/input/include/sge/input/processor.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SGE_INPUT_PROCESSOR_HPP_INCLUDED #define SGE_INPUT_PROCESSOR_HPP_INCLUDED #include <sge/core/detail/class_symbol.hpp> #include <sge/input/processor_fwd.hpp> #include <sge/input/cursor/container.hpp> #include <sge/input/detail/symbol.hpp> #include <sge/input/focus/container.hpp> #include <sge/input/joypad/container.hpp> #include <sge/input/keyboard/container.hpp> #include <sge/input/mouse/container.hpp> #include <sge/window/object_fwd.hpp> #include <fcppt/nonmovable.hpp> namespace sge::input { class SGE_CORE_DETAIL_CLASS_SYMBOL processor { FCPPT_NONMOVABLE(processor); protected: SGE_INPUT_DETAIL_SYMBOL processor(); public: SGE_INPUT_DETAIL_SYMBOL virtual ~processor(); [[nodiscard]] virtual sge::window::object &window() const = 0; [[nodiscard]] virtual sge::input::cursor::container cursors() const = 0; [[nodiscard]] virtual sge::input::focus::container foci() const = 0; [[nodiscard]] virtual sge::input::joypad::container joypads() const = 0; [[nodiscard]] virtual sge::input::keyboard::container keyboards() const = 0; [[nodiscard]] virtual sge::input::mouse::container mice() const = 0; }; } #endif
26.980392
78
0.736919
cpreh
237f6fdbd1cc682f87a412f4e80acb75d1d96931
5,508
cpp
C++
source/projects/ar.swell_tilde/ar.swell_tilde.cpp
isabelgk/airfx
bc97f9a093ceba9cd27020f4b4db1c508a37545f
[ "MIT" ]
16
2021-06-20T04:51:09.000Z
2022-03-30T03:03:32.000Z
source/projects/ar.swell_tilde/ar.swell_tilde.cpp
isabelgk/airfx
bc97f9a093ceba9cd27020f4b4db1c508a37545f
[ "MIT" ]
7
2021-06-20T01:22:22.000Z
2022-01-24T14:33:31.000Z
source/projects/ar.swell_tilde/ar.swell_tilde.cpp
isabelgk/airfx
bc97f9a093ceba9cd27020f4b4db1c508a37545f
[ "MIT" ]
null
null
null
#include "c74_min.h" using namespace c74::min; class swell : public object<swell>, public vector_operator<> { public: MIN_DESCRIPTION {"adds attack"}; MIN_TAGS {""}; MIN_AUTHOR {"Isabel Kaspriskie"}; inlet<> in1 {this, "(signal) Input1"}; inlet<> in2 {this, "(signal) Input2"}; outlet<> out1 {this, "(signal) Output1", "signal"}; outlet<> out2 {this, "(signal) Output2", "signal"}; attribute<number, threadsafe::no, limit::clamp> A {this, "threshold", 0.9, range {0.0, 1.0} }; attribute<number, threadsafe::no, limit::clamp> B {this, "swell", 0.5, range {0.0, 1.0} }; attribute<number, threadsafe::no, limit::clamp> C {this, "mix", 1.0, range {0.0, 1.0} }; message<> dspsetup {this, "dspsetup", MIN_FUNCTION { A = 0.9; B = 0.5; C = 1.0; swellL = 0.0; swellR = 0.0; louderL = false; louderR = false; fpNShapeL = 0.0; fpNShapeR = 0.0; //this is reset: values being initialized only once. Startup values, whatever they are. return {}; } }; void operator()(audio_bundle _input, audio_bundle _output) { double* in1 = _input.samples(0); double* in2 = _input.samples(1); double* out1 = _output.samples(0); double* out2 = _output.samples(1); long sampleFrames = _input.frame_count(); double overallscale = 1.0; overallscale /= 44100.0; overallscale *= samplerate(); double thresholdOn = pow(A,2) * B; double speedOn = (pow(B,2)*0.001)/overallscale; double thresholdOff = thresholdOn * B; double speedOff = (sin(B)*0.01)/overallscale; double wet = C; double dry = 1.0 - wet; long double drySampleL; long double drySampleR; long double inputSampleL; long double inputSampleR; while (--sampleFrames >= 0) { inputSampleL = *in1; inputSampleR = *in2; if (inputSampleL<1.2e-38 && -inputSampleL<1.2e-38) { static int noisesource = 0; //this declares a variable before anything else is compiled. It won't keep assigning //it to 0 for every sample, it's as if the declaration doesn't exist in this context, //but it lets me add this denormalization fix in a single place rather than updating //it in three different locations. The variable isn't thread-safe but this is only //a random seed and we can share it with whatever. noisesource = noisesource % 1700021; noisesource++; int residue = noisesource * noisesource; residue = residue % 170003; residue *= residue; residue = residue % 17011; residue *= residue; residue = residue % 1709; residue *= residue; residue = residue % 173; residue *= residue; residue = residue % 17; double applyresidue = residue; applyresidue *= 0.00000001; applyresidue *= 0.00000001; inputSampleL = applyresidue; } if (inputSampleR<1.2e-38 && -inputSampleR<1.2e-38) { static int noisesource = 0; noisesource = noisesource % 1700021; noisesource++; int residue = noisesource * noisesource; residue = residue % 170003; residue *= residue; residue = residue % 17011; residue *= residue; residue = residue % 1709; residue *= residue; residue = residue % 173; residue *= residue; residue = residue % 17; double applyresidue = residue; applyresidue *= 0.00000001; applyresidue *= 0.00000001; inputSampleR = applyresidue; //this denormalization routine produces a white noise at -300 dB which the noise //shaping will interact with to produce a bipolar output, but the noise is actually //all positive. That should stop any variables from going denormal, and the routine //only kicks in if digital black is input. As a final touch, if you save to 24-bit //the silence will return to being digital black again. } drySampleL = inputSampleL; drySampleR = inputSampleR; if (fabs(inputSampleL) > thresholdOn && louderL == false) louderL = true; if (fabs(inputSampleL) < thresholdOff && louderL == true) louderL = false; if (louderL == true) swellL = (swellL * (1.0 - speedOn)) + speedOn; else swellL *= (1.0 - speedOff); //both poles are a Zeno's arrow: approach but never get to either 1.0 or 0.0 inputSampleL *= swellL; if (fabs(inputSampleR) > thresholdOn && louderR == false) louderR = true; if (fabs(inputSampleR) < thresholdOff && louderR == true) louderR = false; if (louderR == true) swellR = (swellR * (1.0 - speedOn)) + speedOn; else swellR *= (1.0 - speedOff); //both poles are a Zeno's arrow: approach but never get to either 1.0 or 0.0 inputSampleR *= swellR; if (wet !=1.0) { inputSampleL = (inputSampleL * wet) + (drySampleL * dry); inputSampleR = (inputSampleR * wet) + (drySampleR * dry); } //stereo 64 bit dither, made small and tidy. int expon; frexp((double)inputSampleL, &expon); long double dither = (rand()/(RAND_MAX*7.737125245533627e+25))*pow(2,expon+62); dither /= 536870912.0; //needs this to scale to 64 bit zone inputSampleL += (dither-fpNShapeL); fpNShapeL = dither; frexp((double)inputSampleR, &expon); dither = (rand()/(RAND_MAX*7.737125245533627e+25))*pow(2,expon+62); dither /= 536870912.0; //needs this to scale to 64 bit zone inputSampleR += (dither-fpNShapeR); fpNShapeR = dither; //end 64 bit dither *out1 = inputSampleL; *out2 = inputSampleR; *in1++; *in2++; *out1++; *out2++; } } private: long double fpNShapeL; long double fpNShapeR; //default stuff long double swellL; long double swellR; bool louderL; bool louderR; }; MIN_EXTERNAL(swell);
34.21118
95
0.662309
isabelgk
238abc8dd6f4da245d254d61a20a3fa92318a2d3
424
cpp
C++
Limux/src/Platform/OpenGL/OpenGLBuffer.cpp
silvertakana/Lumix
35a6c0d35229a71dc4445369bb400c4e5adca1af
[ "MIT" ]
2
2021-09-25T05:22:50.000Z
2021-09-30T21:04:11.000Z
Limux/src/Platform/OpenGL/OpenGLBuffer.cpp
silvertakana/Lumix
35a6c0d35229a71dc4445369bb400c4e5adca1af
[ "MIT" ]
null
null
null
Limux/src/Platform/OpenGL/OpenGLBuffer.cpp
silvertakana/Lumix
35a6c0d35229a71dc4445369bb400c4e5adca1af
[ "MIT" ]
null
null
null
#include "lmxpch.h" #include "OpenGLBuffer.h" namespace LMX { OpenGLBuffer::OpenGLBuffer(void* data, uint32_t size) { glCreateBuffers(1, &ID); glNamedBufferData(ID, size, data, GL_STATIC_DRAW); } void OpenGLBuffer::Bind(GLenum type) const { glBindBuffer(type, ID); } void OpenGLBuffer::UnBind(GLenum type) const { glBindBuffer(type, 0); } OpenGLBuffer::~OpenGLBuffer() { glDeleteBuffers(1, &ID); } }
16.96
54
0.70283
silvertakana
238dca0057b6ce883051786807ee1eb9f032f726
13,571
cpp
C++
samples/common/cns_openpose/postprocess_body_pose.cpp
HFauto/CNStream
1d4847327fff83eedbc8de6911855c5f7bb2bf22
[ "Apache-2.0" ]
172
2019-08-24T10:05:14.000Z
2022-03-29T07:45:18.000Z
samples/common/cns_openpose/postprocess_body_pose.cpp
HFauto/CNStream
1d4847327fff83eedbc8de6911855c5f7bb2bf22
[ "Apache-2.0" ]
27
2019-09-01T11:04:45.000Z
2022-01-17T09:27:07.000Z
samples/common/cns_openpose/postprocess_body_pose.cpp
HFauto/CNStream
1d4847327fff83eedbc8de6911855c5f7bb2bf22
[ "Apache-2.0" ]
72
2019-08-24T10:13:06.000Z
2022-03-28T08:26:05.000Z
/************************************************************************* * Copyright (C) [2021] by Cambricon, Inc. All rights reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * 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 <opencv2/opencv.hpp> #include <algorithm> #include <array> #include <cmath> #include <cstring> #include <memory> #include <string> #include <tuple> #include <utility> #include <vector> #include "cnstream_frame_va.hpp" #include "cns_openpose.hpp" #include "postproc.hpp" void RemapKeypoints(cns_openpose::Keypoints* keypoints, int src_w, int src_h, int dst_w, int dst_h) { float scaling_factor = std::min(1.0f * src_w / dst_w, 1.0f * src_h / dst_h); const int scaled_w = scaling_factor * dst_w; const int scaled_h = scaling_factor * dst_h; for (auto& points : *keypoints) { for (auto& point : points) { point.x -= (src_w - scaled_w) / 2.0f; point.y -= (src_h - scaled_h) / 2.0f; point.x = std::floor(1.0f * point.x / scaled_w * dst_w); point.y = std::floor(1.0f * point.y / scaled_w * dst_w); } } } /** * @brief Post process for body pose */ template <int knKeypoints, int knLimbs> class PostprocPose : public cnstream::Postproc { static constexpr int knHeatmaps = knKeypoints + knLimbs * 2; public: virtual ~PostprocPose() {} using Heatmaps = std::array<cv::Mat, knHeatmaps>; int Execute(const std::vector<float*>& net_outputs, const std::shared_ptr<edk::ModelLoader>& model, const cnstream::CNFrameInfoPtr& package) override; protected: virtual const std::array<std::pair<int, int>, knLimbs>& GetHeatmapIndexs() = 0; virtual const std::array<std::pair<int, int>, knLimbs>& GetLimbEndpointPairs() = 0; private: Heatmaps GetHeatmaps(float* net_output, const std::shared_ptr<edk::ModelLoader>& model); cns_openpose::Keypoints GetKeypoints(const Heatmaps& heatmaps); cns_openpose::Limbs GetLimbs(const Heatmaps& heatmaps, const cns_openpose::Keypoints& keypoints); }; // class PostprocPose template<int knKeypoints, int knLimbs> int PostprocPose<knKeypoints, knLimbs>::Execute(const std::vector<float*>& net_outputs, const std::shared_ptr<edk::ModelLoader>& model, const cnstream::CNFrameInfoPtr& package) { // model output in NCHW order. see parameter named data_order in Inferencer module. if (model->OutputShape(0).C() != knHeatmaps) LOGF(POSTPROC_POSE) << "The number of heatmaps in model mismatched."; auto frame = package->collection.Get<cnstream::CNDataFramePtr>(cnstream::kCNDataFrameTag); auto heatmaps = GetHeatmaps(net_outputs[0], model); auto keypoints = GetKeypoints(heatmaps); auto total_limbs = GetLimbs(heatmaps, keypoints); RemapKeypoints(&keypoints, model->InputShape(0).W(), model->InputShape(0).H(), frame->width, frame->height); package->collection.Add(cns_openpose::kPoseKeypointsTag, keypoints); package->collection.Add(cns_openpose::kPoseLimbsTag, total_limbs); return 0; } template <int knKeypoints, int knLimbs> typename PostprocPose<knKeypoints, knLimbs>::Heatmaps PostprocPose<knKeypoints, knLimbs>::GetHeatmaps(float* net_output, const std::shared_ptr<edk::ModelLoader>& model) { Heatmaps heatmaps; const int src_w = model->OutputShape(0).W(); const int src_h = model->OutputShape(0).H(); const int src_heatmap_len = src_w * src_h; const cv::Size dst_size(model->InputShape(0).W(), model->InputShape(0).H()); for (int i = 0; i < knHeatmaps; ++i) { cv::Mat src(src_h, src_w, CV_32FC1, net_output + i * src_heatmap_len); cv::Mat dst; cv::resize(src, dst, dst_size, cv::INTER_CUBIC); heatmaps[i] = std::move(dst); } return heatmaps; } template <int knKeypoints, int knLimbs> cns_openpose::Keypoints PostprocPose<knKeypoints, knLimbs>::GetKeypoints(const Heatmaps& heatmaps) { cns_openpose::Keypoints keypoints(knKeypoints - 1); // ignore background for (int i = 0; i < knKeypoints - 1; ++i) { static constexpr double kThreshold = 0.1; cv::Mat confidence_map = heatmaps[i]; // image binaryzation cv::Mat smooth; cv::GaussianBlur(confidence_map, smooth, cv::Size(3, 3), 0, 0); cv::Mat binary; cv::threshold(smooth, binary, kThreshold, 255, cv::THRESH_BINARY); binary.convertTo(binary, CV_8UC1); // find contours std::vector<std::vector<cv::Point>> contours; cv::findContours(binary, contours, cv::RETR_TREE, cv::CHAIN_APPROX_SIMPLE); // local maximum std::vector<cv::Point> points; for (const auto& contour : contours) { cv::Mat mask = cv::Mat::zeros(binary.rows, binary.cols, smooth.type()); cv::fillConvexPoly(mask, contour, cv::Scalar(1)); cv::Point max_loc; cv::minMaxLoc(smooth.mul(mask), NULL, NULL, NULL, &max_loc); points.push_back(max_loc); } keypoints[i] = std::move(points); } return keypoints; } static std::vector<cv::Point> Sampling(cv::Point first_end, const cv::Point& second_end, int nsamples) { cv::Point distance = second_end - first_end; float x_step = 1.0 * distance.x / (nsamples - 1); float y_step = 1.0 * distance.y / (nsamples - 1); std::vector<cv::Point> samples; samples.push_back(first_end); for (int i = 1; i < nsamples - 1; ++i) { samples.emplace_back(cv::Point(std::round(first_end.x + x_step * i), std::round(first_end.y + y_step * i))); } samples.push_back(second_end); return samples; } template <int knKeypoints, int knLimbs> cns_openpose::Limbs PostprocPose<knKeypoints, knLimbs>::GetLimbs(const Heatmaps& heatmaps, const cns_openpose::Keypoints& keypoints) { static constexpr int knSamples = 10; // number of samples between tow points static constexpr float kPafThreshold = 0.1; static constexpr float kSamplesMatchThreshold = 0.7; cns_openpose::Limbs total_limbs; for (int limb_idx = 0; limb_idx < knLimbs; ++limb_idx) { static constexpr int kPafHeatmapsOffset = knKeypoints; int first_ends_idx = GetLimbEndpointPairs()[limb_idx].first; int second_ends_idx = GetLimbEndpointPairs()[limb_idx].second; const cv::Mat& paf_first = heatmaps[kPafHeatmapsOffset + GetHeatmapIndexs()[limb_idx].first]; const cv::Mat& paf_second = heatmaps[kPafHeatmapsOffset + GetHeatmapIndexs()[limb_idx].second]; // both ends of the limb const std::vector<cv::Point>& first_ends = keypoints[first_ends_idx]; const std::vector<cv::Point>& second_ends = keypoints[second_ends_idx]; const int knFirstEnds = static_cast<int>(first_ends.size()); const int knSecondEnds = static_cast<int>(second_ends.size()); std::vector<std::pair<cv::Point, cv::Point>> limbs; // stores second endpoint status (selected or not), selected by which first endpoint and the score. // 0: selected or not, 1: index in limbs, 2: limb score std::vector<std::tuple<bool, size_t, float>> second_end_selected_status(knSecondEnds, std::make_tuple(false, -1, -1.0f)); // find max score between first ends and second ends for (int first_end_idx = 0; first_end_idx < knFirstEnds; ++first_end_idx) { int selected_second_end_idx = -1; float max_score = -1; const cv::Point& first_end = first_ends[first_end_idx]; for (int second_end_idx = 0; second_end_idx < knSecondEnds; ++second_end_idx) { const cv::Point& second_end = second_ends[second_end_idx]; std::pair<float, float> distance = std::make_pair(second_end.x - first_end.x, second_end.y - first_end.y); float norm2 = std::sqrt(distance.first * distance.first + distance.second * distance.second); distance.first /= norm2; distance.second /= norm2; // p(u) std::vector<cv::Point> sample_points = Sampling(first_end, second_end, knSamples); // L(p(u)) float sum_of_sample_score = 0; int num_over_threshold = 0; for (int sample_idx = 0; sample_idx < knSamples; ++sample_idx) { const auto& sample_point = sample_points[sample_idx]; float paf_first_value = paf_first.at<float>(sample_point); float paf_second_value = paf_second.at<float>(sample_point); float score = paf_first_value * distance.first + paf_second_value * distance.second; if (score > kPafThreshold) { ++num_over_threshold; sum_of_sample_score += score; } } // for samples if (1.0f * num_over_threshold / knSamples > kSamplesMatchThreshold) { float avg_score = sum_of_sample_score / sample_points.size(); if (avg_score > max_score) { const auto& selected_status = second_end_selected_status[second_end_idx]; if (std::get<0>(selected_status) && std::get<2>(selected_status) > avg_score) { // selected by other first endpoint and pre-score greater than current score continue; } selected_second_end_idx = second_end_idx; max_score = avg_score; } } // if kSamplesMatchThreshold } // for second ends if (-1 != selected_second_end_idx) { auto& selected_status = second_end_selected_status[selected_second_end_idx]; // found best matchs second end, positions in keypoints vector limbs.emplace_back(std::make_pair(cv::Point(first_ends_idx, first_end_idx), cv::Point(second_ends_idx, selected_second_end_idx))); if (std::get<0>(selected_status)) { // selected by other first endpoint, but current score greater than pre-score. remove limb limbs.erase(limbs.begin() + std::get<1>(selected_status)); } // save second endpoint selected status std::get<0>(selected_status) = true; std::get<1>(selected_status) = limbs.size() - 1; std::get<2>(selected_status) = max_score; } } // for first ends total_limbs.push_back(std::move(limbs)); } // for keypoints return total_limbs; } static constexpr int knBody25Keypoints = 26; // 25 keypoints + 1 background static constexpr int knBody25Limbs = 26; class PostprocBody25Pose : public PostprocPose<knBody25Keypoints, knBody25Limbs> { public: ~PostprocBody25Pose() = default; private: const std::array<std::pair<int, int>, knBody25Limbs>& GetHeatmapIndexs() override { static constexpr std::array<std::pair<int, int>, knBody25Limbs> kBody25HeatmapIndexs { std::make_pair(0, 1), {14, 15}, {22, 23}, {16, 17}, {18, 19}, {24, 25}, {26, 27}, {6, 7}, {2, 3}, {4, 5}, {8, 9}, {10, 11}, {12, 13}, {30, 31}, {32, 33}, {36, 37}, {34, 35}, {38, 39}, {20, 21}, {28, 29}, {40, 41}, {42, 43}, {44, 45}, {46, 47}, {48, 49}, {50, 51} }; return kBody25HeatmapIndexs; } const std::array<std::pair<int, int>, knBody25Limbs>& GetLimbEndpointPairs() override { static constexpr std::array<std::pair<int, int>, knBody25Limbs> kBody25LimbEndpointPairs { std::make_pair(1, 8), {1, 2}, {1, 5}, {2, 3}, {3, 4}, {5, 6}, {6, 7}, {8, 9}, {9, 10}, {10, 11}, {8, 12}, {12, 13}, {13, 14}, {1, 0}, {0, 15}, {15, 17}, {0, 16}, {16, 18}, {2, 17}, {5, 18}, {14, 19}, {19, 20}, {14, 21}, {11, 22}, {22, 23}, {11, 24} }; return kBody25LimbEndpointPairs; } DECLARE_REFLEX_OBJECT_EX(PostprocBody25Pose, cnstream::Postproc) }; // class PostprocBody25Pose IMPLEMENT_REFLEX_OBJECT_EX(PostprocBody25Pose, cnstream::Postproc) static constexpr int knCOCOKeypoints = 19; // 18 keypoints + 1 background static constexpr int knCOCOLimbs = 19; class PostprocCOCOPose : public PostprocPose<knCOCOKeypoints, knCOCOLimbs> { public: ~PostprocCOCOPose() = default; private: const std::array<std::pair<int, int>, knCOCOLimbs>& GetHeatmapIndexs() override { static constexpr std::array<std::pair<int, int>, knCOCOLimbs> kCOCOHeatmapIndexs { std::make_pair(12, 13), {20, 21}, {14, 15}, {16, 17}, {22, 23}, {24, 25}, {0, 1}, {2, 3}, {4, 5}, {6, 7}, {8, 9}, {10, 11}, {28, 29}, {30, 31}, {34, 35}, {32, 33}, {36, 37}, {18, 19}, {26, 27} }; return kCOCOHeatmapIndexs; } const std::array<std::pair<int, int>, knCOCOLimbs>& GetLimbEndpointPairs() override { static constexpr std::array<std::pair<int, int>, knCOCOLimbs> kCOCOLimbEndpointPairs { std::make_pair(1, 2), {1, 5}, {2, 3}, {3, 4}, {5, 6}, {6, 7}, {1, 8}, {8, 9}, {9, 10}, {1, 11}, {11, 12}, {12, 13}, {1, 0}, {0, 14}, {14, 16}, {0, 15}, {15, 17}, {2, 16}, {5, 17} }; return kCOCOLimbEndpointPairs; } DECLARE_REFLEX_OBJECT_EX(PostprocCOCOPose, cnstream::Postproc) }; // class PostprocCOCOPose IMPLEMENT_REFLEX_OBJECT_EX(PostprocCOCOPose, cnstream::Postproc)
44.061688
116
0.658905
HFauto
2391b76a3b21df73fc82d4bd351a1c50c20f30a4
482
cpp
C++
Aula03/usoScanf.cpp
renancosta/ProgramacaoI20221
3bff0c2d39d97ba442683e66ea1551d3777f79ba
[ "MIT" ]
null
null
null
Aula03/usoScanf.cpp
renancosta/ProgramacaoI20221
3bff0c2d39d97ba442683e66ea1551d3777f79ba
[ "MIT" ]
null
null
null
Aula03/usoScanf.cpp
renancosta/ProgramacaoI20221
3bff0c2d39d97ba442683e66ea1551d3777f79ba
[ "MIT" ]
null
null
null
#include<stdlib.h> #include<stdio.h> main(){ int idade1,idade2; float altura1,altura2; printf("Pessoa 1\n"); printf("Informe sua idade: "); scanf("%d",&idade1); printf("Informe sua altura: "); scanf("%f",&altura1); printf("\nPessoa 2\n"); printf("Informe sua idade: "); scanf("%d",&idade2); printf("Informe sua altura: "); scanf("%f",&altura2); printf("Pessoa 1\nIdade: %d\nAltura %.2f",idade1,altura1); printf("\nPessoa 2\nIdade: %d\nAltura %.2f",idade2,altura2); }
24.1
61
0.653527
renancosta
23926c104d34bbe4441171984d5ee3425037264e
689
cpp
C++
P1516.cpp
AndrewWayne/OI_Learning
0fe8580066704c8d120a131f6186fd7985924dd4
[ "MIT" ]
null
null
null
P1516.cpp
AndrewWayne/OI_Learning
0fe8580066704c8d120a131f6186fd7985924dd4
[ "MIT" ]
null
null
null
P1516.cpp
AndrewWayne/OI_Learning
0fe8580066704c8d120a131f6186fd7985924dd4
[ "MIT" ]
null
null
null
#include <cstdio> #include <iostream> using namespace std; long long x, y, m, n, L, d, a, b; void exgcd(long long a, long long b, long long &d, long long &x, long long &y){ if(b) exgcd(b, a%b, d, y, x), y -= x*(a/b); else d = a, x = 1, y = 0; } long long gcd(int u, int v){ return v ? gcd(v, u%v) : u; } int main(){ cin >> x >> y >> m >> n >> L; a = n - m; b = L; L = x - y; if(a < 0){ a = -a; L = -L; } d = gcd(a, b); exgcd(a, b, d, x, y); if(L % d != 0){ cout << "Impossible" << endl; return 0; } x = (x * (L/d) % (b/d) + b/d)%(b/d); cout << x << endl; return 0; }
19.138889
79
0.404935
AndrewWayne
2392982e76eb752ea3fe78ed3b5511ca2d3ee45a
194
cpp
C++
leetcode/Algorithms/FactorialTrailingZeroes/solution.cpp
hxdone/puzzles
b729bce8a61f77ad7cbb70957e00c5ade9a0a35f
[ "Apache-2.0" ]
2
2015-07-03T03:05:30.000Z
2015-07-03T03:05:31.000Z
leetcode/Algorithms/FactorialTrailingZeroes/solution.cpp
hxdone/puzzles
b729bce8a61f77ad7cbb70957e00c5ade9a0a35f
[ "Apache-2.0" ]
null
null
null
leetcode/Algorithms/FactorialTrailingZeroes/solution.cpp
hxdone/puzzles
b729bce8a61f77ad7cbb70957e00c5ade9a0a35f
[ "Apache-2.0" ]
null
null
null
// by hxdone class Solution { public: int trailingZeroes(int n) { int sum = 0; while (n) { n /= 5; sum += n; } return sum; } };
13.857143
31
0.391753
hxdone
2393edef020fbe0b95563bb6486cda2d0ac05229
3,938
cpp
C++
src/quadtree.cpp
JamesBremner/quadtree
5200978410006b67c67e64659c98fb3cb20c7669
[ "BSD-2-Clause" ]
null
null
null
src/quadtree.cpp
JamesBremner/quadtree
5200978410006b67c67e64659c98fb3cb20c7669
[ "BSD-2-Clause" ]
null
null
null
src/quadtree.cpp
JamesBremner/quadtree
5200978410006b67c67e64659c98fb3cb20c7669
[ "BSD-2-Clause" ]
null
null
null
#include <iostream> #include <sstream> #include <vector> #include "cRunWatch.h" #include "quadtree.h" namespace quad { std::vector<cPoint *> cCell::myPointsFound; cCell::cCell(const cPoint &p, float d) : center(p), dim(d / 2), nw(0) { } cCell::~cCell() { if (nw) { delete nw; delete sw; delete ne; delete se; } } bool cCell::contains(const cPoint &p) const { if (!(center.x - dim <= p.x && p.x <= center.x + dim)) return false; if (!(center.y - dim <= p.y && p.y <= center.y + dim)) return false; return true; } void cCell::subdivide() { float dim2 = dim / 2; nw = new cCell(cPoint(center.x - dim2, center.y - dim2), dim); sw = new cCell(cPoint(center.x - dim2, center.y + dim2), dim); ne = new cCell(cPoint(center.x + dim2, center.y - dim2), dim); se = new cCell(cPoint(center.x + dim2, center.y + dim2), dim); if (myPoint.valid) { // move point to child childInsert(myPoint); myPoint.valid = false; } } bool cCell::insert(const cPoint &p) { // check point located in cell if (!contains(p)) return false; // check cell is an empty leaf if (!myPoint.valid) { if (!nw) { // store point here myPoint = p; return true; } } else if (myPoint == p) { // point at same location as previously added //std::cout << "dup "; //throw std::runtime_error("dup"); return true; } // subdivide leaf if (!nw) subdivide(); childInsert(p); return true; } bool cCell::childInsert(const cPoint &p) { if (nw->insert(p)) return true; if (sw->insert(p)) return true; if (ne->insert(p)) return true; if (se->insert(p)) return true; std::cout << "quadtree insertion error\n" << p << " " << text(false) << "\n"; throw std::runtime_error("quadtree insertion error"); } std::vector<cPoint *> cCell::find(const cCell &range) { myPointsFound.clear(); findrec(range); return myPointsFound; } void cCell::findrec( const cCell &range) { //std::cout << "look in " << text(false) << "\n"; // check that range and cell overlap if (!intersect(range)) return; // heck if point in cell is in range if (myPoint.valid) if (range.contains(myPoint)) { //std::cout << "found " << myPoint.text(); myPointsFound.push_back(&myPoint); } if (!nw) return; // find points in children and range nw->findrec(range); sw->findrec(range); ne->findrec(range); se->findrec(range); } bool cCell::intersect(const cCell &range) const { float dx = center.x - range.center.x; float dy = center.y - range.center.y; float d2 = dx * dx + dy * dy; return d2 < (dim + range.dim) * (dim + range.dim); } std::string cCell::text(bool children) const { std::stringstream ss; if (myPoint.valid) ss << "point " << myPoint; else ss << "empty "; ss << " in cell at " << center << " size " << 2 * dim << "\n"; if (children) if (nw) { ss << nw->text(); ss << sw->text(); ss << ne->text(); ss << se->text(); } return ss.str(); } }
24.308642
70
0.452514
JamesBremner
2398c81e98139b368926645cda7a8894d157327e
14,975
cc
C++
Cassie_Example/opt_two_step/gen/opt/J_u_leftToeHeight_cassie.cc
prem-chand/Cassie_CFROST
da4bd51442f86e852cbb630cc91c9a380a10b66d
[ "BSD-3-Clause" ]
null
null
null
Cassie_Example/opt_two_step/gen/opt/J_u_leftToeHeight_cassie.cc
prem-chand/Cassie_CFROST
da4bd51442f86e852cbb630cc91c9a380a10b66d
[ "BSD-3-Clause" ]
null
null
null
Cassie_Example/opt_two_step/gen/opt/J_u_leftToeHeight_cassie.cc
prem-chand/Cassie_CFROST
da4bd51442f86e852cbb630cc91c9a380a10b66d
[ "BSD-3-Clause" ]
null
null
null
/* * Automatically Generated from Mathematica. * Thu 14 Oct 2021 09:55:24 GMT-04:00 */ #ifdef MATLAB_MEX_FILE #include <stdexcept> #include <cmath> #include<math.h> /** * Copied from Wolfram Mathematica C Definitions file mdefs.hpp * Changed marcos to inline functions (Eric Cousineau) */ inline double Power(double x, double y) { return pow(x, y); } inline double Sqrt(double x) { return sqrt(x); } inline double Abs(double x) { return fabs(x); } inline double Exp(double x) { return exp(x); } inline double Log(double x) { return log(x); } inline double Sin(double x) { return sin(x); } inline double Cos(double x) { return cos(x); } inline double Tan(double x) { return tan(x); } inline double ArcSin(double x) { return asin(x); } inline double ArcCos(double x) { return acos(x); } inline double ArcTan(double x) { return atan(x); } /* update ArcTan function to use atan2 instead. */ inline double ArcTan(double x, double y) { return atan2(y,x); } inline double Sinh(double x) { return sinh(x); } inline double Cosh(double x) { return cosh(x); } inline double Tanh(double x) { return tanh(x); } const double E = 2.71828182845904523536029; const double Pi = 3.14159265358979323846264; const double Degree = 0.01745329251994329576924; inline double Sec(double x) { return 1/cos(x); } inline double Csc(double x) { return 1/sin(x); } #endif /* * Sub functions */ static void output1(double *p_output1,const double *var1) { double t197; double t85; double t213; double t476; double t525; double t739; double t750; double t769; double t790; double t580; double t606; double t709; double t991; double t1310; double t1366; double t1375; double t1428; double t1226; double t1272; double t1300; double t1480; double t1492; double t1496; double t1749; double t1758; double t1759; double t1885; double t2016; double t2025; double t2028; double t2178; double t2181; double t2189; double t2274; double t2394; double t2514; double t2574; double t2585; double t2673; double t2678; double t2696; double t2743; double t2752; double t2761; double t2786; double t2858; double t2860; double t2910; double t3006; double t3013; double t3019; double t3065; double t3098; double t3117; double t3123; double t3193; double t3195; double t3196; double t3597; double t3603; double t3615; double t104; double t160; double t3974; double t3988; double t3992; double t775; double t822; double t836; double t1392; double t1432; double t1446; double t1501; double t1548; double t1552; double t1790; double t1993; double t2004; double t4039; double t4040; double t4056; double t2138; double t2155; double t2177; double t2280; double t2286; double t2299; double t2406; double t2486; double t4174; double t4182; double t4187; double t4193; double t4203; double t4259; double t2598; double t2622; double t2629; double t2653; double t2778; double t2788; double t2833; double t4398; double t4415; double t4444; double t4538; double t4543; double t4581; double t2965; double t3000; double t3004; double t3119; double t3187; double t3188; double t4597; double t4625; double t4631; double t4661; double t4683; double t4722; double t3291; double t3327; double t3388; double t4739; double t4742; double t4782; double t4830; double t4839; double t4858; double t3947; double t3994; double t3998; double t4035; double t4160; double t4189; double t4273; double t4452; double t4596; double t4655; double t4728; double t4784; double t4864; double t4894; double t4898; double t4981; double t4993; double t5034; double t5056; double t5100; double t5154; double t1080; double t5453; double t5454; double t5469; double t5507; double t5514; double t5524; double t5680; double t5711; double t5712; double t5747; double t5753; double t5755; double t5818; double t5840; double t5857; double t5884; double t5888; double t5897; double t5916; double t5917; double t5931; double t5956; double t6029; double t6140; double t6523; double t6563; double t6579; double t6672; double t6676; double t6677; double t6716; double t6751; double t6757; double t6783; double t6848; double t6854; double t6875; double t6962; double t6963; double t7076; double t7088; double t7127; double t7225; double t7258; double t7264; double t7332; double t7405; double t7511; double t7615; double t7616; double t7716; double t8823; double t8869; double t8914; double t9342; double t9349; double t9359; double t9364; double t9496; double t9513; double t9516; double t9666; double t9706; double t9760; double t9911; double t10031; double t10033; double t10068; double t10072; double t10121; double t10744; double t10752; double t10759; double t10794; double t10807; double t10818; double t10822; double t10835; double t10846; double t10893; double t10966; double t10976; double t10984; double t11108; double t11132; double t11137; double t11188; double t11191; double t11198; double t11201; double t11209; double t11362; double t11364; double t11374; double t11270; t197 = Sin(var1[4]); t85 = Cos(var1[6]); t213 = Sin(var1[5]); t476 = Cos(var1[5]); t525 = Sin(var1[6]); t739 = Cos(var1[7]); t750 = -1.*t739; t769 = 1. + t750; t790 = Sin(var1[7]); t580 = -1.*t85*t197*t213; t606 = -1.*t476*t197*t525; t709 = t580 + t606; t991 = Cos(var1[4]); t1310 = Cos(var1[8]); t1366 = -1.*t1310; t1375 = 1. + t1366; t1428 = Sin(var1[8]); t1226 = -1.*t991*t739; t1272 = t709*t790; t1300 = t1226 + t1272; t1480 = -1.*t476*t85*t197; t1492 = t197*t213*t525; t1496 = t1480 + t1492; t1749 = Cos(var1[9]); t1758 = -1.*t1749; t1759 = 1. + t1758; t1885 = Sin(var1[9]); t2016 = t1310*t1300; t2025 = t1496*t1428; t2028 = t2016 + t2025; t2178 = t1310*t1496; t2181 = -1.*t1300*t1428; t2189 = t2178 + t2181; t2274 = Cos(var1[10]); t2394 = Sin(var1[10]); t2514 = -1.*t1885*t2028; t2574 = t1749*t2189; t2585 = t2514 + t2574; t2673 = t1749*t2028; t2678 = t1885*t2189; t2696 = t2673 + t2678; t2743 = Cos(var1[11]); t2752 = -1.*t2743; t2761 = 1. + t2752; t2786 = Sin(var1[11]); t2858 = t2394*t2585; t2860 = t2274*t2696; t2910 = t2858 + t2860; t3006 = t2274*t2585; t3013 = -1.*t2394*t2696; t3019 = t3006 + t3013; t3065 = Cos(var1[12]); t3098 = -1.*t3065; t3117 = 1. + t3098; t3123 = Sin(var1[12]); t3193 = -1.*t2786*t2910; t3195 = t2743*t3019; t3196 = t3193 + t3195; t3597 = t2743*t2910; t3603 = t2786*t3019; t3615 = t3597 + t3603; t104 = -1.*t85; t160 = 1. + t104; t3974 = t991*t476*t85; t3988 = -1.*t991*t213*t525; t3992 = t3974 + t3988; t775 = 0.135*t769; t822 = 0.049*t790; t836 = t775 + t822; t1392 = -0.049*t1375; t1432 = -0.09*t1428; t1446 = t1392 + t1432; t1501 = -0.09*t1375; t1548 = 0.049*t1428; t1552 = t1501 + t1548; t1790 = -0.049*t1759; t1993 = -0.21*t1885; t2004 = t1790 + t1993; t4039 = -1.*t991*t85*t213; t4040 = -1.*t991*t476*t525; t4056 = t4039 + t4040; t2138 = -0.21*t1759; t2155 = 0.049*t1885; t2177 = t2138 + t2155; t2280 = -1.*t2274; t2286 = 1. + t2280; t2299 = -0.2707*t2286; t2406 = 0.0016*t2394; t2486 = t2299 + t2406; t4174 = t1310*t3992*t790; t4182 = t4056*t1428; t4187 = t4174 + t4182; t4193 = t1310*t4056; t4203 = -1.*t3992*t790*t1428; t4259 = t4193 + t4203; t2598 = -1. + t2274; t2622 = 0.0016*t2598; t2629 = -0.2707*t2394; t2653 = t2622 + t2629; t2778 = 0.0184*t2761; t2788 = -0.7055*t2786; t2833 = t2778 + t2788; t4398 = -1.*t1885*t4187; t4415 = t1749*t4259; t4444 = t4398 + t4415; t4538 = t1749*t4187; t4543 = t1885*t4259; t4581 = t4538 + t4543; t2965 = -0.7055*t2761; t3000 = -0.0184*t2786; t3004 = t2965 + t3000; t3119 = -1.1135*t3117; t3187 = 0.0216*t3123; t3188 = t3119 + t3187; t4597 = t2394*t4444; t4625 = t2274*t4581; t4631 = t4597 + t4625; t4661 = t2274*t4444; t4683 = -1.*t2394*t4581; t4722 = t4661 + t4683; t3291 = -0.0216*t3117; t3327 = -1.1135*t3123; t3388 = t3291 + t3327; t4739 = -1.*t2786*t4631; t4742 = t2743*t4722; t4782 = t4739 + t4742; t4830 = t2743*t4631; t4839 = t2786*t4722; t4858 = t4830 + t4839; t3947 = 0.135*t991*t213*t525; t3994 = 0.1305*t739*t3992; t3998 = t3992*t836; t4035 = t3992*t790*t1446; t4160 = t4056*t1552; t4189 = t2004*t4187; t4273 = t2177*t4259; t4452 = t2486*t4444; t4596 = t2653*t4581; t4655 = t2833*t4631; t4728 = t3004*t4722; t4784 = t3188*t4782; t4864 = t3388*t4858; t4894 = t3123*t4782; t4898 = t3065*t4858; t4981 = t4894 + t4898; t4993 = 0.0306*t4981; t5034 = t3065*t4782; t5056 = -1.*t3123*t4858; t5100 = t5034 + t5056; t5154 = -1.1312*t5100; t1080 = 0.135*t790; t5453 = t991*t85*t213; t5454 = t991*t476*t525; t5469 = t5453 + t5454; t5507 = t739*t5469; t5514 = t197*t790; t5524 = t5507 + t5514; t5680 = -1.*t1310*t1885*t5524; t5711 = -1.*t1749*t5524*t1428; t5712 = t5680 + t5711; t5747 = t1749*t1310*t5524; t5753 = -1.*t1885*t5524*t1428; t5755 = t5747 + t5753; t5818 = t2394*t5712; t5840 = t2274*t5755; t5857 = t5818 + t5840; t5884 = t2274*t5712; t5888 = -1.*t2394*t5755; t5897 = t5884 + t5888; t5916 = -1.*t2786*t5857; t5917 = t2743*t5897; t5931 = t5916 + t5917; t5956 = t2743*t5857; t6029 = t2786*t5897; t6140 = t5956 + t6029; t6523 = -1.*t739*t197; t6563 = t5469*t790; t6579 = t6523 + t6563; t6672 = -1.*t1310*t6579; t6676 = -1.*t3992*t1428; t6677 = t6672 + t6676; t6716 = t1310*t3992; t6751 = -1.*t6579*t1428; t6757 = t6716 + t6751; t6783 = t1885*t6677; t6848 = t1749*t6757; t6854 = t6783 + t6848; t6875 = t1749*t6677; t6962 = -1.*t1885*t6757; t6963 = t6875 + t6962; t7076 = -1.*t2394*t6854; t7088 = t2274*t6963; t7127 = t7076 + t7088; t7225 = t2274*t6854; t7258 = t2394*t6963; t7264 = t7225 + t7258; t7332 = t2786*t7127; t7405 = t2743*t7264; t7511 = t7332 + t7405; t7615 = t2743*t7127; t7616 = -1.*t2786*t7264; t7716 = t7615 + t7616; t8823 = t1310*t6579; t8869 = t3992*t1428; t8914 = t8823 + t8869; t9342 = -1.*t1885*t8914; t9349 = t9342 + t6848; t9359 = -1.*t1749*t8914; t9364 = t9359 + t6962; t9496 = -1.*t2394*t9349; t9513 = t2274*t9364; t9516 = t9496 + t9513; t9666 = t2274*t9349; t9706 = t2394*t9364; t9760 = t9666 + t9706; t9911 = t2786*t9516; t10031 = t2743*t9760; t10033 = t9911 + t10031; t10068 = t2743*t9516; t10072 = -1.*t2786*t9760; t10121 = t10068 + t10072; t10744 = t1749*t8914; t10752 = t1885*t6757; t10759 = t10744 + t10752; t10794 = -1.*t2274*t10759; t10807 = t9496 + t10794; t10818 = -1.*t2394*t10759; t10822 = t9666 + t10818; t10835 = t2786*t10807; t10846 = t2743*t10822; t10893 = t10835 + t10846; t10966 = t2743*t10807; t10976 = -1.*t2786*t10822; t10984 = t10966 + t10976; t11108 = t2394*t9349; t11132 = t2274*t10759; t11137 = t11108 + t11132; t11188 = -1.*t2786*t11137; t11191 = t11188 + t10846; t11198 = -1.*t2743*t11137; t11201 = t11198 + t10976; t11209 = -1.*t3123*t11191; t11362 = t2743*t11137; t11364 = t2786*t10822; t11374 = t11362 + t11364; t11270 = t3065*t11191; p_output1[0]=1.; p_output1[1]=t1300*t1446 + t1496*t1552 + t2004*t2028 - 0.135*t160*t197*t213 + t2177*t2189 + t2486*t2585 + t2653*t2696 + t2833*t2910 + t3004*t3019 + t3188*t3196 + t3388*t3615 + 0.0306*(t3123*t3196 + t3065*t3615) - 1.1312*(t3065*t3196 - 1.*t3123*t3615) + 0.135*t197*t476*t525 + t709*t836 - 1.*(t1080 - 0.049*t769)*t991 + 0.1305*(t709*t739 + t790*t991); p_output1[2]=t3947 + t3994 + t3998 + t4035 + t4160 + t4189 + t4273 + t4452 + t4596 + t4655 + t4728 + t4784 + t4864 + t4993 + t5154 + 0.135*t160*t476*t991; p_output1[3]=t3947 + t3994 + t3998 + t4035 + t4160 + t4189 + t4273 + t4452 + t4596 + t4655 + t4728 + t4784 + t4864 + t4993 + t5154 - 0.135*t476*t85*t991; p_output1[4]=t1446*t5524 + t1310*t2004*t5524 - 1.*t1428*t2177*t5524 + t2486*t5712 + t2653*t5755 + t2833*t5857 + t3004*t5897 + t3188*t5931 + t3388*t6140 + 0.0306*(t3123*t5931 + t3065*t6140) - 1.1312*(t3065*t5931 - 1.*t3123*t6140) + t5469*(t1080 + 0.049*t739) - 1.*t197*(0.135*t739 - 0.049*t790) + 0.1305*(t197*t739 - 1.*t5469*t790); p_output1[5]=(0.049*t1310 + t1432)*t3992 + (-0.09*t1310 - 0.049*t1428)*t6579 + t2177*t6677 + t2004*t6757 + t2653*t6854 + t2486*t6963 + t3004*t7127 + t2833*t7264 + t3388*t7511 + t3188*t7716 - 1.1312*(-1.*t3123*t7511 + t3065*t7716) + 0.0306*(t3065*t7511 + t3123*t7716); p_output1[6]=-1.1312*(t10121*t3065 - 1.*t10033*t3123) + 0.0306*(t10033*t3065 + t10121*t3123) + t10121*t3188 + t10033*t3388 + (0.049*t1749 + t1993)*t6757 + (-0.21*t1749 - 0.049*t1885)*t8914 + t2653*t9349 + t2486*t9364 + t3004*t9516 + t2833*t9760; p_output1[7]=t10759*(-0.2707*t2274 - 0.0016*t2394) + t10822*t2833 + t10807*t3004 - 1.1312*(t10984*t3065 - 1.*t10893*t3123) + 0.0306*(t10893*t3065 + t10984*t3123) + t10984*t3188 + t10893*t3388 + (0.0016*t2274 + t2629)*t9349; p_output1[8]=t11137*(-0.7055*t2743 + 0.0184*t2786) + t10822*(-0.0184*t2743 + t2788) - 1.1312*(t11209 + t11201*t3065) + 0.0306*(t11270 + t11201*t3123) + t11201*t3188 + t11191*t3388; p_output1[9]=-1.1312*(t11209 - 1.*t11374*t3065) + t11374*(-1.1135*t3065 - 0.0216*t3123) + 0.0306*(t11270 - 1.*t11374*t3123) + t11191*(0.0216*t3065 + t3327); } #ifdef MATLAB_MEX_FILE #include "mex.h" /* * Main function */ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { size_t mrows, ncols; double *var1; double *p_output1; /* Check for proper number of arguments. */ if( nrhs != 1) { mexErrMsgIdAndTxt("MATLAB:MShaped:invalidNumInputs", "One input(s) required (var1)."); } else if( nlhs > 1) { mexErrMsgIdAndTxt("MATLAB:MShaped:maxlhs", "Too many output arguments."); } /* The input must be a noncomplex double vector or scaler. */ mrows = mxGetM(prhs[0]); ncols = mxGetN(prhs[0]); if( !mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) || ( !(mrows == 20 && ncols == 1) && !(mrows == 1 && ncols == 20))) { mexErrMsgIdAndTxt( "MATLAB:MShaped:inputNotRealVector", "var1 is wrong."); } /* Assign pointers to each input. */ var1 = mxGetPr(prhs[0]); /* Create matrices for return arguments. */ plhs[0] = mxCreateDoubleMatrix((mwSize) 10, (mwSize) 1, mxREAL); p_output1 = mxGetPr(plhs[0]); /* Call the calculation subroutine. */ output1(p_output1,var1); } #else // MATLAB_MEX_FILE #include "J_u_leftToeHeight_cassie.hh" namespace RightStance { void J_u_leftToeHeight_cassie_raw(double *p_output1, const double *var1) { // Call Subroutines output1(p_output1, var1); } } #endif // MATLAB_MEX_FILE
23.96
352
0.649883
prem-chand
23a3994cd45bce582d2b4dd466dbc45dec978069
3,636
cpp
C++
src/support.cpp
TehSnappy/lib_lunar_ex
a4cd4a3cdec44c2adaefbf1791b8863db568cbbd
[ "MIT" ]
null
null
null
src/support.cpp
TehSnappy/lib_lunar_ex
a4cd4a3cdec44c2adaefbf1791b8863db568cbbd
[ "MIT" ]
null
null
null
src/support.cpp
TehSnappy/lib_lunar_ex
a4cd4a3cdec44c2adaefbf1791b8863db568cbbd
[ "MIT" ]
1
2019-10-12T03:23:41.000Z
2019-10-12T03:23:41.000Z
#include <stdio.h> #include <math.h> #include <stdlib.h> #include <assert.h> #include <string.h> #include <ctype.h> #include "lunar-master/watdefs.h" #include "lunar-master/afuncs.h" #include "lunar-master/date.h" static const long double j2000 = 2451545.0; static void my_remove_char( char *buff, const char removed) { size_t i, j; for( i = j = 0; buff[i]; i++) if( buff[i] != removed) buff[j++] = buff[i]; buff[j] = '\0'; } static void my_show_remainder( char *buff, long double remainder, unsigned precision) { *buff++ = '.'; assert( remainder >= 0. && remainder < 1.); while( precision--) { unsigned digit; remainder *= 10.; digit = (unsigned)remainder; *buff++ = (char)( '0' + digit); assert( digit <= 9); remainder -= (double)digit; } *buff++ = '\0'; } void DLL_FUNC my_full_ctimel( char *buff, long double t2k, const int format, float tz = 0) { const int precision = (format >> 4) & 0xf, calendar = format & 0xf; const int output_format = (format & FULL_CTIME_FORMAT_MASK); char *ibuff = buff; /* keep track of the start of the output */ int day, month; long units, i; const int leading_zeroes = (format & FULL_CTIME_LEADING_ZEROES); long year, int_t2k, day_of_week; long double add_on = 1.; long double remains; if( output_format == FULL_CTIME_FORMAT_SECONDS) units = seconds_per_day; else if( output_format == FULL_CTIME_FORMAT_HH_MM) units = minutes_per_day; else if( output_format == FULL_CTIME_FORMAT_HH) units = hours_per_day; else /* output in days */ units = 1; for( i = precision; i; i--) add_on /= 10.; if( format & FULL_CTIME_ROUNDING) add_on *= 0.5 / (double)units; else add_on *= 0.05 / seconds_per_day; t2k += add_on; if( output_format == FULL_CTIME_FORMAT_YEAR) { char tbuff[40]; sprintf( tbuff, "%21.16Lf", t2k / 365.25 + 2000.); tbuff[precision + 5] = '\0'; if( !precision) tbuff[4] = '\0'; strcpy( buff, tbuff); if( leading_zeroes) while( *buff == ' ') *buff++ = '0'; return; } if( output_format == FULL_CTIME_FORMAT_JD || output_format == FULL_CTIME_FORMAT_MJD) { char format_str[10]; sprintf( format_str, "JD %%.%dLf", precision); if( output_format == FULL_CTIME_FORMAT_MJD) { *buff++ = 'M'; t2k += j2000 - 2400000.5; } else t2k += j2000; sprintf( buff, format_str, t2k); if( leading_zeroes) while( *buff == ' ') *buff++ = '0'; return; } t2k += .5; int_t2k = (long)floorl( t2k); day_of_week = (int_t2k + 6) % 7; if( day_of_week < 0) /* keep 0 <= day_of_week < 7: */ day_of_week += 7; if( format & FULL_CTIME_DAY_OF_WEEK_FIRST) buff += sprintf( buff, "%s ", set_day_of_week_name( (int)day_of_week, NULL)); day_to_dmy( int_t2k + 2451545, &day, &month, &year, calendar); remains = t2k - (long double)int_t2k; /* i.e., fractional part of day */ i = remains * seconds_per_day; int hours = i / 3600L; int minutes = (i / 60) % 60L; int seconds = i % 60L; int frnt = floor(tz); int back = tz * 100 - frnt * 100; sprintf( buff, "%4ld-%02d-%02dT%02d:%02d:%02d%+03d:%02d", year, month, day, hours, minutes, seconds, frnt, back); } void DLL_FUNC my_full_ctime( char *buff, double jd, const int format, float tz = 0) { my_full_ctimel( buff, (long double)jd - j2000, format, tz); }
27.338346
116
0.578108
TehSnappy
23aec974649df6b1ddb184478d165c1ff9c72a40
1,104
hpp
C++
src/heuristics/acceptCritTemperature.hpp
lucasmpavelski/Adaptive-IG
cf48ffae80597a6fd1738da6b4871fe98a3b5189
[ "Unlicense" ]
null
null
null
src/heuristics/acceptCritTemperature.hpp
lucasmpavelski/Adaptive-IG
cf48ffae80597a6fd1738da6b4871fe98a3b5189
[ "Unlicense" ]
null
null
null
src/heuristics/acceptCritTemperature.hpp
lucasmpavelski/Adaptive-IG
cf48ffae80597a6fd1738da6b4871fe98a3b5189
[ "Unlicense" ]
null
null
null
#pragma once #include <cmath> #include <paradiseo/eo/eo> #include <paradiseo/mo/mo> /** * Acceptance Criterion for extreme intensification : accept if the new solution * is better than previous one */ template <class Neighbor> class acceptCritTemperature : public moAcceptanceCriterion<Neighbor>, public moDummyMemory<Neighbor> { double threshold; moSolComparator<typename Neighbor::EOT> compare; public: using EOT = typename Neighbor::EOT; acceptCritTemperature(double _threshold) : threshold(_threshold) {} /** * Accept if the new solution is better than previous one according to the * comparator * @param _sol1 the previous solution * @param _sol2 the new solution after local search * @return true if the new solution is better than previous one */ auto operator()(EOT& _sol1, EOT& _sol2) -> bool override { if (compare(_sol1, _sol2)) { return true; } else { double prob = std::exp((_sol1.fitness() - _sol2.fitness()) / threshold); bool accept = rng.uniform() <= prob; return accept; } } };
27.6
80
0.679348
lucasmpavelski
23b0aedf3506240106fbfcca4defb72bae6c8ced
4,264
cpp
C++
ProjectLunarFront/Main.cpp
Edgaru089/ProjectLunarFront
bf59c6dec36e0576082acf3c72abf3c82bc92241
[ "MIT" ]
null
null
null
ProjectLunarFront/Main.cpp
Edgaru089/ProjectLunarFront
bf59c6dec36e0576082acf3c72abf3c82bc92241
[ "MIT" ]
null
null
null
ProjectLunarFront/Main.cpp
Edgaru089/ProjectLunarFront
bf59c6dec36e0576082acf3c72abf3c82bc92241
[ "MIT" ]
null
null
null
#include "Main.hpp" #include "Instance.hpp" #include "JudgeWorker.hpp" #include "JudgeRecord.hpp" #include "StringDatabase.hpp" #include "Problem.hpp" #include "Page.hpp" #include "PageStatus.hpp" #include "PageStatusDetail.hpp" Log dlog; ofstream logout; atomic_bool running, stopped; #ifdef _WIN32 //Platform-Depedent: Windows BOOL systemExitEventHandler(DWORD dwCtrlType) { if (dwCtrlType == CTRL_C_EVENT) mlog << Log::Error << "[Main/EVENT] Control-C Console Exit" << dlog; else if (dwCtrlType == CTRL_BREAK_EVENT) mlog << Log::Error << "[Main/EVENT] Control-Break Console Exit" << dlog; else if (dwCtrlType == CTRL_CLOSE_EVENT) mlog << Log::Error << "[Main/EVENT] Control-Close Console Exit" << dlog; else if (dwCtrlType == CTRL_LOGOFF_EVENT) mlog << Log::Error << "[Main/EVENT] System-Logoff Exit" << dlog; else if (dwCtrlType == CTRL_SHUTDOWN_EVENT) mlog << Log::Error << "[Main/EVENT] System-Shutdown Exit" << dlog; else return false; running = false; while (!stopped) this_thread::sleep_for(chrono::milliseconds(50)); return true; } #else // Assuming a POSIX system void sigintHandler(int signal) { if (signal == SIGINT) mlog << Log::Error << "[Main/EVENT] POSIX SIGINT Exit" << dlog; else if (signal == SIGTERM) mlog << Log::Error << "[Main/EVENT] POSIX SIGTERM Exit" << dlog; running = false; } #endif int main(int argc, char* argv[]) try { // Open a binary output stream for logs /*time_t curtime = time(NULL); wchar_t buffer[64] = {}; char signature[] = u8"\ufeff"; // BOM in UTF-8; "signature" wcsftime(buffer, 63, L"logs/%Y-%m-%d-%H.%M.%S.log", localtime(&curtime)); OPEN_FSTREAM_WSTR(logout, buffer, ofstream::binary); logout.write(signature, sizeof(signature) - 1);*/ #if (defined WIN32) || (defined _WIN32) locale::global(locale("", LC_CTYPE)); wcout.imbue(locale("", LC_CTYPE)); #else setlocale(LC_CTYPE, "zh_CN.utf8"); #endif dlog.addOutputStream(wcout); /*dlog.addOutputHandler([&](const wstring& str) { string u8str = wstringToUtf8(str) + "\r\n"; logout.write(u8str.data(), u8str.size()); logout.flush(); });*/ running = true; stopped = false; #ifdef _WIN32 SetConsoleCtrlHandler((PHANDLER_ROUTINE)systemExitEventHandler, true); #else signal(SIGINT, sigintHandler); signal(SIGTERM, sigintHandler); #endif mlog << completeServerNameEx << dlog; Instance instance; setFrameFile(StringParser::replaceSubString(readFileText(L"html/frame.html"), { { "%FOOTER%", completeServerNameEx } })); // Register routes here instance.registerRouteRule("/static/", config.getHostname(), ROUTER(req) { return file(req.GetURI().substr(1)); }); instance.registerRouteRule("/sanae", config.getHostname(), ROUTER(req) { return htmltext("Kochiya Sanae"); }); pageManager.insertPage(make_shared<PageStatus>()); pageManager.insertPage(make_shared<PageStatusDetail>()); pageManager.registerRoutes(instance); instance.start(Instance::Config{}); // while (running) // this_thread::sleep_for(chrono::milliseconds(50)); string word; while (cin >> word && running) { if (word == "stop") break; else if (word == "load") { stringDatabase.initializeWithFolder("objects"); judgeWorker.launch(1); sleep(milliseconds(500)); wstring str; cout << "problem db: "; wcin >> str; problemDatabase.loadFromFile(str); cout << "complete." << endl; } else if (word == "judge") { int id; wstring str; cout << "problem id: "; cin >> id; cout << "code file: "; wcin >> str; cout << "handing in..." << endl; judgeRecordDatabase.handInCode(0, id, readFileText(str), true); cout << "complete." << endl; } } running = false; //instance.stop(); judgeWorker.stop(); stopped = true; return 0; } catch (exception& e) { mlog << Log::Error << "The main closure failed with an uncaught exception: " << e.what() << dlog; mlog << Log::Error << "Exception typename: " << typeid(e).name() #if (defined WIN32) || (defined _WIN32) << " (" << typeid(e).raw_name() << ")" #endif << dlog; mlog << Log::Error << "The program will now fail." << dlog; return 1; } catch (...) { mlog << Log::Error << "The main closure failed with an unknown object thrown." << dlog; mlog << Log::Error << "The program will now fail." << dlog; return 1; }
26.987342
122
0.671435
Edgaru089
23b4ad9cdb20903326df1a29a1593c58bd7812cd
2,406
cpp
C++
raygame/MyColor.cpp
BlueJayAtAIE/RaylibCPP
74dcf59f4c469a21f439344dca14dfba53ee3969
[ "MIT" ]
1
2020-09-09T15:44:45.000Z
2020-09-09T15:44:45.000Z
raygame/MyColor.cpp
BlueJayAtAIE/RaylibCPP
74dcf59f4c469a21f439344dca14dfba53ee3969
[ "MIT" ]
null
null
null
raygame/MyColor.cpp
BlueJayAtAIE/RaylibCPP
74dcf59f4c469a21f439344dca14dfba53ee3969
[ "MIT" ]
null
null
null
#include "MyColor.h" MyColor::MyColor() { } MyColor::MyColor(int red, int green, int blue, int alpha) { r = red; g = green; b = blue; a = alpha; clamp(); } void MyColor::clamp() { if (r > 255) r = 255; if (r < 0) r = 0; if (g > 255) g = 255; if (g < 0) g = 0; if (b > 255) b = 255; if (b < 0) b = 0; if (a > 255) a = 255; if (a < 0) a = 0; } Color MyColor::convertToRaylib() { Color temp; temp.r = r; temp.g = g; temp.b = b; temp.a = a; return temp; } // Arithmetic Operators MyColor MyColor::operator+(const MyColor & rhs) const { MyColor temp((r + rhs.r), (g + rhs.g), (b + rhs.b), (a + rhs.a)); temp.clamp(); return temp; } MyColor MyColor::operator-(const MyColor & rhs) const { MyColor temp((r - rhs.r), (g - rhs.g), (b - rhs.b), (a - rhs.a)); temp.clamp(); return temp; } MyColor MyColor::operator*(const MyColor & rhs) const { MyColor temp((r * rhs.r), (g * rhs.g), (b * rhs.b), (a * rhs.a)); temp.clamp(); return temp; } MyColor MyColor::operator/(const MyColor & rhs) const { MyColor temp((r / rhs.r), (g / rhs.g), (b / rhs.b), (a / rhs.a)); temp.clamp(); return temp; } // Compound Arithmetic Operators MyColor& MyColor::operator+=(const MyColor & rhs) { MyColor temp((r + rhs.r), (g + rhs.g), (b + rhs.b), (a + rhs.a)); temp.clamp(); r = temp.r; g = temp.g; b = temp.b; a = temp.a; return temp; } MyColor& MyColor::operator-=(const MyColor & rhs) { MyColor temp((r + rhs.r), (g + rhs.g), (b + rhs.b), (a + rhs.a)); temp.clamp(); r = temp.r; g = temp.g; b = temp.b; a = temp.a; return temp; } MyColor& MyColor::operator*=(const MyColor & rhs) { MyColor temp((r + rhs.r), (g + rhs.g), (b + rhs.b), (a + rhs.a)); temp.clamp(); r = temp.r; g = temp.g; b = temp.b; a = temp.a; return temp; } MyColor& MyColor::operator/=(const MyColor & rhs) { MyColor temp((r + rhs.r), (g + rhs.g), (b + rhs.b), (a + rhs.a)); temp.clamp(); r = temp.r; g = temp.g; b = temp.b; a = temp.a; return temp; } bool MyColor::operator==(const MyColor & rhs) { if (((r == rhs.r) && (g == rhs.g) && (b == rhs.b) && (a == rhs.a))) { return true; } else { return false; } } bool MyColor::operator!=(const MyColor & rhs) { if (((r != rhs.r) && (g != rhs.g) && (b != rhs.b) && (a != rhs.a))) { return true; } else { return false; } } // Not MyColor MyColor::operator!() const { MyColor temp(-r, -g, -b, a); return temp; }
16.367347
68
0.549875
BlueJayAtAIE
23b901b1ddd924dc75e5064f41c6b706958bf029
3,171
cc
C++
examples/distributed_grid.cc
mpi-advance/Exhanced-MPL-tiny-
9585fdc337a69c207a7c771d850b5ad7542666fa
[ "BSD-3-Clause" ]
2
2021-10-13T03:55:48.000Z
2022-01-28T15:33:54.000Z
examples/distributed_grid.cc
mpi-advance/mpl-subset
9585fdc337a69c207a7c771d850b5ad7542666fa
[ "BSD-3-Clause" ]
null
null
null
examples/distributed_grid.cc
mpi-advance/mpl-subset
9585fdc337a69c207a7c771d850b5ad7542666fa
[ "BSD-3-Clause" ]
null
null
null
#include <cstdlib> #include <iostream> #include <mpl/mpl.hpp> template<std::size_t dim, typename T, typename A> void update_overlap(const mpl::cart_communicator &C, mpl::distributed_grid<dim, T, A> &G, mpl::tag tag = mpl::tag()) { mpl::shift_ranks ranks; for (std::size_t i = 0; i < dim; ++i) { // send to left ranks = C.shift(i, -1); C.sendrecv(G.data(), G.left_border_layout(i), ranks.dest, tag, G.data(), G.right_mirror_layout(i), ranks.source, tag); // send to right ranks = C.shift(i, +1); C.sendrecv(G.data(), G.right_border_layout(i), ranks.dest, tag, G.data(), G.left_mirror_layout(i), ranks.source, tag); } } int main() { const mpl::communicator &comm_world(mpl::environment::comm_world()); { // build a one-dimensional Cartesian communicator // Cartesian is non-cyclic mpl::cart_communicator::sizes sizes({{0, mpl::cart_communicator::nonperiodic}}); mpl::cart_communicator comm_c(comm_world, mpl::dims_create(comm_world.size(), sizes)); // create a distributed grid of 31 total grid points and 2 shadow grid points // to mirror data between adjacent processes mpl::distributed_grid<1, int> G(comm_c, {{31, 2}}); // fill local grid including shadow grid points for (auto i = G.obegin(0), i_end = G.oend(0); i < i_end; ++i) G(i) = comm_c.rank(); // get shadow data from adjacent processes update_overlap(comm_c, G); // print local grid including shadow grid points for (int k = 0; k < comm_c.size(); ++k) { if (k == comm_c.rank()) { for (auto i = G.obegin(0), i_end = G.oend(0); i < i_end; ++i) std::cout << G(i); std::cout << std::endl; } comm_c.barrier(); // barrier may avoid overlapping output } } { // build a two-dimensional Cartesian communicator // Cartesian is cyclic along 1st dimension, non-cyclic along 2nd dimension mpl::cart_communicator::sizes sizes( {{0, mpl::cart_communicator::periodic}, {0, mpl::cart_communicator::nonperiodic}}); mpl::cart_communicator comm_c(comm_world, mpl::dims_create(comm_world.size(), sizes)); // create a distributed grid of 11x13 total grid points and 2 respectively 1 // shadow grid points to mirror data between adjacent processes mpl::distributed_grid<2, int> G(comm_c, {{11, 2}, {13, 1}}); // fill local grid including shadow grid points for (auto j = G.obegin(1), j_end = G.oend(1); j < j_end; ++j) for (auto i = G.obegin(0), i_end = G.oend(0); i < i_end; ++i) G(i, j) = comm_c.rank(); // get shadow data from adjacent processes update_overlap(comm_c, G); // print local grid including shadow grid points for (int k = 0; k < comm_c.size(); ++k) { if (k == comm_c.rank()) { std::cout << std::endl; for (auto j = G.obegin(1), j_end = G.oend(1); j < j_end; ++j) { for (auto i = G.obegin(0), i_end = G.oend(0); i < i_end; ++i) std::cout << G(i, j); std::cout << std::endl; } } comm_c.barrier(); // barrier may avoid overlapping output } } return EXIT_SUCCESS; }
41.181818
91
0.613371
mpi-advance
23bd94d5e5ce23c6580393b45a8a267c1e885e99
1,110
cpp
C++
64.cpp
machinecc/leetcode
32bbf6c1f9124049c046a235c85b14ca9168daa8
[ "MIT" ]
null
null
null
64.cpp
machinecc/leetcode
32bbf6c1f9124049c046a235c85b14ca9168daa8
[ "MIT" ]
null
null
null
64.cpp
machinecc/leetcode
32bbf6c1f9124049c046a235c85b14ca9168daa8
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdlib> #include <string> #include <unordered_set> #include <vector> #include <algorithm> #include <climits> #include <stack> #include <sstream> #include <numeric> #include <unordered_map> using namespace std; class Solution { public: int minPathSum(vector<vector<int>>& grid) { if (grid.size() == 0 || grid[0].size() == 0) return 0; int m = grid.size(); int n = grid[0].size(); int* dp = new int[n]; for (int j = 0; j < n; ++ j) dp[j] = INT_MAX; dp[0] = 0; for (int i = 0; i < m; ++ i) { dp[0] = dp[0] + grid[i][0]; for (int j = 1; j < n; ++ j) { dp[j] = min(dp[j-1], dp[j]) + grid[i][j]; } /* for (int j = 0; j < n; ++j) { cout << dp[j] << ' '; } cout << endl; */ } int ans = dp[n-1]; delete [] dp; return ans; } }; int main() { vector<vector<int>> grid = {{2,0}}; cout << Solution().minPathSum(grid) << endl; return 0; }
15.416667
57
0.445045
machinecc
23bec30b8dedd40fd60e7c39d8c2b4066e60d237
750
cpp
C++
string/165 Compare Version Numbers.cpp
CoderQuinnYoung/leetcode
6ea15c68124b16824bab9ed2e0e5a40c72eb3db1
[ "BSD-3-Clause" ]
null
null
null
string/165 Compare Version Numbers.cpp
CoderQuinnYoung/leetcode
6ea15c68124b16824bab9ed2e0e5a40c72eb3db1
[ "BSD-3-Clause" ]
null
null
null
string/165 Compare Version Numbers.cpp
CoderQuinnYoung/leetcode
6ea15c68124b16824bab9ed2e0e5a40c72eb3db1
[ "BSD-3-Clause" ]
null
null
null
// // 165 Compare Version Numbers.cpp // Leetcode // // Created by Quinn on 2020/12/15. // Copyright © 2020 Quinn. All rights reserved. // #include <stdio.h> #include <string> using namespace std; class Solution { public: int compareVersion(string v1, string v2) { for(int i = 0, j = 0; i < v1.size() || j < v2.size();) { int a = i, b = j; while(a < v1.size() && v1[a] != '.') a++; while(b < v2.size() && v2[b] != '.') b++; int x = a == i ? 0 : stoi(v1.substr(i, a - i)); int y = b == j ? 0 : stoi(v2.substr(j, b - j)); if(x > y) return 1; if(x < y) return -1; i = a + 1; j = b + 1; } return 0; } };
22.058824
64
0.441333
CoderQuinnYoung
23c2037b617b9fd8fe3f9b2460d65e2150ae595b
405
hpp
C++
sources/SoundEffect.hpp
PawelWorwa/SFMLris
525c29eefee2ec68512d3d320fb0e9aae95b9549
[ "MIT" ]
null
null
null
sources/SoundEffect.hpp
PawelWorwa/SFMLris
525c29eefee2ec68512d3d320fb0e9aae95b9549
[ "MIT" ]
4
2018-01-10T19:17:00.000Z
2018-01-10T20:21:27.000Z
sources/SoundEffect.hpp
PawelWorwa/SFMLris
525c29eefee2ec68512d3d320fb0e9aae95b9549
[ "MIT" ]
null
null
null
#ifndef SFMLRIS_SOUNDEFFECT_HPP #define SFMLRIS_SOUNDEFFECT_HPP #include <SFML/Audio/Sound.hpp> #include <SFML/Audio/SoundBuffer.hpp> class SoundEffect { public: explicit SoundEffect(const std::string &filePath); void play(); void playOnce(); private: sf::SoundBuffer buffer; sf::Sound sound; bool played; }; #endif //SFMLRIS_SOUNDEFFECT_HPP
17.608696
58
0.669136
PawelWorwa
23c526ab0e7ce0125042d98e6c6846a1b295e8d9
895
hpp
C++
LD46 - Square Loves Circle/Source/Transitions.hpp
milo-brandt/milos-ludum-dare-entries
6b4907463395ee99720386bca48726a798af14d2
[ "MIT" ]
null
null
null
LD46 - Square Loves Circle/Source/Transitions.hpp
milo-brandt/milos-ludum-dare-entries
6b4907463395ee99720386bca48726a798af14d2
[ "MIT" ]
null
null
null
LD46 - Square Loves Circle/Source/Transitions.hpp
milo-brandt/milos-ludum-dare-entries
6b4907463395ee99720386bca48726a798af14d2
[ "MIT" ]
null
null
null
// // Transitions.hpp // Dummy // // Created by Milo Brandt on 4/18/20. // Copyright © 2020 Milo Brandt. All rights reserved. // #ifndef Transitions_hpp #define Transitions_hpp #include "Common/Window.h" #include "Game/ImmediateData.h" #include <variant> namespace RenderEffects{ struct LoveFade{ Vector2<double> center; double startRadius; double endRadius; double lifetime; double time = 0; bool render(Window& window, ImmediateData& data, double dt); }; struct NormalFade{ double startOpacity; double endOpacity; double lifetime; double time = 0; bool render(Window& window, ImmediateData& data, double dt); }; using Effect = std::variant<LoveFade, NormalFade>; bool render(Effect& effect, Window& window, ImmediateData& data, double dt); }; #endif /* Transitions_hpp */
23.552632
80
0.653631
milo-brandt
23ce6f7b8b7eb697fe5e919e76be54fb05aabb02
12,601
hpp
C++
opentrack/options.hpp
asarnow/opentrack
aed80a837d79eb6997435e062e5fbda0a140a715
[ "ISC" ]
null
null
null
opentrack/options.hpp
asarnow/opentrack
aed80a837d79eb6997435e062e5fbda0a140a715
[ "ISC" ]
null
null
null
opentrack/options.hpp
asarnow/opentrack
aed80a837d79eb6997435e062e5fbda0a140a715
[ "ISC" ]
null
null
null
/* Copyright (c) 2013-2014 Stanislaw Halik * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. */ #pragma once #include <memory> #include <tuple> #include <map> #include <string> #include <QObject> #include <QSettings> #include <QString> #include <QVariant> #include <QMutex> #include <QMutexLocker> #include <QWidget> #include <QComboBox> #include <QCheckBox> #include <QDoubleSpinBox> #include <QSpinBox> #include <QSlider> #include <QLineEdit> #include <QLabel> #include <QTabWidget> #include <QCoreApplication> #include <cinttypes> #include <QDebug> #include <memory> template<typename t> using mem = std::shared_ptr<t>; namespace options { template<typename k, typename v> using map = std::map<k, v>; using std::string; template<typename t> // don't elide usages of the function, qvariant default implicit // conversion results in nonsensical runtime behavior -sh inline t qcruft_to_t (const QVariant& datum); template<> inline int qcruft_to_t<int>(const QVariant& t) { return t.toInt(); } template<> inline QString qcruft_to_t<QString>(const QVariant& t) { return t.toString(); } template<> inline bool qcruft_to_t<bool>(const QVariant& t) { return t.toBool(); } template<> inline double qcruft_to_t<double>(const QVariant& t) { return t.toDouble(); } template<> inline QVariant qcruft_to_t<QVariant>(const QVariant& t) { return t; } // snapshot of qsettings group at given time class group { private: map<string, QVariant> kvs; string name; public: group(const string& name) : name(name) { QSettings conf(ini_pathname(), QSettings::IniFormat); auto q_name = QString::fromStdString(name); conf.beginGroup(q_name); for (auto& k_ : conf.childKeys()) { auto tmp = k_.toUtf8(); string k(tmp); kvs[k] = conf.value(k_); } conf.endGroup(); } static constexpr const char* org = "opentrack-2.3"; void save() { QSettings s(ini_pathname(), QSettings::IniFormat); auto q_name = QString::fromStdString(name); s.beginGroup(q_name); for (auto& i : kvs) { auto k = QString::fromStdString(i.first); s.setValue(k, i.second); } s.endGroup(); s.sync(); } template<typename t> t get(const string& k) { return qcruft_to_t<t>(kvs[k]); } void put(const string& s, const QVariant& d) { kvs[s] = d; } bool contains(const string& s) { return kvs.count(s) != 0; } static constexpr const char* filename_key = "settings-file"; static constexpr const char* default_path = "/settings/default.ini"; static const QString ini_pathname() { QSettings settings(group::org); return settings.value(filename_key, QCoreApplication::applicationDirPath() + default_path).toString(); } static const mem<QSettings> ini_file() { return std::make_shared<QSettings>(ini_pathname(), QSettings::IniFormat); } }; class impl_bundle : public QObject { Q_OBJECT protected: QMutex mtx; const string group_name; group saved; group transient; bool modified; impl_bundle(const impl_bundle&) = delete; impl_bundle& operator=(const impl_bundle&) = delete; signals: void reloading(); void saving(); public: impl_bundle(const string& group_name) : mtx(QMutex::Recursive), group_name(group_name), saved(group_name), transient(saved), modified(false) { } string name() { return group_name; } void reload() { { QMutexLocker l(&mtx); saved = group(group_name); transient = saved; modified = false; } emit reloading(); } void store_kv(const string& name, const QVariant& datum) { QMutexLocker l(&mtx); auto old = transient.get<QVariant>(name); if (!transient.contains(name) || datum != old) { modified = true; transient.put(name, datum); } } bool contains(const string& name) { QMutexLocker l(&mtx); return transient.contains(name); } template<typename t> t get(const string& name) { QMutexLocker l(&mtx); return transient.get<t>(name); } void save() { { QMutexLocker l(&mtx); modified = false; saved = transient; transient.save(); } emit saving(); } bool modifiedp() { QMutexLocker l(&mtx); return modified; } }; class opt_bundle; namespace { template<typename k, typename v, typename cnt = int> struct opt_singleton { public: using pbundle = std::shared_ptr<v>; using tt = std::tuple<cnt, std::weak_ptr<v>>; private: QMutex implsgl_mtx; map<k, tt> implsgl_data; public: opt_singleton() : implsgl_mtx(QMutex::Recursive) {} static opt_singleton<k, v>& datum() { static auto ret = std::make_shared<opt_singleton<k, v>>(); return *ret; } pbundle bundle(const k& key) { QMutexLocker l(&implsgl_mtx); if (implsgl_data.count(key) != 0) { auto shared = std::get<1>(implsgl_data[key]).lock(); if (shared != nullptr) return shared; } qDebug() << "bundle +" << QString::fromStdString(key); auto shr = std::make_shared<v>(key); implsgl_data[key] = tt(cnt(1), shr); return shr; } void bundle_decf(const k& key) { QMutexLocker l(&implsgl_mtx); if (--std::get<0>(implsgl_data[key]) == 0) implsgl_data.erase(key); } }; using pbundle = std::shared_ptr<opt_bundle>; using t_fact = opt_singleton<string, opt_bundle>; } static inline t_fact::pbundle bundle(const string name) { return t_fact::datum().bundle(name); } class opt_bundle : public impl_bundle { public: opt_bundle() : impl_bundle("i-have-no-name") {} opt_bundle(const string& group_name) : impl_bundle(group_name) { } ~opt_bundle() { qDebug() << "bundle -" << QString::fromStdString(group_name); t_fact::datum().bundle_decf(group_name); } }; class base_value : public QObject { Q_OBJECT #define DEFINE_SLOT(t) void setValue(t datum) { store(datum); } #define DEFINE_SIGNAL(t) void valueChanged(t) public: base_value(pbundle b, const string& name) : b(b), self_name(name) {} signals: DEFINE_SIGNAL(double); DEFINE_SIGNAL(int); DEFINE_SIGNAL(bool); DEFINE_SIGNAL(QString); protected: pbundle b; string self_name; template<typename t> void store(const t& datum) { b->store_kv(self_name, datum); emit valueChanged(static_cast<t>(datum)); } public slots: DEFINE_SLOT(double) DEFINE_SLOT(int) DEFINE_SLOT(QString) DEFINE_SLOT(bool) public slots: virtual void reload() = 0; }; static inline string string_from_qstring(const QString& datum) { auto tmp = datum.toUtf8(); return string(tmp.constData()); } template<typename t> class value : public base_value { public: t operator=(const t datum) { store(datum); return datum; } static constexpr const Qt::ConnectionType DIRECT_CONNTYPE = Qt::DirectConnection; static constexpr const Qt::ConnectionType SAFE_CONNTYPE = Qt::UniqueConnection; value(pbundle b, const string& name, t def) : base_value(b, name) { QObject::connect(b.get(), SIGNAL(reloading()), this, SLOT(reload()), DIRECT_CONNTYPE); if (!b->contains(name) || b->get<QVariant>(name).type() == QVariant::Invalid) *this = def; } value(pbundle b, const QString& name, t def) : value(b, string_from_qstring(name), def) {} value(pbundle b, const char* name, t def) : value(b, string(name), def) {} operator t() { return b->get<t>(self_name); } void reload() override { *this = static_cast<t>(*this); } }; template<typename t, typename q> inline void tie_setting(value<t>&, q*); template<> inline void tie_setting(value<int>& v, QComboBox* cb) { cb->setCurrentIndex(v); v = cb->currentIndex(); base_value::connect(cb, SIGNAL(currentIndexChanged(int)), &v, SLOT(setValue(int)), v.DIRECT_CONNTYPE); base_value::connect(&v, SIGNAL(valueChanged(int)), cb, SLOT(setCurrentIndex(int)), v.SAFE_CONNTYPE); } template<> inline void tie_setting(value<QString>& v, QComboBox* cb) { cb->setCurrentText(v); v = cb->currentText(); base_value::connect(cb, SIGNAL(currentTextChanged(QString)), &v, SLOT(setValue(QString)), v.DIRECT_CONNTYPE); base_value::connect(&v, SIGNAL(valueChanged(QString)), cb, SLOT(setCurrentText(QString)), v.SAFE_CONNTYPE); } template<> inline void tie_setting(value<bool>& v, QCheckBox* cb) { cb->setChecked(v); base_value::connect(cb, SIGNAL(toggled(bool)), &v, SLOT(setValue(bool)), v.DIRECT_CONNTYPE); base_value::connect(&v, SIGNAL(valueChanged(bool)), cb, SLOT(setChecked(bool)), v.SAFE_CONNTYPE); } template<> inline void tie_setting(value<double>& v, QDoubleSpinBox* dsb) { dsb->setValue(v); base_value::connect(dsb, SIGNAL(valueChanged(double)), &v, SLOT(setValue(double)), v.DIRECT_CONNTYPE); base_value::connect(&v, SIGNAL(valueChanged(double)), dsb, SLOT(setValue(double)), v.SAFE_CONNTYPE); } template<> inline void tie_setting(value<int>& v, QSpinBox* sb) { sb->setValue(v); base_value::connect(sb, SIGNAL(valueChanged(int)), &v, SLOT(setValue(int)), v.DIRECT_CONNTYPE); base_value::connect(&v, SIGNAL(valueChanged(int)), sb, SLOT(setValue(int)), v.SAFE_CONNTYPE); } template<> inline void tie_setting(value<int>& v, QSlider* sl) { sl->setValue(v); v = sl->value(); base_value::connect(sl, SIGNAL(valueChanged(int)), &v, SLOT(setValue(int)), v.DIRECT_CONNTYPE); base_value::connect(&v, SIGNAL(valueChanged(int)), sl, SLOT(setValue(int)), v.SAFE_CONNTYPE); } template<> inline void tie_setting(value<QString>& v, QLineEdit* le) { le->setText(v); base_value::connect(le, SIGNAL(textChanged(QString)), &v, SLOT(setValue(QString)), v.DIRECT_CONNTYPE); base_value::connect(&v, SIGNAL(valueChanged(QString)),le, SLOT(setText(QString)), v.SAFE_CONNTYPE); } template<> inline void tie_setting(value<QString>& v, QLabel* lb) { lb->setText(v); base_value::connect(&v, SIGNAL(valueChanged(QString)), lb, SLOT(setText(QString)), v.SAFE_CONNTYPE); } template<> inline void tie_setting(value<int>& v, QTabWidget* t) { t->setCurrentIndex(v); base_value::connect(t, SIGNAL(currentChanged(int)), &v, SLOT(setValue(int)), v.DIRECT_CONNTYPE); base_value::connect(&v, SIGNAL(valueChanged(int)), t, SLOT(setCurrentIndex(int)), v.SAFE_CONNTYPE); } }
29.168981
117
0.5594
asarnow
23ceaf9cb955071e61169f036d3a4fe377f8a6b5
30,751
cpp
C++
artifact/storm/src/storm/modelchecker/helper/infinitehorizon/SparseDeterministicInfiniteHorizonHelper.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
null
null
null
artifact/storm/src/storm/modelchecker/helper/infinitehorizon/SparseDeterministicInfiniteHorizonHelper.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
null
null
null
artifact/storm/src/storm/modelchecker/helper/infinitehorizon/SparseDeterministicInfiniteHorizonHelper.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
1
2022-02-05T12:39:53.000Z
2022-02-05T12:39:53.000Z
#include "SparseDeterministicInfiniteHorizonHelper.h" #include "storm/modelchecker/helper/infinitehorizon/internal/ComponentUtility.h" #include "storm/modelchecker/helper/infinitehorizon/internal/LraViHelper.h" #include "storm/storage/SparseMatrix.h" #include "storm/storage/StronglyConnectedComponentDecomposition.h" #include "storm/storage/Scheduler.h" #include "storm/solver/LinearEquationSolver.h" #include "storm/solver/Multiplier.h" #include "storm/solver/LpSolver.h" #include "storm/utility/SignalHandler.h" #include "storm/utility/solver.h" #include "storm/utility/vector.h" #include "storm/environment/solver/LongRunAverageSolverEnvironment.h" #include "storm/environment/solver/TopologicalSolverEnvironment.h" #include "storm/exceptions/UnmetRequirementException.h" #include "storm/exceptions/NotSupportedException.h" namespace storm { namespace modelchecker { namespace helper { template <typename ValueType> SparseDeterministicInfiniteHorizonHelper<ValueType>::SparseDeterministicInfiniteHorizonHelper(storm::storage::SparseMatrix<ValueType> const& transitionMatrix) : SparseInfiniteHorizonHelper<ValueType, false>(transitionMatrix) { // Intentionally left empty. } template <typename ValueType> SparseDeterministicInfiniteHorizonHelper<ValueType>::SparseDeterministicInfiniteHorizonHelper(storm::storage::SparseMatrix<ValueType> const& transitionMatrix, std::vector<ValueType> const& exitRates) : SparseInfiniteHorizonHelper<ValueType, false>(transitionMatrix, exitRates) { // For the CTMC case we assert that the caller actually provided the probabilistic transitions STORM_LOG_ASSERT(this->_transitionMatrix.isProbabilistic(), "Non-probabilistic transitions"); } template <typename ValueType> void SparseDeterministicInfiniteHorizonHelper<ValueType>::createDecomposition() { if (this->_longRunComponentDecomposition == nullptr) { // The decomposition has not been provided or computed, yet. this->_computedLongRunComponentDecomposition = std::make_unique<storm::storage::StronglyConnectedComponentDecomposition<ValueType>>(this->_transitionMatrix, storm::storage::StronglyConnectedComponentDecompositionOptions().onlyBottomSccs()); this->_longRunComponentDecomposition = this->_computedLongRunComponentDecomposition.get(); } } template <typename ValueType> ValueType SparseDeterministicInfiniteHorizonHelper<ValueType>::computeLraForComponent(Environment const& env, ValueGetter const& stateValueGetter, ValueGetter const& actionValueGetter, storm::storage::StronglyConnectedComponent const& component) { // For deterministic models, we compute the LRA for a BSCC STORM_LOG_ASSERT(!this->isProduceSchedulerSet(), "Scheduler production enabled for deterministic model."); auto trivialResult = computeLraForTrivialBscc(env, stateValueGetter, actionValueGetter, component); if (trivialResult.first) { return trivialResult.second; } // Solve nontrivial BSCC with the method specified in the settings storm::solver::LraMethod method = env.solver().lra().getDetLraMethod(); if ((storm::NumberTraits<ValueType>::IsExact || env.solver().isForceExact()) && env.solver().lra().isDetLraMethodSetFromDefault() && method == storm::solver::LraMethod::ValueIteration) { method = storm::solver::LraMethod::GainBiasEquations; STORM_LOG_INFO("Selecting " << storm::solver::toString(method) << " as the solution technique for long-run properties to guarantee exact results. If you want to override this, please explicitly specify a different LRA method."); } else if (env.solver().isForceSoundness() && env.solver().lra().isDetLraMethodSetFromDefault() && method != storm::solver::LraMethod::ValueIteration) { method = storm::solver::LraMethod::ValueIteration; STORM_LOG_INFO("Selecting " << storm::solver::toString(method) << " as the solution technique for long-run properties to guarantee sound results. If you want to override this, please explicitly specify a different LRA method."); } STORM_LOG_TRACE("Computing LRA for BSCC of size " << component.size() << " using '" << storm::solver::toString(method) << "'."); if (method == storm::solver::LraMethod::ValueIteration) { return computeLraForBsccVi(env, stateValueGetter, actionValueGetter, component); } else if (method == storm::solver::LraMethod::LraDistributionEquations) { // We only need the first element of the pair as the lra distribution is not relevant at this point. return computeLraForBsccLraDistr(env, stateValueGetter, actionValueGetter, component).first; } STORM_LOG_WARN_COND(method == storm::solver::LraMethod::GainBiasEquations, "Unsupported lra method selected. Defaulting to " << storm::solver::toString(storm::solver::LraMethod::GainBiasEquations) << "."); // We don't need the bias values return computeLraForBsccGainBias(env, stateValueGetter, actionValueGetter, component).first; } template <typename ValueType> std::pair<bool, ValueType> SparseDeterministicInfiniteHorizonHelper<ValueType>::computeLraForTrivialBscc(Environment const& env, ValueGetter const& stateValueGetter, ValueGetter const& actionValueGetter, storm::storage::StronglyConnectedComponent const& component) { // For deterministic models, we can catch the case where all values are the same. This includes the special case where the BSCC consist only of just one state. bool first = true; ValueType val = storm::utility::zero<ValueType>(); for (auto const& element : component) { auto state = internal::getComponentElementState(element); STORM_LOG_ASSERT(state == *internal::getComponentElementChoicesBegin(element), "Unexpected choice index at state " << state << " of deterministic model."); ValueType curr = stateValueGetter(state) + (this->isContinuousTime() ? (*this->_exitRates)[state] * actionValueGetter(state) : actionValueGetter(state)); if (first) { val = curr; first = false; } else if (val != curr) { return {false, storm::utility::zero<ValueType>()}; } } // All values are the same return {true, val}; } template <> storm::RationalFunction SparseDeterministicInfiniteHorizonHelper<storm::RationalFunction>::computeLraForBsccVi(Environment const& env, ValueGetter const& stateValueGetter, ValueGetter const& actionValueGetter, storm::storage::StronglyConnectedComponent const& bscc) { STORM_LOG_THROW(false, storm::exceptions::NotSupportedException, "The requested Method for LRA computation is not supported for parametric models."); } template <typename ValueType> ValueType SparseDeterministicInfiniteHorizonHelper<ValueType>::computeLraForBsccVi(Environment const& env, ValueGetter const& stateValueGetter, ValueGetter const& actionValueGetter, storm::storage::StronglyConnectedComponent const& bscc) { // Collect parameters of the computation ValueType aperiodicFactor = storm::utility::convertNumber<ValueType>(env.solver().lra().getAperiodicFactor()); // Now create a helper and perform the algorithm if (this->isContinuousTime()) { // We assume a CTMC (with deterministic timed states and no instant states) storm::modelchecker::helper::internal::LraViHelper<ValueType, storm::storage::StronglyConnectedComponent, storm::modelchecker::helper::internal::LraViTransitionsType::DetTsNoIs> viHelper(bscc, this->_transitionMatrix, aperiodicFactor, this->_markovianStates, this->_exitRates); return viHelper.performValueIteration(env, stateValueGetter, actionValueGetter, this->_exitRates); } else { // We assume a DTMC (with deterministic timed states and no instant states) storm::modelchecker::helper::internal::LraViHelper<ValueType, storm::storage::StronglyConnectedComponent, storm::modelchecker::helper::internal::LraViTransitionsType::DetTsNoIs> viHelper(bscc, this->_transitionMatrix, aperiodicFactor); return viHelper.performValueIteration(env, stateValueGetter, actionValueGetter); } } template <typename ValueType> std::pair<ValueType, std::vector<ValueType>> SparseDeterministicInfiniteHorizonHelper<ValueType>::computeLraForBsccGainBias(Environment const& env, ValueGetter const& stateValuesGetter, ValueGetter const& actionValuesGetter, storm::storage::StronglyConnectedComponent const& bscc) { // We build the equation system as in Line 3 of Algorithm 3 from // Kretinsky, Meggendorfer: Efficient Strategy Iteration for Mean Payoff in Markov Decision Processes (ATVA 2017) // https://doi.org/10.1007/978-3-319-68167-2_25 // The first variable corresponds to the gain of the bscc whereas the subsequent variables yield the bias for each state s_1, s_2, .... // No bias variable for s_0 is needed since it is always set to zero, yielding an nxn equation system matrix // To make this work for CTMC, we could uniformize the model. This preserves LRA and ensures that we can compute the // LRA as for a DTMC (the soujourn time in each state is the same). If we then multiply the equations with the uniformization rate, // the uniformization rate cancels out. Hence, we obtain the equation system below. // Get a mapping from global state indices to local ones. std::unordered_map<uint64_t, uint64_t> toLocalIndexMap; uint64_t localIndex = 0; for (auto const& globalIndex : bscc) { toLocalIndexMap[globalIndex] = localIndex; ++localIndex; } // Prepare an environment for the underlying equation solver auto subEnv = env; if (subEnv.solver().getLinearEquationSolverType() == storm::solver::EquationSolverType::Topological) { // Topological solver does not make any sense since the BSCC is connected. subEnv.solver().setLinearEquationSolverType(subEnv.solver().topological().getUnderlyingEquationSolverType(), subEnv.solver().topological().isUnderlyingEquationSolverTypeSetFromDefault()); } subEnv.solver().setLinearEquationSolverPrecision(env.solver().lra().getPrecision(), env.solver().lra().getRelativeTerminationCriterion()); // Build the equation system matrix and vector. storm::solver::GeneralLinearEquationSolverFactory<ValueType> linearEquationSolverFactory; bool isEquationSystemFormat = linearEquationSolverFactory.getEquationProblemFormat(subEnv) == storm::solver::LinearEquationSolverProblemFormat::EquationSystem; storm::storage::SparseMatrixBuilder<ValueType> builder(bscc.size(), bscc.size()); std::vector<ValueType> eqSysVector; eqSysVector.reserve(bscc.size()); // The first row asserts that the weighted bias variables and the reward at s_0 sum up to the gain uint64_t row = 0; ValueType entryValue; for (auto const& globalState : bscc) { ValueType rateAtState = this->_exitRates ? (*this->_exitRates)[globalState] : storm::utility::one<ValueType>(); // Coefficient for the gain variable if (isEquationSystemFormat) { // '1-0' in row 0 and -(-1) in other rows builder.addNextValue(row, 0, storm::utility::one<ValueType>()); } else if (row > 0) { // No coeficient in row 0, othwerise substract the gain builder.addNextValue(row, 0, -storm::utility::one<ValueType>()); } // Compute weighted sum over successor state. As this is a BSCC, each successor state will again be in the BSCC. if (row > 0) { if (isEquationSystemFormat) { builder.addDiagonalEntry(row, rateAtState); } else if (!storm::utility::isOne(rateAtState)) { builder.addDiagonalEntry(row, storm::utility::one<ValueType>() - rateAtState); } } for (auto const& entry : this->_transitionMatrix.getRow(globalState)) { uint64_t col = toLocalIndexMap[entry.getColumn()]; if (col == 0) { //Skip transition to state_0. This corresponds to setting the bias of state_0 to zero continue; } entryValue = entry.getValue() * rateAtState; if (isEquationSystemFormat) { entryValue = -entryValue; } builder.addNextValue(row, col, entryValue); } eqSysVector.push_back(stateValuesGetter(globalState) + rateAtState * actionValuesGetter(globalState)); ++row; } // Create a linear equation solver auto solver = linearEquationSolverFactory.create(subEnv, builder.build()); // Check solver requirements. auto requirements = solver->getRequirements(subEnv); STORM_LOG_THROW(!requirements.hasEnabledCriticalRequirement(), storm::exceptions::UnmetRequirementException, "Solver requirements " + requirements.getEnabledRequirementsAsString() + " not checked."); // Todo: Find bounds on the bias variables. Just inserting the maximal value from the vector probably does not work. std::vector<ValueType> eqSysSol(bscc.size(), storm::utility::zero<ValueType>()); // Take the mean of the rewards as an initial guess for the gain //eqSysSol.front() = std::accumulate(eqSysVector.begin(), eqSysVector.end(), storm::utility::zero<ValueType>()) / storm::utility::convertNumber<ValueType, uint64_t>(bscc.size()); solver->solveEquations(subEnv, eqSysSol, eqSysVector); ValueType gain = eqSysSol.front(); // insert bias value for state 0 eqSysSol.front() = storm::utility::zero<ValueType>(); // Return the gain and the bias values return std::pair<ValueType, std::vector<ValueType>>(std::move(gain), std::move(eqSysSol)); } template <typename ValueType> std::pair<ValueType, std::vector<ValueType>> SparseDeterministicInfiniteHorizonHelper<ValueType>::computeLraForBsccLraDistr(Environment const& env, ValueGetter const& stateValuesGetter, ValueGetter const& actionValuesGetter, storm::storage::StronglyConnectedComponent const& bscc) { // Let A be ab auxiliary Matrix with A[s,s] = R(s,s) - r(s) & A[s,s'] = R(s,s') for s,s' in BSCC and s!=s'. // We build and solve the equation system for // x*A=0 & x_0+...+x_n=1 <=> A^t*x=0=x-x & x_0+...+x_n=1 <=> (1+A^t)*x = x & 1-x_0-...-x_n-1=x_n // Then, x[i] will be the fraction of the time we are in state i. // This method assumes that this BSCC consist of more than one state if (bscc.size() == 1) { ValueType lraValue = stateValuesGetter(*bscc.begin()) + (this->isContinuousTime() ? (*this->_exitRates)[*bscc.begin()] * actionValuesGetter(*bscc.begin()) : actionValuesGetter(*bscc.begin())); return { lraValue, {storm::utility::one<ValueType>()} }; } // Prepare an environment for the underlying linear equation solver auto subEnv = env; if (subEnv.solver().getLinearEquationSolverType() == storm::solver::EquationSolverType::Topological) { // Topological solver does not make any sense since the BSCC is connected. subEnv.solver().setLinearEquationSolverType(subEnv.solver().topological().getUnderlyingEquationSolverType(), subEnv.solver().topological().isUnderlyingEquationSolverTypeSetFromDefault()); } subEnv.solver().setLinearEquationSolverPrecision(env.solver().lra().getPrecision(), env.solver().lra().getRelativeTerminationCriterion()); // Get a mapping from global state indices to local ones as well as a bitvector containing states within the BSCC. std::unordered_map<uint64_t, uint64_t> toLocalIndexMap; storm::storage::BitVector bsccStates(this->_transitionMatrix.getRowCount(), false); uint64_t localIndex = 0; for (auto const& globalIndex : bscc) { bsccStates.set(globalIndex, true); toLocalIndexMap[globalIndex] = localIndex; ++localIndex; } // Build the auxiliary Matrix A. auto auxMatrix = this->_transitionMatrix.getSubmatrix(false, bsccStates, bsccStates, true); // add diagonal entries! uint64_t row = 0; for (auto const& globalIndex : bscc) { ValueType rateAtState = this->_exitRates ? (*this->_exitRates)[globalIndex] : storm::utility::one<ValueType>(); for (auto& entry : auxMatrix.getRow(row)) { if (entry.getColumn() == row) { // This value is non-zero since we have a BSCC with more than one state entry.setValue(rateAtState * (entry.getValue() - storm::utility::one<ValueType>())); } else if (this->isContinuousTime()) { entry.setValue(entry.getValue() * rateAtState); } } ++row; } assert(row == auxMatrix.getRowCount()); // We need to consider A^t. This will not delete diagonal entries since they are non-zero. auxMatrix = auxMatrix.transpose(); // Check whether we need the fixpoint characterization storm::solver::GeneralLinearEquationSolverFactory<ValueType> linearEquationSolverFactory; bool isFixpointFormat = linearEquationSolverFactory.getEquationProblemFormat(subEnv) == storm::solver::LinearEquationSolverProblemFormat::FixedPointSystem; if (isFixpointFormat) { // Add a 1 on the diagonal for (row = 0; row < auxMatrix.getRowCount(); ++row) { for (auto& entry : auxMatrix.getRow(row)) { if (entry.getColumn() == row) { entry.setValue(storm::utility::one<ValueType>() + entry.getValue()); } } } } // We now build the equation system matrix. // We can drop the last row of A and add ones in this row instead to assert that the variables sum up to one // Phase 1: replace the existing entries of the last row with ones uint64_t col = 0; uint64_t lastRow = auxMatrix.getRowCount() - 1; for (auto& entry : auxMatrix.getRow(lastRow)) { entry.setColumn(col); if (isFixpointFormat) { if (col == lastRow) { entry.setValue(storm::utility::zero<ValueType>()); } else { entry.setValue(-storm::utility::one<ValueType>()); } } else { entry.setValue(storm::utility::one<ValueType>()); } ++col; } storm::storage::SparseMatrixBuilder<ValueType> builder(std::move(auxMatrix)); for (; col <= lastRow; ++col) { if (isFixpointFormat) { if (col != lastRow) { builder.addNextValue(lastRow, col, -storm::utility::one<ValueType>()); } } else { builder.addNextValue(lastRow, col, storm::utility::one<ValueType>()); } } std::vector<ValueType> bsccEquationSystemRightSide(bscc.size(), storm::utility::zero<ValueType>()); bsccEquationSystemRightSide.back() = storm::utility::one<ValueType>(); // Create a linear equation solver auto solver = linearEquationSolverFactory.create(subEnv, builder.build()); solver->setBounds(storm::utility::zero<ValueType>(), storm::utility::one<ValueType>()); // Check solver requirements. auto requirements = solver->getRequirements(subEnv); requirements.clearLowerBounds(); requirements.clearUpperBounds(); STORM_LOG_THROW(!requirements.hasEnabledCriticalRequirement(), storm::exceptions::UnmetRequirementException, "Solver requirements " + requirements.getEnabledRequirementsAsString() + " not checked."); std::vector<ValueType> lraDistr(bscc.size(), storm::utility::one<ValueType>() / storm::utility::convertNumber<ValueType, uint64_t>(bscc.size())); solver->solveEquations(subEnv, lraDistr, bsccEquationSystemRightSide); // Calculate final LRA Value ValueType result = storm::utility::zero<ValueType>(); auto solIt = lraDistr.begin(); for (auto const& globalState : bscc) { if (this->isContinuousTime()) { result += (*solIt) * (stateValuesGetter(globalState) + (*this->_exitRates)[globalState] * actionValuesGetter(globalState)); } else { result += (*solIt) * (stateValuesGetter(globalState) + actionValuesGetter(globalState)); } ++solIt; } assert(solIt == lraDistr.end()); return std::pair<ValueType, std::vector<ValueType>>(std::move(result), std::move(lraDistr)); } template <typename ValueType> std::pair<storm::storage::SparseMatrix<ValueType>, std::vector<ValueType>> SparseDeterministicInfiniteHorizonHelper<ValueType>::buildSspMatrixVector(std::vector<ValueType> const& bsccLraValues, std::vector<uint64_t> const& inputStateToBsccIndexMap, storm::storage::BitVector const& statesNotInComponent, bool asEquationSystem) { // Create SSP Matrix. // In contrast to the version for nondeterministic models, we eliminate the auxiliary states representing each BSCC on the fly // Probability mass that would lead to a BSCC will be considered in the rhs of the equation system auto sspMatrix = this->_transitionMatrix.getSubmatrix(false, statesNotInComponent, statesNotInComponent, asEquationSystem); if (asEquationSystem) { sspMatrix.convertToEquationSystem(); } // Create the SSP right-hand-side std::vector<ValueType> rhs; rhs.reserve(sspMatrix.getRowCount()); for (auto const& state : statesNotInComponent) { ValueType stateValue = storm::utility::zero<ValueType>(); for (auto const& transition : this->_transitionMatrix.getRow(state)) { if (!statesNotInComponent.get(transition.getColumn())) { // This transition leads to a BSCC! stateValue += transition.getValue() * bsccLraValues[inputStateToBsccIndexMap[transition.getColumn()]]; } } rhs.push_back(std::move(stateValue)); } return std::make_pair(std::move(sspMatrix), std::move(rhs)); } template <typename ValueType> std::vector<ValueType> SparseDeterministicInfiniteHorizonHelper<ValueType>::buildAndSolveSsp(Environment const& env, std::vector<ValueType> const& componentLraValues) { STORM_LOG_ASSERT(this->_longRunComponentDecomposition != nullptr, "Decomposition not computed, yet."); // For fast transition rewriting, we build a mapping from the input state indices to the state indices of a new transition matrix // which redirects all transitions leading to a former BSCC state to a new (imaginary) auxiliary state. // Each auxiliary state gets assigned the value of that BSCC and we compute expected rewards (aka stochastic shortest path, SSP) on that new system. // For efficiency reasons, we actually build the system where the auxiliary states are already eliminated. // First gather the states that are part of a component // and create a mapping from states that lie in a component to the corresponding component index. storm::storage::BitVector statesInComponents(this->_transitionMatrix.getRowGroupCount()); std::vector<uint64_t> stateIndexMap(this->_transitionMatrix.getRowGroupCount(), std::numeric_limits<uint64_t>::max()); for (uint64_t currentComponentIndex = 0; currentComponentIndex < this->_longRunComponentDecomposition->size(); ++currentComponentIndex) { for (auto const& element : (*this->_longRunComponentDecomposition)[currentComponentIndex]) { uint64_t state = internal::getComponentElementState(element); statesInComponents.set(state); stateIndexMap[state] = currentComponentIndex; } } // Map the non-component states to their index in the SSP. Note that the order of these states will be preserved. uint64_t numberOfNonComponentStates = 0; storm::storage::BitVector statesNotInComponent = ~statesInComponents; for (auto const& nonComponentState : statesNotInComponent) { stateIndexMap[nonComponentState] = numberOfNonComponentStates; ++numberOfNonComponentStates; } // The next step is to create the equation system solving the SSP (unless the whole system consists of BSCCs) std::vector<ValueType> sspValues; if (numberOfNonComponentStates > 0) { storm::solver::GeneralLinearEquationSolverFactory<ValueType> linearEquationSolverFactory; bool isEqSysFormat = linearEquationSolverFactory.getEquationProblemFormat(env) == storm::solver::LinearEquationSolverProblemFormat::EquationSystem; auto sspMatrixVector = buildSspMatrixVector(componentLraValues, stateIndexMap, statesNotInComponent, isEqSysFormat); std::unique_ptr<storm::solver::LinearEquationSolver<ValueType>> solver = linearEquationSolverFactory.create(env, sspMatrixVector.first); auto lowerUpperBounds = std::minmax_element(componentLraValues.begin(), componentLraValues.end()); solver->setBounds(*lowerUpperBounds.first, *lowerUpperBounds.second); // Check solver requirements auto requirements = solver->getRequirements(env); requirements.clearUpperBounds(); requirements.clearLowerBounds(); STORM_LOG_THROW(!requirements.hasEnabledCriticalRequirement(), storm::exceptions::UnmetRequirementException, "Solver requirements " + requirements.getEnabledRequirementsAsString() + " not checked."); sspValues.assign(sspMatrixVector.first.getRowCount(), (*lowerUpperBounds.first + *lowerUpperBounds.second) / storm::utility::convertNumber<ValueType,uint64_t>(2)); solver->solveEquations(env, sspValues, sspMatrixVector.second); } // Prepare result vector. std::vector<ValueType> result(this->_transitionMatrix.getRowGroupCount()); for (uint64_t state = 0; state < stateIndexMap.size(); ++state) { if (statesNotInComponent.get(state)) { result[state] = sspValues[stateIndexMap[state]]; } else { result[state] = componentLraValues[stateIndexMap[state]]; } } return result; } template class SparseDeterministicInfiniteHorizonHelper<double>; template class SparseDeterministicInfiniteHorizonHelper<storm::RationalNumber>; template class SparseDeterministicInfiniteHorizonHelper<storm::RationalFunction>; } } }
71.018476
340
0.605997
glatteis
23d26327a7db8bc2b8610e9dccd146ef0101ed3e
14,772
cpp
C++
src/bindings/Scriptdev2/scripts/northrend/icecrown_citadel/icecrown_citadel/boss_lord_marrowgar.cpp
mfooo/wow
3e5fad4cfdf0fd1c0a2fd7c9844e6f140a1bb32d
[ "OpenSSL" ]
1
2017-11-16T19:04:07.000Z
2017-11-16T19:04:07.000Z
src/bindings/Scriptdev2/scripts/northrend/icecrown_citadel/icecrown_citadel/boss_lord_marrowgar.cpp
mfooo/wow
3e5fad4cfdf0fd1c0a2fd7c9844e6f140a1bb32d
[ "OpenSSL" ]
null
null
null
src/bindings/Scriptdev2/scripts/northrend/icecrown_citadel/icecrown_citadel/boss_lord_marrowgar.cpp
mfooo/wow
3e5fad4cfdf0fd1c0a2fd7c9844e6f140a1bb32d
[ "OpenSSL" ]
null
null
null
/* Copyright (C) 2006 - 2010 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* ScriptData SDName: boss_lord_marrowgar SD%Complete: 85% SDComment: by /dev/rsa SDCategory: Icecrown Citadel EndScriptData */ #include "precompiled.h" #include "def_spire.h" enum { //common SPELL_BERSERK = 47008, //yells //summons NPC_BONE_SPIKE = 38711, NPC_COLD_FLAME = 36672, //Abilities SPELL_SABER_LASH = 71021, SPELL_CALL_COLD_FLAME = 69138, SPELL_CALL_COLD_FLAME_1 = 71580, SPELL_COLD_FLAME = 69146, SPELL_COLD_FLAME_0 = 69145, SPELL_COLD_FLAME_1 = 69147, SPELL_BONE_STRIKE = 69057, SPELL_BONE_STORM = 69076, SPELL_BONE_STRIKE_IMPALE = 69065, SPELL_VEHICLE_HARDCODED = 46598, SPELL_BONE_STORM_STRIKE = 69075, }; struct MANGOS_DLL_DECL boss_lord_marrowgarAI : public BSWScriptedAI { boss_lord_marrowgarAI(Creature* pCreature) : BSWScriptedAI(pCreature) { pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); Reset(); } ScriptedInstance *pInstance; bool intro; void Reset() { if (!pInstance) return; if (m_creature->isAlive()) pInstance->SetData(TYPE_MARROWGAR, NOT_STARTED); resetTimers(); m_creature->SetSpeedRate(MOVE_RUN, 1); m_creature->SetSpeedRate(MOVE_WALK, 1); // m_creature->AddSplineFlag(SPLINEFLAG_WALKMODE); } void MoveInLineOfSight(Unit* pWho) { ScriptedAI::MoveInLineOfSight(pWho); if (intro) return; DoScriptText(-1631000,m_creature); intro = true; } void JustSummoned(Creature* summoned) { if(!pInstance || !summoned) return; summoned->SetCreatorGuid(m_creature->GetObjectGuid()); } void JustReachedHome() { if (pInstance) pInstance->SetData(TYPE_MARROWGAR, FAIL); } void Aggro(Unit *who) { if(!pInstance) return; pInstance->SetData(TYPE_MARROWGAR, IN_PROGRESS); DoScriptText(-1631001,m_creature); } void KilledUnit(Unit* pVictim) { switch (urand(0,1)) { case 0: DoScriptText(-1631006,m_creature,pVictim); break; case 1: DoScriptText(-1631007,m_creature,pVictim); break; }; } void JustDied(Unit *killer) { if(pInstance) pInstance->SetData(TYPE_MARROWGAR, DONE); DoScriptText(-1631009,m_creature); } void doSummonSpike(Unit* pTarget) { if (!pTarget || !pTarget->isAlive()) return; float fPosX, fPosY, fPosZ; pTarget->GetPosition(fPosX, fPosY, fPosZ); if (Unit* pSpike = doSummon(NPC_BONE_SPIKE, fPosX, fPosY, fPosZ + 0.5f)) { pSpike->SetOwnerGuid(m_creature->GetObjectGuid()); pSpike->SetInCombatWith(pTarget); pSpike->AddThreat(pTarget, 1000.0f); } } void UpdateAI(const uint32 diff) { if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; switch(getStage()) { case 0: if (timedQuery(SPELL_BONE_STRIKE, diff)) if (Unit* pTarget = doSelectRandomPlayer(SPELL_BONE_STRIKE_IMPALE, false, 60.0f)) if (doCast(SPELL_BONE_STRIKE, pTarget) == CAST_OK) { doSummonSpike(pTarget); switch (urand(0,1)) { case 0: DoScriptText(-1631003,m_creature,pTarget); break; case 1: DoScriptText(-1631004,m_creature,pTarget); break; case 2: DoScriptText(-1631005,m_creature,pTarget); break; }; }; if (timedQuery(SPELL_BONE_STORM, diff)) setStage(1); if (timedQuery(SPELL_CALL_COLD_FLAME, diff)) { if (urand(0,1)) doCast(SPELL_CALL_COLD_FLAME); else doCast(SPELL_CALL_COLD_FLAME_1); if (m_creature->GetHealthPercent() <= 30.0f) { if (urand(0,1)) doCast(SPELL_CALL_COLD_FLAME); else doCast(SPELL_CALL_COLD_FLAME_1); } } timedCast(SPELL_SABER_LASH, diff); DoMeleeAttackIfReady(); break; case 1: m_creature->InterruptNonMeleeSpells(true); doCast(SPELL_BONE_STORM); setStage(2); DoScriptText(-1631002,m_creature); DoResetThreat(); m_creature->RemoveSplineFlag(SPLINEFLAG_WALKMODE); m_creature->SetSpeedRate(MOVE_RUN, 3); m_creature->SetSpeedRate(MOVE_WALK, 3); break; case 2: if (!m_creature->IsNonMeleeSpellCasted(false)) setStage(3); break; case 3: if (isHeroic()) if (timedQuery(SPELL_BONE_STRIKE, diff, true)) if (Unit* pTarget = doSelectRandomPlayer(SPELL_BONE_STRIKE_IMPALE, false, 60.0f)) doSummonSpike(pTarget); if (timedQuery(SPELL_CALL_COLD_FLAME, diff, true) && m_creature->IsWithinDistInMap(m_creature->getVictim(),2.0f)) { pInstance->SetData(DATA_DIRECTION, (uint32)(1000*2.0f*M_PI_F*((float)urand(1,16)/16.0f))); // if (urand(0,1)) doCast(SPELL_CALL_COLD_FLAME); // else doCast(SPELL_CALL_COLD_FLAME_1); float fPosX, fPosY, fPosZ; m_creature->GetPosition(fPosX, fPosY, fPosZ); doSummon(NPC_COLD_FLAME, fPosX, fPosY, fPosZ); DoResetThreat(); if (Unit* pTarget = doSelectRandomPlayerAtRange(60.0f)) AttackStart(pTarget); } if (!hasAura(SPELL_BONE_STORM_STRIKE, m_creature) && !hasAura(SPELL_BONE_STORM, m_creature)) setStage(4); break; case 4: pInstance->SetData(DATA_DIRECTION, 0); m_creature->SetSpeedRate(MOVE_RUN, 1); m_creature->SetSpeedRate(MOVE_WALK, 1); // m_creature->AddSplineFlag(SPLINEFLAG_WALKMODE); setStage(0); break; default: break; } if (timedQuery(SPELL_BERSERK, diff)) { doCast(SPELL_BERSERK); DoScriptText(-1631008,m_creature); } } }; struct MANGOS_DLL_DECL mob_coldflameAI : public BSWScriptedAI { mob_coldflameAI(Creature *pCreature) : BSWScriptedAI(pCreature) { m_pInstance = ((ScriptedInstance*)pCreature->GetInstanceData()); Reset(); } ScriptedInstance* m_pInstance; bool isFirst; bool isXmode; float m_direction; float x, y, radius; bool isCreator; void Reset() { if(!m_pInstance) return; // m_creature->SetDisplayId(10045); m_creature->SetRespawnDelay(7*DAY); m_creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); m_creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); setStage(0); isCreator = false; SetCombatMovement(false); doCast(SPELL_COLD_FLAME_0); } void AttackStart(Unit *who) { } void JustSummoned(Creature* summoned) { if(!m_pInstance || !summoned) return; summoned->SetCreatorGuid(m_creature->GetObjectGuid()); } void UpdateAI(const uint32 uiDiff) { if(m_pInstance && m_pInstance->GetData(TYPE_MARROWGAR) != IN_PROGRESS) { m_creature->ForcedDespawn(); } if (m_creature->GetCreatorGuid().IsEmpty()) return; if (!isCreator) { if (m_creature->GetCreatorGuid() == m_pInstance->GetData64(NPC_LORD_MARROWGAR)) { isFirst = true; uint32 m_tmpDirection = m_pInstance->GetData(DATA_DIRECTION); m_pInstance->SetData(DATA_DIRECTION,0); if (m_tmpDirection) { m_direction = m_tmpDirection/1000.0f; isXmode = true; } else { m_direction = 2.0f*M_PI_F*((float)urand(1,16)/16.0f); isXmode = false; } } else isFirst = false; isCreator = true; } if (timedQuery(SPELL_COLD_FLAME_0, uiDiff) && !isFirst) m_creature->ForcedDespawn(); if (isFirst && timedQuery(SPELL_COLD_FLAME_1, uiDiff, true)) { if (getStage() < getSpellData(SPELL_COLD_FLAME_0)) { setStage(getStage()+1); radius = getStage()*5; m_creature->GetNearPoint2D(x, y, radius, m_direction); doSummon(NPC_COLD_FLAME, x, y, m_creature->GetPositionZ(), TEMPSUMMON_TIMED_DESPAWN, getSpellData(SPELL_COLD_FLAME_1)); if (isXmode) { m_creature->GetNearPoint2D(x, y, radius, m_direction+M_PI_F/2); doSummon(NPC_COLD_FLAME, x, y, m_creature->GetPositionZ(), TEMPSUMMON_TIMED_DESPAWN, getSpellData(SPELL_COLD_FLAME_1)); m_creature->GetNearPoint2D(x, y, radius, m_direction+M_PI_F); doSummon(NPC_COLD_FLAME, x, y, m_creature->GetPositionZ(), TEMPSUMMON_TIMED_DESPAWN, getSpellData(SPELL_COLD_FLAME_1)); m_creature->GetNearPoint2D(x, y, radius, m_direction+M_PI_F*1.5f); doSummon(NPC_COLD_FLAME, x, y, m_creature->GetPositionZ(), TEMPSUMMON_TIMED_DESPAWN, getSpellData(SPELL_COLD_FLAME_1)); } } else m_creature->ForcedDespawn(); } else timedCast(SPELL_COLD_FLAME, uiDiff); } }; struct MANGOS_DLL_DECL mob_bone_spikeAI : public BSWScriptedAI { mob_bone_spikeAI(Creature *pCreature) : BSWScriptedAI(pCreature) { m_pInstance = ((ScriptedInstance*)pCreature->GetInstanceData()); Reset(); } ScriptedInstance* m_pInstance; ObjectGuid victimGuid; void Reset() { SetCombatMovement(false); m_creature->SetRespawnDelay(7*DAY); victimGuid = ObjectGuid(); m_creature->SetInCombatWithZone(); } void Aggro(Unit* pWho) { if (victimGuid.IsEmpty() && pWho && pWho->GetTypeId() == TYPEID_PLAYER) { victimGuid = pWho->GetObjectGuid(); m_creature->SetInCombatWith(pWho); doCast(SPELL_BONE_STRIKE_IMPALE,pWho); doCast(SPELL_VEHICLE_HARDCODED,pWho); } } void DamageTaken(Unit* pDoneBy, uint32 &uiDamage) { if (uiDamage > m_creature->GetHealth()) if (Player* pVictim = m_creature->GetMap()->GetPlayer(victimGuid)) doRemove(SPELL_BONE_STRIKE_IMPALE,pVictim); } void AttackStart(Unit *who) { } void KilledUnit(Unit* _Victim) { if (Player* pVictim = m_creature->GetMap()->GetPlayer(victimGuid)) if (pVictim->GetObjectGuid() == victimGuid) doRemove(SPELL_BONE_STRIKE_IMPALE,pVictim); } void JustDied(Unit* Killer) { if (Player* pVictim = m_creature->GetMap()->GetPlayer(victimGuid)) doRemove(SPELL_BONE_STRIKE_IMPALE,pVictim); } void UpdateAI(const uint32 uiDiff) { if(m_pInstance && m_pInstance->GetData(TYPE_MARROWGAR) != IN_PROGRESS) { if (Player* pVictim = m_creature->GetMap()->GetPlayer(victimGuid)) doRemove(SPELL_BONE_STRIKE_IMPALE,pVictim); m_creature->ForcedDespawn(); } if (victimGuid.IsEmpty()) return; if (Player* pVictim = m_creature->GetMap()->GetPlayer(victimGuid)) { if(!pVictim->isAlive()) m_creature->ForcedDespawn(); } else m_creature->ForcedDespawn(); } }; CreatureAI* GetAI_mob_bone_spike(Creature* pCreature) { return new mob_bone_spikeAI(pCreature); } CreatureAI* GetAI_mob_coldflame(Creature* pCreature) { return new mob_coldflameAI(pCreature); } CreatureAI* GetAI_boss_lord_marrowgar(Creature* pCreature) { return new boss_lord_marrowgarAI(pCreature); } void AddSC_boss_lord_marrowgar() { Script *newscript; newscript = new Script; newscript->Name = "boss_lord_marrowgar"; newscript->GetAI = &GetAI_boss_lord_marrowgar; newscript->RegisterSelf(); newscript = new Script; newscript->Name = "mob_coldflame"; newscript->GetAI = &GetAI_mob_coldflame; newscript->RegisterSelf(); newscript = new Script; newscript->Name = "mob_bone_spike"; newscript->GetAI = &GetAI_mob_bone_spike; newscript->RegisterSelf(); }
34.115473
139
0.546845
mfooo
23d5d0fe82a7157b45cd3e14aaeecdbb5842c18e
1,782
cpp
C++
source/tvision/tapplica.cpp
ebelin/tvision
bf09d50c30a58298894cd478125c43b91a6e7c79
[ "MIT" ]
null
null
null
source/tvision/tapplica.cpp
ebelin/tvision
bf09d50c30a58298894cd478125c43b91a6e7c79
[ "MIT" ]
1
2020-10-12T22:41:38.000Z
2020-11-05T22:35:39.000Z
source/tvision/tapplica.cpp
jvprat/tvision
394febdb490ce962930db173274a81e10fac82f8
[ "MIT" ]
null
null
null
/*-------------------------------------------------------------------*/ /* filename - tapplica.cpp */ /* */ /* function(s) */ /* TApplication member functions (constructor & destructor) */ /*-------------------------------------------------------------------*/ /* * Turbo Vision - Version 2.0 * * Copyright (c) 1994 by Borland International * All Rights Reserved. * */ #define Uses_TSystemError #define Uses_TEventQueue #define Uses_THardwareInfo #define Uses_TScreen #define Uses_TObject #define Uses_TMouse #define Uses_TApplication #include <tvision/tv.h> TStaticInit::TStaticInit() { // Construct on first use static THardwareInfo hwInfoManager; static TScreen tsc; static TEventQueue teq; static TSystemError sysErr; } void initHistory(); void doneHistory(); TApplication::TApplication() : TProgInit( &TApplication::initStatusLine, &TApplication::initMenuBar, &TApplication::initDeskTop ) { initHistory(); } TApplication::~TApplication() { doneHistory(); } void TApplication::suspend() { TSystemError::suspend(); TEventQueue::suspend(); TScreen::suspend(); } void TApplication::resume() { TScreen::resume(); TEventQueue::resume(); TSystemError::resume(); if( size.x != TScreen::screenWidth || size.y != TScreen::screenHeight ) // If these don't match and screen size shrinked, views will attempt // to draw beyond TDrawBuffer's limits. setScreenMode( TDisplay::smChanged ); }
26.597015
77
0.522447
ebelin
23da388b5a166cf2e3c5c63bc2ef412d32d348d6
896
cpp
C++
src/flower/layer/dropout.cpp
Fs02/Flower
b2a91c78fc6a72766abcf1cac620e22233899d99
[ "MIT" ]
1
2016-12-02T14:33:16.000Z
2016-12-02T14:33:16.000Z
src/flower/layer/dropout.cpp
Fs02/Flower
b2a91c78fc6a72766abcf1cac620e22233899d99
[ "MIT" ]
null
null
null
src/flower/layer/dropout.cpp
Fs02/Flower
b2a91c78fc6a72766abcf1cac620e22233899d99
[ "MIT" ]
null
null
null
#include <flower/layer/dropout.h> #include <cmath> using namespace flower; Dropout::Dropout(double probabilty) : ILayerDef(), probability_(probabilty) {} layer_ptr Dropout::create(Net *net) const { return std::make_shared<DropoutLayer>(net, *this); } DropoutLayer::DropoutLayer(Net *net, const Dropout &definition) : ILayer(net, definition), mask_(0, 0), probability_(definition.probability()) {} Eigen::Tensor<double, 2> DropoutLayer::forward(const Eigen::Tensor<double, 2> &data, bool train) { if (train) { mask_ = (data.random() > probability_).cast<double>() / probability_; // dropout with inverted approach return data * mask_; } return data; } Eigen::Tensor<double, 2> DropoutLayer::backward(const Eigen::Tensor<double, 2> &errors) { Eigen::array<int, 2> transpose({1, 0}); return mask_.shuffle(transpose) * errors; }
22.974359
96
0.678571
Fs02
23da4c60992b779b19b86e9c2838dcb8cd53f88a
398
hpp
C++
src/Utils.hpp
robifr/snake
611c6cc0460a92cca7e033108be13510aeba6b69
[ "MIT" ]
null
null
null
src/Utils.hpp
robifr/snake
611c6cc0460a92cca7e033108be13510aeba6b69
[ "MIT" ]
null
null
null
src/Utils.hpp
robifr/snake
611c6cc0460a92cca7e033108be13510aeba6b69
[ "MIT" ]
null
null
null
#pragma once #include <SDL.h> #include <SDL_ttf.h> struct My_SDL_Deleter { void operator()(SDL_Window* p) const { SDL_DestroyWindow(p); } void operator()(SDL_Renderer* p) const { SDL_DestroyRenderer(p); } void operator()(SDL_Texture* p) const { SDL_DestroyTexture(p); } void operator()(SDL_Surface* p) const { SDL_FreeSurface(p); } void operator()(TTF_Font* p) const { TTF_CloseFont(p); } };
33.166667
67
0.71608
robifr
23da4f11060e930c31d6fed9e4ad7de50db33474
686
cpp
C++
plugins/gdifont/src/get_text_metrics.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
plugins/gdifont/src/get_text_metrics.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
plugins/gdifont/src/get_text_metrics.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <sge/font/exception.hpp> #include <sge/gdifont/device_context.hpp> #include <sge/gdifont/get_text_metrics.hpp> #include <sge/gdifont/include_windows.hpp> #include <fcppt/text.hpp> TEXTMETRIC const sge::gdifont::get_text_metrics(sge::gdifont::device_context const &_device_context) { TEXTMETRIC result; if (::GetTextMetrics(_device_context.get(), &result) == 0) throw sge::font::exception(FCPPT_TEXT("GetTextMetrics failed")); return result; }
32.666667
100
0.734694
cpreh
23db41847375c135f27605b198c71aba58e9244d
2,894
cpp
C++
code/src/engine/task/scheduler_dummy.cpp
shossjer/fimbulwinter
d894e4bddb5d2e6dc31a8112d245c6a1828604e3
[ "0BSD" ]
3
2020-04-29T14:55:58.000Z
2020-08-20T08:43:24.000Z
code/src/engine/task/scheduler_dummy.cpp
shossjer/fimbulwinter
d894e4bddb5d2e6dc31a8112d245c6a1828604e3
[ "0BSD" ]
1
2022-03-12T11:37:46.000Z
2022-03-12T20:17:38.000Z
code/src/engine/task/scheduler_dummy.cpp
shossjer/fimbulwinter
d894e4bddb5d2e6dc31a8112d245c6a1828604e3
[ "0BSD" ]
null
null
null
#include "config.h" #if TASK_USE_DUMMY #include "core/async/Thread.hpp" #include "core/container/Queue.hpp" #include "core/sync/Event.hpp" #include "engine/task/scheduler.hpp" #include "utility/any.hpp" #include "utility/optional.hpp" #include "utility/variant.hpp" namespace { struct Work { engine::Hash strand; engine::task::work_callback * workcall; utility::any data; }; struct Terminate { }; using Message = utility::variant < Work, Terminate >; } namespace engine { namespace task { struct scheduler_impl { core::container::PageQueue<utility::heap_storage<Message>> queue; core::async::Thread thread; core::sync::Event<true> event; }; } } namespace { utility::spinlock singelton_lock; utility::optional<engine::task::scheduler_impl> singelton; engine::task::scheduler_impl * create_impl() { std::lock_guard<utility::spinlock> guard(singelton_lock); if (singelton) return nullptr; singelton.emplace(); return &singelton.value(); } void destroy_impl(engine::task::scheduler_impl & /*impl*/) { std::lock_guard<utility::spinlock> guard(singelton_lock); singelton.reset(); } } namespace { bool parse_message(engine::task::scheduler_impl & impl) { Message message; while (impl.queue.try_pop(message)) { struct { engine::task::scheduler_impl & impl; bool operator () (Work && x) { engine::task::scheduler scheduler(impl); x.workcall(scheduler, x.strand, std::move(x.data)); scheduler.detach(); return true; } bool operator () (Terminate &&) { return false; } } visitor{impl}; if (!visit(visitor, std::move(message))) return false; } return true; } core::async::thread_return thread_decl scheduler_thread(core::async::thread_param arg) { engine::task::scheduler_impl & impl = *static_cast<engine::task::scheduler_impl *>(arg); do { impl.event.wait(); impl.event.reset(); } while (parse_message(impl)); return core::async::thread_return{}; } } namespace engine { namespace task { scheduler_impl * scheduler::construct(ext::ssize thread_count) { if (!debug_verify(0 < thread_count)) return nullptr; scheduler_impl * const impl = create_impl(); if (debug_verify(impl)) { impl->thread = core::async::Thread(scheduler_thread, impl); } return impl; } void scheduler::destruct(scheduler_impl & impl) { if (debug_verify(impl.queue.try_emplace(utility::in_place_type<Terminate>))) { impl.event.set(); impl.thread.join(); } impl.event.reset(); destroy_impl(impl); } void post_work( scheduler & scheduler, engine::Hash strand, work_callback * workcall, utility::any && data) { if (debug_verify(scheduler->queue.try_emplace(utility::in_place_type<Work>, strand, workcall, std::move(data)))) { scheduler->event.set(); } } } } #endif
17.754601
115
0.671389
shossjer
23e2cf346822e124d7474943c2e1bf9f7a2d5db3
8,024
cpp
C++
gui/src/SearchWindow.cpp
eosswedenorg/eosio-keygen
a73689e275a893b719608fe3808eddc030833cf1
[ "MIT" ]
1
2020-04-23T09:23:30.000Z
2020-04-23T09:23:30.000Z
gui/src/SearchWindow.cpp
eosswedenorg/eosio-keygen
a73689e275a893b719608fe3808eddc030833cf1
[ "MIT" ]
16
2019-12-20T14:02:01.000Z
2021-05-07T11:59:52.000Z
gui/src/SearchWindow.cpp
eosswedenorg/eosio-keygen
a73689e275a893b719608fe3808eddc030833cf1
[ "MIT" ]
3
2020-02-14T04:04:45.000Z
2020-04-23T09:23:44.000Z
/** * MIT License * * Copyright (c) 2020-2021 EOS Sw/eden * * 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 <QDebug> #include <QFileDialog> #include <QMessageBox> #include <QScrollBar> #include <QGridLayout> #include <QFuture> #include <QtConcurrent> #include <libeosio/WIF.hpp> #include <eoskeygen/core/leet.hpp> #include <eoskeygen/core/string.hpp> #include "Settings.hpp" #include "gui_text.h" #include "config.hpp" #include "helpers.hpp" #include "SearchWindow.hpp" SearchWindow::SearchWindow(QWidget *parent, Qt::WindowFlags flags) : QWidget (parent, flags), m_status ("status"), m_leet_cb ("L33t"), m_dict_lang ("Dictionary Language"), m_dict_file ("Dictionary File", true), m_btn_exec ("Search"), m_btn_clear ("Clear") { setMinimumSize(600, 400); // Monospaced font QFont f_mono("monospace"); // Output m_output.setFont(f_mono); m_output.setReadOnly(true); // Layout // ------------------------ setLayout(&m_layout); m_layout.setColumnStretch(0, 10); m_layout.setColumnStretch(1, 10); // First row. m_dict_lang.addItems(get_files(CONFIG_DICT_FULL_PATH)); m_dict_lang.setToolTip(EOSIOKEYGEN_GUI_TEXT_DICT_LANG_TOOLTIP); m_dict_file.setToolTip(EOSIOKEYGEN_GUI_TEXT_DICT_FILE_TOOLTIP); m_layout.addWidget(&m_dict_lang, 0, 0); m_layout.addWidget(&m_dict_file, 0, 1); m_layout.addWidget(&m_leet_cb, 0, 2); #ifdef EOSIOKEYGEN_HAVE_THREADS m_num_threads.setValue((int) eoskeygen::KeySearch::max_threads()); m_num_threads.setRange(1, (int) eoskeygen::KeySearch::max_threads()); m_num_threads.setSuffix(" Threads"); m_layout.addWidget(&m_num_threads, 0, 3); #endif /* EOSIOKEYGEN_HAVE_THREADS */ m_num_results.setValue(10); m_num_results.setRange(1, 99); m_num_results.setSuffix(" Results"); m_layout.addWidget(&m_num_results, 0, 4); // Second row. m_layout.addWidget(&m_status, 1, 0, 1, 3); m_layout.addWidget(&m_txt_search, 1, 0, 1, 3); m_layout.addWidget(&m_btn_exec, 1, 3); m_layout.addWidget(&m_btn_clear, 1, 4); // Third row. m_layout.addWidget(&m_output, 2, 0, 1, 0); // Search // ------------------------ m_ksearch.setCallback(this); initSignals(); // Focus search field. m_txt_search.setFocus(); } void SearchWindow::initSignals() { // Buttons connect(&m_btn_exec, SIGNAL(released()), this, SLOT(search())); connect(&m_btn_clear, SIGNAL(released()), &m_output, SLOT(clear())); // Worker Thread connect(&m_worker, SIGNAL(started()), this, SLOT(searchStarted())); connect(&m_worker, SIGNAL(finished()), this, SLOT(searchFinished())); connect(this, SIGNAL(addOutput(QString)), this, SLOT(output(QString))); connect(&m_dict_file, SIGNAL(addNewItem()), this, SLOT(langFileAdd())); } void SearchWindow::loadDictionaries() { QStringList list; eoskeygen::Dictionary tmpDict; std::string base_path(CONFIG_DICT_FULL_PATH); // Clear dictionary first. m_dict.clear(); // Go through all selected languages. list = m_dict_lang.getSelectedItems(); for(QStringList::const_iterator it = list.cbegin(); it != list.cend(); it++) { // Load and add them to dictionary. tmpDict.loadFromFile(base_path + "/" + it->toStdString()); m_dict.add(tmpDict); } // Go through all selected files. list = m_dict_file.getSelectedItems(); for(QStringList::const_iterator it = list.cbegin(); it != list.cend(); it++) { // Load and add them to dictionary. tmpDict.loadFromFile(it->toStdString()); m_dict.add(tmpDict); } } void SearchWindow::onResult(const struct libeosio::ec_keypair* key, const struct eoskeygen::KeySearch::result& result) { int pos = (int) result.pos; int len = (int) result.len; QString pub = QString::fromStdString(libeosio::wif_pub_encode(key->pub, Settings::shouldGenerateFioKeys() ? "FIO" : "EOS")); QString mid = pub.mid(pos, len); QString left = pub.left(pos); QString right = pub.mid(pos + len, pub.size() - pos); eoskeygen::Dictionary::search_result_t dict_res = m_dict.search(pub.toStdString()); QString out = "Public: " + pub.left(3); for(int i = 3; i < pub.length(); ) { if (i == pos) { out += "<font color=red>" + pub.mid(pos, len) + "</font>"; i += len; continue; } // Look in the dictionary. auto dp = dict_res.find(i); if (dp != dict_res.end()) { int p = (int) dp->first; int l = (int) dp->second; out += "<font color=blue>" + pub.mid(p, l) + "</font>"; i += l; continue; } out += pub[i++]; } out += "<br/>Private: " + QString::fromStdString(libeosio::wif_priv_encode(key->secret)); // As this function could be called from a non-gui thread. we use signals. emit addOutput("<p>" + out + "</p>"); } // -------------------- // Slots // -------------------- void SearchWindow::search() { if (m_worker.isRunning()) { m_ksearch.abort(); return; } const std::string& input = m_txt_search.text().toLocal8Bit().constData(); eoskeygen::strlist_t list; if (m_leet_cb.isChecked()) { list = eoskeygen::l33twords(input); } else { list = eoskeygen::strlist::splitw(input); } // Validate that we atleast got something to search for. if (list.size() < 1 || (list.size() == 1 && list[0] == "")) { QMessageBox::warning( this, "Empty search field.", "You must specify atleast one search string" ); return; } loadDictionaries(); m_ksearch.clear(); m_ksearch.addList(list); #ifdef EOSIOKEYGEN_HAVE_THREADS m_ksearch.setThreadCount(m_num_threads.value()); #endif /* EOSIOKEYGEN_HAVE_THREADS */ QFuture<void> future = QtConcurrent::run(&m_ksearch, &eoskeygen::KeySearch::find, m_num_results.value()); m_worker.setFuture(future); m_status.setText("Searching for: " + QString::fromStdString(eoskeygen::strlist::join(list, ", "))); } void SearchWindow::output(const std::string& html) { output(QString::fromStdString(html)); } void SearchWindow::output(const QString& html) { if (m_output.toPlainText().size()) { m_output.setHtml(m_output.toHtml() + html); } else { m_output.setHtml(html); } // Force scrollbar to the bottom. m_output.verticalScrollBar()->setValue(m_output.verticalScrollBar()->maximum()); } void SearchWindow::langFileAdd() { QStringList files = QFileDialog::getOpenFileNames(this, "Select one or more language files"); m_dict_file.addItems(files, true); } void SearchWindow::searchStarted() { m_btn_exec.setText("Cancel"); m_txt_search.setEnabled(false); m_txt_search.setHidden(true); m_dict_lang.setEnabled(false); m_dict_file.setEnabled(false); m_leet_cb.setEnabled(false); m_btn_clear.setEnabled(false); #ifdef EOSIOKEYGEN_HAVE_THREADS m_num_threads.setEnabled(false); #endif /* EOSIOKEYGEN_HAVE_THREADS */ m_num_results.setEnabled(false); } void SearchWindow::searchFinished() { m_btn_exec.setText("Search"); m_txt_search.setEnabled(true); m_txt_search.setHidden(false); m_dict_lang.setEnabled(true); m_dict_file.setEnabled(true); m_leet_cb.setEnabled(true); m_btn_clear.setEnabled(true); #ifdef EOSIOKEYGEN_HAVE_THREADS m_num_threads.setEnabled(true); #endif /* EOSIOKEYGEN_HAVE_THREADS */ m_num_results.setEnabled(true); }
28.154386
126
0.709621
eosswedenorg
23e937c0481d5c9fc19d66de45f00e03d74891bb
3,482
cpp
C++
cpp/logger.cpp
s-bear/miscellanea
6f1398289e3c73057aa89ebcf926a57139ead380
[ "Unlicense" ]
null
null
null
cpp/logger.cpp
s-bear/miscellanea
6f1398289e3c73057aa89ebcf926a57139ead380
[ "Unlicense" ]
null
null
null
cpp/logger.cpp
s-bear/miscellanea
6f1398289e3c73057aa89ebcf926a57139ead380
[ "Unlicense" ]
null
null
null
// This is free and unencumbered software released into the public domain. #include "logger.hpp" #include <sstream> #include <cstdio> #include <functional> namespace logging { logger_t logger; level_t str_to_level(const std::string& str) { if(str == "debug") return logging::debug; else if(str == "info") return logging::info; else if(str == "warning") return logging::warning; else if(str == "error") return logging::error; else if(str == "fatal") return logging::fatal; else if(str == "none") return logging::none; else throw std::runtime_error("Invalid logging::level: " + str); } void set_level(level_t lev) { logger._level = lev; } level_t get_level() { return logger._level; } bool active(level_t lev) { return logger._level <= lev; } std::string tstamp(const std::string& fmt) { time_t now = time(nullptr); tm gmtnow; #ifdef WIN32 gmtime_s(&gmtnow, &now); #else gmtnow = *gmtime(&now); #endif char buffer[128]; strftime(buffer, 128, fmt.c_str(), &gmtnow); return std::string(buffer); } void start(level_t lev) { logger._level = lev; logger.start(); } void start() { logger.start(); } void stop() { logger.stop(); } queue_t::queue_t(logger_t *logger) : logger(logger), mut(), queue() {} queue_t::~queue_t() {} void queue_t::push(const std::string& item) { std::unique_lock lock(mut); queue.push_back(item); if (logger) { lock.unlock(); logger->notify(); } } void queue_t::push(std::string&& item) { std::unique_lock lock(mut); queue.push_back(std::move(item)); if (logger) { lock.unlock(); logger->notify(); } } bool queue_t::pop(std::string& item) { std::unique_lock lock(mut); if (queue.empty()) return false; item = queue.front(); queue.pop_front(); return true; } void queue_t::set_logger(logger_t* logger) { this->logger = logger; } logger_t::logger_t() : _level(info), running(false), sleepy(false) { streams[debug] = &std::cout; streams[info] = &std::cout; streams[warning] = &std::cout; streams[error] = &std::cerr; streams[fatal] = &std::cerr; for (size_t i = 0; i < level_t::none; ++i) queues[i].set_logger(this); } logger_t::~logger_t() { stop(); flush(); log_info(__FILE__,__LINE__) << "END LOG"; flush(); } void logger_t::start() { if (!running.exchange(true)) { thread = std::thread(std::mem_fn(&logger_t::run), &logger); } } void logger_t::stop() { if (running.exchange(false) && thread.joinable()) { notify(); thread.join(); } } void logger_t::run() { while (running) { if (!flush()) { std::unique_lock lock(mut); sleepy = true; while(sleepy) cond.wait_for(lock, std::chrono::milliseconds(200)); } } } void logger_t::notify() { std::unique_lock lock(mut); if (sleepy) { sleepy = false; cond.notify_one(); } } bool logger_t::flush() { std::string s; bool ret = false; for (int i = 0; i < level_t::none; ++i) { if (streams[i] != nullptr) { while (queues[i].pop(s)) { ret = true; (*streams[i]) << s << std::endl; } } } return ret; } void logger_t::set_streams(std::ostream* os) { for (int i = 0; i < level_t::none; ++i) streams[i] = os; } logline::logline(queue_t& queue, const std::string& level) : queue(queue) { os << tstamp() << " [" << level << "] "; } logline::~logline() { queue.push(os.str()); } }
20.850299
79
0.601091
s-bear
23eb150e93023a0bf2eea82377684efb921bc2cc
1,224
cpp
C++
361/a.cpp
vladshablinsky/algo
815392708d00dc8d3159b4866599de64fa9d34fa
[ "MIT" ]
1
2021-10-24T00:46:37.000Z
2021-10-24T00:46:37.000Z
361/a.cpp
vladshablinsky/algo
815392708d00dc8d3159b4866599de64fa9d34fa
[ "MIT" ]
null
null
null
361/a.cpp
vladshablinsky/algo
815392708d00dc8d3159b4866599de64fa9d34fa
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdio> #include <algorithm> #include <vector> using namespace std; vector<int> v; bool can_right(int x) { return x != 3 && x != 9 && x != 6 && x != 0; } bool can_left(int x) { return x != 1 && x != 4 && x != 7 && x != 0; } bool can_down(int x) { return x != 7 && x != 0 && x != 9; } bool can_up(int x) { return x != 1 && x != 2 && x != 3; } int main() { int n; string s; cin >> n; cin >> s; for (int i = 0; i < n; ++i) { v.push_back(s[i] - '0'); } bool flag = true; for (int i = 0; i < n; ++i) { if (!can_up(v[i])) { flag = false; break; } } if (flag) { cout << "NO\n"; return 0; } flag = true; for (int i = 0; i < n; ++i) { if (!can_down(v[i])) { flag = false; break; } } if (flag) { cout << "NO\n"; return 0; } flag = true; for (int i = 0; i < n; ++i) { if (!can_left(v[i])) { flag = false; break; } } if (flag) { cout << "NO\n"; return 0; } flag = true; for (int i = 0; i < n; ++i) { if (!can_right(v[i])) { flag = false; break; } } if (flag) { cout << "NO\n"; return 0; } cout << "YES\n"; return 0; }
14.926829
46
0.430556
vladshablinsky
23ed8b868f27f5f6e73a2d09a277025f0bb0464c
6,158
cc
C++
tests/inter/inter.cc
DavidFarago/crab
c5fba9a132afea11c10f2790d232d192b2d0ae9c
[ "Apache-2.0" ]
null
null
null
tests/inter/inter.cc
DavidFarago/crab
c5fba9a132afea11c10f2790d232d192b2d0ae9c
[ "Apache-2.0" ]
null
null
null
tests/inter/inter.cc
DavidFarago/crab
c5fba9a132afea11c10f2790d232d192b2d0ae9c
[ "Apache-2.0" ]
1
2020-03-01T12:33:53.000Z
2020-03-01T12:33:53.000Z
#include "../program_options.hpp" #include "../common.hpp" #include <crab/cg/cg_bgl.hpp> #include <crab/analysis/graphs/sccg_bgl.hpp> using namespace std; using namespace crab::analyzer; using namespace crab::cfg; using namespace crab::cfg_impl; using namespace crab::domain_impl; using namespace crab::cg; z_cfg_t* foo (variable_factory_t &vfac) { vector<pair<varname_t,crab::variable_type> > params; params.push_back (make_pair (vfac["x"], crab::INT_TYPE)); function_decl<varname_t> decl (crab::INT_TYPE, vfac["foo"], params); // Defining program variables z_var x (vfac ["x"]); z_var y (vfac ["y"]); z_var z (vfac ["z"]); // entry and exit block z_cfg_t* cfg = new z_cfg_t("entry", "exit", decl); // adding blocks z_basic_block_t& entry = cfg->insert ("entry"); z_basic_block_t& exit = cfg->insert ("exit"); // adding control flow entry >> exit; // adding statements entry.add (y, x, 1); exit.add (z , y , 2); exit.ret (vfac ["z"], crab::INT_TYPE); return cfg; } z_cfg_t* rec1 (variable_factory_t &vfac) { vector<pair<varname_t,crab::variable_type> > params; params.push_back (make_pair (vfac["s"], crab::INT_TYPE)); function_decl<varname_t> decl (crab::INT_TYPE, vfac["rec1"], params); // Defining program variables z_var r (vfac ["r"]); z_var s (vfac ["s"]); z_var t (vfac ["t"]); // entry and exit block z_cfg_t* cfg = new z_cfg_t("entry", "exit", decl); // adding blocks z_basic_block_t& entry = cfg->insert ("entry"); z_basic_block_t& exit = cfg->insert ("exit"); // adding control flow entry >> exit; // adding statements entry.sub (r, s, 1); vector<pair<varname_t,crab::variable_type> > args; args.push_back (make_pair (vfac["r"], crab::INT_TYPE)); exit.callsite (make_pair (vfac["t"], crab::INT_TYPE), vfac ["rec2"], args); exit.ret (vfac["t"], crab::INT_TYPE); return cfg; } z_cfg_t* rec2 (variable_factory_t &vfac) { vector<pair<varname_t,crab::variable_type> > params; params.push_back (make_pair (vfac["s1"], crab::INT_TYPE)); function_decl<varname_t> decl (crab::INT_TYPE, vfac["rec2"], params); // Defining program variables z_var r (vfac ["r1"]); z_var s (vfac ["s1"]); z_var t (vfac ["t1"]); // entry and exit block z_cfg_t* cfg = new z_cfg_t("entry", "exit", decl); // adding blocks z_basic_block_t& entry = cfg->insert ("entry"); z_basic_block_t& exit = cfg->insert ("exit"); // adding control flow entry >> exit; // adding statements entry.sub (r, s, 1); vector<pair<varname_t,crab::variable_type> > args; args.push_back (make_pair (vfac["r1"], crab::INT_TYPE)); exit.callsite (make_pair (vfac["t1"], crab::INT_TYPE), vfac ["rec1"], args); args.clear (); //args.push_back (make_pair (vfac["t1"], crab::INT_TYPE)); //exit.callsite (make_pair (vfac["t1"], crab::INT_TYPE), vfac ["foo"], args); exit.ret (vfac["t1"], crab::INT_TYPE); return cfg; } z_cfg_t* bar (variable_factory_t &vfac) { vector<pair<varname_t,crab::variable_type> > params; params.push_back (make_pair (vfac["a"], crab::INT_TYPE)); function_decl<varname_t> decl (crab::INT_TYPE, vfac["bar"], params); // Defining program variables z_var a (vfac ["a"]); z_var x (vfac ["x1"]); z_var y (vfac ["y1"]); z_var w (vfac ["w1"]); // entry and exit block z_cfg_t* cfg = new z_cfg_t("entry", "exit", decl); // adding blocks z_basic_block_t& entry = cfg->insert ("entry"); z_basic_block_t& exit = cfg->insert ("exit"); // adding control flow entry >> exit; // adding statements vector<pair<varname_t,crab::variable_type> > args; args.push_back (make_pair (vfac["x1"], crab::INT_TYPE)); exit.callsite (make_pair (vfac["y1"], crab::INT_TYPE), vfac ["foo"], args); entry.assign (x, a); entry.assign (w, 5); exit.ret (vfac["y1"], crab::INT_TYPE); return cfg; } z_cfg_t* m (variable_factory_t &vfac) { vector<pair<varname_t,crab::variable_type> > params; function_decl<varname_t> decl (crab::INT_TYPE, vfac["main"], params); // Defining program variables z_var x (vfac ["x2"]); z_var y (vfac ["y2"]); z_var z (vfac ["z2"]); // entry and exit block z_cfg_t* cfg = new z_cfg_t("entry", "exit", decl); // adding blocks z_basic_block_t& entry = cfg->insert ("entry"); z_basic_block_t& exit = cfg->insert ("exit"); // adding control flow entry >> exit; // adding statements entry.assign(x, 3); vector<pair<varname_t,crab::variable_type> > args; args.push_back (make_pair (vfac["x2"], crab::INT_TYPE)); entry.callsite (make_pair (vfac["y2"], crab::INT_TYPE), vfac ["bar"], args); args.clear (); ///// args.push_back (make_pair (vfac["y2"], crab::INT_TYPE)); entry.callsite (make_pair (vfac["z3"], crab::INT_TYPE), vfac ["rec1"], args); args.clear (); ///// exit.add (z, y, 2); args.push_back (make_pair (vfac["z2"], crab::INT_TYPE)); exit.callsite (make_pair (vfac["w2"], crab::INT_TYPE), vfac ["foo"], args); exit.ret (vfac["w2"], crab::INT_TYPE); return cfg; } int main (int argc, char** argv ) { SET_TEST_OPTIONS(argc,argv) variable_factory_t vfac; z_cfg_t* t1 = foo (vfac); z_cfg_t* t2 = bar (vfac); z_cfg_t* t3 = rec1 (vfac); z_cfg_t* t4 = rec2 (vfac); z_cfg_t* t5 = m (vfac); crab::outs() << *t1 << "\n"; crab::outs() << *t2 << "\n"; crab::outs() << *t3 << "\n"; crab::outs() << *t4 << "\n"; crab::outs() << *t5 << "\n"; vector<z_cfg_ref_t> cfgs; cfgs.push_back(*t1); cfgs.push_back(*t2); cfgs.push_back(*t3); cfgs.push_back(*t4); cfgs.push_back(*t5); typedef call_graph<z_cfg_ref_t> callgraph_t; typedef call_graph_ref<callgraph_t> callgraph_ref_t; boost::scoped_ptr<callgraph_t> cg(new callgraph_t(cfgs)); inter_run<z_dbm_domain_t, z_interval_domain_t> (&*cg, false, 2, 2, 20, stats_enabled); #ifdef HAVE_APRON inter_run<z_opt_oct_apron_domain_t, z_interval_domain_t> (&*cg, false, 2, 2, 20, stats_enabled); #endif inter_run<z_term_domain_t, z_interval_domain_t> (&*cg, false, 2, 2, 20, stats_enabled); inter_run<z_num_domain_t, z_num_domain_t> (&*cg, false, 2, 2, 20, stats_enabled); delete t1; delete t2; delete t3; delete t4; delete t5; return 0; }
32.582011
98
0.655083
DavidFarago
23f23405a1b5eb52cc77c99528980fa9a84b5abd
4,267
cc
C++
chats.cc
cadencorontzos/statsAndChats
aa402ce6215011f8d0ddf39d8426c6edf78705c9
[ "Apache-2.0" ]
null
null
null
chats.cc
cadencorontzos/statsAndChats
aa402ce6215011f8d0ddf39d8426c6edf78705c9
[ "Apache-2.0" ]
null
null
null
chats.cc
cadencorontzos/statsAndChats
aa402ce6215011f8d0ddf39d8426c6edf78705c9
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include "gram.hh" // next_word_in(line): // // Process the characters of the std::string object 'line', seeking // the next contiguous sequence of letters within that string. // // Once it has processed that next word, it modifies 'line' to exclude // the prefix of processed characters from it, and returns that next // word as a string. The word will be a string of lowercase alphabetic // characters. // // It returns the empty string once the line has been fully processed. // std::string next_word_in(std::string &line) { std::string word = ""; int i; for (i=0; i < line.size(); i++) { char c = line[i]; // Make letters lowercase. if ('A' <= c && c <= 'Z') { c = c+32; } // Include letters or contraction marks as part of a word. if (('a' <= c && c <= 'z') || c == '\'') { word += c; // If we hit a "stopper", emit it as a word. } else if (c == '.' || c == '!' || c == '?') { if (word.size() > 0) { line.erase(0,i); return word; } else { word += c; line.erase(0,1); return word; } // If we hit any non-letter, emit a word. } else { if (word.size() > 0) { line.erase(0,i); return word; } } } // End of the line, emit that ending word. line.erase(0,i); return word; } // train_chat(): // // Returns a new dictionary of word/bigram followers built using the // structure of the text from `std::cin`. // gram::dict* train_chat(void) { gram::dict *d = gram::build(9,2); //we give our hashtable a load factor of 2 std::string line; std::string w1 = "."; std::string w2 = next_word_in(line); std::string w = ""; // Read until the end of text entry. while (std::cin || line != "") { if (line == "") { std::getline(std::cin,line); } w = next_word_in(line); if (w != "") { gram::add(d,w1,w2,w); // Add a follower `w` for the bigram words `w1` and `w2`. gram::add(d,w1,w2); // Add a follower `w` for the word `w2`. w1 = w2; w2 = w; } } gram::add(d,w1,w2); // Add the last word as a follower. gram::add(d,w1,w2,"."); // Include the last word as preceding a stopper `.`. return d; } // chat(d, lineWidth, numLines): // // Using the text-trained word/bigram dictionary of followers, // generate a random text with `numLines`, where each line is // no longer than `lineWidth` characters. // void chat(gram::dict* d, int lineWidth, int numLines) { //varibles to keep track of line width and # of lines int currentLineWidth = 0; int currentNumLines = 0; //our two strings to build the trigrams with std::string oneStr = get(d, "."); std::string twoStr = get(d,".",oneStr); while(currentNumLines < numLines){ do{ currentLineWidth+=oneStr.length(); //if our oneStr is a stopper, we don't output a space before it //if we our one the last line with a stopper, we end the chat there for more fluidity if(oneStr == "." || oneStr== "!" || oneStr == ","){ std::cout << oneStr; if(currentNumLines == (numLines -1)){ std::cout <<std::endl; return; } } //otherwise, we just output the word with a space before it else{ std::cout << " " << oneStr; currentLineWidth++; } //we them make a new word from the previous two words std::string temp = twoStr; twoStr = get(d,oneStr,twoStr); oneStr = temp; }while(currentLineWidth+oneStr.length() < lineWidth); currentLineWidth = 0; if(currentNumLines < numLines-1){ std::cout << std::endl; } currentNumLines++; } //Just in case we did not reac a stopper on the last line, we put on so it looks more real std::cout << "."<<std::endl; } // main() // // Processes std::cin as a sequence of words, training a // random process based on its bigrams and trigrams, // as specified in a `gram::dict`. // // Generates a random text using that process' `gram::dict` // int main(int argc, char **argv) { // // Build a dictionary of word/bigram followers based on the text entered. std::cout << "READING text from STDIN. Hit ctrl-d when done entering text.\n"; gram::dict* d = train_chat(); chat(d,60,20); //reallocates the dict gram::destroy(d); }
26.018293
92
0.599719
cadencorontzos