blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
41905e4e5496c53926bd2adc343864c49b9bc0b4
767aed1b0bf8609dd22c713a3857c2044708ce70
/timer_class.cpp
6ec6fbb324f236f39e7ed4065f75a08bab593153
[]
no_license
wuaiu/boost
cff1dde9d8935854765ad10338beac8523381237
eed9a9386a1c2fe0c9588438744a549d206823c5
refs/heads/master
2021-01-01T20:14:54.264238
2017-07-31T12:14:05
2017-07-31T12:14:05
98,799,272
0
0
null
null
null
null
UTF-8
C++
false
false
438
cpp
#include<iostream> #include<boost/timer.hpp> using namespace std; using boost::timer; int main() { timer t; //输出最大时间跨度,时间精度,从构造实例开始经过的时间 cout << "max timespan:" << t.elapsed_max() / 3600 << "h" << endl; cout << "min timespan:" << t.elapsed_min() << "s" << endl; cout << "now time elapased :" << t.elapsed() << "s" << endl; //重置计时器 t.restart(); getchar(); return 0; }
[ "460906320@example.com" ]
460906320@example.com
64d29fbc127bed59a3ca8da829b09e49d2fd52ff
06f62d82a03116144ff4de343a99b579254aff56
/cpp/mindalpha/array_hash_map.h
ed331fbe15c06cd32fcab0074e6bc021514a97a3
[ "Apache-2.0" ]
permissive
zyclove/MindAlpha
10aa7fd6d47261347850fd5e19399686aaeb99c6
69f599f89ba82688d692accfd9283444a2de7403
refs/heads/main
2023-07-04T06:34:32.599825
2021-07-27T05:37:23
2021-07-27T05:37:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
19,875
h
// // Copyright 2021 Mobvista // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #pragma once #include <stdio.h> #include <stdint.h> #include <string.h> #include <iostream> #include <sstream> #include <vector> #include <stdexcept> #include <memory> #include <utility> #include <spdlog/spdlog.h> #include <mindalpha/hashtable_helpers.h> #include <mindalpha/memory_buffer.h> #include <mindalpha/map_file_header.h> // // ``array_hash_map.h`` defines class ``ArrayHashMap`` which avoids pointers when // implementing hashtable and is more memory efficient and serialization friendly // than ``std::unordered_map``. The hash algorithm is also improved by avoiding // modulo of general primes. // namespace mindalpha { template<typename TKey, typename TValue> class ArrayHashMap { public: ArrayHashMap() { static_assert(sizeof(TKey) <= sizeof(uint64_t), "invalid key type"); } explicit ArrayHashMap(int64_t value_count_per_key) : ArrayHashMap() { if (value_count_per_key < 0) throw std::runtime_error("value_count_per_key must be non-negative."); value_count_per_key_ = static_cast<uint64_t>(value_count_per_key); } ArrayHashMap(ArrayHashMap&& rhs) : keys_buffer_(std::move(rhs.keys_buffer_)) , values_buffer_(std::move(rhs.values_buffer_)) , next_buffer_(std::move(rhs.next_buffer_)) , first_buffer_(std::move(rhs.first_buffer_)) , key_count_(rhs.key_count_) , bucket_count_(rhs.bucket_count_) , value_count_(rhs.value_count_) , value_count_per_key_(rhs.value_count_per_key_) , keys_(rhs.keys_) , values_(rhs.values_) , next_(rhs.next_) , first_(rhs.first_) { rhs.key_count_ = 0; rhs.bucket_count_ = 0; rhs.value_count_ = 0; rhs.value_count_per_key_ = static_cast<uint64_t>(-1); rhs.keys_ = nullptr; rhs.values_ = nullptr; rhs.next_ = nullptr; rhs.first_ = nullptr; } ~ArrayHashMap() { key_count_ = 0; bucket_count_ = 0; value_count_ = 0; value_count_per_key_ = static_cast<uint64_t>(-1); keys_ = nullptr; values_ = nullptr; next_ = nullptr; first_ = nullptr; } void Swap(ArrayHashMap& other) { keys_buffer_.Swap(other.keys_buffer_); values_buffer_.Swap(other.values_buffer_); next_buffer_.Swap(other.next_buffer_); first_buffer_.Swap(other.first_buffer_); std::swap(key_count_, other.key_count_); std::swap(bucket_count_, other.bucket_count_); std::swap(value_count_, other.value_count_); std::swap(value_count_per_key_, other.value_count_per_key_); std::swap(keys_, other.keys_); std::swap(values_, other.values_); std::swap(next_, other.next_); std::swap(first_, other.first_); } const TKey* GetKeysArray() const { return keys_; } const TValue* GetValuesArray() const { return values_; } void Reserve(uint64_t size) { if (value_count_per_key_ == static_cast<uint64_t>(-1)) throw std::runtime_error("value_count_per_key is not set."); if (bucket_count_ >= size) return; Reallocate(size); } void Reallocate(uint64_t size) { if (value_count_per_key_ == static_cast<uint64_t>(-1)) throw std::runtime_error("value_count_per_key is not set."); if (key_count_ > size) return; if (size == 0) { Deallocate(); return; } const uint64_t bucket_count = HashtableHelpers::GetPowerBucketCount(size); const uint64_t limit = std::numeric_limits<uint32_t>::max(); if (bucket_count > limit) { std::ostringstream serr; serr << "store " << size << " keys "; serr << "requires " << bucket_count << " buckets, "; serr << "but at most " << limit << " are allowed."; throw std::runtime_error(serr.str()); } keys_buffer_.Reallocate(bucket_count * sizeof(TKey)); values_buffer_.Reallocate(bucket_count * value_count_per_key_ * sizeof(TValue)); next_buffer_.Reallocate(bucket_count * sizeof(uint32_t)); first_buffer_.Reallocate(bucket_count * sizeof(uint32_t)); bucket_count_ = bucket_count; keys_ = static_cast<TKey*>(keys_buffer_.GetPointer()); values_ = static_cast<TValue*>(values_buffer_.GetPointer()); next_ = static_cast<uint32_t*>(next_buffer_.GetPointer()); first_ = static_cast<uint32_t*>(first_buffer_.GetPointer()); BuildHashIndex(); } int64_t Find(TKey key) const { if (bucket_count_ == 0) return -1; const uint32_t nil = uint32_t(-1); const uint64_t bucket = GetBucket(key); uint32_t i = first_[bucket]; while (i != nil) { if (keys_[i] == key) return static_cast<int64_t>(i); i = next_[i]; } return -1; } int64_t FindOrInit(TKey key) { bool is_new; int64_t index; GetOrInit(key, is_new, index); return index; } const TValue* Get(TKey key) const { if (bucket_count_ == 0) return nullptr; if (value_count_per_key_ == static_cast<uint64_t>(-1)) throw std::runtime_error("value_count_per_key is not set."); const uint32_t nil = uint32_t(-1); const uint64_t bucket = get_bucket(key); uint32_t i = first_[bucket]; while (i != nil) { if (keys_[i] == key) return &values_[i * value_count_per_key_]; i = next_[i]; } return nullptr; } TValue* GetOrInit(TKey key, bool& is_new, int64_t& index) { if (value_count_per_key_ == static_cast<uint64_t>(-1)) throw std::runtime_error("value_count_per_key is not set."); const uint32_t nil = uint32_t(-1); if (bucket_count_ > 0) { const uint64_t b = GetBucket(key); uint32_t i = first_[b]; while (i != nil) { if (keys_[i] == key) { is_new = false; index = i; return &values_[i * value_count_per_key_]; } i = next_[i]; } } if (key_count_ == bucket_count_) EnsureCapacity(); const uint64_t bucket = GetBucket(key); index = static_cast<int64_t>(key_count_); keys_[index] = key; next_[index] = first_[bucket]; first_[bucket] = static_cast<uint32_t>(index); is_new = true; key_count_++; value_count_ += value_count_per_key_; return &values_[index * value_count_per_key_]; } TValue* GetOrInit(TKey key, bool& is_new) { int64_t index; return GetOrInit(key, is_new, index); } TValue* GetOrInit(TKey key) { bool is_new; return GetOrInit(key, is_new); } void Clear() { key_count_ = 0; value_count_ = 0; BuildHashIndex(); } void Deallocate() { keys_buffer_.Deallocate(); values_buffer_.Deallocate(); next_buffer_.Deallocate(); first_buffer_.Deallocate(); key_count_ = 0; bucket_count_ = 0; value_count_ = 0; keys_ = nullptr; values_ = nullptr; next_ = nullptr; first_ = nullptr; } template<typename Func> void Prune(Func pred) { if (value_count_per_key_ == static_cast<uint64_t>(-1)) throw std::runtime_error("value_count_per_key is not set."); uint64_t v = 0; for (uint64_t i = 0; i < key_count_; i++) { const TKey key = keys_[i]; const TValue* values = &values_[i * value_count_per_key_]; if (!pred(i, key, values, value_count_per_key_)) { if (v != i) { keys_[v] = key; memcpy(&values_[v * value_count_per_key_], values, value_count_per_key_ * sizeof(TValue)); } v++; } } if (v < key_count_) { key_count_ = v; value_count_ = v * value_count_per_key_; Reallocate(key_count_); } } void Dump(std::ostream& out = std::cerr, uint64_t count_limit = uint64_t(-1)) const { if (value_count_per_key_ == static_cast<uint64_t>(-1)) throw std::runtime_error("value_count_per_key is not set."); for (uint64_t i = 0; i < key_count_; i++) { if (i >= count_limit) break; TKey key = keys_[i];; const TValue* values = &values_[i * value_count_per_key_]; out << key << ": ["; for (uint64_t j = 0; j < value_count_per_key_; j++) out << (j ? ", " : "") << as_number(values[j]); out << "]\n"; } } uint64_t GetHashCode() const { uint64_t hash = 0; for (uint64_t key: *this) { uint64_t c = key; const TValue* const values = Get(key); const uint8_t* const bytes = reinterpret_cast<const uint8_t*>(values); const uint64_t num_bytes = value_count_per_key_ * sizeof(TValue); for (uint64_t i = 0; i < num_bytes; i++) c = c * 31 + bytes[i]; hash ^= c; } return hash; } class iterator { public: iterator(const ArrayHashMap<TKey, TValue>* map, uint64_t index) : map_(map), index_(index) { } iterator& operator++() { if (index_ < map_->key_count_) index_++; return *this; } TKey operator*() const { if (index_ < map_->key_count_) return map_->keys_[index_]; else return TKey(-1); } bool operator==(const iterator& rhs) const { return index_ == rhs.index_ && map_ == rhs.map_; } bool operator!=(const iterator& rhs) const { return !(*this == rhs); } private: const ArrayHashMap<TKey, TValue>* map_; uint64_t index_; }; iterator begin() const { return iterator(this, 0); } iterator end() const { return iterator(this, key_count_); } uint64_t size() const { return key_count_; } template<typename Func> void Each(Func action) { if (value_count_per_key_ == static_cast<uint64_t>(-1)) throw std::runtime_error("value_count_per_key is not set."); for (uint64_t i = 0; i < key_count_; i++) { const TKey key = keys_[i]; const TValue* values = &values_[i * value_count_per_key_]; action(i, key, values, value_count_per_key_); } } template<typename Func> void Serialize(const std::string& path, Func write, uint64_t value_count_per_key = static_cast<uint64_t>(-1)) { if (value_count_per_key_ == static_cast<uint64_t>(-1)) throw std::runtime_error("value_count_per_key is not set."); if (value_count_per_key == static_cast<uint64_t>(-1)) value_count_per_key = value_count_per_key_; if (value_count_per_key > value_count_per_key_) throw std::runtime_error("value_count_per_key exceeds that in the map."); std::string hint; hint.append("Fail to serialize ArrayHashMap to \""); hint.append(path); hint.append("\"; "); MapFileHeader header; header.FillBasicFields(); header.key_type = static_cast<uint64_t>(DataTypeToCode<TKey>::value); header.value_type = static_cast<uint64_t>(DataTypeToCode<TValue>::value); header.key_count = key_count_; header.bucket_count = bucket_count_; header.value_count = value_count_per_key * key_count_; header.value_count_per_key = value_count_per_key; write(static_cast<const void*>(&header), sizeof(header)); write(static_cast<const void*>(keys_), key_count_ * sizeof(TKey)); if (value_count_per_key == value_count_per_key_) write(static_cast<const void*>(values_), value_count_ * sizeof(TValue)); else { for (uint64_t i = 0; i < key_count_; i++) { const TValue* values = &values_[i * value_count_per_key_]; write(static_cast<const void*>(values), value_count_per_key * sizeof(TValue)); } } write(static_cast<const void*>(next_), key_count_ * sizeof(uint32_t)); write(static_cast<const void*>(first_), bucket_count_ * sizeof(uint32_t)); } template<typename Func> void Deserialize(const std::string& path, Func read) { std::string hint; hint.append("Fail to deserialize ArrayHashMap from \""); hint.append(path); hint.append("\"; "); MapFileHeader header; read(static_cast<void*>(&header), sizeof(header), hint, "map file header"); header.Validate(hint); uint64_t value_count = header.value_count; uint64_t value_count_per_key = header.value_count_per_key; if (header.key_type != static_cast<uint64_t>(DataTypeToCode<TKey>::value)) { const DataType key_type_1 = static_cast<DataType>(header.key_type); const DataType key_type_2 = DataTypeToCode<TKey>::value; const size_t key_size_1 = DataTypeToSize(key_type_1); const size_t key_size_2 = DataTypeToSize(key_type_2); if (key_size_1 != key_size_2) { std::ostringstream serr; serr << "key types mismatch; "; serr << "expect '" << DataTypeToString(DataTypeToCode<TKey>::value) << "', "; serr << "found '" << DataTypeToString(static_cast<DataType>(header.key_type)) << "'."; throw std::runtime_error(serr.str()); } } if (header.value_type != static_cast<uint64_t>(DataTypeToCode<TValue>::value)) { const DataType value_type_1 = static_cast<DataType>(header.value_type); const DataType value_type_2 = DataTypeToCode<TValue>::value; const size_t value_size_1 = DataTypeToSize(value_type_1); const size_t value_size_2 = DataTypeToSize(value_type_2); if (value_size_1 != value_size_2) { if (value_count_per_key * value_size_1 % value_size_2 == 0) { value_count = value_count * value_size_1 / value_size_2; value_count_per_key = value_count_per_key * value_size_1 / value_size_2; } else { std::ostringstream serr; serr << "value types mismatch; "; serr << "expect '" << DataTypeToString(DataTypeToCode<TValue>::value) << "', "; serr << "found '" << DataTypeToString(static_cast<DataType>(header.value_type)) << "'. "; serr << "value_count_per_key = " << value_count_per_key; throw std::runtime_error(serr.str()); } } } value_count_per_key_ = value_count_per_key; Clear(); Reserve(header.bucket_count); read(static_cast<void*>(keys_), header.key_count * sizeof(TKey), hint, "keys array"); read(static_cast<void*>(values_), value_count * sizeof(TValue), hint, "values array"); read(static_cast<void*>(next_), header.key_count * sizeof(uint32_t), hint, "next array"); read(static_cast<void*>(first_), header.bucket_count * sizeof(uint32_t), hint, "first array"); key_count_ = header.key_count; bucket_count_ = header.bucket_count; value_count_ = value_count; } void SerializeTo(const std::string& path, uint64_t value_count_per_key = static_cast<uint64_t>(-1)) { FILE* fout = fopen(path.c_str(), "wb"); if (fout == NULL) { std::ostringstream serr; serr << "can not open file \"" << path << "\" for map serializing; "; serr << strerror(errno); throw std::runtime_error(serr.str()); } std::unique_ptr<FILE, decltype(&fclose)> fout_guard(fout, &fclose); Serialize(path, [fout](const void* ptr, size_t size) { fwrite(ptr, 1, size, fout); }, value_count_per_key); } void DeserializeFrom(const std::string& path) { std::string hint; hint.append("Fail to deserialize ArrayHashMap from \""); hint.append(path); hint.append("\"; "); FILE* fin = fopen(path.c_str(), "rb"); if (fin == NULL) { std::ostringstream serr; serr << hint; serr << "can not open file. "; serr << strerror(errno); throw std::runtime_error(serr.str()); } uint64_t offset = 0; std::unique_ptr<FILE, decltype(&fclose)> fin_guard(fin, &fclose); Deserialize(path, [fin, &offset](void* ptr, size_t size, const std::string& hint, const std::string& what) { const size_t nread = fread(ptr, 1, size, fin); if (nread != size) { std::ostringstream serr; serr << hint; serr << "incomplete " << what << ", "; serr << size << " bytes expected, "; serr << "but only " << nread << " are read successfully. "; serr << "offset = " << offset << " (0x" << std::hex << offset << ")"; throw std::runtime_error(serr.str()); } offset += nread; }); } private: uint64_t GetBucket(TKey key) const { return HashtableHelpers::FastModulo(static_cast<uint64_t>(key)) & (bucket_count_ - 1); } void BuildHashIndex() { memset(first_, -1, bucket_count_ * sizeof(uint32_t)); for (uint64_t i = 0; i < key_count_; i++) { const TKey key = keys_[i]; const uint64_t bucket = GetBucket(key); next_[i] = first_[bucket]; first_[bucket] = static_cast<uint32_t>(i); } } void EnsureCapacity() { uint64_t min_capacity = key_count_ * 2; if (min_capacity == 0) min_capacity = 1000; uint64_t size = HashtableHelpers::GetPowerBucketCount(min_capacity); uint64_t capacity = size; if (capacity < min_capacity) capacity = min_capacity; Reserve(capacity); } MemoryBuffer keys_buffer_; MemoryBuffer values_buffer_; MemoryBuffer next_buffer_; MemoryBuffer first_buffer_; uint64_t key_count_ = 0; uint64_t bucket_count_ = 0; uint64_t value_count_ = 0; uint64_t value_count_per_key_ = static_cast<uint64_t>(-1); TKey* keys_ = nullptr; TValue* values_ = nullptr; uint32_t* next_ = nullptr; uint32_t* first_ = nullptr; }; }
[ "huaidong.xiong@mobvista.com" ]
huaidong.xiong@mobvista.com
91ed4bb7331eb9b054f24b682e5ba43e1bf0a770
3341f663e286a733f8a8335464037384f6e4bf94
/content/browser/renderer_host/input/mouse_latency_browsertest.cc
cfc239f3fd611e1fd262967e9fa0edaf7307299e
[ "BSD-3-Clause" ]
permissive
ZZbitmap/chromium
f18b462aa22a574f3850fe87ce0b2a614c6ffe06
bc796eea45503c990ab65173b6bcb469811aaaf3
refs/heads/master
2022-11-15T04:05:01.082328
2020-06-08T13:55:53
2020-06-08T13:55:53
270,664,211
0
0
BSD-3-Clause
2020-06-08T13:55:55
2020-06-08T12:41:58
null
UTF-8
C++
false
false
13,517
cc
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <memory> #include <string> #include <utility> #include <vector> #include "base/bind.h" #include "base/json/json_reader.h" #include "base/run_loop.h" #include "base/test/test_timeouts.h" #include "build/build_config.h" #include "content/browser/renderer_host/input/synthetic_gesture.h" #include "content/browser/renderer_host/input/synthetic_gesture_controller.h" #include "content/browser/renderer_host/input/synthetic_gesture_target.h" #include "content/browser/renderer_host/input/synthetic_smooth_move_gesture.h" #include "content/browser/renderer_host/input/synthetic_tap_gesture.h" #include "content/browser/renderer_host/render_widget_host_factory.h" #include "content/browser/renderer_host/render_widget_host_impl.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/common/input/synthetic_gesture_params.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/tracing_controller.h" #include "content/public/test/browser_test.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/content_browser_test.h" #include "content/public/test/content_browser_test_utils.h" #include "content/shell/browser/shell.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "testing/gmock/include/gmock/gmock.h" namespace { const char kDataURL[] = "data:text/html;charset=utf-8," "<!DOCTYPE html>" "<html>" "<head>" "<title>Mouse event trace events reported.</title>" "<script>" " let i=0;" " document.addEventListener('mousemove', () => {" " var end = performance.now() + 20;" " while(performance.now() < end);" " document.body.style.backgroundColor = 'rgb(' + (i++) + ',0,0)'" " });" " document.addEventListener('wheel', (e) => {" " if (!e.cancelable)" " return;" " var end = performance.now() + 50;" " while(performance.now() < end);" " });" "</script>" "<style>" "body {" " height:3000px;" // Prevent text selection logic from triggering, as it makes the test flaky. " user-select: none;" "}" "</style>" "</head>" "<body>" "</body>" "</html>"; } // namespace namespace content { // This class listens for terminated latency info events. It listens // for both the mouse event ack and the gpu swap buffers event since // the event could occur in either. class TracingRenderWidgetHost : public RenderWidgetHostImpl { public: TracingRenderWidgetHost(RenderWidgetHostDelegate* delegate, RenderProcessHost* process, int32_t routing_id, mojo::PendingRemote<mojom::Widget> widget, bool hidden) : RenderWidgetHostImpl(delegate, process, routing_id, std::move(widget), hidden, std::make_unique<FrameTokenMessageQueue>()) { } void OnMouseEventAck( const MouseEventWithLatencyInfo& event, blink::mojom::InputEventResultSource ack_source, blink::mojom::InputEventResultState ack_result) override { RenderWidgetHostImpl::OnMouseEventAck(event, ack_source, ack_result); } private: }; class TracingRenderWidgetHostFactory : public RenderWidgetHostFactory { public: TracingRenderWidgetHostFactory() { RenderWidgetHostFactory::RegisterFactory(this); } ~TracingRenderWidgetHostFactory() override { RenderWidgetHostFactory::UnregisterFactory(); } std::unique_ptr<RenderWidgetHostImpl> CreateRenderWidgetHost( RenderWidgetHostDelegate* delegate, RenderProcessHost* process, int32_t routing_id, mojo::PendingRemote<mojom::Widget> widget_interface, bool hidden) override { return std::make_unique<TracingRenderWidgetHost>( delegate, process, routing_id, std::move(widget_interface), hidden); } private: DISALLOW_COPY_AND_ASSIGN(TracingRenderWidgetHostFactory); }; class MouseLatencyBrowserTest : public ContentBrowserTest { public: MouseLatencyBrowserTest() {} ~MouseLatencyBrowserTest() override {} RenderWidgetHostImpl* GetWidgetHost() { return RenderWidgetHostImpl::From( shell()->web_contents()->GetRenderViewHost()->GetWidget()); } void OnSyntheticGestureCompleted(SyntheticGesture::Result result) { EXPECT_EQ(SyntheticGesture::GESTURE_FINISHED, result); runner_->Quit(); } void OnTraceDataCollected(std::unique_ptr<std::string> trace_data_string) { std::unique_ptr<base::Value> trace_data = base::JSONReader::ReadDeprecated(*trace_data_string); ASSERT_TRUE(trace_data); trace_data_ = trace_data->Clone(); runner_->Quit(); } protected: void LoadURL() { const GURL data_url(kDataURL); EXPECT_TRUE(NavigateToURL(shell(), data_url)); RenderWidgetHostImpl* host = GetWidgetHost(); host->GetView()->SetSize(gfx::Size(400, 400)); } // Generate mouse events for a synthetic click at |point|. void DoSyncClick(const gfx::PointF& position) { SyntheticTapGestureParams params; params.gesture_source_type = SyntheticGestureParams::MOUSE_INPUT; params.position = position; params.duration_ms = 100; std::unique_ptr<SyntheticTapGesture> gesture( new SyntheticTapGesture(params)); GetWidgetHost()->QueueSyntheticGesture( std::move(gesture), base::BindOnce(&MouseLatencyBrowserTest::OnSyntheticGestureCompleted, base::Unretained(this))); // Runs until we get the OnSyntheticGestureCompleted callback runner_ = std::make_unique<base::RunLoop>(); runner_->Run(); } // Generate mouse events drag from |position|. void DoSyncCoalescedMoves(const gfx::PointF position, const gfx::Vector2dF& delta1, const gfx::Vector2dF& delta2) { SyntheticSmoothMoveGestureParams params; params.input_type = SyntheticSmoothMoveGestureParams::MOUSE_DRAG_INPUT; params.start_point.SetPoint(position.x(), position.y()); params.distances.push_back(delta1); params.distances.push_back(delta2); std::unique_ptr<SyntheticSmoothMoveGesture> gesture( new SyntheticSmoothMoveGesture(params)); GetWidgetHost()->QueueSyntheticGesture( std::move(gesture), base::BindOnce(&MouseLatencyBrowserTest::OnSyntheticGestureCompleted, base::Unretained(this))); // Runs until we get the OnSyntheticGestureCompleted callback runner_ = std::make_unique<base::RunLoop>(); runner_->Run(); } // Generate mouse wheel scroll. void DoSyncCoalescedMouseWheel(const gfx::PointF position, const gfx::Vector2dF& delta) { SyntheticSmoothScrollGestureParams params; params.gesture_source_type = SyntheticGestureParams::MOUSE_INPUT; params.anchor = position; params.distances.push_back(delta); GetWidgetHost()->QueueSyntheticGesture( SyntheticGesture::Create(params), base::BindOnce(&MouseLatencyBrowserTest::OnSyntheticGestureCompleted, base::Unretained(this))); // Runs until we get the OnSyntheticGestureCompleted callback runner_ = std::make_unique<base::RunLoop>(); runner_->Run(); } void StartTracing() { base::trace_event::TraceConfig trace_config( "{" "\"enable_argument_filter\":false," "\"enable_systrace\":false," "\"included_categories\":[" "\"latencyInfo\"" "]," "\"record_mode\":\"record-until-full\"" "}"); base::RunLoop run_loop; ASSERT_TRUE(TracingController::GetInstance()->StartTracing( trace_config, run_loop.QuitClosure())); run_loop.Run(); } const base::Value& StopTracing() { bool success = TracingController::GetInstance()->StopTracing( TracingController::CreateStringEndpoint( base::BindOnce(&MouseLatencyBrowserTest::OnTraceDataCollected, base::Unretained(this)))); EXPECT_TRUE(success); // Runs until we get the OnTraceDataCollected callback, which populates // trace_data_; runner_ = std::make_unique<base::RunLoop>(); runner_->Run(); return trace_data_; } std::string ShowTraceEventsWithId(const std::string& id_to_show, const base::ListValue* traceEvents) { std::stringstream stream; for (size_t i = 0; i < traceEvents->GetSize(); ++i) { const base::DictionaryValue* traceEvent; if (!traceEvents->GetDictionary(i, &traceEvent)) continue; std::string id; if (!traceEvent->GetString("id", &id)) continue; if (id == id_to_show) stream << *traceEvent; } return stream.str(); } void AssertTraceIdsBeginAndEnd(const base::Value& trace_data, const std::string& trace_event_name) { const base::DictionaryValue* trace_data_dict; ASSERT_TRUE(trace_data.GetAsDictionary(&trace_data_dict)); const base::ListValue* traceEvents; ASSERT_TRUE(trace_data_dict->GetList("traceEvents", &traceEvents)); std::map<std::string, int> trace_ids; for (size_t i = 0; i < traceEvents->GetSize(); ++i) { const base::DictionaryValue* traceEvent; ASSERT_TRUE(traceEvents->GetDictionary(i, &traceEvent)); std::string name; ASSERT_TRUE(traceEvent->GetString("name", &name)); if (name != trace_event_name) continue; std::string id; if (traceEvent->GetString("id", &id)) ++trace_ids[id]; } for (auto i : trace_ids) { // Each trace id should show up once for the begin, and once for the end. EXPECT_EQ(2, i.second) << ShowTraceEventsWithId(i.first, traceEvents); } } private: std::unique_ptr<base::RunLoop> runner_; base::Value trace_data_; TracingRenderWidgetHostFactory widget_factory_; DISALLOW_COPY_AND_ASSIGN(MouseLatencyBrowserTest); }; // Ensures that LatencyInfo async slices are reported correctly for MouseUp and // MouseDown events in the case where no swap is generated. // Disabled on Android because we don't support synthetic mouse input on // Android (crbug.com/723618). // Disabled on due to flakiness (https://crbug.com/800303, https://crbug.com/815363). IN_PROC_BROWSER_TEST_F(MouseLatencyBrowserTest, DISABLED_MouseDownAndUpRecordedWithoutSwap) { LoadURL(); auto filter = std::make_unique<InputMsgWatcher>( GetWidgetHost(), blink::WebInputEvent::Type::kMouseUp); StartTracing(); DoSyncClick(gfx::PointF(100, 100)); EXPECT_EQ(blink::mojom::InputEventResultState::kNotConsumed, filter->GetAckStateWaitIfNecessary()); const base::Value& trace_data = StopTracing(); const base::DictionaryValue* trace_data_dict; trace_data.GetAsDictionary(&trace_data_dict); ASSERT_TRUE(trace_data.GetAsDictionary(&trace_data_dict)); const base::ListValue* traceEvents; ASSERT_TRUE(trace_data_dict->GetList("traceEvents", &traceEvents)); std::vector<std::string> trace_event_names; for (size_t i = 0; i < traceEvents->GetSize(); ++i) { const base::DictionaryValue* traceEvent; ASSERT_TRUE(traceEvents->GetDictionary(i, &traceEvent)); std::string name; ASSERT_TRUE(traceEvent->GetString("name", &name)); if (name != "InputLatency::MouseUp" && name != "InputLatency::MouseDown") continue; trace_event_names.push_back(name); } // We see two events per async slice, a begin and an end. EXPECT_THAT(trace_event_names, testing::UnorderedElementsAre( "InputLatency::MouseDown", "InputLatency::MouseDown", "InputLatency::MouseUp", "InputLatency::MouseUp")); } // Ensures that LatencyInfo async slices are reported correctly for MouseMove // events in the case where events are coalesced. (crbug.com/771165). // Disabled on Android because we don't support synthetic mouse input on Android // (crbug.com/723618). // http://crbug.com/801629 : Flaky on multiple platforms. IN_PROC_BROWSER_TEST_F(MouseLatencyBrowserTest, DISABLED_CoalescedMouseMovesCorrectlyTerminated) { LoadURL(); StartTracing(); DoSyncCoalescedMoves(gfx::PointF(100, 100), gfx::Vector2dF(150, 150), gfx::Vector2dF(250, 250)); // The following wait is the upper bound for gpu swap completed callback. It // is two frames to account for double buffering. MainThreadFrameObserver observer(RenderWidgetHostImpl::From( shell()->web_contents()->GetRenderViewHost()->GetWidget())); observer.Wait(); observer.Wait(); const base::Value& trace_data = StopTracing(); AssertTraceIdsBeginAndEnd(trace_data, "InputLatency::MouseMove"); } // TODO(https://crbug.com/923627): This is flaky on multiple platforms. IN_PROC_BROWSER_TEST_F(MouseLatencyBrowserTest, DISABLED_CoalescedMouseWheelsCorrectlyTerminated) { LoadURL(); StartTracing(); DoSyncCoalescedMouseWheel(gfx::PointF(100, 100), gfx::Vector2dF(0, -100)); const base::Value& trace_data = StopTracing(); AssertTraceIdsBeginAndEnd(trace_data, "InputLatency::MouseWheel"); } } // namespace content
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
92ff9b29b3914885497a9c3cd9d6a9f78ef47034
9a01e08109e4ea23f2201f98c6ad054dbcd3be15
/src/cld/Frontend/Compiler/SemanticAnalysisExpressions.cpp
1540aa68b6a0f0551c34629394eb393f2088517b
[ "MIT" ]
permissive
zero9178/cld
ebee9af3162ad6e0e2d61eb2889dd019e3e67270
2899ade8045074c5ee939253d2d7f8067c46e72d
refs/heads/master
2023-05-03T03:21:44.662744
2021-05-09T21:01:09
2021-05-09T21:01:09
171,492,773
20
2
null
null
null
null
UTF-8
C++
false
false
184,093
cpp
#include "SemanticAnalysis.hpp" #include <cld/Support/Expected.hpp> #include <cld/Support/Util.hpp> #include "ConstValue.hpp" #include "ErrorMessages.hpp" #include "SourceInterface.hpp" cld::IntrVarPtr<cld::Semantics::ExpressionBase> cld::Semantics::SemanticAnalysis::visit(const Syntax::Expression& node) { if (node.getOptionalAssignmentExpressions().empty()) { return visit(node.getAssignmentExpression()); } std::vector<std::pair<IntrVarPtr<ExpressionBase>, Lexer::CTokenIterator>> expressions; expressions.emplace_back(visit(node.getAssignmentExpression()), node.getOptionalAssignmentExpressions().front().first); auto ref = tcb::span(node.getOptionalAssignmentExpressions().data(), node.getOptionalAssignmentExpressions().size() - 1); for (const auto* iter = ref.begin(); iter != ref.end(); iter++) { auto& [token, exp] = *iter; expressions.emplace_back(visit(exp), (iter + 1)->first); } auto last = lvalueConversion(visit(node.getOptionalAssignmentExpressions().back().second)); IntrVarValue type = last->getType(); return std::make_unique<CommaExpression>(std::move(type), std::move(expressions), std::move(last)); } bool cld::Semantics::SemanticAnalysis::isModifiableLValue(const cld::Semantics::ExpressionBase& expression) const { if (expression.getValueCategory() != ValueCategory::Lvalue) { return false; } return !isConst(expression.getType()); } bool cld::Semantics::SemanticAnalysis::isConst(const Type& type) const { if (type.isConst()) { return true; } if (!isRecord(type) || !isCompleteType(type)) { return false; } auto& fields = getFields(type); for (auto& iter : fields) { if (isConst(*iter.second.type)) { return true; } } return false; } bool cld::Semantics::SemanticAnalysis::doAssignmentLikeConstraints( const Type& lhsType, IntrVarPtr<ExpressionBase>& rhsValue, cld::function_ref<void()> mustBeArithmetic, cld::function_ref<void()> mustBeArithmeticOrPointer, cld::function_ref<void()> incompleteType, cld::function_ref<void()> incompatibleTypes, cld::function_ref<void()> notICE, cld::function_ref<void(const ConstValue&)> notNull, cld::function_ref<void()> mustBePointer, cld::function_ref<void()> voidFunctionPointers) { if (isArithmetic(lhsType)) { if (!isBool(lhsType)) { if (!rhsValue->getType().isUndefined() && !isArithmetic(rhsValue->getType())) { mustBeArithmetic(); return false; } } else if (!rhsValue->getType().isUndefined() && !isScalar(rhsValue->getType())) { mustBeArithmeticOrPointer(); return false; } if (lhsType != rhsValue->getType()) { rhsValue = std::make_unique<Conversion>(*removeQualifiers(lhsType), Conversion::Implicit, std::move(rhsValue)); } return true; } if (isRecord(lhsType)) { if (!isCompleteType(lhsType)) { incompleteType(); return false; } if (!rhsValue->getType().isUndefined() && !typesAreCompatible(*removeQualifiers(lhsType), *removeQualifiers(rhsValue->getType()))) { incompatibleTypes(); return false; } return true; } if (lhsType.is<VectorType>()) { if (!rhsValue->getType().isUndefined() && !typesAreCompatible(*removeQualifiers(lhsType), *removeQualifiers(rhsValue->getType()))) { incompatibleTypes(); return false; } return true; } if (!lhsType.is<PointerType>()) { return true; } if (auto npc = checkPointerOperandsForNPC(*rhsValue, lhsType); !npc || *npc != NPCCheck::WrongType) { if (!npc) { notNull(npc.error()); return false; } switch (*npc) { case NPCCheck::Success: rhsValue = std::make_unique<Conversion>(removeQualifiers(lhsType), Conversion::Implicit, std::move(rhsValue)); return true; case NPCCheck::NotConstExpr: notICE(); return false; default: CLD_UNREACHABLE; } } if (!rhsValue->getType().isUndefined() && !rhsValue->getType().is<PointerType>()) { mustBePointer(); return false; } if (rhsValue->getType().isUndefined()) { return true; } auto& lhsElementType = getPointerElementType(lhsType); auto& rhsElementType = getPointerElementType(rhsValue->getType()); if (isVoid(lhsElementType) != isVoid(rhsElementType)) { bool leftIsVoid = isVoid(lhsElementType); auto& nonVoidType = leftIsVoid ? rhsElementType : lhsElementType; if (nonVoidType.is<FunctionType>()) { voidFunctionPointers(); return false; } if ((!lhsElementType.isConst() && rhsElementType.isConst()) || (!lhsElementType.isVolatile() && rhsElementType.isVolatile())) { incompatibleTypes(); return false; } if (removeQualifiers(lhsElementType) != removeQualifiers(rhsElementType)) { rhsValue = std::make_unique<Conversion>(removeQualifiers(lhsType), Conversion::Implicit, std::move(rhsValue)); } return true; } if (!typesAreCompatible(removeQualifiers(lhsElementType), removeQualifiers(rhsElementType))) { incompatibleTypes(); return false; } if ((!lhsElementType.isConst() && rhsElementType.isConst()) || (!lhsElementType.isVolatile() && rhsElementType.isVolatile())) { incompatibleTypes(); return false; } if (removeQualifiers(lhsElementType) != removeQualifiers(rhsElementType)) { rhsValue = std::make_unique<Conversion>(removeQualifiers(lhsType), Conversion::Implicit, std::move(rhsValue)); } return true; } void cld::Semantics::SemanticAnalysis::checkVectorCompoundAssign(const IntrVarPtr<ExpressionBase>& lhs, const Type& lhsType, Lexer::CTokenIterator token, const IntrVarPtr<ExpressionBase>& rhs) { if (lhsType.is<VectorType>() && rhs->getType().is<VectorType>()) { if (rhs->getType() != lhsType) { log(Errors::Semantics::TYPE_OF_VECTOR_OPERANDS_OF_BINARY_OPERATOR_N_MUST_MATCH.args( *token, m_sourceInterface, *token, *lhs, *rhs)); } } else { log(Errors::Semantics::CONVERSION_OF_SCALAR_IN_VECTOR_OPERATION_COULD_CAUSE_TRUNCATION.args( *token, m_sourceInterface, *lhs, *rhs)); } if (!lhs->getType().is<VectorType>() && lhsType.is<VectorType>()) { log(Errors::Semantics::CANNOT_ASSIGN_INCOMPATIBLE_TYPES.args(*token, m_sourceInterface, *lhs, *token, *rhs)); } } cld::IntrVarPtr<cld::Semantics::ExpressionBase> cld::Semantics::SemanticAnalysis::visit(const Syntax::AssignmentExpression& node) { if (node.getOptionalConditionalExpressions().empty()) { return visit(node.getConditionalExpression()); } auto ref = tcb::span(node.getOptionalConditionalExpressions()); auto rhsValue = lvalueConversion(visit(ref.back().conditionalExpression)); for (auto iter = ref.rbegin(); iter != ref.rend(); iter++) { auto& [kind, token, rhs] = *iter; auto lhsValue = iter + 1 != ref.rend() ? visit((iter + 1)->conditionalExpression) : visit(node.getConditionalExpression()); if (!lhsValue->isUndefined() && !isModifiableLValue(*lhsValue)) { log(Errors::Semantics::LEFT_OPERAND_OF_OPERATOR_N_MUST_NOT_BE_A_TEMPORARY_OR_CONST.args( *lhsValue, m_sourceInterface, *token, *lhsValue)); } auto resultType = removeQualifiers(lhsValue->getType()); IntrVarValue lhsType = lhsValue->getType(); switch (kind) { case Syntax::AssignmentExpression::NoOperator: { if (isArray(lhsValue->getType())) { log(Errors::Semantics::CANNOT_ASSIGN_TO_ARRAY_TYPE_N.args(*lhsValue, m_sourceInterface, *lhsValue, *token)); } doAssignmentLikeConstraints( lhsValue->getType(), rhsValue, [&, token = token] { log(Errors::Semantics::EXPECTED_RIGHT_OPERAND_OF_OPERATOR_N_TO_BE_AN_ARITHMETIC_TYPE.args( *rhsValue, m_sourceInterface, *token, *rhsValue)); }, [&, token = token] { log(Errors::Semantics::EXPECTED_RIGHT_OPERAND_OF_OPERATOR_N_TO_BE_AN_ARITHMETIC_OR_POINTER_TYPE .args(*rhsValue, m_sourceInterface, *token, *rhsValue)); }, [&, token = token] { log(Errors::Semantics::CANNOT_ASSIGN_TO_INCOMPLETE_TYPE_N.args(*lhsValue, m_sourceInterface, *lhsValue, *token)); }, [&, token = token] { log(Errors::Semantics::CANNOT_ASSIGN_INCOMPATIBLE_TYPES.args(*lhsValue, m_sourceInterface, *lhsValue, *token, *rhsValue)); }, [&, token = token] { log(Errors::Semantics::EXPECTED_RIGHT_OPERAND_OF_OPERATOR_N_TO_BE_NULL_2.args( *rhsValue, m_sourceInterface, *token, *rhsValue)); }, [&, token = token](const ConstValue& constant) { log(Errors::Semantics::EXPECTED_RIGHT_OPERAND_OF_OPERATOR_N_TO_BE_NULL.args( *rhsValue, m_sourceInterface, *token, *rhsValue, constant)); }, [&, token = token] { log(Errors::Semantics::EXPECTED_RIGHT_OPERAND_OF_OPERATOR_N_TO_BE_A_POINTER_TYPE.args( *rhsValue, m_sourceInterface, *token, *rhsValue)); }, [&, token = token] { if (isVoid(getPointerElementType(lhsValue->getType()))) { log(Errors::Semantics::CANNOT_ASSIGN_FUNCTION_POINTER_TO_VOID_POINTER.args( *lhsValue, m_sourceInterface, *lhsValue, *token, *rhsValue)); } else { log(Errors::Semantics::CANNOT_ASSIGN_VOID_POINTER_TO_FUNCTION_POINTER.args( *lhsValue, m_sourceInterface, *lhsValue, *token, *rhsValue)); } }); break; } case Syntax::AssignmentExpression::PlusAssign: case Syntax::AssignmentExpression::MinusAssign: { if (!lhsValue->isUndefined() && !isScalar(lhsValue->getType()) && !lhsValue->getType().is<VectorType>()) { log(Errors::Semantics::LEFT_OPERAND_OF_OPERATOR_N_MUST_BE_AN_ARITHMETIC_OR_POINTER_TYPE.args( *lhsValue, m_sourceInterface, *token, *lhsValue)); } if (lhsValue->getType().is<PointerType>()) { auto& elementType = getPointerElementType(lhsValue->getType()); if (elementType.is<FunctionType>()) { log(Errors::Semantics::POINTER_TO_FUNCTION_TYPE_NOT_ALLOWED_IN_POINTER_ARITHMETIC.args( *lhsValue, m_sourceInterface, *lhsValue)); } else if (!isCompleteType(elementType)) { log(Errors::Semantics::INCOMPLETE_TYPE_N_USED_IN_POINTER_ARITHMETIC.args( *lhsValue, m_sourceInterface, elementType, *lhsValue, lhsValue->getType())); } if (!rhsValue->getType().isUndefined() && !isInteger(rhsValue->getType())) { log(Errors::Semantics::EXPECTED_RIGHT_OPERAND_OF_OPERATOR_N_TO_BE_AN_INTEGER_TYPE.args( *rhsValue, m_sourceInterface, *token, *rhsValue)); } } else if (isArithmetic(lhsValue->getType())) { if (!rhsValue->getType().isUndefined() && !isArithmetic(rhsValue->getType())) { log(Errors::Semantics::EXPECTED_RIGHT_OPERAND_OF_OPERATOR_N_TO_BE_AN_ARITHMETIC_TYPE.args( *rhsValue, m_sourceInterface, *token, *rhsValue)); } else if (isArithmetic(rhsValue->getType())) { arithmeticConversion(&lhsType, rhsValue); } } else if (lhsValue->getType().is<VectorType>()) { arithmeticConversion(&lhsType, rhsValue); checkVectorCompoundAssign(lhsValue, lhsType, token, rhsValue); } break; } // Doing a simple check is redundant in compound assignments. Either we had a diagnostic saying that at // least one operand does not fit the constraints and we don't want further noise or // they're both arithmetic types and we already know they can only be compatible case Syntax::AssignmentExpression::DivideAssign: case Syntax::AssignmentExpression::MultiplyAssign: { arithmeticConversion(&lhsType, rhsValue); if (!lhsType->isUndefined() && !isArithmetic(lhsType) && !lhsType->is<VectorType>()) { log(Errors::Semantics::LEFT_OPERAND_OF_OPERATOR_N_MUST_BE_AN_ARITHMETIC_TYPE.args( *lhsValue, m_sourceInterface, *token, *lhsValue)); } if (!rhsValue->getType().isUndefined() && !isArithmetic(rhsValue->getType()) && !rhsValue->getType().is<VectorType>()) { log(Errors::Semantics::RIGHT_OPERAND_OF_OPERATOR_N_MUST_BE_AN_ARITHMETIC_TYPE.args( *rhsValue, m_sourceInterface, *token, *rhsValue)); } if (lhsType->is<VectorType>() || rhsValue->getType().is<VectorType>()) { checkVectorCompoundAssign(lhsValue, lhsType, token, rhsValue); } break; } case Syntax::AssignmentExpression::BitAndAssign: case Syntax::AssignmentExpression::BitOrAssign: case Syntax::AssignmentExpression::BitXorAssign: case Syntax::AssignmentExpression::ModuloAssign: { arithmeticConversion(&lhsType, rhsValue); if (!lhsType->isUndefined() && !isInteger(lhsType) && (!lhsType->is<VectorType>() || !isInteger(getVectorElementType(lhsType)))) { log(Errors::Semantics::LEFT_OPERAND_OF_OPERATOR_N_MUST_BE_AN_INTEGER_TYPE.args( *lhsValue, m_sourceInterface, *token, *lhsValue)); } if (!rhsValue->isUndefined() && !isInteger(rhsValue->getType()) && (!rhsValue->getType().is<VectorType>() || !isInteger(getVectorElementType(rhsValue->getType())))) { log(Errors::Semantics::RIGHT_OPERAND_OF_OPERATOR_N_MUST_BE_AN_INTEGER_TYPE.args( *rhsValue, m_sourceInterface, *token, *rhsValue)); } if (lhsType->is<VectorType>() || rhsValue->getType().is<VectorType>()) { checkVectorCompoundAssign(lhsValue, lhsType, token, rhsValue); } break; } case Syntax::AssignmentExpression::LeftShiftAssign: case Syntax::AssignmentExpression::RightShiftAssign: { if (lhsType->is<VectorType>() || rhsValue->getType().is<VectorType>()) { arithmeticConversion(&lhsType, rhsValue); } else { lhsType = integerPromotion(std::move(lhsType)); rhsValue = integerPromotion(std::move(rhsValue)); } if (!lhsType->isUndefined() && !isInteger(lhsType) && (!lhsType->is<VectorType>() || !isInteger(getVectorElementType(lhsType)))) { log(Errors::Semantics::LEFT_OPERAND_OF_OPERATOR_N_MUST_BE_AN_INTEGER_TYPE.args( *lhsValue, m_sourceInterface, *token, *lhsValue)); } if (!rhsValue->isUndefined() && !isInteger(rhsValue->getType()) && (!rhsValue->getType().is<VectorType>() || !isInteger(getVectorElementType(rhsValue->getType())))) { log(Errors::Semantics::RIGHT_OPERAND_OF_OPERATOR_N_MUST_BE_AN_INTEGER_TYPE.args( *rhsValue, m_sourceInterface, *token, *rhsValue)); } if (lhsType->is<VectorType>() || rhsValue->getType().is<VectorType>()) { checkVectorCompoundAssign(lhsValue, lhsType, token, rhsValue); } break; } } rhsValue = std::make_unique<Assignment>( std::move(resultType), std::move(lhsValue), std::move(lhsType), [kind = kind] { switch (kind) { case Syntax::AssignmentExpression::NoOperator: return Assignment::Simple; case Syntax::AssignmentExpression::PlusAssign: return Assignment::Plus; case Syntax::AssignmentExpression::MinusAssign: return Assignment::Minus; case Syntax::AssignmentExpression::DivideAssign: return Assignment::Divide; case Syntax::AssignmentExpression::MultiplyAssign: return Assignment::Multiply; case Syntax::AssignmentExpression::ModuloAssign: return Assignment::Modulo; case Syntax::AssignmentExpression::LeftShiftAssign: return Assignment::LeftShift; case Syntax::AssignmentExpression::RightShiftAssign: return Assignment::RightShift; case Syntax::AssignmentExpression::BitAndAssign: return Assignment::BitAnd; case Syntax::AssignmentExpression::BitOrAssign: return Assignment::BitOr; case Syntax::AssignmentExpression::BitXorAssign: return Assignment::BitXor; } CLD_UNREACHABLE; }(), token, std::move(rhsValue)); } return rhsValue; } cld::IntrVarPtr<cld::Semantics::ExpressionBase> cld::Semantics::SemanticAnalysis::visit(const Syntax::PrimaryExpression& node) { return cld::match(node, [&](auto&& value) -> IntrVarPtr<ExpressionBase> { return visit(value); }); } std::unique_ptr<cld::Semantics::Constant> cld::Semantics::SemanticAnalysis::visit(const Syntax::PrimaryExpressionConstant& node) { const auto& options = getLanguageOptions(); if (std::holds_alternative<llvm::APSInt>(node.getValue()) || std::holds_alternative<llvm::APFloat>(node.getValue())) { switch (node.getType()) { case Lexer::CToken::Type::None: CLD_UNREACHABLE; case Lexer::CToken::Type::UnsignedShort: return std::make_unique<Constant>(PrimitiveType(PrimitiveType::UnsignedShort, options), node.getValue(), node.begin(), node.end()); case Lexer::CToken::Type::Int: return std::make_unique<Constant>(PrimitiveType(PrimitiveType::Int, options), node.getValue(), node.begin(), node.end()); case Lexer::CToken::Type::UnsignedInt: return std::make_unique<Constant>(PrimitiveType(PrimitiveType::UnsignedInt, options), node.getValue(), node.begin(), node.end()); case Lexer::CToken::Type::Long: return std::make_unique<Constant>(PrimitiveType(PrimitiveType::Long, options), node.getValue(), node.begin(), node.end()); case Lexer::CToken::Type::UnsignedLong: return std::make_unique<Constant>(PrimitiveType(PrimitiveType::UnsignedLong, options), node.getValue(), node.begin(), node.end()); case Lexer::CToken::Type::LongLong: return std::make_unique<Constant>(PrimitiveType(PrimitiveType::LongLong, options), node.getValue(), node.begin(), node.end()); case Lexer::CToken::Type::UnsignedLongLong: return std::make_unique<Constant>(PrimitiveType(PrimitiveType::UnsignedLongLong, options), node.getValue(), node.begin(), node.end()); case Lexer::CToken::Type::Float: return std::make_unique<Constant>(PrimitiveType(PrimitiveType::Float, options), node.getValue(), node.begin(), node.end()); case Lexer::CToken::Type::Double: return std::make_unique<Constant>(PrimitiveType(PrimitiveType::Double, options), node.getValue(), node.begin(), node.end()); case Lexer::CToken::Type::LongDouble: return std::make_unique<Constant>(PrimitiveType(PrimitiveType::LongDouble, options), node.getValue(), node.begin(), node.end()); } } else if (std::holds_alternative<std::string>(node.getValue())) { auto& string = cld::get<std::string>(node.getValue()); return std::make_unique<Constant>( ArrayType(typeAlloc<PrimitiveType>(PrimitiveType::Char, options), string.size() + 1), node.getValue(), node.begin(), node.end()); } else if (std::holds_alternative<Lexer::NonCharString>(node.getValue())) { auto& string = cld::get<Lexer::NonCharString>(node.getValue()); if (string.type == Lexer::NonCharString::Wide) { return std::make_unique<Constant>( ArrayType(typeAlloc<PrimitiveType>(options.wcharUnderlyingType, options), string.characters.size() + 1), node.getValue(), node.begin(), node.end()); } } CLD_UNREACHABLE; } cld::IntrVarPtr<cld::Semantics::ExpressionBase> cld::Semantics::SemanticAnalysis::visit(const Syntax::PrimaryExpressionIdentifier& node) { auto* result = lookupDecl(node.getIdentifier()->getText()); if (!result || std::holds_alternative<TypedefInfo*>(*result)) { log(Errors::Semantics::UNDECLARED_IDENTIFIER_N.args(*node.getIdentifier(), m_sourceInterface, *node.getIdentifier())); return std::make_unique<ErrorExpression>(node); } if (auto* value = std::get_if<std::pair<ConstValue, IntrVarValue<Type>>>(result)) { if (value->second->isUndefined()) { return std::make_unique<ErrorExpression>(node); } if (value->first.isUndefined()) { return std::make_unique<ErrorExpression>(value->second, node); } return std::make_unique<Constant>(value->second, cld::match(value->first.getValue(), [](auto&& value) -> Constant::Variant { using T = std::decay_t<decltype(value)>; if constexpr (std::is_constructible_v<Constant::Variant, T>) { return value; } CLD_UNREACHABLE; }), node.getIdentifier(), node.getIdentifier() + 1); } auto& type = cld::match( *result, [](const std::pair<ConstValue, IntrVarValue<Type>>&) -> const Type& { CLD_UNREACHABLE; }, [](const TypedefInfo*) -> const Type& { CLD_UNREACHABLE; }, [](const BuiltinFunction* builtinFunction) -> const Type& { return builtinFunction->getType(); }, [&](const auto* ptr) -> const Type& { if (getCurrentFunctionScope() && getCurrentFunctionScope()->currentFunction->getFunctionGroup().isInline() && getCurrentFunctionScope()->currentFunction->getLinkage() == Linkage::External && ptr->getLinkage() == Linkage::Internal) { log(Errors::Semantics:: INLINE_FUNCTION_N_WITH_EXTERNAL_LINKAGE_IS_NOT_ALLOWED_TO_CONTAIN_OR_ACCESS_THE_INTERNAL_IDENTIFIER_N .args(*ptr->getNameToken(), m_sourceInterface, *getCurrentFunctionScope()->currentFunction->getNameToken(), *ptr->getNameToken())); } return ptr->getType(); }); auto& useable = cld::match(*result, [](auto&& value) -> Useable& { using T = std::remove_pointer_t<std::decay_t<decltype(value)>>; if constexpr (std::is_base_of_v<Useable, T>) { return *value; } CLD_UNREACHABLE; }); useable.incrementUsage(); if (auto* deprecatedAttribute = useable.match( [](const auto& value) -> const DeprecatedAttribute* { return value.template getAttributeIf<DeprecatedAttribute>(); }, [](const BuiltinFunction&) -> const DeprecatedAttribute* { return nullptr; })) { auto* nameToken = useable.match([](const auto& value) -> Lexer::CTokenIterator { return value.getNameToken(); }, [](const BuiltinFunction&) -> Lexer::CTokenIterator { CLD_UNREACHABLE; }); if (deprecatedAttribute->optionalMessage) { if (useable.is<FunctionDeclaration>() || useable.is<FunctionDefinition>()) { if (log(Warnings::Semantics::FUNCTION_N_IS_DEPRECATED_N.args(*node.getIdentifier(), m_sourceInterface, *node.getIdentifier(), *deprecatedAttribute->optionalMessage))) { log(Notes::Semantics::MARKED_DEPRECATED_HERE.args(*nameToken, m_sourceInterface, *nameToken)); } } else if (useable.is<VariableDeclaration>()) { if (log(Warnings::Semantics::VARIABLE_N_IS_DEPRECATED_N.args(*node.getIdentifier(), m_sourceInterface, *node.getIdentifier(), *deprecatedAttribute->optionalMessage))) { log(Notes::Semantics::MARKED_DEPRECATED_HERE.args(*nameToken, m_sourceInterface, *nameToken)); } } } else { if (useable.is<FunctionDeclaration>() || useable.is<FunctionDefinition>()) { if (log(Warnings::Semantics::FUNCTION_N_IS_DEPRECATED.args(*node.getIdentifier(), m_sourceInterface, *node.getIdentifier()))) { log(Notes::Semantics::MARKED_DEPRECATED_HERE.args(*nameToken, m_sourceInterface, *nameToken)); } } else if (useable.is<VariableDeclaration>()) { if (log(Warnings::Semantics::VARIABLE_N_IS_DEPRECATED.args(*node.getIdentifier(), m_sourceInterface, *node.getIdentifier()))) { log(Notes::Semantics::MARKED_DEPRECATED_HERE.args(*nameToken, m_sourceInterface, *nameToken)); } } } } return std::make_unique<DeclarationRead>(type, useable, node.getIdentifier()); } cld::IntrVarPtr<cld::Semantics::ExpressionBase> cld::Semantics::SemanticAnalysis::visit(const Syntax::PrimaryExpressionParentheses& node) { return visit(node.getExpression()); } cld::IntrVarPtr<cld::Semantics::ExpressionBase> cld::Semantics::SemanticAnalysis::visit(const Syntax::PrimaryExpressionBuiltinVAArg& vaArg) { auto expression = visit(vaArg.getAssignmentExpression()); auto [isConst, isVolatile] = std::pair{expression->getType().isConst(), expression->getType().isVolatile()}; expression = lvalueConversion(std::move(expression)); auto& vaList = *getTypedef("__builtin_va_list"); if (!expression->getType().isUndefined() && (!typesAreCompatible(expression->getType(), *adjustParameterType(vaList.type)) || isConst || isVolatile)) { log(Errors::Semantics::CANNOT_PASS_INCOMPATIBLE_TYPE_TO_PARAMETER_N_OF_TYPE_VA_LIST.args( *expression, m_sourceInterface, 1, *expression)); } auto type = declaratorsToType(vaArg.getTypeName().getSpecifierQualifiers(), vaArg.getTypeName().getAbstractDeclarator()); if (!isCompleteType(type)) { log(Errors::Semantics::INCOMPLETE_TYPE_N_IN_VA_ARG.args(vaArg.getTypeName(), m_sourceInterface, type, vaArg.getTypeName())); return std::make_unique<ErrorExpression>(vaArg); } type = removeQualifiers(type); return std::make_unique<BuiltinVAArg>(std::move(type), vaArg.getBuiltinToken(), vaArg.getOpenParentheses(), std::move(expression), vaArg.getCloseParentheses()); } cld::IntrVarPtr<cld::Semantics::ExpressionBase> cld::Semantics::SemanticAnalysis::visit(const Syntax::PrimaryExpressionBuiltinOffsetOf& node) { auto retType = PrimitiveType(getLanguageOptions().sizeTType, getLanguageOptions()); auto type = declaratorsToType(node.getTypeName().getSpecifierQualifiers(), node.getTypeName().getAbstractDeclarator()); if (type->isUndefined() || !isRecord(type)) { if (!isRecord(type)) { log(Errors::Semantics::TYPE_N_IN_OFFSETOF_MUST_BE_A_STRUCT_OR_UNION_TYPE.args( node.getTypeName(), m_sourceInterface, type, node.getTypeName())); } return std::make_unique<ErrorExpression>(std::move(retType), node); } auto& fields = getFields(type); auto result = fields.find(node.getMemberName()->getText()); if (result == fields.end()) { reportNoMember(type, *node.getMemberName()); return std::make_unique<ErrorExpression>(std::move(retType), node); } if (result->second.bitFieldBounds) { log(Errors::Semantics::BITFIELD_NOT_ALLOWED_IN_OFFSET_OF.args(*node.getMemberName(), m_sourceInterface, *node.getMemberName())); return std::make_unique<ErrorExpression>(std::move(retType), node); } tcb::span<const Lexer::CToken> range(node.getMemberName(), node.getMemberName() + 1); std::uint64_t currentOffset = 0; const Type* currentType = type.data(); for (auto& iter : result->second.indices) { if (currentType->is<UnionType>()) { auto fieldLayout = getFieldLayout(*currentType); currentType = fieldLayout[iter].type; continue; } auto memLayout = getMemoryLayout(*currentType); currentOffset += memLayout[iter].offset; currentType = memLayout[iter].type; } bool runtimeEvaluated = false; std::vector<std::variant<IntrVarPtr<ExpressionBase>, const Field*>> runtimeVariant; runtimeVariant.emplace_back(&result->second); std::optional<diag::PointRange> failedConstExpr; for (auto& iter : node.getMemberSuffix()) { if (std::holds_alternative<Lexer::CTokenIterator>(iter)) { if (!isRecord(*currentType)) { log(Errors::Semantics::EXPECTED_STRUCT_OR_UNION_ON_THE_LEFT_SIDE_OF_THE_DOT_OPERATOR_2.args( range, m_sourceInterface, range, *currentType)); return std::make_unique<ErrorExpression>(std::move(retType), node); } auto& subFields = getFields(*currentType); auto subResult = subFields.find(cld::get<Lexer::CTokenIterator>(iter)->getText()); if (subResult == subFields.end()) { reportNoMember(*currentType, *cld::get<Lexer::CTokenIterator>(iter)); return std::make_unique<ErrorExpression>(std::move(retType), node); } if (subResult->second.bitFieldBounds) { log(Errors::Semantics::BITFIELD_NOT_ALLOWED_IN_OFFSET_OF.args( *cld::get<Lexer::CTokenIterator>(iter), m_sourceInterface, *cld::get<Lexer::CTokenIterator>(iter))); return std::make_unique<ErrorExpression>(std::move(retType), node); } runtimeVariant.emplace_back(&subResult->second); range = tcb::span(node.getMemberName(), cld::get<Lexer::CTokenIterator>(iter) + 1); for (auto& index : subResult->second.indices) { if (currentType->is<UnionType>()) { auto fieldLayout = getFieldLayout(*currentType); currentType = fieldLayout[index].type; continue; } auto memLayout = getMemoryLayout(*currentType); currentOffset += memLayout[index].offset; currentType = memLayout[index].type; } } else { if (!isArray(*currentType)) { log(Errors::Semantics::EXPECTED_ARRAY_TYPE_ON_THE_LEFT_SIDE_OF_THE_SUBSCRIPT_OPERATOR.args( range, m_sourceInterface, range, *currentType)); return std::make_unique<ErrorExpression>(std::move(retType), node); } currentType = &getArrayElementType(*currentType); auto& subscript = cld::get<Syntax::PrimaryExpressionBuiltinOffsetOf::Subscript>(iter); cld::ScopeExit exit{[&] { range = tcb::span(node.getMemberName(), subscript.closeBracket + 1); }}; auto expression = lvalueConversion(visit(*subscript.expression)); if (expression->isUndefined()) { return std::make_unique<ErrorExpression>(std::move(retType), node); } if (!isInteger(expression->getType())) { log(Errors::Semantics::EXPECTED_OTHER_OPERAND_TO_BE_OF_INTEGER_TYPE.args(*expression, m_sourceInterface, *expression)); return std::make_unique<ErrorExpression>(std::move(retType), node); } if (runtimeEvaluated) { runtimeVariant.emplace_back(std::move(expression)); continue; } auto constant = evaluateConstantExpression(*expression); runtimeVariant.emplace_back(std::move(expression)); if (!constant) { failedConstExpr = diag::getPointRange(*cld::get<IntrVarPtr<ExpressionBase>>(runtimeVariant.back())); runtimeEvaluated = true; continue; } auto size = currentType->getSizeOf(*this); if (constant->getInteger().isSigned()) { currentOffset += size * constant->getInteger().getSExtValue(); } else { currentOffset += size * constant->getInteger().getZExtValue(); } } } if (runtimeEvaluated) { return std::make_unique<BuiltinOffsetOf>( getLanguageOptions(), node.getBuiltinToken(), node.getOpenParentheses(), BuiltinOffsetOf::RuntimeEval{std::move(type), std::move(runtimeVariant), std::move(failedConstExpr)}, node.getCloseParentheses()); } return std::make_unique<BuiltinOffsetOf>(getLanguageOptions(), node.getBuiltinToken(), node.getOpenParentheses(), currentOffset, node.getCloseParentheses()); } cld::IntrVarPtr<cld::Semantics::ExpressionBase> cld::Semantics::SemanticAnalysis::visit(const Syntax::PostFixExpression& node) { return cld::match(node, [&](auto&& value) { return visit(value); }); } cld::IntrVarPtr<cld::Semantics::ExpressionBase> cld::Semantics::SemanticAnalysis::visit(const Syntax::PostFixExpressionPrimaryExpression& node) { return visit(node.getPrimaryExpression()); } cld::IntrVarPtr<cld::Semantics::ExpressionBase> cld::Semantics::SemanticAnalysis::visit(const Syntax::PostFixExpressionSubscript& node) { auto first = lvalueConversion(visit(node.getPostFixExpression())); auto second = lvalueConversion(visit(node.getExpression())); if (first->getType().isUndefined() || second->getType().isUndefined()) { return std::make_unique<ErrorExpression>(node); } if (!first->getType().is<PointerType>() && !second->getType().is<PointerType>() && !first->getType().is<VectorType>() && !second->getType().is<VectorType>()) { log(Errors::Semantics::EXPECTED_ONE_OPERAND_TO_BE_OF_POINTER_TYPE.args(node.getPostFixExpression(), m_sourceInterface, *first, *second)); return std::make_unique<ErrorExpression>(node); } if (first->getType().is<VectorType>() || second->getType().is<VectorType>()) { auto& vectorExpr = first->getType().is<VectorType>() ? first : second; auto& intExpr = &vectorExpr == &first ? second : first; if (!isInteger(intExpr->getType())) { log(Errors::Semantics::EXPECTED_OTHER_OPERAND_TO_BE_OF_INTEGER_TYPE.args(*intExpr, m_sourceInterface, *intExpr)); return std::make_unique<ErrorExpression>(node); } IntrVarValue elementType = getVectorElementType(vectorExpr->getType()); return std::make_unique<SubscriptOperator>(std::move(elementType), &vectorExpr == &first, std::move(first), node.getOpenBracket(), std::move(second), node.getCloseBracket()); } auto& pointerExpr = first->getType().is<PointerType>() ? first : second; auto& intExpr = &pointerExpr == &first ? second : first; if (!isInteger(intExpr->getType())) { log(Errors::Semantics::EXPECTED_OTHER_OPERAND_TO_BE_OF_INTEGER_TYPE.args(*intExpr, m_sourceInterface, *intExpr)); return std::make_unique<ErrorExpression>(node); } IntrVarValue elementType = getPointerElementType(pointerExpr->getType()); if (!isCompleteType(elementType)) { log(Errors::Semantics::POINTER_TO_INCOMPLETE_TYPE_N_NOT_ALLOWED_IN_SUBSCRIPT_OPERATOR.args( *pointerExpr, m_sourceInterface, elementType, *pointerExpr)); return std::make_unique<ErrorExpression>(node); } if (elementType->is<FunctionType>()) { log(Errors::Semantics::POINTER_TO_FUNCTION_TYPE_NOT_ALLOWED_IN_SUBSCRIPT_OPERATOR.args( *pointerExpr, m_sourceInterface, *pointerExpr)); return std::make_unique<ErrorExpression>(node); } return std::make_unique<SubscriptOperator>(std::move(elementType), &pointerExpr == &first, std::move(first), node.getOpenBracket(), std::move(second), node.getCloseBracket()); } void cld::Semantics::SemanticAnalysis::reportNoMember(const Type& recordType, const Lexer::CToken& identifier) { if (recordType.is<UnionType>()) { if (isAnonymous(recordType)) { log(Errors::Semantics::NO_MEMBER_CALLED_N_FOUND_IN_ANONYMOUS_UNION.args(identifier, m_sourceInterface, identifier)); } else { log(Errors::Semantics::NO_MEMBER_CALLED_N_FOUND_IN_UNION_N.args(identifier, m_sourceInterface, identifier, recordType.as<UnionType>().getUnionName())); } } if (recordType.is<StructType>()) { if (isAnonymous(recordType)) { log(Errors::Semantics::NO_MEMBER_CALLED_N_FOUND_IN_ANONYMOUS_STRUCT.args(identifier, m_sourceInterface, identifier)); } else { log(Errors::Semantics::NO_MEMBER_CALLED_N_FOUND_IN_STRUCT_N.args( identifier, m_sourceInterface, identifier, recordType.as<StructType>().getStructName())); } } } std::optional<std::pair<cld::IntrVarValue<cld::Semantics::Type>, const cld::Semantics::Field * CLD_NON_NULL>> cld::Semantics::SemanticAnalysis::checkMemberAccess(const Type& recordType, const Syntax::PostFixExpression& postFixExpr, const Lexer::CToken& identifier) { const FieldMap* fields = nullptr; if (auto* structType = recordType.tryAs<StructType>()) { auto* structDef = std::get_if<StructDefinition>(&structType->getInfo().type); if (!structDef) { log(Errors::Semantics::STRUCT_N_IS_AN_INCOMPLETE_TYPE.args(postFixExpr, m_sourceInterface, structType->getStructName(), postFixExpr)); return {}; } fields = &structDef->getFields(); } if (auto* unionType = recordType.tryAs<UnionType>()) { auto* unionDef = std::get_if<UnionDefinition>(&unionType->getInfo().type); if (!unionDef) { log(Errors::Semantics::UNION_N_IS_AN_INCOMPLETE_TYPE.args(postFixExpr, m_sourceInterface, unionType->getUnionName(), postFixExpr)); return {}; } fields = &unionDef->getFields(); } CLD_ASSERT(fields); auto result = fields->find(identifier.getText()); if (result == fields->end()) { reportNoMember(recordType, identifier); return {}; } IntrVarValue type = *result->second.type; if (std::pair{recordType.isConst(), recordType.isVolatile()} > std::pair{result->second.type->isConst(), result->second.type->isVolatile()}) { type->setConst(recordType.isConst()); type->setVolatile(recordType.isVolatile()); } return std::pair(std::move(type), &result->second); } cld::IntrVarPtr<cld::Semantics::ExpressionBase> cld::Semantics::SemanticAnalysis::visit(const Syntax::PostFixExpressionDot& node) { auto structOrUnion = visit(node.getPostFixExpression()); if (structOrUnion->isUndefined()) { return std::make_unique<ErrorExpression>(node); } if (!isRecord(structOrUnion->getType())) { log(Errors::Semantics::EXPECTED_STRUCT_OR_UNION_ON_THE_LEFT_SIDE_OF_THE_DOT_OPERATOR.args( *structOrUnion, m_sourceInterface, *structOrUnion)); return std::make_unique<ErrorExpression>(node); } auto result = checkMemberAccess(structOrUnion->getType(), node.getPostFixExpression(), *node.getIdentifier()); if (!result) { return std::make_unique<ErrorExpression>(node); } auto& [type, field] = *result; if (type->isUndefined()) { return std::make_unique<ErrorExpression>(node); } auto category = structOrUnion->getValueCategory(); return std::make_unique<MemberAccess>(type, category, std::move(structOrUnion), *field, node.getIdentifier()); } cld::IntrVarPtr<cld::Semantics::ExpressionBase> cld::Semantics::SemanticAnalysis::visit(const Syntax::PostFixExpressionArrow& node) { auto structOrUnionPtr = lvalueConversion(visit(node.getPostFixExpression())); if (structOrUnionPtr->isUndefined()) { return std::make_unique<ErrorExpression>(node); } if (!structOrUnionPtr->getType().is<PointerType>()) { log(Errors::Semantics::EXPECTED_POINTER_TO_STRUCT_OR_UNION_ON_THE_LEFT_SIDE_OF_THE_ARROW_OPERATOR.args( *structOrUnionPtr, m_sourceInterface, *structOrUnionPtr)); return std::make_unique<ErrorExpression>(node); } auto& structOrUnion = getPointerElementType(structOrUnionPtr->getType()); if (!isRecord(structOrUnion)) { log(Errors::Semantics::EXPECTED_POINTER_TO_STRUCT_OR_UNION_ON_THE_LEFT_SIDE_OF_THE_ARROW_OPERATOR.args( *structOrUnionPtr, m_sourceInterface, *structOrUnionPtr)); return std::make_unique<ErrorExpression>(node); } auto result = checkMemberAccess(structOrUnion, node.getPostFixExpression(), *node.getIdentifier()); if (!result) { return std::make_unique<ErrorExpression>(node); } auto& [type, field] = *result; if (type->isUndefined()) { return std::make_unique<ErrorExpression>(node); } return std::make_unique<MemberAccess>(type, ValueCategory::Lvalue, std::move(structOrUnionPtr), *field, node.getIdentifier()); } namespace { bool isBuiltinKind(const cld::Semantics::ExpressionBase& expression, cld::Semantics::BuiltinFunction::Kind kind) { auto* declRead = expression.tryAs<cld::Semantics::DeclarationRead>(); if (!declRead) { return false; } auto* builtin = declRead->getDeclRead().tryAs<cld::Semantics::BuiltinFunction>(); if (!builtin) { return false; } return builtin->getKind() == kind; } bool isSyncBuiltinWithType(const cld::Semantics::ExpressionBase& expression) { auto* declRead = expression.tryAs<cld::Semantics::DeclarationRead>(); if (!declRead) { return false; } auto* builtin = declRead->getDeclRead().tryAs<cld::Semantics::BuiltinFunction>(); if (!builtin) { return false; } switch (builtin->getKind()) { case cld::Semantics::BuiltinFunction::SyncFetchAndAdd: case cld::Semantics::BuiltinFunction::SyncFetchAndSub: case cld::Semantics::BuiltinFunction::SyncFetchAndOr: case cld::Semantics::BuiltinFunction::SyncFetchAndAnd: case cld::Semantics::BuiltinFunction::SyncFetchAndXor: case cld::Semantics::BuiltinFunction::SyncFetchAndNand: case cld::Semantics::BuiltinFunction::SyncAddAndFetch: case cld::Semantics::BuiltinFunction::SyncSubAndFetch: case cld::Semantics::BuiltinFunction::SyncOrAndFetch: case cld::Semantics::BuiltinFunction::SyncAndAndFetch: case cld::Semantics::BuiltinFunction::SyncXorAndFetch: case cld::Semantics::BuiltinFunction::SyncNandAndFetch: case cld::Semantics::BuiltinFunction::SyncBoolCompareAndSwap: case cld::Semantics::BuiltinFunction::SyncValCompareAndSwap: case cld::Semantics::BuiltinFunction::SyncLockTestAndSet: case cld::Semantics::BuiltinFunction::SyncLockRelease: return true; default: return false; } } bool isBuiltinFunction(const cld::Semantics::ExpressionBase& expression) { auto* declRead = expression.tryAs<cld::Semantics::DeclarationRead>(); if (!declRead) { return false; } return declRead->getDeclRead().is<cld::Semantics::BuiltinFunction>(); } } // namespace std::unique_ptr<cld::Semantics::CallExpression> cld::Semantics::SemanticAnalysis::visitVAStart(const Syntax::PostFixExpressionFunctionCall& node, IntrVarPtr<ExpressionBase>&& function) { std::vector<IntrVarPtr<ExpressionBase>> arguments; if (node.getOptionalAssignmentExpressions().size() < 2) { log(Errors::Semantics::NOT_ENOUGH_ARGUMENTS_FOR_CALLING_FUNCTION_VA_START_EXPECTED_N_GOT_N.args( *function, m_sourceInterface, 2, node.getOptionalAssignmentExpressions().size(), *function)); } else if (node.getOptionalAssignmentExpressions().size() > 2) { log(Errors::Semantics::TOO_MANY_ARGUMENTS_FOR_CALLING_FUNCTION_VA_START_EXPECTED_N_GOT_N.args( *function, m_sourceInterface, 2, node.getOptionalAssignmentExpressions().size(), *function, tcb::span(node.getOptionalAssignmentExpressions()).subspan(2))); } else { arguments.push_back(visit(node.getOptionalAssignmentExpressions()[0])); auto& vaList = *getTypedef("__builtin_va_list"); if (!arguments[0]->getType().isUndefined() && !typesAreCompatible(arguments[0]->getType(), vaList.type)) { log(Errors::Semantics::CANNOT_PASS_INCOMPATIBLE_TYPE_TO_PARAMETER_N_OF_TYPE_VA_LIST.args( *arguments[0], m_sourceInterface, 1, *arguments[0])); } // even if the call is done using "__builtin_va_start(list,...)" the list is actually passed as a pointer. // In the case of x86_64 ABI __builtin_va_list is an array type causing pointer decay, in the case // of Windows x64 it's basically as if &list was written. Since this is a builtin call the backend will // have to do special handling either way but we'll insert an lvalueConversion now to force array to pointer // decay if (isArray(vaList.type)) { arguments.back() = lvalueConversion(std::move(arguments.back())); } auto expression = visit(node.getOptionalAssignmentExpressions()[1]); if (!getCurrentFunctionScope()) { log(Errors::Semantics::CANNOT_USE_VA_START_OUTSIDE_OF_A_FUNCTION.args(*function, m_sourceInterface, *function)); } else if (!getCurrentFunctionScope()->currentFunction->getType().isLastVararg()) { log(Errors::Semantics::CANNOT_USE_VA_START_IN_A_FUNCTION_WITH_FIXED_ARGUMENT_COUNT.args( *function, m_sourceInterface, *function)); } else if (auto* declRead = expression->tryAs<DeclarationRead>(); !declRead || (!getCurrentFunctionScope()->currentFunction->getParameterDeclarations().empty() && &declRead->getDeclRead() != getCurrentFunctionScope()->currentFunction->getParameterDeclarations().back().get())) { log(Warnings::Semantics::SECOND_ARGUMENT_OF_VA_START_SHOULD_BE_THE_LAST_PARAMETER.args( *expression, m_sourceInterface, *expression)); } arguments.push_back(lvalueConversion(std::move(expression))); } auto* functionType = &function->getType(); return std::make_unique<CallExpression>( PrimitiveType(PrimitiveType::Void, getLanguageOptions()), std::make_unique<Conversion>(PointerType(functionType), Conversion::LValue, std::move(function)), node.getOpenParentheses(), std::move(arguments), node.getCloseParentheses()); } std::unique_ptr<cld::Semantics::CallExpression> cld::Semantics::SemanticAnalysis::visitPrefetch(const Syntax::PostFixExpressionFunctionCall& node, IntrVarPtr<ExpressionBase>&& function) { std::vector<IntrVarPtr<ExpressionBase>> arguments; auto& ft = function->getType().as<FunctionType>(); if (node.getOptionalAssignmentExpressions().size() == 0) { auto& decl = function->as<DeclarationRead>(); log(Errors::Semantics::NOT_ENOUGH_ARGUMENTS_FOR_CALLING_FUNCTION_N_EXPECTED_AT_LEAST_N_GOT_N.args( decl, m_sourceInterface, *decl.getIdentifierToken(), 1, 0)); } else if (node.getOptionalAssignmentExpressions().size() > 3) { auto& decl = function->as<DeclarationRead>(); log(Errors::Semantics::TOO_MANY_ARGUMENTS_FOR_CALLING_FUNCTION_N_EXPECTED_N_GOT_N.args( decl, m_sourceInterface, *decl.getIdentifierToken(), 3, node.getOptionalAssignmentExpressions().size(), tcb::span(node.getOptionalAssignmentExpressions()).subspan(3))); } else { arguments.push_back( checkFunctionArg(1, *ft.getParameters()[0].type, visit(node.getOptionalAssignmentExpressions()[0]))); if (node.getOptionalAssignmentExpressions().size() > 1) { auto expression = visit(node.getOptionalAssignmentExpressions()[1]); if (!expression->isUndefined()) { auto constant = evaluateConstantExpression(*expression); if (!constant || !isInteger(expression->getType())) { log(Errors::Semantics::EXPECTED_INTEGER_CONSTANT_EXPRESSION_AS_SECOND_ARGUMENT_TO_BUILTIN_PREFETCH .args(*expression, m_sourceInterface, *expression)); } else if (constant->getInteger() != 0 && constant->getInteger() != 1) { log(Errors::Semantics::EXPECTED_A_VALUE_OF_0_OR_1_AS_SECOND_ARGUMENT_TO_BUILTIN_PREFETCH.args( *expression, m_sourceInterface, *expression, *constant)); } } arguments.push_back(std::move(expression)); } if (node.getOptionalAssignmentExpressions().size() > 2) { auto expression = visit(node.getOptionalAssignmentExpressions()[2]); if (!expression->isUndefined()) { auto constant = evaluateConstantExpression(*expression); if (!constant || !isInteger(expression->getType())) { log(Errors::Semantics::EXPECTED_INTEGER_CONSTANT_EXPRESSION_AS_THIRD_ARGUMENT_TO_BUILTIN_PREFETCH .args(*expression, m_sourceInterface, *expression)); } else if (constant->getInteger() < 0 || constant->getInteger() > 3) { log(Errors::Semantics::EXPECTED_A_VALUE_OF_0_TO_3_AS_THIRD_ARGUMENT_TO_BUILTIN_PREFETCH.args( *expression, m_sourceInterface, *expression, *constant)); } } arguments.push_back(std::move(expression)); } } return std::make_unique<CallExpression>( PrimitiveType(PrimitiveType::Void, getLanguageOptions()), std::make_unique<Conversion>(PointerType(&ft), Conversion::LValue, std::move(function)), node.getOpenParentheses(), std::move(arguments), node.getCloseParentheses()); } std::unique_ptr<cld::Semantics::CallExpression> cld::Semantics::SemanticAnalysis::visitExpectWithProbability(const Syntax::PostFixExpressionFunctionCall& node, IntrVarPtr<ExpressionBase>&& function) { std::vector<IntrVarPtr<ExpressionBase>> arguments; auto& ft = function->getType().as<FunctionType>(); if (node.getOptionalAssignmentExpressions().size() < 3) { auto& decl = function->as<DeclarationRead>(); log(Errors::Semantics::NOT_ENOUGH_ARGUMENTS_FOR_CALLING_FUNCTION_N_EXPECTED_N_GOT_N.args( decl, m_sourceInterface, *decl.getIdentifierToken(), 3, node.getOptionalAssignmentExpressions().size())); } else if (node.getOptionalAssignmentExpressions().size() > 3) { auto& decl = function->as<DeclarationRead>(); log(Errors::Semantics::TOO_MANY_ARGUMENTS_FOR_CALLING_FUNCTION_N_EXPECTED_N_GOT_N.args( decl, m_sourceInterface, *decl.getIdentifierToken(), 3, node.getOptionalAssignmentExpressions().size(), tcb::span(node.getOptionalAssignmentExpressions()).subspan(3))); } else { arguments.push_back( checkFunctionArg(1, *ft.getParameters()[0].type, visit(node.getOptionalAssignmentExpressions()[0]))); arguments.push_back( checkFunctionArg(2, *ft.getParameters()[1].type, visit(node.getOptionalAssignmentExpressions()[1]))); arguments.push_back( checkFunctionArg(3, *ft.getParameters()[2].type, visit(node.getOptionalAssignmentExpressions()[2]))); if (arguments.back() && !arguments.back()->isUndefined()) { auto constant = evaluateConstantExpression(*arguments.back(), Arithmetic); if (!constant || !isArithmetic(arguments.back()->getType())) { log(Errors::Semantics:: EXPECTED_ARITHMETIC_CONSTANT_EXPRESSION_AS_THIRD_ARGUMENT_TO_BUILTIN_EXPECT_WITH_PROBABILITY .args(*arguments.back(), m_sourceInterface, *arguments.back())); } else if (constant->getFloating() < llvm::APFloat(constant->getFloating().getSemantics(), 0) || constant->getFloating() > llvm::APFloat(constant->getFloating().getSemantics(), 1)) { log(Errors::Semantics::EXPECTED_A_VALUE_OF_0_TO_1_AS_THIRD_ARGUMENT_TO_BUILTIN_EXPECT_WITH_PROBABILITY .args(*arguments.back(), m_sourceInterface, *arguments.back(), *constant)); } } } return std::make_unique<CallExpression>( PrimitiveType(PrimitiveType::Void, getLanguageOptions()), std::make_unique<Conversion>(PointerType(&ft), Conversion::LValue, std::move(function)), node.getOpenParentheses(), std::move(arguments), node.getCloseParentheses()); } std::unique_ptr<cld::Semantics::CallExpression> cld::Semantics::SemanticAnalysis::visitSyncBuiltinWithT(const Syntax::PostFixExpressionFunctionCall& node, IntrVarPtr<ExpressionBase>&& function) { auto& type = function->getType(); function = std::make_unique<Conversion>(PointerType(&type), Conversion::LValue, std::move(function)); auto& ft = getPointerElementType(function->getType()).as<FunctionType>(); IntrVarValue placeholder = ErrorType{}; std::vector<IntrVarPtr<ExpressionBase>> arguments; if (checkFunctionCount(*function, ft, node)) { auto& decl = function->as<Conversion>().getExpression().as<DeclarationRead>(); arguments.push_back(lvalueConversion(visit(node.getOptionalAssignmentExpressions()[0]))); if (!arguments.back()->getType().is<PointerType>()) { log(Errors::Semantics::EXPECTED_POINTER_TYPE_AS_FIRST_ARGUMENT_TO_N.args( *arguments.back(), m_sourceInterface, *decl.getIdentifierToken(), *arguments.back())); } else { auto& elementType = getPointerElementType(arguments.back()->getType()); if (elementType.isConst()) { log(Errors::Semantics::POINTER_ELEMENT_TYPE_IN_N_MAY_NOT_BE_CONST_QUALIFIED.args( *arguments.back(), m_sourceInterface, *decl.getIdentifierToken(), *arguments.back())); } if (!isInteger(elementType) && !elementType.is<PointerType>()) { log(Errors::Semantics::POINTER_ELEMENT_TYPE_IN_N_MUST_BE_AN_INTEGER_OR_POINTER_TYPe.args( *arguments.back(), m_sourceInterface, *decl.getIdentifierToken(), *arguments.back())); } else if (isBool(elementType)) { log(Errors::Semantics::POINTER_ELEMENT_TYPE_IN_N_MUST_NOT_BE_BOOL.args( *arguments.back(), m_sourceInterface, *decl.getIdentifierToken(), *arguments.back())); } else if (elementType.getSizeOf(*this) > 8) { log(Errors::Semantics::POINTER_ELEMENT_TYPE_IN_N_MUST_NOT_HAVE_A_SIZE_GREATER_THAN_8.args( *arguments.back(), m_sourceInterface, *decl.getIdentifierToken(), *arguments.back())); } placeholder = removeQualifiers(elementType); } std::size_t i = 1; for (; i < ft.getParameters().size(); i++) { if (ft.getParameters()[i].type->isUndefined()) { arguments.push_back( checkFunctionArg(i + 1, placeholder, visit(node.getOptionalAssignmentExpressions()[i]))); } else { arguments.push_back(checkFunctionArg(i + 1, *ft.getParameters()[i].type, visit(node.getOptionalAssignmentExpressions()[i]))); } } for (; i < node.getOptionalAssignmentExpressions().size(); i++) { visit(node.getOptionalAssignmentExpressions()[i]); } } if (ft.getReturnType().isUndefined()) { return std::make_unique<CallExpression>(std::move(placeholder), std::move(function), node.getOpenParentheses(), std::move(arguments), node.getCloseParentheses()); } return std::make_unique<CallExpression>(ft.getReturnType(), std::move(function), node.getOpenParentheses(), std::move(arguments), node.getCloseParentheses()); } cld::IntrVarPtr<cld::Semantics::ExpressionBase> cld::Semantics::SemanticAnalysis::checkFunctionArg(std::size_t i, IntrVarValue<Type> paramType, IntrVarPtr<ExpressionBase>&& expression) { paramType = removeQualifiers(adjustParameterType(paramType)); if (paramType->isUndefined()) { return {}; } expression = lvalueConversion(std::move(expression)); if (expression->isUndefined()) { return {std::move(expression)}; } doAssignmentLikeConstraints( paramType, expression, [&] { log(Errors::Semantics::EXPECTED_ARGUMENT_N_TO_BE_AN_ARITHMETIC_TYPE.args(*expression, m_sourceInterface, i, *expression)); }, [&] { log(Errors::Semantics::EXPECTED_ARGUMENT_N_TO_BE_AN_ARITHMETIC_OR_POINTER_TYPE.args( *expression, m_sourceInterface, i, *expression)); }, [&] { log(Errors::Semantics::CANNOT_PASS_ARGUMENT_TO_INCOMPLETE_TYPE_N_OF_PARAMETER_N.args( *expression, m_sourceInterface, paramType, i, *expression)); }, [&] { log(Errors::Semantics::CANNOT_PASS_INCOMPATIBLE_TYPE_TO_PARAMETER_N_OF_TYPE_N.args( *expression, m_sourceInterface, i, paramType, *expression)); }, [&] { log(Errors::Semantics::EXPECTED_ARGUMENT_N_TO_BE_NULL_2.args(*expression, m_sourceInterface, i, *expression)); }, [&](const ConstValue& constant) { log(Errors::Semantics::EXPECTED_ARGUMENT_N_TO_BE_NULL.args(*expression, m_sourceInterface, i, *expression, constant)); }, [&] { log(Errors::Semantics::EXPECTED_ARGUMENT_N_TO_BE_A_POINTER_TYPE.args(*expression, m_sourceInterface, i, *expression)); }, [&] { if (isVoid(getPointerElementType(paramType))) { log(Errors::Semantics::CANNOT_PASS_FUNCTION_POINTER_TO_VOID_POINTER_PARAMETER.args( *expression, m_sourceInterface, *expression)); } else { log(Errors::Semantics::CANNOT_PASS_VOID_POINTER_TO_FUNCTION_POINTER_PARAMETER.args( *expression, m_sourceInterface, *expression)); } }); return {std::move(expression)}; } bool cld::Semantics::SemanticAnalysis::checkFunctionCount(const ExpressionBase& function, const FunctionType& ft, const Syntax::PostFixExpressionFunctionCall& node) { auto callsFunction = [&] { if (!function.is<Conversion>()) { return false; } auto& conversion = function.as<Conversion>(); if (conversion.getKind() != Conversion::LValue) { return false; } if (!conversion.getExpression().is<DeclarationRead>()) { return false; } auto& decl = conversion.getExpression().as<DeclarationRead>(); return decl.getDeclRead().match( [](const FunctionDefinition&) { return true; }, [](const FunctionDeclaration&) { return true; }, [](const VariableDeclaration&) { return false; }, [](const BuiltinFunction&) { return true; }); }(); auto& argumentTypes = ft.getParameters(); if (node.getOptionalAssignmentExpressions().size() < argumentTypes.size()) { if (!ft.isLastVararg()) { if (callsFunction) { auto& decl = function.as<Conversion>().getExpression().as<DeclarationRead>(); log(Errors::Semantics::NOT_ENOUGH_ARGUMENTS_FOR_CALLING_FUNCTION_N_EXPECTED_N_GOT_N.args( decl, m_sourceInterface, *decl.getIdentifierToken(), argumentTypes.size(), node.getOptionalAssignmentExpressions().size())); } else { log(Errors::Semantics::NOT_ENOUGH_ARGUMENTS_FOR_FUNCTION_CALL_EXPECTED_N_GOT_N.args( function, m_sourceInterface, argumentTypes.size(), node.getOptionalAssignmentExpressions().size(), function)); } } else { if (callsFunction) { auto& decl = function.as<Conversion>().getExpression().as<DeclarationRead>(); log(Errors::Semantics::NOT_ENOUGH_ARGUMENTS_FOR_CALLING_FUNCTION_N_EXPECTED_AT_LEAST_N_GOT_N.args( decl, m_sourceInterface, *decl.getIdentifierToken(), argumentTypes.size(), node.getOptionalAssignmentExpressions().size())); } else { log(Errors::Semantics::NOT_ENOUGH_ARGUMENTS_FOR_FUNCTION_CALL_EXPECTED_AT_LEAST_N_GOT_N.args( function, m_sourceInterface, argumentTypes.size(), node.getOptionalAssignmentExpressions().size(), function)); } } return false; } if (!ft.isLastVararg() && node.getOptionalAssignmentExpressions().size() > argumentTypes.size()) { if (callsFunction) { auto& decl = function.as<Conversion>().getExpression().as<DeclarationRead>(); log(Errors::Semantics::TOO_MANY_ARGUMENTS_FOR_CALLING_FUNCTION_N_EXPECTED_N_GOT_N.args( decl, m_sourceInterface, *decl.getIdentifierToken(), argumentTypes.size(), node.getOptionalAssignmentExpressions().size(), tcb::span(node.getOptionalAssignmentExpressions()).subspan(argumentTypes.size()))); } else { log(Errors::Semantics::TOO_MANY_ARGUMENTS_FOR_FUNCTION_CALL_EXPECTED_N_GOT_N.args( function, m_sourceInterface, argumentTypes.size(), node.getOptionalAssignmentExpressions().size(), function, tcb::span(node.getOptionalAssignmentExpressions()).subspan(argumentTypes.size()))); } return false; } return true; } cld::IntrVarPtr<cld::Semantics::ExpressionBase> cld::Semantics::SemanticAnalysis::visit(const Syntax::PostFixExpressionFunctionCall& node) { auto function = visit(node.getPostFixExpression()); if (isBuiltinKind(*function, BuiltinFunction::VAStart)) { return visitVAStart(node, std::move(function)); } if (isBuiltinKind(*function, BuiltinFunction::Prefetch)) { return visitPrefetch(node, std::move(function)); } if (isBuiltinKind(*function, BuiltinFunction::ExpectWithProbability)) { return visitExpectWithProbability(node, std::move(function)); } if (isSyncBuiltinWithType(*function)) { return visitSyncBuiltinWithT(node, std::move(function)); } if (!isBuiltinFunction(*function)) { function = lvalueConversion(std::move(function)); if (!function->getType().is<PointerType>() || !getPointerElementType(function->getType()).is<FunctionType>()) { if (!function->getType().isUndefined()) { log(Errors::Semantics::CANNOT_CALL_NON_FUNCTION_TYPE.args( *function, m_sourceInterface, *function, *node.getOpenParentheses(), *node.getCloseParentheses())); } for (auto& iter : node.getOptionalAssignmentExpressions()) { visit(iter); } return std::make_unique<ErrorExpression>(node); } } else { auto& type = function->getType(); function = std::make_unique<Conversion>(PointerType(&type), Conversion::LValue, std::move(function)); } auto& ft = getPointerElementType(function->getType()).as<FunctionType>(); std::vector<IntrVarPtr<ExpressionBase>> arguments; if (ft.isKandR()) { for (auto& iter : node.getOptionalAssignmentExpressions()) { arguments.push_back(defaultArgumentPromotion(visit(iter))); } } else { if (checkFunctionCount(*function, ft, node)) { std::size_t i = 0; for (; i < ft.getParameters().size(); i++) { arguments.push_back(checkFunctionArg(i + 1, *ft.getParameters()[i].type, visit(node.getOptionalAssignmentExpressions()[i]))); } for (; i < node.getOptionalAssignmentExpressions().size(); i++) { arguments.push_back(defaultArgumentPromotion(visit(node.getOptionalAssignmentExpressions()[i]))); } } } return std::make_unique<CallExpression>(ft.getReturnType(), std::move(function), node.getOpenParentheses(), std::move(arguments), node.getCloseParentheses()); } cld::IntrVarPtr<cld::Semantics::ExpressionBase> cld::Semantics::SemanticAnalysis::checkIncrementAndDecrement(const Syntax::Node& node, UnaryOperator::Kind kind, IntrVarPtr<ExpressionBase>&& value, Lexer::CTokenIterator opToken) { if (value->isUndefined()) { return {std::move(value)}; } if (!isScalar(value->getType())) { log(Errors::Semantics::OPERAND_OF_N_MUST_BE_AN_ARITHMETIC_OR_POINTER_TYPE.args(*value, m_sourceInterface, *opToken, *value)); return std::make_unique<ErrorExpression>(node); } if (value->getValueCategory() != ValueCategory::Lvalue || value->getType().isConst()) { log(Errors::Semantics::OPERAND_OF_OPERATOR_N_MUST_NOT_BE_A_TEMPORARY_OR_CONST.args(*value, m_sourceInterface, *opToken, *value)); } if (isArithmetic(value->getType())) { auto type = removeQualifiers(value->getType()); return std::make_unique<UnaryOperator>(std::move(type), ValueCategory::Rvalue, kind, opToken, std::move(value)); } auto& elementType = getPointerElementType(value->getType()); if (!isCompleteType(elementType)) { log(Errors::Semantics::INCOMPLETE_TYPE_N_USED_IN_POINTER_ARITHMETIC.args(*value, m_sourceInterface, elementType, *value, value->getType())); } else if (elementType.is<FunctionType>()) { log(Errors::Semantics::POINTER_TO_FUNCTION_TYPE_NOT_ALLOWED_IN_POINTER_ARITHMETIC.args( *value, m_sourceInterface, *value)); return std::make_unique<ErrorExpression>(node); } auto type = removeQualifiers(value->getType()); return std::make_unique<UnaryOperator>(std::move(type), ValueCategory::Rvalue, kind, opToken, std::move(value)); } cld::IntrVarPtr<cld::Semantics::ExpressionBase> cld::Semantics::SemanticAnalysis::visit(const Syntax::PostFixExpressionIncrement& node) { return checkIncrementAndDecrement(node, UnaryOperator::PostIncrement, visit(node.getPostFixExpression()), node.getIncrementToken()); } cld::IntrVarPtr<cld::Semantics::ExpressionBase> cld::Semantics::SemanticAnalysis::visit(const Syntax::PostFixExpressionDecrement& node) { return checkIncrementAndDecrement(node, UnaryOperator::PostDecrement, visit(node.getPostFixExpression()), node.getDecrementToken()); } cld::IntrVarPtr<cld::Semantics::ExpressionBase> cld::Semantics::SemanticAnalysis::visit(const Syntax::PostFixExpressionTypeInitializer& node) { std::vector<ParsedAttribute<>> attributes; auto type = declaratorsToType(node.getTypeName().getSpecifierQualifiers(), node.getTypeName().getAbstractDeclarator(), &attributes); if (type->isUndefined()) { visit(node.getInitializerList(), type, !inFunction() || m_inStaticInitializer); return std::make_unique<ErrorExpression>(node); } attributes = applyAttributes(std::pair{&type, diag::getPointRange(node.getTypeName())}, std::move(attributes)); reportNotApplicableAttributes(attributes); if (type->is<FunctionType>()) { log(Errors::Semantics::CANNOT_INITIALIZE_FUNCTION_TYPE.args(node.getTypeName(), m_sourceInterface, node.getTypeName(), type)); visit(node.getInitializerList(), ErrorType{}, !inFunction() || m_inStaticInitializer); return std::make_unique<ErrorExpression>(node); } if (isVariableLengthArray(type)) { log(Errors::Semantics::CANNOT_INITIALIZE_VARIABLE_LENGTH_ARRAY_TYPE.args(node.getTypeName(), m_sourceInterface, node.getTypeName(), type)); visit(node.getInitializerList(), ErrorType{}, !inFunction() || m_inStaticInitializer); return std::make_unique<ErrorExpression>(node); } Initializer value{std::make_unique<ErrorExpression>(node)}; if (type->is<AbstractArrayType>()) { std::size_t size = 0; value = visit(node.getInitializerList(), type, !inFunction() || m_inStaticInitializer, &size); auto& abstractArrayType = type->as<AbstractArrayType>(); type = ArrayType(&abstractArrayType.getType(), size, flag::useFlags = type->getFlags()); } else { value = visit(node.getInitializerList(), type, !inFunction() || m_inStaticInitializer); } return std::make_unique<CompoundLiteral>(std::move(type), node.getOpenParentheses(), std::move(value), node.getCloseParentheses(), node.getInitializerList().end(), m_inStaticInitializer); } cld::IntrVarPtr<cld::Semantics::ExpressionBase> cld::Semantics::SemanticAnalysis::visit(const Syntax::UnaryExpression& node) { return cld::match(node, [&](auto&& value) -> IntrVarPtr<ExpressionBase> { return visit(value); }); } cld::IntrVarPtr<cld::Semantics::ExpressionBase> cld::Semantics::SemanticAnalysis::visit(const Syntax::UnaryExpressionPostFixExpression& node) { return visit(node.getPostFixExpression()); } cld::IntrVarPtr<cld::Semantics::ExpressionBase> cld::Semantics::SemanticAnalysis::visit(const Syntax::UnaryExpressionUnaryOperator& node) { auto value = visit(node.getCastExpression()); if (value->isUndefined()) { return std::make_unique<ErrorExpression>(node); } switch (node.getOperator()) { case Syntax::UnaryExpressionUnaryOperator::UnaryOperator::Increment: return checkIncrementAndDecrement(node, UnaryOperator::PreIncrement, visit(node.getCastExpression()), node.getUnaryToken()); case Syntax::UnaryExpressionUnaryOperator::UnaryOperator::Decrement: return checkIncrementAndDecrement(node, UnaryOperator::PreDecrement, visit(node.getCastExpression()), node.getUnaryToken()); case Syntax::UnaryExpressionUnaryOperator::UnaryOperator::Ampersand: { if (auto* declRead = value->tryAs<DeclarationRead>()) { if (auto* decl = declRead->getDeclRead().tryAs<VariableDeclaration>(); decl && decl->getLifetime() == Lifetime::Register) { log(Errors::Semantics::CANNOT_TAKE_ADDRESS_OF_DECLARATION_ANNOTATED_WITH_REGISTER.args( *value, m_sourceInterface, *node.getUnaryToken(), *value)); } } if (auto* subscript = value->tryAs<SubscriptOperator>(); subscript && subscript->getPointerExpression().getType().is<VectorType>()) { log(Errors::Semantics::CANNOT_TAKE_ADDRESS_OF_VECTOR_ELEMENT.args(*value, m_sourceInterface, *node.getUnaryToken(), *value)); } if (isBitfieldAccess(*value)) { log(Errors::Semantics::CANNOT_TAKE_ADDRESS_OF_BITFIELD.args(*value, m_sourceInterface, *node.getUnaryToken(), *value)); } if (!value->is<CallExpression>() && value->getValueCategory() != ValueCategory::Lvalue) { log(Errors::Semantics::CANNOT_TAKE_ADDRESS_OF_TEMPORARY.args(*value, m_sourceInterface, *node.getUnaryToken(), *value)); } auto element = typeAlloc(value->getType()); return std::make_unique<UnaryOperator>(PointerType(element), ValueCategory::Rvalue, UnaryOperator::AddressOf, node.getUnaryToken(), std::move(value)); } case Syntax::UnaryExpressionUnaryOperator::UnaryOperator::Asterisk: { value = lvalueConversion(std::move(value)); if (!value->getType().isUndefined() && !value->getType().is<PointerType>()) { log(Errors::Semantics::CANNOT_DEREFERENCE_NON_POINTER_TYPE_N.args( *node.getUnaryToken(), m_sourceInterface, *node.getUnaryToken(), *value)); return std::make_unique<ErrorExpression>(node); } if (value->getType().isUndefined()) { return std::make_unique<ErrorExpression>(node); } auto& elementType = getPointerElementType(value->getType()); return std::make_unique<UnaryOperator>(elementType, ValueCategory::Lvalue, UnaryOperator::Dereference, node.getUnaryToken(), std::move(value)); } case Syntax::UnaryExpressionUnaryOperator::UnaryOperator::Minus: case Syntax::UnaryExpressionUnaryOperator::UnaryOperator::Plus: { value = integerPromotion(std::move(value)); if (!value->getType().isUndefined() && !isArithmetic(value->getType()) && !value->getType().is<VectorType>()) { log(Errors::Semantics::OPERAND_OF_OPERATOR_N_MUST_BE_AN_ARITHMETIC_TYPE.args( *node.getUnaryToken(), m_sourceInterface, *node.getUnaryToken(), *value)); return std::make_unique<ErrorExpression>(node); } IntrVarValue type = value->getType(); return std::make_unique<UnaryOperator>( type, ValueCategory::Rvalue, node.getOperator() == Syntax::UnaryExpressionUnaryOperator::UnaryOperator::Minus ? UnaryOperator::Minus : UnaryOperator::Plus, node.getUnaryToken(), std::move(value)); } break; case Syntax::UnaryExpressionUnaryOperator::UnaryOperator::BitNot: { value = integerPromotion(std::move(value)); if (!value->getType().isUndefined() && !isInteger(value->getType()) && (!value->getType().is<VectorType>() || !isInteger(getVectorElementType(value->getType())))) { log(Errors::Semantics::OPERAND_OF_OPERATOR_N_MUST_BE_AN_INTEGER_TYPE.args( *node.getUnaryToken(), m_sourceInterface, *node.getUnaryToken(), *value)); return std::make_unique<ErrorExpression>(node); } IntrVarValue type = value->getType(); return std::make_unique<UnaryOperator>(type, ValueCategory::Rvalue, UnaryOperator::BitwiseNegate, node.getUnaryToken(), std::move(value)); } case Syntax::UnaryExpressionUnaryOperator::UnaryOperator::LogicalNot: { value = integerPromotion(std::move(value)); if (!value->getType().isUndefined() && !isScalar(value->getType())) { log(Errors::Semantics::OPERAND_OF_OPERATOR_N_MUST_BE_AN_ARITHMETIC_OR_POINTER_TYPE.args( *node.getUnaryToken(), m_sourceInterface, *node.getUnaryToken(), *value)); } value = toBool(std::move(value)); return std::make_unique<UnaryOperator>(PrimitiveType(PrimitiveType::Int, getLanguageOptions()), ValueCategory::Rvalue, UnaryOperator::BooleanNegate, node.getUnaryToken(), std::move(value)); } case Syntax::UnaryExpressionUnaryOperator::UnaryOperator ::GNUExtension: return value; } CLD_UNREACHABLE; } cld::IntrVarPtr<cld::Semantics::ExpressionBase> cld::Semantics::SemanticAnalysis::visit(const Syntax::UnaryExpressionSizeOf& node) { return cld::match( node.getVariant(), [&](const std::unique_ptr<Syntax::UnaryExpression>& unaryExpression) -> IntrVarPtr<ExpressionBase> { auto exp = visit(*unaryExpression); if (exp->isUndefined()) { return std::make_unique<ErrorExpression>(node); } auto& type = exp->getType(); if (!isCompleteType(type)) { log(Errors::Semantics::INCOMPLETE_TYPE_N_IN_SIZE_OF.args(*exp, m_sourceInterface, type, *exp)); return std::make_unique<ErrorExpression>(node); } if (type.is<FunctionType>()) { log(Errors::Semantics::FUNCTION_TYPE_NOT_ALLOWED_IN_SIZE_OF.args(*exp, m_sourceInterface, *exp, type)); return std::make_unique<ErrorExpression>(node); } if (isBitfieldAccess(*exp)) { log(Errors::Semantics::BITFIELD_NOT_ALLOWED_IN_SIZE_OF.args(*exp, m_sourceInterface, *exp)); } if (!isVariableLengthArray(type)) { auto size = exp->getType().getSizeOf(*this); return std::make_unique<SizeofOperator>(getLanguageOptions(), node.getSizeOfToken(), size, std::move(exp)); } return std::make_unique<SizeofOperator>(getLanguageOptions(), node.getSizeOfToken(), std::nullopt, std::move(exp)); }, [&](const std::unique_ptr<Syntax::TypeName>& typeName) -> IntrVarPtr<ExpressionBase> { std::vector<ParsedAttribute<>> attributes; auto type = declaratorsToType(typeName->getSpecifierQualifiers(), typeName->getAbstractDeclarator(), &attributes); if (type->isUndefined()) { return std::make_unique<ErrorExpression>(node); } reportNotApplicableAttributes(attributes); if (!isCompleteType(type)) { log(Errors::Semantics::INCOMPLETE_TYPE_N_IN_SIZE_OF.args(*typeName, m_sourceInterface, type, *typeName)); return std::make_unique<ErrorExpression>(node); } if (type->is<FunctionType>()) { log(Errors::Semantics::FUNCTION_TYPE_NOT_ALLOWED_IN_SIZE_OF.args(*typeName, m_sourceInterface, *typeName, type)); return std::make_unique<ErrorExpression>(node); } if (!isVariableLengthArray(type)) { auto size = type->getSizeOf(*this); return std::make_unique<SizeofOperator>( getLanguageOptions(), node.getSizeOfToken(), size, SizeofOperator::TypeVariant{node.getSizeOfToken() + 1, std::move(type), node.end() - 1}); } return std::make_unique<SizeofOperator>( getLanguageOptions(), node.getSizeOfToken(), std::nullopt, SizeofOperator::TypeVariant{node.getSizeOfToken() + 1, std::move(type), node.end() - 1}); }); } std::unique_ptr<cld::Semantics::Constant> cld::Semantics::SemanticAnalysis::visit(const Syntax::UnaryExpressionDefined& node) { CLD_ASSERT(m_definedCallback); if (m_definedCallback(node.getIdentifier())) { return std::make_unique<Constant>(PrimitiveType(PrimitiveType::LongLong, getLanguageOptions()), llvm::APSInt(llvm::APInt(64, 1), false), node.begin(), node.end()); } return std::make_unique<Constant>(PrimitiveType(PrimitiveType::LongLong, getLanguageOptions()), llvm::APSInt(64, false), node.begin(), node.end()); } cld::IntrVarPtr<cld::Semantics::ExpressionBase> cld::Semantics::SemanticAnalysis::visit(const Syntax::CastExpression& node) { return cld::match( node.getVariant(), [&](const Syntax::UnaryExpression& unaryExpression) -> IntrVarPtr<ExpressionBase> { return visit(unaryExpression); }, [&](const Syntax::CastExpression::CastVariant& cast) -> IntrVarPtr<ExpressionBase> { std::vector<ParsedAttribute<>> attributes; auto type = declaratorsToType(cast.typeName.getSpecifierQualifiers(), cast.typeName.getAbstractDeclarator(), &attributes); if (type->isUndefined()) { visit(*cast.cast); return std::make_unique<ErrorExpression>(node); } reportNotApplicableAttributes(attributes); auto value = visit(*cast.cast); if (value->isUndefined()) { return std::make_unique<ErrorExpression>(node); } value = lvalueConversion(std::move(value)); if (isVoid(type)) { return std::make_unique<Cast>(removeQualifiers(type), cast.openParentheses, cast.closeParentheses, std::move(value)); } if (!isScalar(type) && !type->is<VectorType>()) { log(Errors::Semantics::TYPE_IN_CAST_MUST_BE_AN_ARITHMETIC_OR_POINTER_TYPE.args( cast.typeName, m_sourceInterface, cast.typeName, type)); return std::make_unique<ErrorExpression>(node); } if (!isScalar(value->getType()) && !value->getType().is<VectorType>()) { log(Errors::Semantics::EXPRESSION_IN_CAST_MUST_BE_AN_ARITHMETIC_OR_POINTER_TYPE.args( *value, m_sourceInterface, *value)); return std::make_unique<ErrorExpression>(node); } type = lvalueConversion(std::move(type)); if (type->is<VectorType>() || value->getType().is<VectorType>()) { if (type->is<VectorType>() != value->getType().is<VectorType>()) { // Only one of them is a vector if (!isInteger(type) && !isInteger(value->getType())) { if (value->getType().is<VectorType>()) { log(Errors::Semantics::CANNOT_CAST_FROM_VECTOR_TYPE_TO_NON_INTEGER_OR_VECTOR_TYPE.args( *value, m_sourceInterface, cast.typeName, type, *value)); } else { log(Errors::Semantics::CANNOT_CAST_TO_VECTOR_TYPE_FROM_NON_INTEGER_OR_VECTOR_TYPE.args( *value, m_sourceInterface, cast.typeName, type, *value)); } return std::make_unique<ErrorExpression>(node); } } auto toSize = type->getSizeOf(*this); auto fromSize = value->getType().getSizeOf(*this); if (toSize != fromSize) { auto toString = "sizeof(" + diag::StringConverter<Type>::inArg(type, &m_sourceInterface) + ") = " + std::to_string(toSize); auto fromString = "sizeof(" + diag::StringConverter<Type>::inArg(value->getType(), &m_sourceInterface) + ") = " + std::to_string(fromSize); if (type->is<VectorType>()) { log(Errors::Semantics::CANNOT_CAST_TO_VECTOR_TYPE_FROM_TYPE_OF_DIFFERING_SIZE.args( *value, m_sourceInterface, cast.typeName, toString, *value, fromString)); } else { log(Errors::Semantics::CANNOT_CAST_FROM_VECTOR_TYPE_TO_TYPE_OF_DIFFERING_SIZE.args( *value, m_sourceInterface, cast.typeName, toString, *value, fromString)); } return std::make_unique<ErrorExpression>(node); } } else if (type->is<PointerType>()) { if (!value->getType().is<PointerType>() && !isInteger(value->getType())) { log(Errors::Semantics::CANNOT_CAST_NON_INTEGER_AND_POINTER_TYPE_N_TO_POINTER_TYPE.args( *value, m_sourceInterface, *value)); return std::make_unique<ErrorExpression>(node); } } else if (value->getType().is<PointerType>()) { if (!type->is<PointerType>() && !isInteger(type)) { log(Errors::Semantics::CANNOT_CAST_POINTER_TYPE_TO_NON_INTEGER_AND_POINTER_TYPE.args( cast.typeName, m_sourceInterface, cast.typeName, *value)); return std::make_unique<ErrorExpression>(node); } } return std::make_unique<Cast>(std::move(type), cast.openParentheses, cast.closeParentheses, std::move(value)); }); } bool cld::Semantics::SemanticAnalysis::checkVectorBinaryOp(const IntrVarPtr<ExpressionBase>& lhs, Lexer::CTokenIterator token, const IntrVarPtr<ExpressionBase>& rhs) { if (lhs->getType().is<VectorType>() || rhs->getType().is<VectorType>()) { if (lhs->getType().is<VectorType>() && rhs->getType().is<VectorType>()) { if (rhs->getType() != lhs->getType()) { log(Errors::Semantics::TYPE_OF_VECTOR_OPERANDS_OF_BINARY_OPERATOR_N_MUST_MATCH.args( *token, m_sourceInterface, *token, *lhs, *rhs)); return true; } } else { log(Errors::Semantics::CONVERSION_OF_SCALAR_IN_VECTOR_OPERATION_COULD_CAUSE_TRUNCATION.args( *token, m_sourceInterface, *lhs, *rhs)); return true; } } return false; } cld::IntrVarPtr<cld::Semantics::ExpressionBase> cld::Semantics::SemanticAnalysis::visit(const Syntax::Term& node) { auto value = visit(node.getCastExpression()); if (node.getOptionalCastExpressions().empty()) { return value; } for (auto& [kind, token, rhs] : node.getOptionalCastExpressions()) { auto rhsValue = visit(rhs); switch (kind) { case Syntax::Term::BinaryDivide: case Syntax::Term::BinaryMultiply: { arithmeticConversion(&value, rhsValue); bool errors = false; if (!value->isUndefined() && !isArithmetic(value->getType()) && !value->getType().is<VectorType>()) { log(Errors::Semantics::LEFT_OPERAND_OF_OPERATOR_N_MUST_BE_AN_ARITHMETIC_TYPE.args( *value, m_sourceInterface, *token, *value)); errors = true; } if (!rhsValue->isUndefined() && !isArithmetic(rhsValue->getType()) && !value->getType().is<VectorType>()) { log(Errors::Semantics::RIGHT_OPERAND_OF_OPERATOR_N_MUST_BE_AN_ARITHMETIC_TYPE.args( *rhsValue, m_sourceInterface, *token, *rhsValue)); errors = true; } errors = checkVectorBinaryOp(value, token, rhsValue) || errors; if (value->isUndefined() || rhsValue->isUndefined() || errors) { value = std::make_unique<ErrorExpression>(value->begin(), rhsValue->end()); continue; } IntrVarValue type = value->getType(); value = std::make_unique<BinaryOperator>(type, std::move(value), kind == Syntax::Term::BinaryDivide ? BinaryOperator::Divide : BinaryOperator::Multiply, token, std::move(rhsValue)); continue; } case Syntax::Term::BinaryModulo: { arithmeticConversion(&value, rhsValue); bool errors = false; if (!value->isUndefined() && !isInteger(value->getType()) && (!value->getType().is<VectorType>() || !isInteger(getVectorElementType(value->getType())))) { log(Errors::Semantics::LEFT_OPERAND_OF_OPERATOR_N_MUST_BE_AN_INTEGER_TYPE.args( *value, m_sourceInterface, *token, *value)); errors = true; } if (!rhsValue->isUndefined() && !isInteger(rhsValue->getType()) && (!value->getType().is<VectorType>() || !isInteger(getVectorElementType(value->getType())))) { log(Errors::Semantics::RIGHT_OPERAND_OF_OPERATOR_N_MUST_BE_AN_INTEGER_TYPE.args( *rhsValue, m_sourceInterface, *token, *rhsValue)); errors = true; } errors = checkVectorBinaryOp(value, token, rhsValue) || errors; if (value->isUndefined() || rhsValue->isUndefined() || errors) { value = std::make_unique<ErrorExpression>(value->begin(), rhsValue->end()); continue; } IntrVarValue type = value->getType(); value = std::make_unique<BinaryOperator>(type, std::move(value), BinaryOperator::Modulo, token, std::move(rhsValue)); continue; } } } return value; } cld::IntrVarPtr<cld::Semantics::ExpressionBase> cld::Semantics::SemanticAnalysis::visit(const Syntax::AdditiveExpression& node) { auto value = visit(node.getTerm()); if (node.getOptionalTerms().empty()) { return value; } for (auto& [kind, token, rhs] : node.getOptionalTerms()) { auto rhsValue = visit(rhs); if ((isArithmetic(value->getType()) && isArithmetic(rhsValue->getType())) || value->getType().is<VectorType>() || rhsValue->getType().is<VectorType>()) { arithmeticConversion(&value, rhsValue); } else { value = lvalueConversion(std::move(value)); rhsValue = lvalueConversion(std::move(rhsValue)); } bool errors = false; if (!value->getType().isUndefined() && !isScalar(value->getType()) && !value->getType().is<VectorType>()) { log(Errors::Semantics::LEFT_OPERAND_OF_OPERATOR_N_MUST_BE_AN_ARITHMETIC_OR_POINTER_TYPE.args( *value, m_sourceInterface, *token, *value)); errors = true; } if (!rhsValue->getType().isUndefined() && !isScalar(rhsValue->getType()) && !value->getType().is<VectorType>()) { log(Errors::Semantics::RIGHT_OPERAND_OF_OPERATOR_N_MUST_BE_AN_ARITHMETIC_OR_POINTER_TYPE.args( *rhsValue, m_sourceInterface, *token, *rhsValue)); errors = true; } if ((value->getType().is<VectorType>() && rhsValue->getType().is<PointerType>()) || (value->getType().is<PointerType>() && rhsValue->getType().is<VectorType>())) { log(Errors::Semantics::POINTER_ARITHMETIC_WITH_VECTORS_IS_NOT_ALLOWED.args(*token, m_sourceInterface, *value, *token, *rhsValue)); errors = true; } else { errors = checkVectorBinaryOp(value, token, rhsValue) || errors; } if (value->getType().isUndefined() || rhsValue->getType().isUndefined() || errors) { value = std::make_unique<ErrorExpression>(value->begin(), rhsValue->end()); continue; } switch (kind) { case Syntax::AdditiveExpression::BinaryMinus: { if (isArithmetic(value->getType()) && isArithmetic(rhsValue->getType())) { IntrVarValue type = value->getType(); value = std::make_unique<BinaryOperator>(std::move(type), std::move(value), BinaryOperator::Subtraction, token, std::move(rhsValue)); continue; } if (value->getType().is<VectorType>()) { IntrVarValue type = value->getType(); value = std::make_unique<BinaryOperator>(std::move(type), std::move(value), BinaryOperator::Subtraction, token, std::move(rhsValue)); continue; } if (isArithmetic(value->getType()) && rhsValue->getType().is<PointerType>()) { log(Errors::Semantics::CANNOT_SUBTRACT_POINTER_FROM_ARITHMETIC_TYPE.args( *value, m_sourceInterface, *value, *token, *rhsValue)); IntrVarValue type = rhsValue->getType(); value = std::make_unique<BinaryOperator>(std::move(type), std::move(value), BinaryOperator::Subtraction, token, std::move(rhsValue)); continue; } // value is guaranteed to be a pointer type now, rhsValue is a scalar auto& valueElementType = getPointerElementType(value->getType()); if (!isCompleteType(valueElementType)) { log(Errors::Semantics::INCOMPLETE_TYPE_N_USED_IN_POINTER_ARITHMETIC.args( *value, m_sourceInterface, valueElementType, *value, value->getType())); } else if (valueElementType.is<FunctionType>()) { log(Errors::Semantics::POINTER_TO_FUNCTION_TYPE_NOT_ALLOWED_IN_POINTER_ARITHMETIC.args( *value, m_sourceInterface, *value)); } if (rhsValue->getType().is<PointerType>()) { auto& rhsElementType = getPointerElementType(rhsValue->getType()); if (!isCompleteType(rhsElementType)) { log(Errors::Semantics::INCOMPLETE_TYPE_N_USED_IN_POINTER_ARITHMETIC.args( *rhsValue, m_sourceInterface, rhsElementType, *rhsValue, rhsValue->getType())); } else if (rhsElementType.is<FunctionType>()) { log(Errors::Semantics::POINTER_TO_FUNCTION_TYPE_NOT_ALLOWED_IN_POINTER_ARITHMETIC.args( *rhsValue, m_sourceInterface, *rhsValue)); } if (!typesAreCompatible(*removeQualifiers(valueElementType), *removeQualifiers(rhsElementType))) { log(Errors::Semantics::CANNOT_SUBTRACT_POINTERS_OF_INCOMPATIBLE_TYPES.args( *value, m_sourceInterface, *value, *token, *rhsValue)); } value = std::make_unique<BinaryOperator>( PrimitiveType(getLanguageOptions().ptrdiffType, getLanguageOptions()), std::move(value), BinaryOperator::Subtraction, token, std::move(rhsValue)); } else { if (!isInteger(rhsValue->getType())) { log(Errors::Semantics::EXPECTED_RIGHT_OPERAND_OF_OPERATOR_N_TO_BE_AN_INTEGER_TYPE.args( *rhsValue, m_sourceInterface, *token, *rhsValue)); } IntrVarValue type = value->getType(); value = std::make_unique<BinaryOperator>(std::move(type), std::move(value), BinaryOperator::Subtraction, token, std::move(rhsValue)); } continue; } case Syntax::AdditiveExpression::BinaryPlus: { if (isArithmetic(value->getType()) && isArithmetic(rhsValue->getType())) { IntrVarValue type = value->getType(); value = std::make_unique<BinaryOperator>(std::move(type), std::move(value), BinaryOperator::Addition, token, std::move(rhsValue)); continue; } if (value->getType().is<VectorType>()) { IntrVarValue type = value->getType(); value = std::make_unique<BinaryOperator>(std::move(type), std::move(value), BinaryOperator::Addition, token, std::move(rhsValue)); continue; } auto& pointerExpr = value->getType().is<PointerType>() ? value : rhsValue; auto& intExpr = &pointerExpr == &value ? rhsValue : value; if (!isInteger(intExpr->getType())) { log(Errors::Semantics::EXPECTED_OTHER_OPERAND_OF_OPERATOR_N_TO_BE_OF_INTEGER_TYPE.args( *intExpr, m_sourceInterface, *token, *intExpr)); } auto& elementType = getPointerElementType(pointerExpr->getType()); if (!isCompleteType(elementType)) { log(Errors::Semantics::INCOMPLETE_TYPE_N_USED_IN_POINTER_ARITHMETIC.args( *pointerExpr, m_sourceInterface, elementType, *pointerExpr, pointerExpr->getType())); } else if (elementType.is<FunctionType>()) { log(Errors::Semantics::POINTER_TO_FUNCTION_TYPE_NOT_ALLOWED_IN_POINTER_ARITHMETIC.args( *pointerExpr, m_sourceInterface, *pointerExpr)); } IntrVarValue type = pointerExpr->getType(); value = std::make_unique<BinaryOperator>(std::move(type), std::move(value), BinaryOperator::Addition, token, std::move(rhsValue)); continue; } } } return value; } cld::IntrVarPtr<cld::Semantics::ExpressionBase> cld::Semantics::SemanticAnalysis::visit(const Syntax::ShiftExpression& node) { auto value = visit(node.getAdditiveExpression()); if (node.getOptionalAdditiveExpressions().empty()) { return value; } value = integerPromotion(std::move(value)); for (auto& [kind, token, rhs] : node.getOptionalAdditiveExpressions()) { auto rhsValue = visit(rhs); if (value->getType().is<VectorType>() || rhsValue->getType().is<VectorType>()) { arithmeticConversion(&value, rhsValue); } else { rhsValue = integerPromotion(std::move(rhsValue)); } bool errors = false; if (!value->getType().isUndefined() && !isInteger(value->getType()) && (!value->getType().is<VectorType>() || !isInteger(getVectorElementType(value->getType())))) { log(Errors::Semantics::LEFT_OPERAND_OF_OPERATOR_N_MUST_BE_AN_INTEGER_TYPE.args(*value, m_sourceInterface, *token, *value)); errors = true; } if (!rhsValue->getType().isUndefined() && !isInteger(rhsValue->getType()) && (!rhsValue->getType().is<VectorType>() || !isInteger(getVectorElementType(rhsValue->getType())))) { log(Errors::Semantics::RIGHT_OPERAND_OF_OPERATOR_N_MUST_BE_AN_INTEGER_TYPE.args( *rhsValue, m_sourceInterface, *token, *rhsValue)); errors = true; } errors = checkVectorBinaryOp(value, token, rhsValue) || errors; if (value->getType().isUndefined() || rhsValue->getType().isUndefined() || errors) { value = std::make_unique<ErrorExpression>(value->begin(), rhsValue->end()); continue; } IntrVarValue type = value->getType(); value = std::make_unique<BinaryOperator>(std::move(type), std::move(value), kind == Syntax::ShiftExpression::Left ? BinaryOperator::LeftShift : BinaryOperator::RightShift, token, std::move(rhsValue)); continue; } return value; } cld::Semantics::VectorType cld::Semantics::SemanticAnalysis::vectorCompResultType(const VectorType& vectorType, const LanguageOptions& options) { auto elementCount = vectorType.getSize(); if (isInteger(getVectorElementType(vectorType))) { switch (getVectorElementType(vectorType).as<PrimitiveType>().getKind()) { case PrimitiveType::Char: if (options.charIsSigned) { return vectorType; } [[fallthrough]]; case PrimitiveType::UnsignedChar: return VectorType(typeAlloc<PrimitiveType>(PrimitiveType::SignedChar, options), elementCount); case PrimitiveType::UnsignedShort: return VectorType(typeAlloc<PrimitiveType>(PrimitiveType::Short, options), elementCount); case PrimitiveType::UnsignedInt: return VectorType(typeAlloc<PrimitiveType>(PrimitiveType::Int, options), elementCount); case PrimitiveType::UnsignedLong: return VectorType(typeAlloc<PrimitiveType>(PrimitiveType::Long, options), elementCount); case PrimitiveType::UnsignedLongLong: return VectorType(typeAlloc<PrimitiveType>(PrimitiveType::LongLong, options), elementCount); default: return vectorType; } } auto bitWidth = getVectorElementType(vectorType).as<PrimitiveType>().getBitCount(); if (bitWidth == options.sizeOfShort * 8) { return VectorType(typeAlloc<PrimitiveType>(PrimitiveType::Short, options), elementCount); } if (bitWidth == options.sizeOfInt * 8) { return VectorType(typeAlloc<PrimitiveType>(PrimitiveType::Int, options), elementCount); } if (bitWidth == options.sizeOfLong * 8) { return VectorType(typeAlloc<PrimitiveType>(PrimitiveType::Long, options), elementCount); } if (bitWidth == 64) { return VectorType(typeAlloc<PrimitiveType>(PrimitiveType::LongLong, options), elementCount); } CLD_UNREACHABLE; } cld::IntrVarPtr<cld::Semantics::ExpressionBase> cld::Semantics::SemanticAnalysis::visit(const Syntax::RelationalExpression& node) { auto value = visit(node.getShiftExpression()); if (node.getOptionalShiftExpressions().empty()) { return value; } for (auto& [kind, token, rhs] : node.getOptionalShiftExpressions()) { IntrVarValue resultType = PrimitiveType(PrimitiveType::Int, getLanguageOptions()); auto rhsValue = visit(rhs); if ((isArithmetic(value->getType()) && isArithmetic(rhsValue->getType())) || value->getType().is<VectorType>() || rhsValue->getType().is<VectorType>()) { arithmeticConversion(&value, rhsValue); } else { value = lvalueConversion(std::move(value)); rhsValue = lvalueConversion(std::move(rhsValue)); } if (!value->isUndefined() && !isScalar(value->getType()) && !value->getType().is<VectorType>()) { log(Errors::Semantics::LEFT_OPERAND_OF_OPERATOR_N_MUST_BE_AN_ARITHMETIC_OR_POINTER_TYPE.args( *value, m_sourceInterface, *token, *value)); } else if (isArithmetic(value->getType()) && !rhsValue->getType().is<VectorType>()) { if (!rhsValue->isUndefined() && !isArithmetic(rhsValue->getType())) { log(Errors::Semantics::EXPECTED_RIGHT_OPERAND_OF_OPERATOR_N_TO_BE_AN_ARITHMETIC_TYPE.args( *rhsValue, m_sourceInterface, *token, *rhsValue)); } } else if (value->getType().is<PointerType>()) { if (!rhsValue->isUndefined() && !rhsValue->getType().is<PointerType>()) { log(Errors::Semantics::EXPECTED_RIGHT_OPERAND_OF_OPERATOR_N_TO_BE_A_POINTER_TYPE.args( *rhsValue, m_sourceInterface, *token, *rhsValue)); } else if (!rhsValue->isUndefined()) { auto rhsElementType = removeQualifiers(getPointerElementType(rhsValue->getType())); auto valueElementType = removeQualifiers(getPointerElementType(value->getType())); if (valueElementType->is<FunctionType>()) { log(Errors::Semantics::POINTER_TO_FUNCTION_TYPE_NOT_ALLOWED_IN_POINTER_ARITHMETIC.args( *value, m_sourceInterface, *value)); if (rhsElementType->is<FunctionType>()) { log(Errors::Semantics::POINTER_TO_FUNCTION_TYPE_NOT_ALLOWED_IN_POINTER_ARITHMETIC.args( *rhsValue, m_sourceInterface, *rhsValue)); } } else { if (rhsElementType->is<FunctionType>()) { log(Errors::Semantics::POINTER_TO_FUNCTION_TYPE_NOT_ALLOWED_IN_POINTER_ARITHMETIC.args( *rhsValue, m_sourceInterface, *rhsValue)); } else if (!typesAreCompatible(valueElementType, rhsElementType)) { log(Errors::Semantics::CANNOT_COMPARE_POINTERS_OF_INCOMPATIBLE_TYPES.args( *value, m_sourceInterface, *value, *token, *rhsValue)); } } } } else if (value->getType().is<VectorType>() || rhsValue->getType().is<VectorType>()) { if (checkVectorBinaryOp(value, token, rhsValue)) { value = std::make_unique<ErrorExpression>(value->begin(), rhsValue->end()); continue; } resultType = vectorCompResultType(value->getType().as<VectorType>(), getLanguageOptions()); } value = std::make_unique<BinaryOperator>( std::move(resultType), std::move(value), [kind = kind] { switch (kind) { case Syntax::RelationalExpression::GreaterThan: return BinaryOperator::GreaterThan; case Syntax::RelationalExpression::GreaterThanOrEqual: return BinaryOperator::GreaterOrEqual; case Syntax::RelationalExpression::LessThan: return BinaryOperator::LessThan; case Syntax::RelationalExpression::LessThanOrEqual: return BinaryOperator::LessOrEqual; } CLD_UNREACHABLE; }(), token, std::move(rhsValue)); } return value; } cld::IntrVarPtr<cld::Semantics::ExpressionBase> cld::Semantics::SemanticAnalysis::visit(const Syntax::EqualityExpression& node) { auto value = visit(node.getRelationalExpression()); if (node.getOptionalRelationalExpressions().empty()) { return value; } for (auto& [kind, token, rhs] : node.getOptionalRelationalExpressions()) { IntrVarValue resultType = PrimitiveType(PrimitiveType::Int, getLanguageOptions()); auto rhsValue = visit(rhs); if ((isArithmetic(value->getType()) && isArithmetic(rhsValue->getType())) || value->getType().is<VectorType>() || rhsValue->getType().is<VectorType>()) { arithmeticConversion(&value, rhsValue); } else { value = lvalueConversion(std::move(value)); rhsValue = lvalueConversion(std::move(rhsValue)); } if (!value->isUndefined() && !isScalar(value->getType()) && !value->getType().is<VectorType>()) { log(Errors::Semantics::LEFT_OPERAND_OF_OPERATOR_N_MUST_BE_AN_ARITHMETIC_OR_POINTER_TYPE.args( *value, m_sourceInterface, *token, *value)); } else if (isArithmetic(value->getType()) && !rhsValue->getType().is<VectorType>()) { if (rhsValue->getType().is<PointerType>() && isInteger(value->getType())) { auto constant = evaluateConstantExpression(*value); if (!constant || constant->getInteger() != 0) { log(Errors::Semantics::EXPECTED_RIGHT_OPERAND_OF_OPERATOR_N_TO_BE_AN_ARITHMETIC_TYPE.args( *rhsValue, m_sourceInterface, *token, *rhsValue)); } value = std::make_unique<Conversion>(rhsValue->getType(), Conversion::Implicit, std::move(value)); } else if (!rhsValue->isUndefined() && !isArithmetic(rhsValue->getType())) { log(Errors::Semantics::EXPECTED_RIGHT_OPERAND_OF_OPERATOR_N_TO_BE_AN_ARITHMETIC_TYPE.args( *rhsValue, m_sourceInterface, *token, *rhsValue)); } } else if (value->getType().is<PointerType>()) { if (auto npc = checkPointerOperandsForNPC(*rhsValue, value->getType()); !npc || *npc != NPCCheck::WrongType) { if (!npc) { log(Errors::Semantics::EXPECTED_RIGHT_OPERAND_OF_OPERATOR_N_TO_BE_NULL.args( *rhsValue, m_sourceInterface, *token, *rhsValue, npc.error())); } else { switch (*npc) { case NPCCheck::NotConstExpr: log(Errors::Semantics::EXPECTED_RIGHT_OPERAND_OF_OPERATOR_N_TO_BE_NULL_2.args( *rhsValue, m_sourceInterface, *token, *rhsValue)); break; default: break; } } rhsValue = std::make_unique<Conversion>(value->getType(), Conversion::Implicit, std::move(rhsValue)); } else if (!rhsValue->isUndefined() && !rhsValue->getType().is<PointerType>()) { log(Errors::Semantics::EXPECTED_RIGHT_OPERAND_OF_OPERATOR_N_TO_BE_A_POINTER_TYPE.args( *rhsValue, m_sourceInterface, *token, *rhsValue)); } else if (!rhsValue->isUndefined()) { auto valueElementType = removeQualifiers(getPointerElementType(value->getType())); auto rhsElementType = removeQualifiers(getPointerElementType(rhsValue->getType())); if (!isVoid(valueElementType) && !isVoid(rhsElementType)) { if (!typesAreCompatible(valueElementType, rhsElementType)) { log(Errors::Semantics::CANNOT_COMPARE_POINTERS_OF_INCOMPATIBLE_TYPES.args( *value, m_sourceInterface, *value, *token, *rhsValue)); } } else { if (isVoid(valueElementType)) { if (rhsElementType->is<FunctionType>()) { if (npc = checkNullPointerConstant(*value), !npc || *npc != NPCCheck::Success) { if (!npc) { log(Errors::Semantics::EXPECTED_LEFT_OPERAND_OF_OPERATOR_N_TO_BE_NULL.args( *value, m_sourceInterface, *token, *value, npc.error())); } else { log(Errors::Semantics::CANNOT_COMPARE_POINTERS_OF_INCOMPATIBLE_TYPES.args( *value, m_sourceInterface, *value, *token, *rhsValue)); } } else { value = std::make_unique<Conversion>(rhsValue->getType(), Conversion::Implicit, std::move(value)); } } else { value = std::make_unique<Conversion>(rhsValue->getType(), Conversion::Implicit, std::move(value)); } } else { if (valueElementType->is<FunctionType>()) { log(Errors::Semantics::CANNOT_COMPARE_POINTERS_OF_INCOMPATIBLE_TYPES.args( *value, m_sourceInterface, *value, *token, *rhsValue)); } else { rhsValue = std::make_unique<Conversion>(value->getType(), Conversion::Implicit, std::move(rhsValue)); } } } } } else if (value->getType().is<VectorType>() || rhsValue->getType().is<VectorType>()) { if (checkVectorBinaryOp(value, token, rhsValue)) { value = std::make_unique<ErrorExpression>(value->begin(), rhsValue->end()); continue; } resultType = vectorCompResultType(value->getType().as<VectorType>(), getLanguageOptions()); } value = std::make_unique<BinaryOperator>(std::move(resultType), std::move(value), kind == Syntax::EqualityExpression::Equal ? BinaryOperator::Equal : BinaryOperator::NotEqual, token, std::move(rhsValue)); } return value; } std::unique_ptr<cld::Semantics::BinaryOperator> cld::Semantics::SemanticAnalysis::doBitOperators(IntrVarPtr<ExpressionBase>&& lhs, BinaryOperator::Kind kind, Lexer::CTokenIterator token, IntrVarPtr<ExpressionBase>&& rhs) { if ((isArithmetic(lhs->getType()) && isArithmetic(rhs->getType())) || lhs->getType().is<VectorType>() || rhs->getType().is<VectorType>()) { arithmeticConversion(&lhs, rhs); } bool errors = false; if (!lhs->isUndefined() && !isInteger(lhs->getType()) && (!lhs->getType().is<VectorType>() || !isInteger(getVectorElementType(lhs->getType())))) { log(Errors::Semantics::LEFT_OPERAND_OF_OPERATOR_N_MUST_BE_AN_INTEGER_TYPE.args(*lhs, m_sourceInterface, *token, *lhs)); errors = true; } if (!rhs->isUndefined() && !isInteger(rhs->getType()) && (!rhs->getType().is<VectorType>() || !isInteger(getVectorElementType(rhs->getType())))) { log(Errors::Semantics::RIGHT_OPERAND_OF_OPERATOR_N_MUST_BE_AN_INTEGER_TYPE.args(*rhs, m_sourceInterface, *token, *rhs)); errors = true; } errors = checkVectorBinaryOp(lhs, token, rhs) || errors; if (errors) { return std::make_unique<BinaryOperator>(ErrorType{}, std::move(lhs), kind, token, std::move(rhs)); } IntrVarValue type = lhs->getType(); return std::make_unique<BinaryOperator>(std::move(type), std::move(lhs), kind, token, std::move(rhs)); } cld::IntrVarPtr<cld::Semantics::ExpressionBase> cld::Semantics::SemanticAnalysis::visit(const Syntax::BitAndExpression& node) { auto value = visit(node.getEqualityExpression()); if (node.getOptionalEqualityExpressions().empty()) { return value; } for (auto& [token, rhs] : node.getOptionalEqualityExpressions()) { value = doBitOperators(std::move(value), BinaryOperator::BitAnd, token, visit(rhs)); } return value; } cld::IntrVarPtr<cld::Semantics::ExpressionBase> cld::Semantics::SemanticAnalysis::visit(const Syntax::BitXorExpression& node) { auto value = visit(node.getBitAndExpression()); if (node.getOptionalBitAndExpressions().empty()) { return value; } for (auto& [token, rhs] : node.getOptionalBitAndExpressions()) { value = doBitOperators(std::move(value), BinaryOperator::BitXor, token, visit(rhs)); } return value; } cld::IntrVarPtr<cld::Semantics::ExpressionBase> cld::Semantics::SemanticAnalysis::visit(const Syntax::BitOrExpression& node) { auto value = visit(node.getBitXorExpression()); if (node.getOptionalBitXorExpressions().empty()) { return value; } for (auto& [token, rhs] : node.getOptionalBitXorExpressions()) { value = doBitOperators(std::move(value), BinaryOperator::BitOr, token, visit(rhs)); } return value; } std::unique_ptr<cld::Semantics::BinaryOperator> cld::Semantics::SemanticAnalysis::doLogicOperators(IntrVarPtr<ExpressionBase>&& lhs, BinaryOperator::Kind kind, Lexer::CTokenIterator token, IntrVarPtr<ExpressionBase>&& rhs) { lhs = lvalueConversion(std::move(lhs)); rhs = lvalueConversion(std::move(rhs)); if (!lhs->isUndefined() && !isScalar(lhs->getType())) { log(Errors::Semantics::LEFT_OPERAND_OF_OPERATOR_N_MUST_BE_AN_ARITHMETIC_OR_POINTER_TYPE.args( *lhs, m_sourceInterface, *token, *lhs)); } if (!rhs->isUndefined() && !isScalar(rhs->getType())) { log(Errors::Semantics::RIGHT_OPERAND_OF_OPERATOR_N_MUST_BE_AN_ARITHMETIC_OR_POINTER_TYPE.args( *rhs, m_sourceInterface, *token, *rhs)); } lhs = toBool(std::move(lhs)); rhs = toBool(std::move(rhs)); return std::make_unique<BinaryOperator>(PrimitiveType(PrimitiveType::Int, getLanguageOptions()), std::move(lhs), kind, token, std::move(rhs)); } cld::IntrVarPtr<cld::Semantics::ExpressionBase> cld::Semantics::SemanticAnalysis::visit(const Syntax::LogicalAndExpression& node) { auto value = visit(node.getBitOrExpression()); if (node.getOptionalBitOrExpressions().empty()) { return value; } for (auto& [token, rhs] : node.getOptionalBitOrExpressions()) { value = doLogicOperators(std::move(value), BinaryOperator::LogicAnd, token, visit(rhs)); } return value; } cld::IntrVarPtr<cld::Semantics::ExpressionBase> cld::Semantics::SemanticAnalysis::visit(const Syntax::LogicalOrExpression& node) { auto value = visit(node.getAndExpression()); if (node.getOptionalAndExpressions().empty()) { return value; } for (auto& [token, rhs] : node.getOptionalAndExpressions()) { value = doLogicOperators(std::move(value), BinaryOperator::LogicOr, token, visit(rhs)); } return value; } cld::IntrVarPtr<cld::Semantics::ExpressionBase> cld::Semantics::SemanticAnalysis::visit(const Syntax::ConditionalExpression& node) { auto condition = visit(node.getLogicalOrExpression()); if (!node.getOptionalConditionalExpression() && !node.getOptionalExpression() && !node.getOptionalQuestionMark() && !node.getOptionalColon()) { return condition; } condition = lvalueConversion(std::move(condition)); if (!condition->isUndefined() && !isScalar(condition->getType())) { log(Errors::Semantics::FIRST_OPERAND_OF_CONDITIONAL_EXPRESSION_MUST_BE_AN_ARITHMETIC_OR_POINTER_TYPE.args( *condition, m_sourceInterface, *condition, *node.getOptionalQuestionMark(), *node.getOptionalColon())); } condition = toBool(std::move(condition)); auto second = visit(*node.getOptionalExpression()); auto third = visit(*node.getOptionalConditionalExpression()); if ((isArithmetic(second->getType()) && isArithmetic(third->getType())) || second->getType().is<VectorType>() || third->getType().is<VectorType>()) { arithmeticConversion(&second, third); } else { second = lvalueConversion(std::move(second)); third = lvalueConversion(std::move(third)); } IntrVarValue resultType = ErrorType{}; if (isArithmetic(second->getType()) && !third->getType().is<VectorType>()) { if (third->getType().is<PointerType>() && isInteger(second->getType())) { auto constant = evaluateConstantExpression(*second); if (!constant || constant->getInteger() != 0) { log(Errors::Semantics::EXPECTED_THIRD_OPERAND_OF_CONDITIONAL_EXPRESSION_TO_BE_AN_ARITHMETIC_TYPE.args( *third, m_sourceInterface, *third, *node.getOptionalQuestionMark(), *node.getOptionalColon())); } second = std::make_unique<Conversion>(third->getType(), Conversion::Implicit, std::move(second)); } else if (!third->isUndefined() && !isArithmetic(third->getType())) { log(Errors::Semantics::EXPECTED_THIRD_OPERAND_OF_CONDITIONAL_EXPRESSION_TO_BE_AN_ARITHMETIC_TYPE.args( *third, m_sourceInterface, *third, *node.getOptionalQuestionMark(), *node.getOptionalColon())); } resultType = third->getType(); } else if (isVoid(second->getType())) { if (!third->isUndefined() && !isVoid(third->getType())) { log(Errors::Semantics::EXPECTED_THIRD_OPERAND_OF_CONDITIONAL_EXPRESSION_TO_BE_VOID.args( *third, m_sourceInterface, *third, *node.getOptionalQuestionMark(), *node.getOptionalColon())); } resultType = second->getType(); } else if (second->getType().is<PointerType>()) { if (auto npc = checkPointerOperandsForNPC(*third, second->getType()); !npc || *npc != NPCCheck::WrongType) { if (!npc) { log(Errors::Semantics::EXPECTED_THIRD_OPERAND_OF_CONDITIONAL_EXPRESSION_TO_BE_NULL.args( *third, m_sourceInterface, *third, npc.error(), *node.getOptionalQuestionMark(), *node.getOptionalColon())); } else { switch (*npc) { case NPCCheck::NotConstExpr: log(Errors::Semantics::EXPECTED_THIRD_OPERAND_OF_CONDITIONAL_EXPRESSION_TO_BE_NULL_2.args( *third, m_sourceInterface, *third, *node.getOptionalQuestionMark(), *node.getOptionalColon())); break; default: break; } } third = std::make_unique<Conversion>(second->getType(), Conversion::Implicit, std::move(third)); resultType = second->getType(); } else if (!third->isUndefined() && !third->getType().is<PointerType>()) { log(Errors::Semantics::EXPECTED_THIRD_OPERAND_OF_CONDITIONAL_EXPRESSION_TO_BE_A_POINTER_TYPE.args( *third, m_sourceInterface, *third, *node.getOptionalQuestionMark(), *node.getOptionalColon())); } else if (!third->isUndefined()) { auto& secondElementType = getPointerElementType(second->getType()); auto& thirdElementType = getPointerElementType(third->getType()); auto secondWithoutQualifier = removeQualifiers(secondElementType); auto thirdWithoutQualifier = removeQualifiers(thirdElementType); if (!isVoid(secondWithoutQualifier) && !isVoid(thirdWithoutQualifier) && !typesAreCompatible(secondWithoutQualifier, thirdWithoutQualifier)) { log(Errors::Semantics::POINTER_TYPES_IN_CONDITIONAL_EXPRESSION_MUST_BE_OF_COMPATIBLE_TYPES.args( *node.getOptionalQuestionMark(), m_sourceInterface, *node.getOptionalQuestionMark(), *second, *node.getOptionalColon(), *third)); } else if (isVoid(secondWithoutQualifier) || isVoid(*thirdWithoutQualifier)) { resultType.emplace<PointerType>(typeAlloc<PrimitiveType>( PrimitiveType::Void, getLanguageOptions(), flag::isConst = secondElementType.isConst() || thirdElementType.isConst(), flag::isVolatile = secondElementType.isVolatile() || thirdElementType.isVolatile())); } else { IntrVarValue composite = compositeType(secondWithoutQualifier, thirdWithoutQualifier); composite->setConst(secondElementType.isConst() || thirdElementType.isConst()); composite->setVolatile(secondElementType.isVolatile() || thirdElementType.isVolatile()); resultType.emplace<PointerType>(typeAlloc(std::move(*composite))); } } } else if (isRecord(second->getType()) && !third->isUndefined()) { if (!typesAreCompatible(second->getType(), third->getType())) { log(Errors::Semantics::TYPES_IN_CONDITIONAL_EXPRESSION_MUST_BE_OF_COMPATIBLE_TYPES.args( *node.getOptionalQuestionMark(), m_sourceInterface, *node.getOptionalQuestionMark(), *second, *node.getOptionalColon(), *third)); } else { resultType = second->getType(); } } else if (second->getType().is<VectorType>() || third->getType().is<VectorType>()) { if (second->getType().is<VectorType>() && third->getType().is<VectorType>()) { if (second->getType() != third->getType()) { log(Errors::Semantics::TYPE_OF_VECTOR_OPERANDS_IN_CONDITIONAL_OPERATOR_MUST_MATCH.args( *node.getOptionalQuestionMark(), m_sourceInterface, *node.getOptionalQuestionMark(), *second, *node.getOptionalColon(), *third)); } } else { log(Errors::Semantics::CONVERSION_OF_SCALAR_IN_VECTOR_OPERATION_COULD_CAUSE_TRUNCATION.args( *node.getOptionalColon(), m_sourceInterface, *second, *third)); } } return std::make_unique<Conditional>(resultType, std::move(condition), node.getOptionalQuestionMark(), std::move(second), node.getOptionalColon(), std::move(third)); } cld::IntrVarPtr<cld::Semantics::ExpressionBase> cld::Semantics::SemanticAnalysis::lvalueConversion(IntrVarPtr<ExpressionBase>&& expression) { if (expression->getValueCategory() != ValueCategory::Lvalue) { // It's a lil weird to not be doing an lvalue conversion here but pretty much every user of lvalueConversion // probably expects it to also handle array to pointer decay even if the array is an rvalue if (isArray(expression->getType())) { auto& elementType = getArrayElementType(expression->getType()); return std::make_unique<Conversion>(PointerType(&elementType), Conversion::Implicit, std::move(expression)); } return std::move(expression); } if (isArray(expression->getType())) { auto& elementType = getArrayElementType(expression->getType()); return std::make_unique<Conversion>(PointerType(&elementType), Conversion::LValue, std::move(expression)); } if (expression->getType().is<FunctionType>()) { if (isBuiltinFunction(*expression)) { log(Errors::Semantics::BUILTIN_FUNCTION_MAY_ONLY_BE_CALLED_DIRECTLY.args(*expression, m_sourceInterface, *expression)); } auto type = typeAlloc(expression->getType()); return std::make_unique<Conversion>(PointerType(type), Conversion::LValue, std::move(expression)); } auto& type = expression->getType(); if (!type.isVolatile() && !type.isConst() && (!type.is<PointerType>() || !type.as<PointerType>().isRestricted())) { IntrVarValue copy = type; return std::make_unique<Conversion>(std::move(copy), Conversion::LValue, std::move(expression)); } IntrVarValue newType = type; newType->setConst(false); newType->setVolatile(false); if (auto* pointer = newType->tryAs<PointerType>()) { newType = PointerType(&pointer->getElementType()); } return std::make_unique<Conversion>(std::move(newType), Conversion::LValue, std::move(expression)); } cld::IntrVarValue<cld::Semantics::Type> cld::Semantics::SemanticAnalysis::lvalueConversion(cld::IntrVarValue<Type> type) { if (isArray(type)) { auto& elementType = getArrayElementType(type); return PointerType(&elementType); } if (type->is<FunctionType>()) { return PointerType(typeAlloc(std::move(*type))); } // If the expression isn't an lvalue and not qualified then conversion is redundant if (!type->isVolatile() && !type->isConst() && (!type->is<PointerType>() || !type->as<PointerType>().isRestricted())) { return type; } type->setConst(false); type->setVolatile(false); if (auto* pointer = type->tryAs<PointerType>()) { type.emplace<PointerType>(&pointer->getElementType()); } return type; } cld::IntrVarPtr<cld::Semantics::ExpressionBase> cld::Semantics::SemanticAnalysis::defaultArgumentPromotion(IntrVarPtr<ExpressionBase>&& expression) { expression = integerPromotion(std::move(expression)); if (!isArithmetic(expression->getType())) { return std::move(expression); } auto& prim = expression->getType().as<PrimitiveType>(); if (prim.getKind() != PrimitiveType::Kind::Float) { return std::move(expression); } return std::make_unique<Conversion>(PrimitiveType(PrimitiveType::Double, getLanguageOptions()), Conversion::DefaultArgumentPromotion, std::move(expression)); } cld::IntrVarPtr<cld::Semantics::ExpressionBase> cld::Semantics::SemanticAnalysis::integerPromotion(IntrVarPtr<ExpressionBase>&& expression) { expression = lvalueConversion(std::move(expression)); if (auto* enumType = expression->getType().tryAs<EnumType>()) { return std::make_unique<Conversion>(enumType->getInfo().type.getType(), Conversion::IntegerPromotion, std::move(expression)); } if (!isArithmetic(expression->getType())) { return std::move(expression); } auto& prim = expression->getType().as<PrimitiveType>(); if (prim.isFloatingPoint() || prim.getBitCount() >= getLanguageOptions().sizeOfInt * 8) { return std::move(expression); } return std::make_unique<Conversion>(PrimitiveType(PrimitiveType::Int, getLanguageOptions()), Conversion::IntegerPromotion, std::move(expression)); } std::unique_ptr<cld::Semantics::Conversion> cld::Semantics::SemanticAnalysis::toBool(IntrVarPtr<ExpressionBase>&& expression) { return std::make_unique<Conversion>(PrimitiveType(PrimitiveType::Bool, getLanguageOptions()), Conversion::Implicit, std::move(expression)); } void cld::Semantics::SemanticAnalysis::arithmeticConversion( std::variant<cld::IntrVarPtr<ExpressionBase> * CLD_NON_NULL, cld::IntrVarValue<Type> * CLD_NON_NULL> lhs, cld::IntrVarPtr<cld::Semantics::ExpressionBase>& rhs) { auto getLhsType = [](auto&& value) -> const Type& { return cld::match( value, [](IntrVarValue<Type>* type) -> const Type& { return *type; }, [](IntrVarPtr<ExpressionBase>* ptr) -> const Type& { return (*ptr)->getType(); }); }; if (getLhsType(lhs).is<VectorType>() || rhs->getType().is<VectorType>()) { cld::match(lhs, [&](auto* lhs) { *lhs = lvalueConversion(std::move(*lhs)); }); rhs = lvalueConversion(std::move(rhs)); if (getLhsType(lhs).is<VectorType>() && rhs->getType().is<VectorType>()) { std::size_t lhsKind = getVectorElementType(getLhsType(lhs)).as<PrimitiveType>().getKind(); std::size_t rhsKind = getVectorElementType(rhs->getType()).as<PrimitiveType>().getKind(); if (lhsKind == rhsKind) { return; } if (lhsKind > rhsKind) { switch (lhsKind) { case PrimitiveType::UnsignedChar: case PrimitiveType::UnsignedShort: case PrimitiveType::UnsignedInt: case PrimitiveType::UnsignedLong: case PrimitiveType::UnsignedLongLong: lhsKind--; default: break; } if (lhsKind == rhsKind) { rhs = std::make_unique<Conversion>(getLhsType(lhs), Conversion::ArithmeticConversion, std::move(rhs)); } return; } switch (rhsKind) { case PrimitiveType::UnsignedChar: case PrimitiveType::UnsignedShort: case PrimitiveType::UnsignedInt: case PrimitiveType::UnsignedLong: case PrimitiveType::UnsignedLongLong: rhsKind--; default: break; } if (lhsKind == rhsKind) { cld::match( lhs, [&](IntrVarValue<Type>* lhs) { *lhs = rhs->getType(); }, [&](IntrVarPtr<ExpressionBase>* lhs) { *lhs = std::make_unique<Conversion>(rhs->getType(), Conversion::ArithmeticConversion, std::move(*lhs)); }); } return; } auto& vectorType = getLhsType(lhs).is<VectorType>() ? getLhsType(lhs) : rhs->getType(); auto& scalarType = &vectorType == &getLhsType(lhs) ? rhs->getType() : getLhsType(lhs); auto scalar = &vectorType == &getLhsType(lhs) ? decltype(lhs){&rhs} : lhs; if (!isArithmetic(scalarType)) { return; } auto& elementType = getVectorElementType(vectorType); std::size_t scalarKind; if (scalarType.is<EnumType>()) { scalarKind = integerPromotion(scalarType)->as<PrimitiveType>().getKind(); } else { scalarKind = scalarType.as<PrimitiveType>().getKind(); } // Signed and unsigned element types are seen as equal switch (scalarKind) { case PrimitiveType::UnsignedChar: case PrimitiveType::UnsignedShort: case PrimitiveType::UnsignedInt: case PrimitiveType::UnsignedLong: case PrimitiveType::UnsignedLongLong: scalarKind--; default: break; } std::size_t elementKind = elementType.as<PrimitiveType>().getKind(); switch (elementKind) { case PrimitiveType::UnsignedChar: case PrimitiveType::UnsignedShort: case PrimitiveType::UnsignedInt: case PrimitiveType::UnsignedLong: case PrimitiveType::UnsignedLongLong: elementKind--; default: break; } if (elementKind == scalarKind) { cld::match( scalar, [&](IntrVarValue<Type>* type) { *type = vectorType; }, [&](IntrVarPtr<ExpressionBase>* expr) { *expr = std::make_unique<Conversion>(vectorType, Conversion::ArithmeticConversion, integerPromotion(std::move(*expr))); }); return; } auto doCasts = [&] { cld::match( scalar, [&](IntrVarValue<Type>* type) { *type = integerPromotion(*type); }, [&](IntrVarPtr<ExpressionBase>* expr) { *expr = std::make_unique<Conversion>(vectorType, Conversion::ArithmeticConversion, integerPromotion(std::move(*expr))); }); }; // if they are both integers or both floating point types we can safely up cast if (isInteger(elementType) == isInteger(scalarType) && scalarKind < elementKind) { doCasts(); return; } // if the type of something is theoretically larger than the element type of a vector that leads to an error. // Exception to that however is if the scalar is a constant that would fit into the element type of the vector // aka can be safely downcast. auto* expr = std::get_if<IntrVarPtr<ExpressionBase>*>(&scalar); if (!expr) { return; } auto* constant = (**expr)->tryAs<Constant>(); if (!constant) { return; } cld::match( constant->getValue(), [&](const llvm::APSInt& apsInt) { if (isInteger(elementType)) { auto bitWidth = elementType.as<PrimitiveType>().getBitCount(); if (llvm::APSInt::isSameValue(apsInt.extOrTrunc(bitWidth), apsInt)) { doCasts(); } } else { auto kind = elementType.as<PrimitiveType>().getKind(); llvm::APFloat temp(kind == PrimitiveType::Double ? llvm::APFloatBase::IEEEdouble() : llvm::APFloatBase::IEEEsingle()); temp.convertFromAPInt(apsInt, apsInt.isSigned(), llvm::APFloatBase::roundingMode::NearestTiesToEven); auto copy = apsInt; bool exact; temp.convertToInteger(copy, llvm::APFloatBase::roundingMode::NearestTiesToEven, &exact); if (llvm::APSInt::isSameValue(copy, apsInt)) { doCasts(); } } }, [&](const llvm::APFloat& apFloat) { if (isInteger(elementType)) { auto width = elementType.as<PrimitiveType>().getBitCount(); bool isSigned = elementType.as<PrimitiveType>().isSigned(); llvm::APSInt temp(width, !isSigned); bool exact = true; apFloat.convertToInteger(temp, llvm::APFloatBase::roundingMode::NearestTiesToEven, &exact); if (exact) { doCasts(); } } else { auto kind = elementType.as<PrimitiveType>().getKind(); bool notExact = false; auto temp = apFloat; temp.convert(kind == PrimitiveType::Double ? llvm::APFloatBase::IEEEdouble() : llvm::APFloatBase::IEEEsingle(), llvm::APFloatBase::roundingMode::NearestTiesToEven, &notExact); if (!notExact) { doCasts(); } } }, [](auto&&) { CLD_UNREACHABLE; }); return; } cld::match(lhs, [&](auto* lhs) { *lhs = integerPromotion(std::move(*lhs)); }); rhs = integerPromotion(std::move(rhs)); if (!isArithmetic(getLhsType(lhs)) || !isArithmetic(rhs->getType())) { return; } if (getLhsType(lhs) == rhs->getType()) { return; } auto& lhsPrim = getLhsType(lhs).as<PrimitiveType>(); auto& rhsPrim = rhs->getType().as<PrimitiveType>(); IntrVarValue type = ErrorType{}; if (lhsPrim.isFloatingPoint() || rhsPrim.isFloatingPoint()) { auto [floating, biggest] = std::max(std::pair(lhsPrim.isFloatingPoint(), lhsPrim.getKind()), std::pair(rhsPrim.isFloatingPoint(), rhsPrim.getKind())); (void)floating; switch (biggest) { case PrimitiveType::Kind::Float: type = PrimitiveType(PrimitiveType::Float, getLanguageOptions()); break; case PrimitiveType::Kind::Double: type = PrimitiveType(PrimitiveType::Double, getLanguageOptions()); break; case PrimitiveType::Kind::LongDouble: type = PrimitiveType(PrimitiveType::LongDouble, getLanguageOptions()); break; default: CLD_UNREACHABLE; } } else if (rhsPrim.isSigned() == lhsPrim.isSigned() || rhsPrim.getBitCount() != lhsPrim.getBitCount()) { auto [bits, sign, lhsUsed] = std::max(std::tuple(lhsPrim.getBitCount(), lhsPrim.isSigned(), true), std::tuple(rhsPrim.getBitCount(), rhsPrim.isSigned(), false)); type = lhsUsed ? getLhsType(lhs) : rhs->getType(); } else { type = !lhsPrim.isSigned() ? getLhsType(lhs) : rhs->getType(); } cld::match( lhs, [&](IntrVarValue<Type>* lhs) { *lhs = type; }, [&](IntrVarPtr<ExpressionBase>* lhs) { *lhs = std::make_unique<Conversion>(type, Conversion::ArithmeticConversion, std::move(*lhs)); }); rhs = std::make_unique<Conversion>(std::move(type), Conversion::ArithmeticConversion, std::move(rhs)); } cld::IntrVarPtr<cld::Semantics::ExpressionBase> cld::Semantics::SemanticAnalysis::doSingleElementInitialization(const Syntax::Node& node, const Type& type, IntrVarPtr<ExpressionBase>&& expression, bool staticLifetime, std::size_t* size) { CLD_ASSERT(!type.isUndefined() && !expression->isUndefined()); if (isArray(type)) { auto& elementType = getArrayElementType(type); if (!isCharacterLikeType(elementType, getLanguageOptions())) { log(Errors::Semantics::ARRAY_MUST_BE_INITIALIZED_WITH_INITIALIZER_LIST.args(*expression, m_sourceInterface, *expression)); return std::make_unique<ErrorExpression>(node); } if (!isStringLiteralExpr(*expression)) { if (isCharType(elementType)) { log(Errors::Semantics::ARRAY_MUST_BE_INITIALIZED_WITH_STRING_OR_INITIALIZER_LIST.args( *expression, m_sourceInterface, *expression)); } else { log(Errors::Semantics::ARRAY_MUST_BE_INITIALIZED_WITH_WIDE_STRING_OR_INITIALIZER_LIST.args( *expression, m_sourceInterface, *expression)); } return std::make_unique<ErrorExpression>(node); } auto& str = expression->as<Constant>().getValue(); if (std::holds_alternative<std::string>(str) && !isCharType(elementType)) { log(Errors::Semantics::CANNOT_INITIALIZE_WCHART_ARRAY_WITH_STRING_LITERAL.args( *expression, m_sourceInterface, *expression)); return std::make_unique<ErrorExpression>(node); } if (isCharType(elementType) && std::holds_alternative<Lexer::NonCharString>(str)) { log(Errors::Semantics::CANNOT_INITIALIZE_CHAR_ARRAY_WITH_WIDE_STRING_LITERAL.args( *expression, m_sourceInterface, *expression)); return std::make_unique<ErrorExpression>(node); } } else { expression = lvalueConversion(std::move(expression)); } if (staticLifetime) { auto result = evaluateConstantExpression(*expression, Mode::Initialization); if (!result) { for (auto& iter : result.error()) { log(iter); } } } doAssignmentLikeConstraints( type, expression, [&] { log(Errors::Semantics::EXPECTED_INITIALIZER_TO_BE_AN_ARITHMETIC_TYPE.args(*expression, m_sourceInterface, *expression)); }, [&] { log(Errors::Semantics::EXPECTED_INITIALIZER_TO_BE_AN_ARITHMETIC_OR_POINTER_TYPE.args( *expression, m_sourceInterface, *expression)); }, [&] { CLD_UNREACHABLE; }, [&] { log(Errors::Semantics::CANNOT_INITIALIZE_VARIABLE_OF_TYPE_N_WITH_INCOMPATIBLE_TYPE_N.args( *expression, m_sourceInterface, type, *expression)); }, [&] { log(Errors::Semantics::EXPECTED_INITIALIZER_TO_BE_NULL_2.args(*expression, m_sourceInterface, *expression)); }, [&](const ConstValue& constant) { log(Errors::Semantics::EXPECTED_INITIALIZER_TO_BE_NULL.args(*expression, m_sourceInterface, *expression, constant)); }, [&] { log(Errors::Semantics::EXPECTED_INITIALIZER_TO_BE_A_POINTER_TYPE.args(*expression, m_sourceInterface, *expression)); }, [&] { if (isVoid(type.as<PointerType>().getElementType())) { log(Errors::Semantics::CANNOT_INITIALIZE_VOID_POINTER_WITH_FUNCTION_POINTER.args( *expression, m_sourceInterface, *expression)); } else { log(Errors::Semantics::CANNOT_INITIALIZE_FUNCTION_POINTER_WITH_VOID_POINTER_PARAMETER.args( *expression, m_sourceInterface, *expression)); } }); if (type.is<AbstractArrayType>() && size) { auto& elementType = getArrayElementType(type); if (isCharType(elementType)) { if (expression->is<Constant>() && std::holds_alternative<std::string>(expression->as<Constant>().getValue())) { *size = cld::get<std::string>(expression->as<Constant>().getValue()).size() + 1; } } else if (elementType.is<PrimitiveType>() && removeQualifiers(elementType) == PrimitiveType(getLanguageOptions().wcharUnderlyingType, getLanguageOptions())) { if (expression->is<Constant>() && std::holds_alternative<Lexer::NonCharString>(expression->as<Constant>().getValue())) { *size = cld::get<Lexer::NonCharString>(expression->as<Constant>().getValue()).characters.size() + 1; } } } return std::move(expression); } cld::Semantics::Initializer cld::Semantics::SemanticAnalysis::visit(const Syntax::Initializer& node, const Type& type, bool staticLifetime, std::size_t* size) { return cld::match( node.getVariant(), [&](const Syntax::AssignmentExpression& assignmentExpression) -> Initializer { auto value = visit(assignmentExpression); if (type.isUndefined() || value->isUndefined()) { return std::make_unique<ErrorExpression>(assignmentExpression); } if (!isStringLiteralExpr(*value)) { value = lvalueConversion(std::move(value)); } return doSingleElementInitialization(assignmentExpression, type, std::move(value), staticLifetime, size); }, [&](const Syntax::InitializerList& initializerList) -> Initializer { return visit(initializerList, type, staticLifetime, size); }); } cld::Semantics::Initializer cld::Semantics::SemanticAnalysis::visit(const Syntax::InitializerList& node, const Type& type, bool staticLifetime, std::size_t* size) { if (!type.isUndefined() && !isArray(type) && !isRecord(type) && node.getNonCommaExpressionsAndBlocks().size() == 1 && node.getNonCommaExpressionsAndBlocks()[0].second.empty() && std::holds_alternative<Syntax::AssignmentExpression>( node.getNonCommaExpressionsAndBlocks()[0].first.getVariant())) { return visit(node.getNonCommaExpressionsAndBlocks()[0].first, type, staticLifetime, size); } if (!type.isUndefined() && !isAggregate(type)) { log(Errors::Semantics::CANNOT_INITIALIZE_ARITHMETIC_OR_POINTER_TYPE_WITH_INITIALIZER_LIST.args( node, m_sourceInterface, node)); return std::make_unique<ErrorExpression>(node); } std::size_t otherSize = 0; if (!size) { size = &otherSize; } *size = 1; class Node; class INode { public: const Type* CLD_NON_NULL type; std::size_t index; const INode* CLD_NULLABLE parent; virtual INode& at(std::size_t index) = 0; virtual const INode& at(std::size_t index) const = 0; virtual std::size_t size() const = 0; virtual void resize(std::size_t size) = 0; virtual ~INode() = default; virtual void push_back(Node&& node) = 0; }; class Node final : public INode { std::vector<Node> m_children; public: Node& at(std::size_t index) override { CLD_ASSERT(index < m_children.size()); return m_children[index]; } const Node& at(std::size_t index) const override { CLD_ASSERT(index < m_children.size()); return m_children[index]; } std::size_t size() const override { return m_children.size(); } void resize(std::size_t size) override { m_children.resize(size); } void push_back(Node&& node) override { m_children.push_back(std::move(node)); } Node() = default; Node(const Node&) = delete; Node& operator=(const Node&) = delete; Node(Node&&) noexcept = default; Node& operator=(Node&&) noexcept = default; Node(const Type& type, std::size_t index, const INode& parent) { this->type = &type; this->index = index; this->parent = &parent; } }; class Top final : public INode { std::vector<std::unique_ptr<Node>> m_children; public: explicit Top(const Type& type) { this->type = &type; index = static_cast<std::size_t>(-1); parent = nullptr; } Node& at(std::size_t index) override { CLD_ASSERT(index < m_children.size()); return *m_children[index]; } const Node& at(std::size_t index) const override { CLD_ASSERT(index < m_children.size()); return *m_children[index]; } std::size_t size() const override { return m_children.size(); } void resize(std::size_t size) override { auto prevSize = m_children.size(); m_children.resize(size); for (std::size_t i = prevSize; i < m_children.size(); i++) { m_children[i] = std::make_unique<Node>(); } } void push_back(Node&& node) override { m_children.push_back(std::make_unique<Node>(std::move(node))); } } top(type); auto assignChildren = YComb{[&](auto&& self, const Type& type, INode& parent) -> void { if (isRecord(type)) { auto ref = getFieldLayout(type); if (ref.back().type->is<AbstractArrayType>()) { ref = ref.subspan(1); } parent.resize(ref.size()); for (std::size_t i = 0; i < ref.size(); i++) { parent.at(i).type = ref[i].type; parent.at(i).index = i; parent.at(i).parent = &parent; if (isAggregate(*ref[i].type)) { self(*ref[i].type, parent.at(i)); } } } if (auto* arrayType = type.tryAs<ArrayType>()) { parent.resize(arrayType->getSize()); for (std::size_t i = 0; i < arrayType->getSize(); i++) { parent.at(i).type = &arrayType->getType(); parent.at(i).index = i; parent.at(i).parent = &parent; if (isAggregate(arrayType->getType())) { self(arrayType->getType(), parent.at(i)); } } } if (auto* vectorType = type.tryAs<VectorType>()) { parent.resize(vectorType->getSize()); for (std::size_t i = 0; i < vectorType->getSize(); i++) { parent.at(i).type = &vectorType->getType(); parent.at(i).index = i; parent.at(i).parent = &parent; if (isAggregate(vectorType->getType())) { self(vectorType->getType(), parent.at(i)); } } } }}; bool abstractArray = false; if (type.is<AbstractArrayType>()) { abstractArray = true; top.resize(1); top.at(0).type = &getArrayElementType(type); top.at(0).index = 0; top.at(0).parent = &top; if (isAggregate(*top.at(0).type)) { assignChildren(*top.at(0).type, top.at(0)); } } else { assignChildren(type, top); } auto finishRest = YComb{[&](auto&& self, Syntax::InitializerList::vector::const_iterator begin, Syntax::InitializerList::vector::const_iterator end) -> void { for (auto iter = begin; iter != end; iter++) { auto& [initializer, designationList] = *iter; if (!designationList.empty()) { // We can check if they're proper integer constant expressions but that's about // it for (auto& desig : designationList) { if (!std::holds_alternative<Syntax::ConstantExpression>(desig)) { continue; } auto exp = visit(cld::get<Syntax::ConstantExpression>(desig)); } } if (std::holds_alternative<Syntax::InitializerList>(initializer.getVariant())) { auto& initializerList = cld::get<Syntax::InitializerList>(initializer.getVariant()); self(initializerList.getNonCommaExpressionsAndBlocks().begin(), initializerList.getNonCommaExpressionsAndBlocks().end()); } else { visit(cld::get<Syntax::AssignmentExpression>(initializer.getVariant())); } } }}; if (type.isUndefined()) { finishRest(node.getNonCommaExpressionsAndBlocks().begin(), node.getNonCommaExpressionsAndBlocks().end()); return std::make_unique<ErrorExpression>(node); } std::vector<InitializerList::Initialization> initializations; const INode* CLD_NULLABLE current = &top; std::size_t currentIndex = 0; std::vector<std::size_t> path; for (auto iter = node.getNonCommaExpressionsAndBlocks().begin(); iter != node.getNonCommaExpressionsAndBlocks().end(); iter++) { auto& [initializer, designationList] = *iter; if (!designationList.empty()) { current = &top; for (auto& desig : designationList) { if (&desig != &designationList.front()) { current = &current->at(currentIndex); } if (isArray(*current->type)) { if (!std::holds_alternative<Syntax::ConstantExpression>(desig)) { log(Errors::Semantics::EXPECTED_INDEX_DESIGNATOR_FOR_ARRAY_TYPE.args( *cld::get<Lexer::CTokenIterator>(desig), m_sourceInterface, *cld::get<Lexer::CTokenIterator>(desig))); finishRest(iter, node.getNonCommaExpressionsAndBlocks().end()); return std::make_unique<ErrorExpression>(node); } auto exp = visit(cld::get<Syntax::ConstantExpression>(desig)); auto constant = evaluateConstantExpression(*exp); if (!constant) { for (auto& mes : constant.error()) { log(mes); } finishRest(iter + 1, node.getNonCommaExpressionsAndBlocks().end()); return std::make_unique<ErrorExpression>(node); } if (!isInteger(exp->getType())) { log(Errors::Semantics::ONLY_INTEGERS_ALLOWED_IN_INTEGER_CONSTANT_EXPRESSIONS.args( *exp, m_sourceInterface, *exp)); finishRest(iter + 1, node.getNonCommaExpressionsAndBlocks().end()); return std::make_unique<ErrorExpression>(node); } if (constant->getInteger().isNegative()) { log(Errors::Semantics::DESIGNATOR_INDEX_MUST_NOT_BE_NEGATIVE.args(*exp, m_sourceInterface, *exp, *constant)); finishRest(iter + 1, node.getNonCommaExpressionsAndBlocks().end()); return std::make_unique<ErrorExpression>(node); } if (!(current == &top && abstractArray) && constant->getInteger() >= current->type->as<ArrayType>().getSize()) { log(Errors::Semantics::DESIGNATOR_INDEX_OUT_OF_RANGE_FOR_ARRAY_TYPE_N.args( *exp, m_sourceInterface, *current->type, *exp, *constant)); finishRest(iter + 1, node.getNonCommaExpressionsAndBlocks().end()); return std::make_unique<ErrorExpression>(node); } if (current == &top && abstractArray) { *size = std::max(*size, constant->getInteger().getZExtValue() + 1); auto prevSize = top.size(); for (std::size_t i = prevSize; i < *size; i++) { top.push_back({top.type->as<AbstractArrayType>().getType(), i, top}); assignChildren(*top.at(i).type, top.at(i)); } } currentIndex = constant->getInteger().getZExtValue(); } else if (isRecord(*current->type)) { if (!std::holds_alternative<Lexer::CTokenIterator>(desig)) { if (current->type->is<StructType>()) { log(Errors::Semantics::EXPECTED_MEMBER_DESIGNATOR_FOR_STRUCT_TYPE.args( desig, m_sourceInterface, desig)); } else { log(Errors::Semantics::EXPECTED_MEMBER_DESIGNATOR_FOR_UNION_TYPE.args( desig, m_sourceInterface, desig)); } finishRest(iter, node.getNonCommaExpressionsAndBlocks().end()); return std::make_unique<ErrorExpression>(node); } const auto* token = cld::get<Lexer::CTokenIterator>(desig); auto& fields = getFields(*current->type); auto result = std::find_if(fields.begin(), fields.end(), [name = token->getText()](const auto& pair) { return pair.second.name == name; }); if (result == fields.end()) { current->type->match( [&](const StructType& structType) { if (structType.isAnonymous()) { log(Errors::Semantics::NO_MEMBER_CALLED_N_FOUND_IN_ANONYMOUS_STRUCT.args( *token, m_sourceInterface, *token)); } else { log(Errors::Semantics::NO_MEMBER_CALLED_N_FOUND_IN_STRUCT_N.args( *token, m_sourceInterface, *token, structType.getStructName())); } }, [&](const UnionType& unionType) { if (unionType.isAnonymous()) { log(Errors::Semantics::NO_MEMBER_CALLED_N_FOUND_IN_ANONYMOUS_UNION.args( *token, m_sourceInterface, *token)); } else { log(Errors::Semantics::NO_MEMBER_CALLED_N_FOUND_IN_UNION_N.args( *token, m_sourceInterface, *token, unionType.getUnionName())); } }, [&](const auto&) { CLD_UNREACHABLE; }); finishRest(iter + 1, node.getNonCommaExpressionsAndBlocks().end()); return std::make_unique<ErrorExpression>(node); } if (result->second.type->is<AbstractArrayType>()) { log(Errors::Semantics::CANNOT_INITIALIZE_FLEXIBLE_ARRAY_MEMBER.args(*token, m_sourceInterface, *token)); finishRest(iter, node.getNonCommaExpressionsAndBlocks().end()); return std::make_unique<ErrorExpression>(node); } if (result->second.parentTypes.empty()) { currentIndex = result - fields.begin(); } else { for (auto index : tcb::span(result->second.indices.data(), result->second.indices.size() - 1)) { current = &current->at(index); } currentIndex = result->second.indices.back(); } } else if (!current->type->isUndefined()) { if (std::holds_alternative<Syntax::ConstantExpression>(desig)) { log(Errors::Semantics::CANNOT_INDEX_INTO_NON_ARRAY_TYPE_N.args(desig, m_sourceInterface, *current->type, desig)); } else { log(Errors::Semantics::CANNOT_ACCESS_MEMBERS_OF_NON_STRUCT_OR_UNION_TYPE_N.args( desig, m_sourceInterface, *current->type, desig)); } finishRest(iter, node.getNonCommaExpressionsAndBlocks().end()); return std::make_unique<ErrorExpression>(node); } } } while (current && currentIndex >= current->size()) { if (current == &top && abstractArray) { top.push_back({getArrayElementType(*top.type), top.size(), top}); *size = currentIndex + 1; assignChildren(*top.at(currentIndex).type, top.at(currentIndex)); } else { currentIndex = current->index + 1; current = current->parent; } } if (!current) { log(Errors::Semantics::NO_MORE_SUB_OBJECTS_TO_INITIALIZE.args(initializer, m_sourceInterface, initializer)); finishRest(iter, node.getNonCommaExpressionsAndBlocks().end()); return std::make_unique<ErrorExpression>(node); } path.clear(); { auto index = currentIndex; const auto* curr = current; while (true) { path.push_back(index); if (!curr->parent) { break; } index = curr->index; curr = curr->parent; } } if (std::holds_alternative<Syntax::InitializerList>(initializer.getVariant())) { if (current->at(currentIndex).type->isUndefined()) { finishRest(iter, node.getNonCommaExpressionsAndBlocks().end()); return std::make_unique<ErrorExpression>(node); } auto merge = visit(cld::get<Syntax::InitializerList>(initializer.getVariant()), *current->at(currentIndex).type, staticLifetime, nullptr); if (std::holds_alternative<InitializerList>(merge)) { auto& initializerList = cld::get<InitializerList>(merge); initializations.reserve(initializations.size() + initializerList.getFields().size()); std::transform( std::move_iterator(std::move(initializerList).getFields().begin()), std::move_iterator(std::move(initializerList).getFields().end()), std::back_inserter(initializations), [&](InitializerList::Initialization&& initialization) -> InitializerList::Initialization&& { initialization.path.insert(initialization.path.begin(), path.rbegin(), path.rend()); return std::move(initialization); }); } else { auto& expr = cld::get<IntrVarPtr<ExpressionBase>>(merge); initializations.push_back({{path.rbegin(), path.rend()}, std::move(expr)}); } } else { auto expression = visit(cld::get<Syntax::AssignmentExpression>(initializer.getVariant())); if (expression->getType().isUndefined()) { finishRest(iter + 1, node.getNonCommaExpressionsAndBlocks().end()); } if (!isStringLiteralExpr(*expression)) { expression = lvalueConversion(std::move(expression)); } else if (currentIndex == 0 && &top == current && node.getNonCommaExpressionsAndBlocks().size() == 1 && designationList.empty() && isCharArray(*top.type, getLanguageOptions())) { // Handles the case of a string literal being used to initialize the top level object with optional // braces surrounding it return doSingleElementInitialization(initializer, type, std::move(expression), staticLifetime, size); } while (isAggregate(*current->at(currentIndex).type)) { if (typesAreCompatible(*removeQualifiers(expression->getType()), *current->at(currentIndex).type) || (isCharArray(*current->at(currentIndex).type, getLanguageOptions()) && isStringLiteralExpr(*expression))) { break; } current = &current->at(currentIndex); currentIndex = 0; path.insert(path.begin(), 0); } if (current->at(currentIndex).type->isUndefined()) { finishRest(iter + 1, node.getNonCommaExpressionsAndBlocks().end()); return std::make_unique<ErrorExpression>(node); } expression = doSingleElementInitialization(initializer, *current->at(currentIndex).type, std::move(expression), staticLifetime, nullptr); initializations.push_back({{path.rbegin(), path.rend()}, std::move(expression)}); } if (current->type->is<UnionType>()) { currentIndex = current->index + 1; current = current->parent; } else { currentIndex++; } } return InitializerList(std::move(initializations)); } cld::Expected<cld::Semantics::SemanticAnalysis::NPCCheck, cld::Semantics::ConstValue> cld::Semantics::SemanticAnalysis::checkNullPointerConstant(const ExpressionBase& expression) { // C99 6.3.2.3§3: // An integer constant expression with the value 0, or such an expression cast to type // void *, is called a null pointer constant. const ExpressionBase* expr = &expression; if (expression.is<Cast>() && expression.getType().is<PointerType>() && isVoid(expression.getType().as<PointerType>().getElementType()) && expression.getType().as<PointerType>().getElementType().getFlags() == Type::Nothing) { expr = &expression.as<Cast>().getExpression(); } if (!isInteger(expr->getType())) { return NPCCheck::WrongType; } auto constant = evaluateConstantExpression(*expr); if (!constant) { return NPCCheck::NotConstExpr; } if (constant->getInteger() != 0) { return *constant; } return NPCCheck::Success; } cld::Expected<cld::Semantics::SemanticAnalysis::NPCCheck, cld::Semantics::ConstValue> cld::Semantics::SemanticAnalysis::checkPointerOperandsForNPC(const ExpressionBase& possibleNPC, const Type& otherType) { // if the expression is void*, the other type is not a pointer to a function and the null pointer check failed, // fail with a WrongType error, allowing callees to check whether pointer conversion would work auto npc = checkNullPointerConstant(possibleNPC); if ((!npc || *npc != NPCCheck::WrongType) && ((npc && *npc == NPCCheck::Success) || otherType.as<PointerType>().getElementType().is<FunctionType>() || !possibleNPC.getType().is<PointerType>())) { return npc; } return NPCCheck::WrongType; }
[ "markus.boeck02@gmail.com" ]
markus.boeck02@gmail.com
1d78940135b253255243087f8dc6209cd132b721
2f557f60fc609c03fbb42badf2c4f41ef2e60227
/DataFormats/Math/interface/GraphWalker.h
c36fdc73ea3f435150ed074116b1a4242adb1909
[ "Apache-2.0" ]
permissive
CMS-TMTT/cmssw
91d70fc40a7110832a2ceb2dc08c15b5a299bd3b
80cb3a25c0d63594fe6455b837f7c3cbe3cf42d7
refs/heads/TMTT_1060
2020-03-24T07:49:39.440996
2020-03-04T17:21:36
2020-03-04T17:21:36
142,576,342
3
5
Apache-2.0
2019-12-05T21:16:34
2018-07-27T12:48:13
C++
UTF-8
C++
false
false
4,929
h
#ifndef DATA_FORMATS_MATH_GRAPH_WALKER_H #define DATA_FORMATS_MATH_GRAPH_WALKER_H #include "DataFormats/Math/interface/Graph.h" #include <queue> #include <vector> namespace math { /** a walker for an acyclic directed multigraph */ template <class N, class E> class GraphWalker { public: using index_type = typename math::Graph<N,E>::index_type; using index_result = typename math::Graph<N,E>::index_result; using edge_type = typename math::Graph<N,E>::edge_type; using edge_list = typename math::Graph<N,E>::edge_list; using edge_iterator = typename math::Graph<N,E>::edge_iterator; using const_edge_iterator = typename math::Graph<N,E>::const_edge_iterator; // only a const-edge_range! using edge_range = std::pair<const_edge_iterator, const_edge_iterator>; using stack_type = std::vector<edge_range>; using bfs_type = std::queue<edge_type>; using result_type = bool; using value_type = typename math::Graph<N,E>::value_type; public: //! creates a walker rooted by the first candidate root found in the underlying Graph GraphWalker(const Graph<N,E> &); //! creates a walker rooted by the node given GraphWalker(const Graph<N,E> &, const N & ); // operations result_type firstChild(); result_type nextSibling(); result_type parent(); result_type next(); inline value_type current() const; result_type next_bfs(); value_type current_bfs() const; void reset(); const stack_type & stack() const { return stack_;} protected: // stack_.back().first corresponds to index of the current node! stack_type stack_; // hierarchical stack used in navigation bfs_type queue_; // breath first search queue edge_list root_; // root of the walker const Graph<N,E> & graph_; private: GraphWalker() = delete; }; template<class N, class E> GraphWalker<N,E>::GraphWalker(const Graph<N,E> & g) : graph_(g) { // complexity = (no nodes) * (no edges) graph_.findRoots(root_); stack_.emplace_back(edge_range(root_.begin(),root_.end())); if (!root_.empty()) { queue_.push(root_[0]); } } template<class N, class E> GraphWalker<N,E>::GraphWalker(const Graph<N,E> & g, const N & root) : graph_(g) { index_result rr = graph_.nodeIndex(root); if (!rr.second) // no such root node, no walker can be created! throw root; root_.emplace_back(edge_type(rr.first, 0)); stack_.emplace_back(edge_range(root_.begin(),root_.end())); queue_.push(root_[0]); } template<class N, class E> typename GraphWalker<N,E>::value_type GraphWalker<N,E>::current() const { const edge_range & er = stack_.back(); return value_type(graph_.nodeData(er.first->first), graph_.edgeData(er.first->second)); } template<class N, class E> typename GraphWalker<N,E>::value_type GraphWalker<N,E>::current_bfs() const { const edge_type & e = queue_.front(); return value_type(graph_.nodeData(e.first), graph_.edgeData(e.second)); } template<class N, class E> void GraphWalker<N,E>::reset() { stack_.clear(); stack_.emplace_back(edge_range(root_.begin(),root_.end())); queue_.clear(); if (root_.size()) { queue_.push(root_[0]); } } template<class N, class E> typename GraphWalker<N,E>::result_type GraphWalker<N,E>::firstChild() { result_type result = false; const edge_range & adjEdges = graph_.edges(stack_.back().first->first); if (adjEdges.first != adjEdges.second) { stack_.emplace_back(adjEdges); result = true; } return result; } template<class N, class E> typename GraphWalker<N,E>::result_type GraphWalker<N,E>::nextSibling() { result_type result = false; edge_range & siblings = stack_.back(); if (siblings.first != (siblings.second - 1) ) { ++siblings.first; result = true; } return result; } template<class N, class E> typename GraphWalker<N,E>::result_type GraphWalker<N,E>::parent() { result_type result = false; if (stack_.size()>1) { stack_.pop_back(); result = true; } return result; } template<class N, class E> typename GraphWalker<N,E>::result_type GraphWalker<N,E>::next() { result_type result = false; if (firstChild()) { result = true; } else if(stack_.size()>1 && nextSibling()) { result = true; } else { while(parent()) { if(stack_.size()>1 && nextSibling()) { result = true; break; } } } return result; } template<class N, class E> typename GraphWalker<N,E>::result_type GraphWalker<N,E>::next_bfs() { result_type result(false); if (!queue_.empty()) { const edge_type & e = queue_.front(); const edge_range & er = graph_.edges(e.first); const_edge_iterator it(er.first), ed(er.second); for (; it != ed; ++it) { queue_.push(*it); } queue_.pop(); if (!queue_.empty()) { result=true; } } return result; } } // namespase math #endif
[ "ianna.osborne@cern.ch" ]
ianna.osborne@cern.ch
d2f77d5224f51d3b6337c768baa4e47d2d943fe2
78632136f73b88bf807a7e8598710531931db790
/src/BOJ/2nd/11000/11055.cpp
287fbddf8e9f3230644b80b1a7b480111a64cdef
[]
no_license
ycs1m1yk/PS
b5962264324cc82ce7a256555442237da615de02
a6e3619c119f4cb86d1ba160302597738bbb1f9f
refs/heads/master
2022-05-09T10:26:49.545895
2022-04-17T15:30:06
2022-04-17T15:30:06
222,115,340
1
0
null
null
null
null
UTF-8
C++
false
false
854
cpp
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int MAX = 1000; int N, sequence[MAX], cache[MAX]; /* TEST CASE 11 1 4 100 2 50 60 3 5 6 7 8 10 1 2 3 100 101 102 10 11 12 13 */ int solve(int pos){ if(pos==0){ return sequence[0]; } int& ret=cache[pos]; if(ret!=-1) return ret; ret = sequence[pos]; for(int i=0; i<pos; i++){ if(sequence[i]<sequence[pos]){ ret=max(ret, solve(i)+sequence[pos]); } } return ret; } int main() { memset(cache, -1, sizeof(cache)); scanf("%d", &N); for (int i = 0; i < N; i++) { scanf("%d", &sequence[i]); } int result = sequence[0]; for(int i=0; i<N; i++){ result=max(result, solve(i)); } printf("%d", result); }
[ "satoly4@gmail.com" ]
satoly4@gmail.com
fd043aa4922e5b4cc79320d6892505c8f95325e9
36d63d28b33d1f3f22262302372b1dab8eb01d69
/bus_protocols/uds_handler.h
d2470ee9ae9d256dfd4a4065b4c1a5fe05507058
[ "MIT" ]
permissive
qiuba2008/SavvyCAN
d6115c09968a5ee08ead04267b943f00500ba900
b7888765a2cbb32315f762d7e48c64de893c901d
refs/heads/master
2021-06-27T03:14:25.590822
2017-09-14T17:09:21
2017-09-14T17:09:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,858
h
#ifndef UDS_HANDLER_H #define UDS_HANDLER_H #include <Qt> #include <QObject> #include <QDebug> #include "can_structs.h" #include "isotp_message.h" class ISOTP_HANDLER; namespace UDS_SERVICES { enum { OBDII_SHOW_CURRENT = 1, OBDII_SHOW_FREEZE = 2, OBDII_SHOW_STORED_DTC = 3, OBDII_CLEAR_DTC = 4, OBDII_TEST_O2 = 5, OBDII_TEST_RESULTS = 6, OBDII_SHOW_PENDING_DTC = 7, OBDII_CONTROL_DEVICES = 8, OBDII_VEH_INFO = 9, OBDII_PERM_DTC = 0xA, DIAG_CONTROL = 0x10, ECU_RESET = 0x11, GMLAN_READ_FAILURE_RECORD = 0x12, CLEAR_DIAG = 0x14, READ_DTC = 0x19, GMLAN_READ_DIAGNOSTIC_ID = 0x1A, RETURN_TO_NORMAL = 0x20, READ_BY_ID = 0x22, READ_BY_ADDR = 0x23, READ_SCALING_ID = 0x24, SECURITY_ACCESS = 0x27, COMM_CTRL = 0x28, READ_DATA_ID_PERIODIC = 0x2A, DYNAMIC_DATA_DEFINE = 0x2C, DEFINE_PID_BY_ADDR = 0x2D, WRITE_BY_ID = 0x2E, IO_CTRL = 0x2F, ROUTINE_CTRL = 0x31, REQUEST_DOWNLOAD = 0x34, REQUEST_UPLOAD = 0x35, TRANSFER_DATA = 0x36, REQ_TRANS_EXIT = 0x37, REQ_FILE_TRANS = 0x38, GMLAN_WRITE_DID = 0x3B, WRITE_BY_ADDR = 0x3D, TESTER_PRESENT = 0x3E, NEG_RESPONSE = 0x7F, ACCESS_TIMING = 0x83, SECURED_DATA_TRANS = 0x84, CTRL_DTC_SETTINGS = 0x85, RESPONSE_ON_EVENT = 0x86, RESPONSE_LINK_CTRL = 0x87, GMLAN_REPORT_PROG_STATE = 0xA2, GMLAN_ENTER_PROG_MODE = 0xA5, GMLAN_CHECK_CODES = 0xA9, GMLAN_READ_DPID = 0xAA, GMLAN_DEVICE_CTRL = 0xAE }; } struct CODE_STRUCT { int code; QString shortDesc; QString longDesc; }; class UDS_MESSAGE: public ISOTP_MESSAGE { public: int service; int subFunc; int subFuncLen; bool isErrorReply; UDS_MESSAGE(); }; class UDS_HANDLER : public QObject { Q_OBJECT public: UDS_HANDLER(); ~UDS_HANDLER(); void setExtendedAddressing(bool mode); static UDS_HANDLER* getInstance(); void setReception(bool mode); //set whether to accept and forward frames or not void sendUDSFrame(const UDS_MESSAGE &msg); void setProcessAllIDs(bool state); void setFlowCtrl(bool state); void addFilter(int pBusId, uint32_t ID, uint32_t mask); void removeFilter(int pBusId, uint32_t ID, uint32_t mask); void clearAllFilters(); QString getServiceShortDesc(int service); QString getServiceLongDesc(int service); QString getNegativeResponseShort(int respCode); QString getNegativeResponseLong(int respCode); public slots: void gotISOTPFrame(ISOTP_MESSAGE msg); signals: void newUDSMessage(UDS_MESSAGE msg); private: QList<ISOTP_MESSAGE> messageBuffer; const QVector<CANFrame> *modelFrames; bool isReceiving; bool useExtendedAddressing; void processFrame(const CANFrame &frame); ISOTP_HANDLER *isoHandler; }; #endif // UDS_HANDLER_H
[ "collink@kkmfg.com" ]
collink@kkmfg.com
a63a658686ad742e0bf6286bd763ae7a264826f7
9a3b9d80afd88e1fa9a24303877d6e130ce22702
/src/Providers/UNIXProviders/SecurityServiceForSystem/UNIX_SecurityServiceForSystem_TRU64.hxx
57a9379049c0a66a28a8dac14e4922108958e8ca
[ "MIT" ]
permissive
brunolauze/openpegasus-providers
3244b76d075bc66a77e4ed135893437a66dd769f
f24c56acab2c4c210a8d165bb499cd1b3a12f222
refs/heads/master
2020-04-17T04:27:14.970917
2015-01-04T22:08:09
2015-01-04T22:08:09
19,707,296
0
0
null
null
null
null
UTF-8
C++
false
false
1,833
hxx
//%LICENSE//////////////////////////////////////////////////////////////// // // Licensed to The Open Group (TOG) under one or more contributor license // agreements. Refer to the OpenPegasusNOTICE.txt file distributed with // this work for additional information regarding copyright ownership. // Each contributor licenses this file to you under the OpenPegasus Open // Source License; you may not use this file except in compliance with the // License. // // 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. // ////////////////////////////////////////////////////////////////////////// // //%///////////////////////////////////////////////////////////////////////// #ifdef PEGASUS_OS_TRU64 #ifndef __UNIX_SECURITYSERVICEFORSYSTEM_PRIVATE_H #define __UNIX_SECURITYSERVICEFORSYSTEM_PRIVATE_H #endif #endif
[ "brunolauze@msn.com" ]
brunolauze@msn.com
a3bb3fbb1ac74cecd47a8f7ab55317e99e93e1f2
d96349b211a135bc63e828f186e3560c0d383197
/Cp5/5-1-3_trainning.cpp
70b43edd6008a722eb654d7ff6666c44e7822c23
[]
no_license
masa-k0101/Self-Study_Cpp
116904e7a45d8d211e85b3e20cfbfc602dd866f4
1fdd3b0637274934e7730ca87a400bf2c97daf8f
refs/heads/master
2022-12-14T01:59:20.763522
2020-09-15T13:20:08
2020-09-15T13:20:08
263,053,847
0
0
null
null
null
null
UTF-8
C++
false
false
866
cpp
#include<iostream> #include<cstdio> //scanfのためのインクルード namespace A { class data { int day, month, year; public: data(const char *str); data(int m, int d, int y) { day = d; month = m; year = y; } void show() { std::cout << month << '/' << day << '/' << year << "\n"; } }; data::data(const char *str) { sscanf(str, "%d%*c%d%*c%d", &month, &day, &year); } } main() { // 文字列を使って日付オブジェクトを作る A::data sdata("11/1/92"); // 整数を使って日付オブジェクトを作る A::data idata(11, 1, 92); sdata.show(); idata.show(); return 0; }
[ "noreply@github.com" ]
masa-k0101.noreply@github.com
1fa824ed7862552b43f80a8772e39639ec3d9b53
a61a21484fa9d29152793b0010334bfe2fed71eb
/Skyrim/include/Skyrim/Camera/BleedoutCameraState.h
b0e33caa10d42632c5947efa9b0bdf43b7325991
[]
no_license
kassent/IndividualizedShoutCooldowns
784e3c62895869c7826dcdbdeea6e8e177e8451c
f708063fbc8ae21ef7602e03b4804ae85518f551
refs/heads/master
2021-01-19T05:22:24.794134
2017-04-06T13:00:19
2017-04-06T13:00:19
87,429,558
3
3
null
null
null
null
UTF-8
C++
false
false
562
h
#pragma once #include "TESCameraState.h" /*============================================================================== class BleedoutCameraState +0000 (_vtbl=010E3184) 0000: class BleedoutCameraState 0000: | class ThirdPersonState 0000: | | class TESCameraState 0004: | | | struct BSIntrusiveRefCounted 0010: | | class PlayerInputHandler ==============================================================================*/ class BleedoutCameraState : public ThirdPersonState { public: BleedoutCameraState(); virtual ~BleedoutCameraState(); };
[ "wangzhengzewzz@gmail.com" ]
wangzhengzewzz@gmail.com
6cccef3db1c0b3c6dbb348ee34b386fb5c75c20d
d41556fff75e81fbdd0b2b9ebbc0f40caf85a186
/testException.cxx
71fd38500baa56351b03b0dc8b1be0297609d3dc
[]
no_license
glehmann/connectedComponent
46d26601334ab7038b925e913532816a26988ac0
2b4205be1250224fff0470162d1cf6862b39f8ad
refs/heads/master
2021-01-19T09:28:16.361724
2006-10-25T06:29:32
2006-10-25T06:29:32
3,272,709
0
0
null
null
null
null
UTF-8
C++
false
false
6,769
cxx
// test and time connected component labelling in itk #include <iomanip> #include <stdlib.h> #include <itkImageFileReader.h> #include <itkImageFileWriter.h> #include "itkConnectedComponentImageFilter.h" #include "itkConnectedComponentImageFilter1.h" #include "itkConnectedComponentImageFilter2.h" #include "itkConnectedComponentImageFilter3.h" #include "itkConnectedComponentImageFilter4.h" #include "itkTimeProbe.h" #include "itkBinaryThresholdImageFilter.h" //const int dimensions = 2; // 2d case // ./testLabelling /home/richardb/Build/itk-mima2/Insight/Examples/Data/BrainMidSagittalSlice.png crap.tif 100 // 3d case // ./testLabelling brain.tif crap.tif 100 3 template <int dimensions, class InputPixelType, class OutputPixelType> void ThreshAndLabel(std::string infile, std::string outfile, int thresh, int repeats, bool fullyConnected, int whichMethod, int OutVal=255, int InVal=0) { typedef itk::Image< InputPixelType, dimensions > InputImageType; typedef itk::Image< OutputPixelType, dimensions > OutputImageType; typedef itk::BinaryThresholdImageFilter< InputImageType, InputImageType > ThresholdFilterType; typedef itk::ConnectedComponentImageFilter<InputImageType, OutputImageType> LabelFilt0; typedef itk::ConnectedComponentImageFilter1<InputImageType, OutputImageType> LabelFilt1; typedef itk::ConnectedComponentImageFilter2<InputImageType, OutputImageType> LabelFilt2; typedef itk::ConnectedComponentImageFilter3<InputImageType, OutputImageType> LabelFilt3; typedef itk::ConnectedComponentImageFilter4<InputImageType, OutputImageType> LabelFilt4; typedef itk::ImageFileReader< InputImageType > ReaderType; typedef itk::ImageFileWriter< OutputImageType > WriterType; // the reader, writer and thresholding objects typename ReaderType::Pointer reader; typename WriterType::Pointer writer; typename ThresholdFilterType::Pointer threshfilter; reader = ReaderType::New(); writer = WriterType::New(); threshfilter = ThresholdFilterType::New(); // Labelling objects typename LabelFilt0::Pointer labeller0; typename LabelFilt1::Pointer labeller1; typename LabelFilt2::Pointer labeller2; typename LabelFilt3::Pointer labeller3; typename LabelFilt4::Pointer labeller4; labeller0 = LabelFilt0::New(); labeller1 = LabelFilt1::New(); labeller2 = LabelFilt2::New(); labeller3 = LabelFilt3::New(); labeller4 = LabelFilt4::New(); // set up reader reader->SetFileName(infile.c_str()); threshfilter->SetInput(reader->GetOutput()); // set up the thresholder threshfilter->SetOutsideValue(OutVal); threshfilter->SetInsideValue(InVal); threshfilter->SetUpperThreshold( thresh ); threshfilter->SetLowerThreshold( 0 ); threshfilter->Update(); std::cout << "Image size = " << reader->GetOutput()->GetLargestPossibleRegion().GetSize() << std::endl; std::cout << "Read file and thresholded. Now labelling " << repeats << " times" << std::endl; itk::TimeProbe ltime; switch (whichMethod) { case 0: labeller0->SetFullyConnected(fullyConnected); labeller0->SetInput(threshfilter->GetOutput()); for (int i=0;i<repeats;i++) { // set first labeller ltime.Start(); labeller0->Update(); ltime.Stop(); labeller0->Modified(); } writer->SetInput(labeller0->GetOutput()); break; case 1: labeller1->SetFullyConnected(fullyConnected); labeller1->SetInput(threshfilter->GetOutput()); for (int i=0;i<repeats;i++) { // set first labeller ltime.Start(); labeller1->Update(); ltime.Stop(); labeller1->Modified(); } writer->SetInput(labeller1->GetOutput()); break; case 2: labeller2->SetFullyConnected(fullyConnected); labeller2->SetInput(threshfilter->GetOutput()); for (int i=0;i<repeats;i++) { // set first labeller ltime.Start(); labeller2->Update(); ltime.Stop(); labeller2->Modified(); } writer->SetInput(labeller2->GetOutput()); break; case 3: labeller3->SetFullyConnected(fullyConnected); labeller3->SetInput(threshfilter->GetOutput()); for (int i=0;i<repeats;i++) { // set first labeller ltime.Start(); labeller3->Update(); ltime.Stop(); labeller3->Modified(); } writer->SetInput(labeller3->GetOutput()); break; case 4: labeller4->SetFullyConnected(fullyConnected); labeller4->SetInput(threshfilter->GetOutput()); for (int i=0;i<repeats;i++) { // set first labeller ltime.Start(); labeller4->Update(); ltime.Stop(); labeller4->Modified(); } writer->SetInput(labeller4->GetOutput()); break; default: std::cerr << "Unknown labelling option" << std::endl; } writer->SetFileName(outfile.c_str()); writer->Update(); std::cout << "Method \t repeats \t mean time" << std::endl; std::cout << std::setprecision(3) << whichMethod << "\t" << repeats << "\t" << ltime.GetMeanTime() << std::endl; } int main( int argc, char * argv[] ) { if( argc < 8 ) { std::cerr << "Usage: " << argv[0] << " inputImageFile "; std::cerr << " outputImageFile threshold dimensions labellernumber[0-3] repeats connect[0,1]" << std::endl; return EXIT_FAILURE; } // Assume the input type is char typedef unsigned char InputPixelType; typedef unsigned char OutputPixelType; //typedef int OutputPixelType; std::string Infile = argv[1]; std::string Outfile = argv[2]; int thresh = atoi(argv[3]); int dimensions=atoi(argv[4]); int whichMethod=atoi(argv[5]); int repeats = atoi(argv[6]); bool connect = (bool)atoi(argv[7]); std::cout << "Labelling summary:" << std::endl; std::cout << " source : " << Infile << std::endl; std::cout << " threshold : " << thresh << std::endl; std::cout << " dimensions : " << dimensions << std::endl; std::cout << " method : " << whichMethod << std::endl; std::cout << " repeats : " << repeats << std::endl; std::cout << " fully connected : " << connect << std::endl; switch(dimensions) { case 2: try { ThreshAndLabel<2, InputPixelType, OutputPixelType>(Infile, Outfile, thresh, repeats, connect, whichMethod); return EXIT_FAILURE; } catch (itk::ExceptionObject & e) { std::cout << "Exception caught" << std::endl; } break; case 3: ThreshAndLabel<3, InputPixelType, OutputPixelType>(Infile, Outfile, thresh, repeats, connect, whichMethod); break; default: std::cerr << "Unsupported dimensions" << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
[ "none" ]
none
7372c1d02c6f5b2e0eb47865f82edfe41117d913
3a19bf0ccf936ba839101d9e3cc6ddf6242e48e3
/SlowSequence.cpp
49e51fd716b741a971c3a71ca62a69f8156b6aa5
[]
no_license
emli/topcoder
a9cdefb062d4ac930d41975186e5a9e4b4f916f7
a4fea69e9b1b4935870941743a28d17a4cf67756
refs/heads/master
2021-06-10T05:28:28.001258
2021-04-10T17:57:24
2021-04-10T17:57:24
165,861,120
0
0
null
null
null
null
UTF-8
C++
false
false
3,579
cpp
#include <vector> #include <list> #include <map> #include <set> #include <queue> #include <deque> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> using namespace std; class SlowSequence { public: void go(int cur,int n,int s,vector<int> &a,vector<int> &ans,bool &ok){ if (n == 0 && s == 0){ ans = a; ok = true; return; } if (n > 0 && !ok) { a.push_back(cur + 1); go(cur + 1, n - 1, s - (cur + 1), a, ans,ok); a.pop_back(); a.push_back(cur - 1); go(cur - 1, n - 1, s - (cur - 1), a, ans,ok); a.pop_back(); } } vector <int> construct(int n, int s) { vector<int> a = {0},ans; bool ok = false; go(0,n - 1,s,a,ans,ok); return ans; } }; // BEGIN KAWIGIEDIT TESTING // Generated by KawigiEdit 2.1.4 (beta) modified by pivanof bool KawigiEdit_RunTest(int testNum, int p0, int p1, bool hasAnswer, vector <int> p2) { cout << "Test " << testNum << ": [" << p0 << "," << p1; cout << "]" << endl; SlowSequence *obj; vector <int> answer; obj = new SlowSequence(); clock_t startTime = clock(); answer = obj->construct(p0, p1); clock_t endTime = clock(); delete obj; bool res; res = true; cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl; if (hasAnswer) { cout << "Desired answer:" << endl; cout << "\t" << "{"; for (int i = 0; int(p2.size()) > i; ++i) { if (i > 0) { cout << ","; } cout << p2[i]; } cout << "}" << endl; } cout << "Your answer:" << endl; cout << "\t" << "{"; for (int i = 0; int(answer.size()) > i; ++i) { if (i > 0) { cout << ","; } cout << answer[i]; } cout << "}" << endl; if (hasAnswer) { if (answer.size() != p2.size()) { res = false; } else { for (int i = 0; int(answer.size()) > i; ++i) { if (answer[i] != p2[i]) { res = false; } } } } if (!res) { cout << "DOESN'T MATCH!!!!" << endl; } else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) { cout << "FAIL the timeout" << endl; res = false; } else if (hasAnswer) { cout << "Match :-)" << endl; } else { cout << "OK, but is it right?" << endl; } cout << "" << endl; return res; } int main() { bool all_right; all_right = true; int p0; int p1; vector <int> p2; { // ----- test 0 ----- p0 = 4; p1 = 4; int t2[] = {0,1,2,1}; p2.assign(t2, t2 + sizeof(t2) / sizeof(t2[0])); all_right = KawigiEdit_RunTest(0, p0, p1, true, p2) && all_right; // ------------------ } { // ----- test 1 ----- p0 = 8; p1 = 0; int t2[] = {0,1,0,-1,0,-1,0,1}; p2.assign(t2, t2 + sizeof(t2) / sizeof(t2[0])); all_right = KawigiEdit_RunTest(1, p0, p1, true, p2) && all_right; // ------------------ } { // ----- test 2 ----- p0 = 1; p1 = 4700; p2.clear() /*{}*/; all_right = KawigiEdit_RunTest(2, p0, p1, true, p2) && all_right; // ------------------ } { // ----- test 3 ----- p0 = 5; p1 = -10; int t2[] = {0,-1,-2,-3,-4}; p2.assign(t2, t2 + sizeof(t2) / sizeof(t2[0])); all_right = KawigiEdit_RunTest(3, p0, p1, true, p2) && all_right; // ------------------ } if (all_right) { cout << "You're a stud (at least on the example cases)!" << endl; } else { cout << "Some of the test cases had errors." << endl; } return 0; } // END KAWIGIEDIT TESTING //Powered by KawigiEdit 2.1.4 (beta) modified by pivanof!
[ "esulaimanov@nurtelecom.kg" ]
esulaimanov@nurtelecom.kg
f1cb6c60995ef9c9a777d2f5d0cee4f791c21c33
19371b0acd6358dc5aa7d39a5a038e05413b60e8
/build-BookShop-Desktop_Qt_5_5_1_clang_64bit-Debug/moc_mainwindow.cpp
5aba49ee42ad210761caf452206cb18abe77780e
[]
no_license
Duke-Fan/qt_mysql
30b0b066da80c42aafb01c44b4adc04ba4fa3256
eb7b78c9e6d97cb927a7671d29c34ec82d908002
refs/heads/master
2021-12-08T10:01:33.473844
2016-03-03T16:48:24
2016-03-03T16:48:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,460
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'mainwindow.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.5.1) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../BookShop/mainwindow.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'mainwindow.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.5.1. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_MainWindow_t { QByteArrayData data[4]; char stringdata0[23]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_MainWindow_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_MainWindow_t qt_meta_stringdata_MainWindow = { { QT_MOC_LITERAL(0, 0, 10), // "MainWindow" QT_MOC_LITERAL(1, 11, 5), // "login" QT_MOC_LITERAL(2, 17, 0), // "" QT_MOC_LITERAL(3, 18, 4) // "info" }, "MainWindow\0login\0\0info" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_MainWindow[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 2, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 0, 24, 2, 0x08 /* Private */, 3, 0, 25, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, QMetaType::Void, 0 // eod }; void MainWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { MainWindow *_t = static_cast<MainWindow *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->login(); break; case 1: _t->info(); break; default: ; } } Q_UNUSED(_a); } const QMetaObject MainWindow::staticMetaObject = { { &QMainWindow::staticMetaObject, qt_meta_stringdata_MainWindow.data, qt_meta_data_MainWindow, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *MainWindow::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *MainWindow::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_MainWindow.stringdata0)) return static_cast<void*>(const_cast< MainWindow*>(this)); return QMainWindow::qt_metacast(_clname); } int MainWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QMainWindow::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 2) qt_static_metacall(this, _c, _id, _a); _id -= 2; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 2) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 2; } return _id; } QT_END_MOC_NAMESPACE
[ "chenx324@yeah.net" ]
chenx324@yeah.net
ae1bcfdfe6d01809315169eb6ca2dabcf04307fe
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/chrome/browser/metrics/perf/perf_output.cc
4988d54fafe8f338733df81e207c2b89dcc0c35c
[ "BSD-3-Clause" ]
permissive
metux/chromium-suckless
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
72a05af97787001756bae2511b7985e61498c965
refs/heads/orig
2022-12-04T23:53:58.681218
2017-04-30T10:59:06
2017-04-30T23:35:58
89,884,931
5
3
BSD-3-Clause
2022-11-23T20:52:53
2017-05-01T00:09:08
null
UTF-8
C++
false
false
1,994
cc
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/metrics/perf/perf_output.h" #include "base/bind.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/debug_daemon_client.h" PerfOutputCall::PerfOutputCall( scoped_refptr<base::TaskRunner> blocking_task_runner, base::TimeDelta duration, const std::vector<std::string>& perf_args, const DoneCallback& callback) : blocking_task_runner_(blocking_task_runner), duration_(duration), perf_args_(perf_args), done_callback_(callback), weak_factory_(this) { DCHECK(thread_checker_.CalledOnValidThread()); perf_data_pipe_reader_.reset(new chromeos::PipeReaderForString( blocking_task_runner_, base::Bind(&PerfOutputCall::OnIOComplete, weak_factory_.GetWeakPtr()))); base::ScopedFD pipe_write_end = perf_data_pipe_reader_->StartIO(); chromeos::DebugDaemonClient* client = chromeos::DBusThreadManager::Get()->GetDebugDaemonClient(); client->GetPerfOutput(duration_, perf_args_, pipe_write_end.get(), base::Bind(&PerfOutputCall::OnGetPerfOutputError, weak_factory_.GetWeakPtr())); } PerfOutputCall::~PerfOutputCall() {} void PerfOutputCall::OnIOComplete() { DCHECK(thread_checker_.CalledOnValidThread()); std::string stdout_data; perf_data_pipe_reader_->GetData(&stdout_data); done_callback_.Run(stdout_data); // The callback may delete us, so it's hammertime: Can't touch |this|. } void PerfOutputCall::OnGetPerfOutputError(const std::string& error_name, const std::string& error_message) { DCHECK(thread_checker_.CalledOnValidThread()); // Signal pipe reader to shut down. This will cause // OnIOComplete to be called, probably with an empty string. perf_data_pipe_reader_->OnDataReady(-1); }
[ "enrico.weigelt@gr13.net" ]
enrico.weigelt@gr13.net
dc57fdb19befb6ef721de5f7617f1cb33038a3a3
c91fe5e19619a52be32920c1a88fc5f4d13a2b9c
/MSO_Demo/ProgressInit.h
c03be94dfbb5beb9ae09f2444d7a6aa7a1c7c30b
[]
no_license
beracho/tryMorpho
ca09b5b3ce390901491d0f6189173f52e4c96534
819e0bb80621aac331311d9ee707a5a5354fdb64
refs/heads/master
2020-04-03T19:53:19.051089
2018-10-31T10:15:20
2018-10-31T10:15:20
155,539,005
0
1
null
null
null
null
UTF-8
C++
false
false
1,610
h
/************************************************************ Copyright (c) 2002-2005, Morpho ************************************************************/ // ProgressInit.h : header file // #if !defined(AFX_PROGRESSINIT_H__94AC751B_54FD_485F_B187_27C19DFABF22__INCLUDED_) #define AFX_PROGRESSINIT_H__94AC751B_54FD_485F_B187_27C19DFABF22__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 ///////////////////////////////////////////////////////////////////////////// // CProgressInit dialog class CProgressInit : public CDialog { // Construction public: CProgressInit(CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(CProgressInit) enum { IDD = IDD_PROGRESS_INIT }; CStatic m_static_BioAvi; CString m_cs_Mess; CString m_cs_Mess2; CString m_cs_Mess3; CString m_cs_Mess4; CString m_cs_Mess5; CString m_cs_Mess10; CString m_cs_Mess11; CString m_cs_Mess12; CString m_cs_Mess13; CString m_cs_Mess14; CString m_cs_MainMess; //}}AFX_DATA // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CProgressInit) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(CProgressInit) // NOTE: the ClassWizard will add member functions here //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_PROGRESSINIT_H__94AC751B_54FD_485F_B187_27C19DFABF22__INCLUDED_)
[ "beracho_15@hotmail.com" ]
beracho_15@hotmail.com
33bb5730ebf75d9eb7e07d2747ded0c2d1788efa
d0a0bc979981dedf56e83f1d3a4b4bf21c93670b
/.svn/pristine/33/33bb5730ebf75d9eb7e07d2747ded0c2d1788efa.svn-base
f921c14fdd5554aecb7d3eae28af5ebbe9559704
[ "MIT", "GPL-3.0-only" ]
permissive
bebest2010/ipchain
a0a19e024d275116a0bd0347d4eef67ec4451a17
bb3de245646d1164c182fdc1add9bc375ab9db80
refs/heads/master
2020-04-01T04:37:46.050366
2018-09-21T09:42:27
2018-09-21T09:42:27
152,870,938
0
0
MIT
2018-10-13T12:42:55
2018-10-13T12:42:54
null
UTF-8
C++
false
false
15,057
// Copyright (c) 2011-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_QT_WALLETMODEL_H #define BITCOIN_QT_WALLETMODEL_H #include "paymentrequestplus.h" #include "walletmodeltransaction.h" #include "support/allocators/secure.h" #include <map> #include <vector> #include <QVector> #include <QObject> #include <QDate> class AddressTableModel; class OptionsModel; class PlatformStyle; class RecentRequestsTableModel; class TransactionTableModel; class WalletModelTransaction; class CValidationState; class CCoinControl; class CKeyID; class COutPoint; class COutput; class CPubKey; class CWallet; class uint256; QT_BEGIN_NAMESPACE class QTimer; QT_END_NAMESPACE class SendCoinsRecipient { public: explicit SendCoinsRecipient() : amount(0), fSubtractFeeFromAmount(false), nVersion(SendCoinsRecipient::CURRENT_VERSION) { } explicit SendCoinsRecipient(const QString &addr, const QString &_label, const CAmount& _amount, const QString &_message): address(addr), label(_label), amount(_amount), message(_message), fSubtractFeeFromAmount(false), nVersion(SendCoinsRecipient::CURRENT_VERSION) {} QString address; QString label; CAmount amount; // If from a payment request, this is used for storing the memo QString message; // If from a payment request, paymentRequest.IsInitialized() will be true PaymentRequestPlus paymentRequest; // Empty if no authentication or invalid signature/cert/etc. QString authenticatedMerchant; bool fSubtractFeeFromAmount; // memory only static const int CURRENT_VERSION = 1; int nVersion; ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action) { std::string sAddress = address.toStdString(); std::string sLabel = label.toStdString(); std::string sMessage = message.toStdString(); std::string sPaymentRequest; if (!ser_action.ForRead() && paymentRequest.IsInitialized()) paymentRequest.SerializeToString(&sPaymentRequest); std::string sAuthenticatedMerchant = authenticatedMerchant.toStdString(); READWRITE(this->nVersion); READWRITE(sAddress); READWRITE(sLabel); READWRITE(amount); READWRITE(sMessage); READWRITE(sPaymentRequest); READWRITE(sAuthenticatedMerchant); if (ser_action.ForRead()) { address = QString::fromStdString(sAddress); label = QString::fromStdString(sLabel); message = QString::fromStdString(sMessage); if (!sPaymentRequest.empty()) paymentRequest.parse(QByteArray::fromRawData(sPaymentRequest.data(), sPaymentRequest.size())); authenticatedMerchant = QString::fromStdString(sAuthenticatedMerchant); } } }; /** Interface to Bitcoin wallet from Qt view code. */ class WalletModel : public QObject { Q_OBJECT public: explicit WalletModel(const PlatformStyle *platformStyle, CWallet *wallet, OptionsModel *optionsModel, QObject *parent = 0); ~WalletModel(); enum StatusCode // Returned by sendCoins { OK, InvalidAmount, InvalidAddress, AmountExceedsBalance, AmountWithFeeExceedsBalance, DuplicateAddress, TransactionCreationFailed, // Error returned when wallet is still locked TransactionCommitFailed, AbsurdFee, PaymentRequestExpired, PsdErr, NumErr, InitErr }; enum EncryptionStatus { Unencrypted, // !wallet->IsCrypted() Locked, // wallet->IsCrypted() && wallet->IsLocked() Unlocked // wallet->IsCrypted() && !wallet->IsLocked() }; OptionsModel *getOptionsModel(); AddressTableModel *getAddressTableModel(); TransactionTableModel *getTransactionTableModel(); RecentRequestsTableModel *getRecentRequestsTableModel(); CAmount getBalance(const CCoinControl *coinControl = NULL) const; CAmount GetDetained() const; int GetDepth() const; uint64_t getpow10(uint64_t oldnum,int n); CAmount getUnconfirmedBalance() const; CAmount getImmatureBalance() const; bool haveWatchOnly() const; CAmount getWatchBalance() const; CAmount getWatchUnconfirmedBalance() const; CAmount getWatchImmatureBalance() const; EncryptionStatus getEncryptionStatus() const; // Check address for validity bool validateAddress(const QString &address); // Return status record for SendCoins, contains error id + information struct SendCoinsReturn { SendCoinsReturn(StatusCode _status = OK, QString _reasonCommitFailed = "") : status(_status), reasonCommitFailed(_reasonCommitFailed) { } StatusCode status; QString reasonCommitFailed; }; struct CBookKeep { std::string time; std::string award; }; struct keepupaccountInfo{ CAmount Coin_; QString Add_; }; void getbookkeepList(std::vector<WalletModel::CBookKeep>& bookkeeplist); //20180201 void startTimerControl(); QString processeCoinsCreateReturn(const WalletModel::SendCoinsReturn &sendCoinsReturn); SendCoinsReturn prepareeCoinsCreate(QString coin_name,QString coin_md5,QString coin_label,QString timestr,QString add1,QString &msg,int inttimr,int accuracy,uint64_t amount1); //20180201 // prepare transaction for getting txfee before sending coins SendCoinsReturn prepareTransaction(WalletModelTransaction &transaction, const CCoinControl *coinControl = NULL); SendCoinsReturn prepareBookkeepingTransaction(QString add1,CAmount amount1,std::string &error,WalletModelTransaction &transaction, const CCoinControl *coinControl); SendCoinsReturn sendBookkeeping(QString add2,WalletModelTransaction &transaction); SendCoinsReturn prepareExitBookkeeping(const CCoinControl *coinControl,std::string &error); SendCoinsReturn ExitBookkeeping(WalletModelTransaction &transaction); SendCoinsReturn prepareeCoinsCreateTransaction(QStringList label,QString add1,WalletModelTransaction &transaction, const CCoinControl *coinControl); SendCoinsReturn prepareeCoinsSendCreateTransaction(std::string& Txid,int Index,uint64_t eCount,WalletModelTransaction &transaction, std::string &error, const CCoinControl *coinControl = NULL); SendCoinsReturn prepareNormalTransaction(WalletModelTransaction &transaction, const CCoinControl *coinControl = NULL); SendCoinsReturn prepareIPCRegTransaction(WalletModelTransaction &transaction, uint8_t ExtendType, uint32_t startTime, uint32_t stopTime, uint8_t reAuthorize, uint8_t uniqueAuthorize, std::string hash, std::string labelTitle, std::string txLabel, const CCoinControl *coinControl = NULL); SendCoinsReturn prepareIPCSendTransaction(std::string& IPCSendvinTxid,int Index, WalletModelTransaction &transaction, const CCoinControl *coinControl = NULL); SendCoinsReturn prepareIPCAuthorizationTransaction(WalletModelTransaction &transaction,std::string txid,int txi, QStringList data, const CCoinControl *coinControl = NULL); SendCoinsReturn prepareTokenRegTransaction(WalletModelTransaction &transaction, const CCoinControl *coinControl = NULL); SendCoinsReturn prepareTokenTransaction(WalletModelTransaction &transaction, const CCoinControl *coinControl = NULL); SendCoinsReturn sendIpcTransfer(); SendCoinsReturn sendCoins(WalletModelTransaction &transaction); SendCoinsReturn sendcreateeCoins(); bool setWalletEncrypted(bool encrypted, const SecureString &passphrase); // Passphrase only needed when unlocking bool setWalletLocked(bool locked, const SecureString &passPhrase=SecureString()); bool changePassphrase(const SecureString &oldPass, const SecureString &newPass); // Wallet backup bool backupWallet(const QString &filename); // RAI object for unlocking wallet, returned by requestUnlock() class UnlockContext { public: UnlockContext(WalletModel *wallet, bool valid, bool relock); ~UnlockContext(); bool isValid() const { return valid; } // Copy operator and constructor transfer the context UnlockContext(const UnlockContext& obj) { CopyFrom(obj); } UnlockContext& operator=(const UnlockContext& rhs) { CopyFrom(rhs); return *this; } private: WalletModel *wallet; bool valid; mutable bool relock; // mutable, as it can be set to false by copying void CopyFrom(const UnlockContext& rhs); }; UnlockContext requestUnlock(); bool getPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const; bool havePrivKey(const CKeyID &address) const; bool getPrivKey(const CKeyID &address, CKey& vchPrivKeyOut) const; void getOutputs(const std::vector<COutPoint>& vOutpoints, std::vector<COutput>& vOutputs); bool isSpent(const COutPoint& outpoint) const; void listCoins(std::map<QString, std::vector<COutput> >& mapCoins) const; bool isLockedCoin(uint256 hash, unsigned int n) const; void lockCoin(COutPoint& output); void unlockCoin(COutPoint& output); void listLockedCoins(std::vector<COutPoint>& vOutpts); void loadReceiveRequests(std::vector<std::string>& vReceiveRequests); bool saveReceiveRequest(const std::string &sAddress, const int64_t nId, const std::string &sRequest); bool transactionCanBeAbandoned(uint256 hash) const; bool abandonTransaction(uint256 hash) const; static bool isWalletEnabled(); bool hdEnabled() const; int getDefaultConfirmTarget() const; //ipclist std::vector<COutput> m_ipcCoins; std::vector<COutput> m_eCoins; //get ipc list void getIpcListCoins(QVector<QStringList>&); void getTokenListCoins(std::map<std::string, uint64_t>&); QStringList getInfoFromIpcList(int index); bool CreateIpcRegister(QString,QString,QString,QString,int,QString &msg,int &fee); bool CreateWalletFromFile(QString); QString IntTimeToQStringTime(int); QString IntTimeToLocalQStringTime(int inttime); QString IntTimeToQStringTimeForDetilDialog(int); bool sendIpcCoins(); bool LoadWalletFromFile(QString filepath); bool transferIpc(QString address,QString &errstr); //20180201 bool preparetransferIpc(QString address,QString &msg); bool prepareauthorizationIpc(QString address,int license,int exclusive,int intstart,int intend,QString& msg); bool sendauthorizationIpc(QString &msg); WalletModel::SendCoinsReturn prepareecoinaffrim(QString num,QString add,QString name); WalletModel::SendCoinsReturn sendecoinaffrim(); WalletModel::SendCoinsReturn sendtransferIpc(); //20180201 bool authorizationIpc(QString,int,int,int,int,QString&); CAmount getTotal(QList<SendCoinsRecipient>&,QSet<QString>&,int &); bool ExportWalletToFile(std::string); bool CheckPassword(); bool CheckIsCrypted(); int GetAccuracyBySymbol(std::string tokensymbol); std::string m_sendcoinerror; QString getAccuracyNumstr(QString name ,QString num); QString getDeposit(QString address); void setUpdataFinished(); bool m_bFinishedLoading; int GetDepthInMainChain(int iIndex); QString GetECoinCanUseNum(QString name); QString GetIssueDateBySymbol(QString name); QString GetTimeOfTokenInChain(int iIndex); QDate getSySQDate(); bool CanIPCTransaction(int iIndex); bool copyFileToPath(QString sourceDir ,QString toDir, bool coverFileIfExist); QString getCreditValue(QString strDeposit); private: CWallet *wallet; WalletModelTransaction *m_WalletModelTransactionIpcRegister; WalletModelTransaction *m_WalletModelTransactioneCoinRegister; WalletModelTransaction *m_WalletModelTransactioneCoinSend1; WalletModelTransaction *m_WalletModelTransactionIpcTransfer; WalletModelTransaction *currentTransaction1; bool fHaveWatchOnly; bool fForceCheckBalanceChanged; bool ipcSendIsValidState; int ipcSelectFromList; // Wallet has an options model for wallet-specific options // (transaction fee, for example) OptionsModel *optionsModel; AddressTableModel *addressTableModel; TransactionTableModel *transactionTableModel; RecentRequestsTableModel *recentRequestsTableModel; // Cache some values to be able to detect changes CAmount cachedBalance; CAmount cachedUnconfirmedBalance; CAmount cachedImmatureBalance; CAmount cachedWatchOnlyBalance; CAmount cachedWatchUnconfBalance; CAmount cachedWatchImmatureBalance; CAmount cachednewDepositBalance; EncryptionStatus cachedEncryptionStatus; int cachedNumBlocks; QTimer *pollTimer; QTimer *pollTimer_; void subscribeToCoreSignals(); void unsubscribeFromCoreSignals(); void checkBalanceChanged(); Q_SIGNALS: // Signal that balance in wallet changed void balanceChanged(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance, const CAmount& watchOnlyBalance, const CAmount& watchUnconfBalance, const CAmount& watchImmatureBalance,const CAmount& depositBalance); // Encryption status of wallet changed void encryptionStatusChanged(int status); // Signal emitted when wallet needs to be unlocked // It is valid behaviour for listeners to keep the wallet locked after this signal; // this means that the unlocking failed or was cancelled. void requireUnlock(); // Fired when a message should be reported to the user void message(const QString &title, const QString &message, unsigned int style); // Coins sent: from wallet, to recipient, in (serialized) transaction: void coinsSent(CWallet* wallet, SendCoinsRecipient recipient, QByteArray transaction); // Show progress dialog e.g. for rescan void showProgress(const QString &title, int nProgress); // Watch-only address added void notifyWatchonlyChanged(bool fHaveWatchonly); void updateIpcList(); void updataLoadingFinished(); void updataLater(); public Q_SLOTS: /* Wallet status might have changed */ void updateStatus(); /* New transaction, or transaction changed status */ void updateTransaction(); /* New, updated or removed address book entry */ void updateAddressBook(const QString &address, const QString &label, bool isMine, const QString &purpose, int status); /* Watch-only added */ void updateWatchOnlyFlag(bool fHaveWatchonly); /* Current, immature or unconfirmed balance might have changed - emit 'balanceChanged' if so */ void pollBalanceChanged(); void updateTimer(); }; #endif // BITCOIN_QT_WALLETMODEL_H
[ "34546443+IPCChain@users.noreply.github.com" ]
34546443+IPCChain@users.noreply.github.com
5637fa36510a85a1e8d3d23a831ccc3bab198cd3
5e2ed0faff2fa033efba3b3345f2d0c27efaa3ac
/eear-Plugin/JuceLibraryCode/modules/juce_core/time/juce_Time.cpp
8b12acbb4342b2d07bdb2201cbbb14e9cc4b085e
[]
no_license
carthach/eear
f498f40ea824abd5d51270e7789bd742de352ccd
8decda157866fb00490b23769769b29821dc0039
refs/heads/master
2020-04-15T12:41:02.720908
2016-06-30T14:40:39
2016-06-30T14:40:39
41,671,635
6
2
null
null
null
null
UTF-8
C++
false
false
22,628
cpp
/* ============================================================================== This file is part of the juce_core module of the JUCE library. Copyright (c) 2015 - ROLI Ltd. 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. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ------------------------------------------------------------------------------ NOTE! This permissive ISC license applies ONLY to files within the juce_core module! All other JUCE modules are covered by a dual GPL/commercial license, so if you are using any other modules, be sure to check that you also comply with their license. For more details, visit www.juce.com ============================================================================== */ namespace TimeHelpers { static struct tm millisecondsToTM (const int64 jdm) noexcept { struct tm result; const int days = (int) (jdm / 86400LL); const int a = 32044 + days; const int b = (4 * a + 3) / 146097; const int c = a - (b * 146097) / 4; const int d = (4 * c + 3) / 1461; const int e = c - (d * 1461) / 4; const int m = (5 * e + 2) / 153; result.tm_mday = e - (153 * m + 2) / 5 + 1; result.tm_mon = m + 2 - 12 * (m / 10); result.tm_year = b * 100 + d - 6700 + (m / 10); result.tm_wday = (days + 1) % 7; result.tm_yday = -1; int t = (int) (jdm % 86400LL); result.tm_hour = t / 3600; t %= 3600; result.tm_min = t / 60; result.tm_sec = t % 60; result.tm_isdst = -1; return result; } static bool isBeyond1970to2030Range (const int64 seconds) { return seconds < 86400LL || seconds >= 2145916800LL; } static struct tm millisToLocal (const int64 millis) noexcept { const int64 seconds = millis / 1000; if (isBeyond1970to2030Range (seconds)) { const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000); return millisecondsToTM (seconds + timeZoneAdjustment + 210866803200LL); } struct tm result; time_t now = static_cast<time_t> (seconds); #if JUCE_WINDOWS && JUCE_MINGW return *localtime (&now); #elif JUCE_WINDOWS if (now >= 0 && now <= 0x793406fff) localtime_s (&result, &now); else zerostruct (result); #else localtime_r (&now, &result); // more thread-safe #endif return result; } static struct tm millisToUTC (const int64 millis) noexcept { const int64 seconds = millis / 1000; if (isBeyond1970to2030Range (seconds)) return millisecondsToTM (seconds + 210866803200LL); struct tm result; time_t now = static_cast<time_t> (seconds); #if JUCE_WINDOWS && JUCE_MINGW return *gmtime (&now); #elif JUCE_WINDOWS if (now >= 0 && now <= 0x793406fff) gmtime_s (&result, &now); else zerostruct (result); #else gmtime_r (&now, &result); // more thread-safe #endif return result; } static int getUTCOffsetSeconds (const int64 millis) noexcept { struct tm utc = millisToUTC (millis); utc.tm_isdst = -1; // Treat this UTC time as local to find the offset return (int) ((millis / 1000) - (int64) mktime (&utc)); } static int extendedModulo (const int64 value, const int modulo) noexcept { return (int) (value >= 0 ? (value % modulo) : (value - ((value / modulo) + 1) * modulo)); } static inline String formatString (const String& format, const struct tm* const tm) { #if JUCE_ANDROID typedef CharPointer_UTF8 StringType; #elif JUCE_WINDOWS typedef CharPointer_UTF16 StringType; #else typedef CharPointer_UTF32 StringType; #endif #ifdef JUCE_MSVC if (tm->tm_year < -1900 || tm->tm_year > 8099) return String(); // Visual Studio's library can only handle 0 -> 9999 AD #endif for (size_t bufferSize = 256; ; bufferSize += 256) { HeapBlock<StringType::CharType> buffer (bufferSize); const size_t numChars = #if JUCE_ANDROID strftime (buffer, bufferSize - 1, format.toUTF8(), tm); #elif JUCE_WINDOWS wcsftime (buffer, bufferSize - 1, format.toWideCharPointer(), tm); #else wcsftime (buffer, bufferSize - 1, format.toUTF32(), tm); #endif if (numChars > 0 || format.isEmpty()) return String (StringType (buffer), StringType (buffer) + (int) numChars); } } static uint32 lastMSCounterValue = 0; } //============================================================================== Time::Time() noexcept : millisSinceEpoch (0) { } Time::Time (const Time& other) noexcept : millisSinceEpoch (other.millisSinceEpoch) { } Time::Time (const int64 ms) noexcept : millisSinceEpoch (ms) { } Time::Time (const int year, const int month, const int day, const int hours, const int minutes, const int seconds, const int milliseconds, const bool useLocalTime) noexcept { jassert (year > 100); // year must be a 4-digit version if (year < 1971 || year >= 2038 || ! useLocalTime) { // use extended maths for dates beyond 1970 to 2037.. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000)) : 0; const int a = (13 - month) / 12; const int y = year + 4800 - a; const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5 + (y * 365) + (y / 4) - (y / 100) + (y / 400) - 32045; const int64 s = ((int64) jd) * 86400LL - 210866803200LL; millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment)) + milliseconds; } else { struct tm t; t.tm_year = year - 1900; t.tm_mon = month; t.tm_mday = day; t.tm_hour = hours; t.tm_min = minutes; t.tm_sec = seconds; t.tm_isdst = -1; millisSinceEpoch = 1000 * (int64) mktime (&t); if (millisSinceEpoch < 0) millisSinceEpoch = 0; else millisSinceEpoch += milliseconds; } } Time::~Time() noexcept { } Time& Time::operator= (const Time& other) noexcept { millisSinceEpoch = other.millisSinceEpoch; return *this; } //============================================================================== int64 Time::currentTimeMillis() noexcept { #if JUCE_WINDOWS && ! JUCE_MINGW struct _timeb t; _ftime_s (&t); return ((int64) t.time) * 1000 + t.millitm; #else struct timeval tv; gettimeofday (&tv, nullptr); return ((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000; #endif } Time JUCE_CALLTYPE Time::getCurrentTime() noexcept { return Time (currentTimeMillis()); } //============================================================================== uint32 juce_millisecondsSinceStartup() noexcept; uint32 Time::getMillisecondCounter() noexcept { const uint32 now = juce_millisecondsSinceStartup(); if (now < TimeHelpers::lastMSCounterValue) { // in multi-threaded apps this might be called concurrently, so // make sure that our last counter value only increases and doesn't // go backwards.. if (now < TimeHelpers::lastMSCounterValue - 1000) TimeHelpers::lastMSCounterValue = now; } else { TimeHelpers::lastMSCounterValue = now; } return now; } uint32 Time::getApproximateMillisecondCounter() noexcept { if (TimeHelpers::lastMSCounterValue == 0) getMillisecondCounter(); return TimeHelpers::lastMSCounterValue; } void Time::waitForMillisecondCounter (const uint32 targetTime) noexcept { for (;;) { const uint32 now = getMillisecondCounter(); if (now >= targetTime) break; const int toWait = (int) (targetTime - now); if (toWait > 2) { Thread::sleep (jmin (20, toWait >> 1)); } else { // xxx should consider using mutex_pause on the mac as it apparently // makes it seem less like a spinlock and avoids lowering the thread pri. for (int i = 10; --i >= 0;) Thread::yield(); } } } //============================================================================== double Time::highResolutionTicksToSeconds (const int64 ticks) noexcept { return ticks / (double) getHighResolutionTicksPerSecond(); } int64 Time::secondsToHighResolutionTicks (const double seconds) noexcept { return (int64) (seconds * (double) getHighResolutionTicksPerSecond()); } //============================================================================== String Time::toString (const bool includeDate, const bool includeTime, const bool includeSeconds, const bool use24HourClock) const noexcept { String result; if (includeDate) { result << getDayOfMonth() << ' ' << getMonthName (true) << ' ' << getYear(); if (includeTime) result << ' '; } if (includeTime) { const int mins = getMinutes(); result << (use24HourClock ? getHours() : getHoursInAmPmFormat()) << (mins < 10 ? ":0" : ":") << mins; if (includeSeconds) { const int secs = getSeconds(); result << (secs < 10 ? ":0" : ":") << secs; } if (! use24HourClock) result << (isAfternoon() ? "pm" : "am"); } return result.trimEnd(); } String Time::formatted (const String& format) const { struct tm t (TimeHelpers::millisToLocal (millisSinceEpoch)); return TimeHelpers::formatString (format, &t); } //============================================================================== int Time::getYear() const noexcept { return TimeHelpers::millisToLocal (millisSinceEpoch).tm_year + 1900; } int Time::getMonth() const noexcept { return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mon; } int Time::getDayOfYear() const noexcept { return TimeHelpers::millisToLocal (millisSinceEpoch).tm_yday; } int Time::getDayOfMonth() const noexcept { return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mday; } int Time::getDayOfWeek() const noexcept { return TimeHelpers::millisToLocal (millisSinceEpoch).tm_wday; } int Time::getHours() const noexcept { return TimeHelpers::millisToLocal (millisSinceEpoch).tm_hour; } int Time::getMinutes() const noexcept { return TimeHelpers::millisToLocal (millisSinceEpoch).tm_min; } int Time::getSeconds() const noexcept { return TimeHelpers::extendedModulo (millisSinceEpoch / 1000, 60); } int Time::getMilliseconds() const noexcept { return TimeHelpers::extendedModulo (millisSinceEpoch, 1000); } int Time::getHoursInAmPmFormat() const noexcept { const int hours = getHours(); if (hours == 0) return 12; if (hours <= 12) return hours; return hours - 12; } bool Time::isAfternoon() const noexcept { return getHours() >= 12; } bool Time::isDaylightSavingTime() const noexcept { return TimeHelpers::millisToLocal (millisSinceEpoch).tm_isdst != 0; } String Time::getTimeZone() const noexcept { String zone[2]; #if JUCE_MSVC _tzset(); for (int i = 0; i < 2; ++i) { char name[128] = { 0 }; size_t length; _get_tzname (&length, name, 127, i); zone[i] = name; } #else #if JUCE_MINGW #warning "Can't find a replacement for tzset on mingw - ideas welcome!" #else tzset(); #endif const char** const zonePtr = (const char**) tzname; zone[0] = zonePtr[0]; zone[1] = zonePtr[1]; #endif if (isDaylightSavingTime()) { zone[0] = zone[1]; if (zone[0].length() > 3 && zone[0].containsIgnoreCase ("daylight") && zone[0].contains ("GMT")) zone[0] = "BST"; } return zone[0].substring (0, 3); } int Time::getUTCOffsetSeconds() const noexcept { return TimeHelpers::getUTCOffsetSeconds (millisSinceEpoch); } String Time::getUTCOffsetString (bool includeSemiColon) const { if (int seconds = getUTCOffsetSeconds()) { const int minutes = seconds / 60; return String::formatted (includeSemiColon ? "%+03d:%02d" : "%+03d%02d", minutes / 60, minutes % 60); } return "Z"; } String Time::toISO8601 (bool includeDividerCharacters) const { return String::formatted (includeDividerCharacters ? "%04d-%02d-%02dT%02d:%02d:%02.03f" : "%04d%02d%02dT%02d%02d%02.03f", getYear(), getMonth() + 1, getDayOfMonth(), getHours(), getMinutes(), getSeconds() + getMilliseconds() / 1000.0) + getUTCOffsetString (includeDividerCharacters); } static int parseFixedSizeIntAndSkip (String::CharPointerType& t, int numChars, char charToSkip) noexcept { int n = 0; for (int i = numChars; --i >= 0;) { const int digit = (int) (*t - '0'); if (! isPositiveAndBelow (digit, 10)) return -1; ++t; n = n * 10 + digit; } if (charToSkip != 0 && *t == (juce_wchar) charToSkip) ++t; return n; } Time Time::fromISO8601 (StringRef iso) noexcept { String::CharPointerType t = iso.text; const int year = parseFixedSizeIntAndSkip (t, 4, '-'); if (year < 0) return Time(); const int month = parseFixedSizeIntAndSkip (t, 2, '-'); if (month < 0) return Time(); const int day = parseFixedSizeIntAndSkip (t, 2, 0); if (day < 0) return Time(); int hours = 0, minutes = 0, milliseconds = 0; if (*t == 'T') { ++t; hours = parseFixedSizeIntAndSkip (t, 2, ':'); if (hours < 0) return Time(); minutes = parseFixedSizeIntAndSkip (t, 2, ':'); if (minutes < 0) return Time(); milliseconds = (int) (1000.0 * CharacterFunctions::readDoubleValue (t)); } const juce_wchar nextChar = t.getAndAdvance(); if (nextChar == '-' || nextChar == '+') { const int offsetHours = parseFixedSizeIntAndSkip (t, 2, ':'); if (offsetHours < 0) return Time(); const int offsetMinutes = parseFixedSizeIntAndSkip (t, 2, 0); if (offsetMinutes < 0) return Time(); const int offsetMs = (offsetHours * 60 + offsetMinutes) * 60 * 1000; milliseconds += nextChar == '-' ? offsetMs : -offsetMs; // NB: this seems backwards but is correct! } else if (nextChar != 0 && nextChar != 'Z') { return Time(); } Time result (year, month - 1, day, hours, minutes, 0, 0, false); result.millisSinceEpoch += milliseconds; return result; } String Time::getMonthName (const bool threeLetterVersion) const { return getMonthName (getMonth(), threeLetterVersion); } String Time::getWeekdayName (const bool threeLetterVersion) const { return getWeekdayName (getDayOfWeek(), threeLetterVersion); } static const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; static const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; String Time::getMonthName (int monthNumber, const bool threeLetterVersion) { monthNumber %= 12; return TRANS (threeLetterVersion ? shortMonthNames [monthNumber] : longMonthNames [monthNumber]); } String Time::getWeekdayName (int day, const bool threeLetterVersion) { static const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; static const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; day %= 7; return TRANS (threeLetterVersion ? shortDayNames [day] : longDayNames [day]); } //============================================================================== Time& Time::operator+= (RelativeTime delta) noexcept { millisSinceEpoch += delta.inMilliseconds(); return *this; } Time& Time::operator-= (RelativeTime delta) noexcept { millisSinceEpoch -= delta.inMilliseconds(); return *this; } Time operator+ (Time time, RelativeTime delta) noexcept { Time t (time); return t += delta; } Time operator- (Time time, RelativeTime delta) noexcept { Time t (time); return t -= delta; } Time operator+ (RelativeTime delta, Time time) noexcept { Time t (time); return t += delta; } const RelativeTime operator- (Time time1, Time time2) noexcept { return RelativeTime::milliseconds (time1.toMilliseconds() - time2.toMilliseconds()); } bool operator== (Time time1, Time time2) noexcept { return time1.toMilliseconds() == time2.toMilliseconds(); } bool operator!= (Time time1, Time time2) noexcept { return time1.toMilliseconds() != time2.toMilliseconds(); } bool operator< (Time time1, Time time2) noexcept { return time1.toMilliseconds() < time2.toMilliseconds(); } bool operator> (Time time1, Time time2) noexcept { return time1.toMilliseconds() > time2.toMilliseconds(); } bool operator<= (Time time1, Time time2) noexcept { return time1.toMilliseconds() <= time2.toMilliseconds(); } bool operator>= (Time time1, Time time2) noexcept { return time1.toMilliseconds() >= time2.toMilliseconds(); } static int getMonthNumberForCompileDate (const String& m) noexcept { for (int i = 0; i < 12; ++i) if (m.equalsIgnoreCase (shortMonthNames[i])) return i; // If you hit this because your compiler has an unusual __DATE__ // format, let us know so we can add support for it! jassertfalse; return 0; } Time Time::getCompilationDate() { StringArray dateTokens, timeTokens; dateTokens.addTokens (__DATE__, true); dateTokens.removeEmptyStrings (true); timeTokens.addTokens (__TIME__, ":", StringRef()); return Time (dateTokens[2].getIntValue(), getMonthNumberForCompileDate (dateTokens[0]), dateTokens[1].getIntValue(), timeTokens[0].getIntValue(), timeTokens[1].getIntValue()); } //============================================================================== //============================================================================== #if JUCE_UNIT_TESTS class TimeTests : public UnitTest { public: TimeTests() : UnitTest ("Time") {} void runTest() override { beginTest ("Time"); Time t = Time::getCurrentTime(); expect (t > Time()); Thread::sleep (15); expect (Time::getCurrentTime() > t); expect (t.getTimeZone().isNotEmpty()); expect (t.getUTCOffsetString (true) == "Z" || t.getUTCOffsetString (true).length() == 6); expect (t.getUTCOffsetString (false) == "Z" || t.getUTCOffsetString (false).length() == 5); expect (Time::fromISO8601 (t.toISO8601 (true)) == t); expect (Time::fromISO8601 (t.toISO8601 (false)) == t); expect (Time::fromISO8601 ("2016-02-16") == Time (2016, 1, 16, 0, 0, 0, 0, false)); expect (Time::fromISO8601 ("20160216Z") == Time (2016, 1, 16, 0, 0, 0, 0, false)); expect (Time::fromISO8601 ("2016-02-16T15:03:57+00:00") == Time (2016, 1, 16, 15, 3, 57, 0, false)); expect (Time::fromISO8601 ("20160216T150357+0000") == Time (2016, 1, 16, 15, 3, 57, 0, false)); expect (Time::fromISO8601 ("2016-02-16T15:03:57.999+00:00") == Time (2016, 1, 16, 15, 3, 57, 999, false)); expect (Time::fromISO8601 ("20160216T150357.999+0000") == Time (2016, 1, 16, 15, 3, 57, 999, false)); expect (Time::fromISO8601 ("2016-02-16T15:03:57.999Z") == Time (2016, 1, 16, 15, 3, 57, 999, false)); expect (Time::fromISO8601 ("20160216T150357.999Z") == Time (2016, 1, 16, 15, 3, 57, 999, false)); expect (Time::fromISO8601 ("2016-02-16T15:03:57.999-02:30") == Time (2016, 1, 16, 17, 33, 57, 999, false)); expect (Time::fromISO8601 ("20160216T150357.999-0230") == Time (2016, 1, 16, 17, 33, 57, 999, false)); } }; static TimeTests timeTests; #endif
[ "carthach@carthach.tk" ]
carthach@carthach.tk
42fbaf4d6202a73de58e2cfcc9a679f30e04f0f3
f34f24353324fc7c67b329435fd2a0be35a05349
/Hinode_DevAtlas_Jam2/Source/Hinode_DevAtlas_Jam2/Characters/SapphireLv3Enemy.cpp
def588ac823b225767590da17a3506cb8b1fce8d
[]
no_license
Josh1182021/Hinode-DevAtlas-Jam2
3cc9edd0c0770ada53cdd88c1cea6eb47a1f8bde
091ea26ed494f4bae2debe2b289db581e4d75fe8
refs/heads/master
2023-03-24T06:43:17.852306
2021-03-18T04:54:51
2021-03-18T04:54:51
283,803,461
0
0
null
null
null
null
UTF-8
C++
false
false
1,808
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "SapphireLv3Enemy.h" #include "Components/CapsuleComponent.h" #include "Kismet/GameplayStatics.h" #include "Hinode_DevAtlas_Jam2/Characters/SapphireMainCharacter.h" #include "Hinode_DevAtlas_Jam2/Actors/SapphireLv3EnemySpawner.h" // Sets default values ASapphireLv3Enemy::ASapphireLv3Enemy() { // Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; } void ASapphireLv3Enemy::Died() { if(GetOwner()) { ASapphireLv3EnemySpawner* Spawner = Cast<ASapphireLv3EnemySpawner>(GetOwner()); if(Spawner) { UE_LOG(LogTemp, Warning, TEXT("got here")); Spawner->SpawnEnemyCPP(); } } Destroy(); } // Called when the game starts or when spawned void ASapphireLv3Enemy::BeginPlay() { Super::BeginPlay(); GetCapsuleComponent()->OnComponentHit.AddDynamic(this, &ASapphireLv3Enemy::OnHit); } // Called every frame void ASapphireLv3Enemy::Tick(float DeltaTime) { Super::Tick(DeltaTime); } // Called to bind functionality to input void ASapphireLv3Enemy::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); } void ASapphireLv3Enemy::OnHit(UPrimitiveComponent* HitComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse, const FHitResult& Hit) { if (OtherActor == nullptr || OtherActor == this) { return; } ASapphireMainCharacter* PlayerRef = Cast<ASapphireMainCharacter>(OtherActor); if(PlayerRef == nullptr) { return; } else { UGameplayStatics::ApplyDamage(OtherActor, Damage, Controller, this, DamageType); UGameplayStatics::ApplyDamage(this , Damage, Controller, this, DamageType); } }
[ "66659887+Josh1182021@users.noreply.github.com" ]
66659887+Josh1182021@users.noreply.github.com
56e5fc2f8fe710ea5568e83699ad2fa83ada3f45
5ff10b372f99b3eed9bde75ac0007e4383dc42a6
/00 Source File/UIImageObject.h
6ac9fe494d4147c5d8afbd4c605d9358f9909577
[]
no_license
RyunosukeHonda/Util
4a3dc94413068b408785e973a3bb7a5f00d23a9f
d9e235eeee0f336009545bc20e60c92471eae31b
refs/heads/master
2020-05-18T16:07:39.315632
2019-05-28T14:42:57
2019-05-28T14:42:57
184,518,192
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
1,052
h
/** * @file UIImageObject.h * @brief UI用画像オブジェクトクラス定義ファイル * @author Ryunosuke Honda. */ #pragma once #include "RectTransform.h" #include "IObject.h" #include "TextureID.h" #include "UIImageRenderDesc.h" /** * UI用画像オブジェクトクラス */ class UIImageObject : public RectTransform, public IObject { public: /** * @fn * コンストラクタ */ UIImageObject(const TextureID& id); /** * @fn * デストラクタ */ virtual ~UIImageObject(); /** * @fn * テクスチャID設定 */ void setID(const TextureID& id); /** * @fn * 色設定 * @param (color) 設定する色 * @detail * シェーダーに送る色を設定するだけなので * 対応しているシェーダーのみ色が変わります */ void setColor(const Color4& color); // IObject を介して継承されました virtual void draw(IRenderer & renderer) override; protected: //!描画記述子 UIImageRenderDesc mDesc; }; /* End of File *****************************************************/
[ "ryuh19961105@gmail.com" ]
ryuh19961105@gmail.com
8e234ff06cea1867d142ab4bf7e4706b09d23c7c
7a6105f869babcd056723fe785475814852b1bc6
/Client/View/Editor/File.h
422036fe5c2761fc2c64522bea52d4cedd4e095b
[]
no_license
uvbs/TowerDefense
79b4eedfe331981a4f1db55de17304a6f8189377
c6c0801c31b9896b37fba301f4fcbb541c456a38
refs/heads/master
2020-03-21T10:26:38.971016
2018-03-11T22:57:17
2018-03-11T22:57:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
261
h
#ifndef TOWERDEFENSE_FILE_H #define TOWERDEFENSE_FILE_H #include <fstream> class File { private: std::fstream file; public: File(const std::string& fileName); ~File(); void write(const std::string& content); }; #endif //TOWERDEFENSE_FILE_H
[ "damiancassinotti.33@gmail.com" ]
damiancassinotti.33@gmail.com
5ae96b32d01ac71f2ec12b29b638e96a7cec83d8
2d5a912ddcdd4c39a82868e950b670f3995b8783
/PYTHONSOURCE/devel/include/baxter_maintenance_msgs/UpdateStatus.h
a633d1d6c678088b7c9de3aed220b6bf5841ab63
[]
no_license
julitosnchez/TFG
27214334539aa893756d1d7ed8c263b68ee78baf
dc7285ed3797610db8ce902c588f588b7304b6f7
refs/heads/master
2020-03-27T22:18:39.675387
2018-09-07T08:57:06
2018-09-07T08:57:06
147,220,362
0
0
null
null
null
null
UTF-8
C++
false
false
7,060
h
// Generated by gencpp from file baxter_maintenance_msgs/UpdateStatus.msg // DO NOT EDIT! #ifndef BAXTER_MAINTENANCE_MSGS_MESSAGE_UPDATESTATUS_H #define BAXTER_MAINTENANCE_MSGS_MESSAGE_UPDATESTATUS_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> namespace baxter_maintenance_msgs { template <class ContainerAllocator> struct UpdateStatus_ { typedef UpdateStatus_<ContainerAllocator> Type; UpdateStatus_() : status(0) , progress(0.0) , long_description() { } UpdateStatus_(const ContainerAllocator& _alloc) : status(0) , progress(0.0) , long_description(_alloc) { (void)_alloc; } typedef uint16_t _status_type; _status_type status; typedef float _progress_type; _progress_type progress; typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _long_description_type; _long_description_type long_description; enum { STS_IDLE = 0u }; enum { STS_INVALID = 1u }; enum { STS_BUSY = 2u }; enum { STS_CANCELLED = 3u }; enum { STS_ERR = 4u }; enum { STS_MOUNT_UPDATE = 5u }; enum { STS_VERIFY_UPDATE = 6u }; enum { STS_PREP_STAGING = 7u }; enum { STS_MOUNT_STAGING = 8u }; enum { STS_EXTRACT_UPDATE = 9u }; enum { STS_LOAD_KEXEC = 10u }; typedef boost::shared_ptr< ::baxter_maintenance_msgs::UpdateStatus_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::baxter_maintenance_msgs::UpdateStatus_<ContainerAllocator> const> ConstPtr; }; // struct UpdateStatus_ typedef ::baxter_maintenance_msgs::UpdateStatus_<std::allocator<void> > UpdateStatus; typedef boost::shared_ptr< ::baxter_maintenance_msgs::UpdateStatus > UpdateStatusPtr; typedef boost::shared_ptr< ::baxter_maintenance_msgs::UpdateStatus const> UpdateStatusConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::baxter_maintenance_msgs::UpdateStatus_<ContainerAllocator> & v) { ros::message_operations::Printer< ::baxter_maintenance_msgs::UpdateStatus_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace baxter_maintenance_msgs namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False} // {'baxter_maintenance_msgs': ['/home/jsm/ros_ws/src/baxter_common/baxter_maintenance_msgs/msg'], 'std_msgs': ['/opt/ros/indigo/share/std_msgs/cmake/../msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::baxter_maintenance_msgs::UpdateStatus_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::baxter_maintenance_msgs::UpdateStatus_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct IsMessage< ::baxter_maintenance_msgs::UpdateStatus_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::baxter_maintenance_msgs::UpdateStatus_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::baxter_maintenance_msgs::UpdateStatus_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::baxter_maintenance_msgs::UpdateStatus_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::baxter_maintenance_msgs::UpdateStatus_<ContainerAllocator> > { static const char* value() { return "74e246350421569590252c39e8aa7b85"; } static const char* value(const ::baxter_maintenance_msgs::UpdateStatus_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0x74e2463504215695ULL; static const uint64_t static_value2 = 0x90252c39e8aa7b85ULL; }; template<class ContainerAllocator> struct DataType< ::baxter_maintenance_msgs::UpdateStatus_<ContainerAllocator> > { static const char* value() { return "baxter_maintenance_msgs/UpdateStatus"; } static const char* value(const ::baxter_maintenance_msgs::UpdateStatus_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::baxter_maintenance_msgs::UpdateStatus_<ContainerAllocator> > { static const char* value() { return "# See the class UpdateRunner()\n\ # status: One-word description of the current action being performed\n\ # long_description: Details pertaining to status if any. Used for verbose error messages.\n\ \n\ uint16 status\n\ float32 progress\n\ string long_description\n\ \n\ uint16 STS_IDLE = 0\n\ uint16 STS_INVALID = 1\n\ uint16 STS_BUSY = 2\n\ uint16 STS_CANCELLED = 3\n\ uint16 STS_ERR = 4\n\ uint16 STS_MOUNT_UPDATE = 5\n\ uint16 STS_VERIFY_UPDATE = 6\n\ uint16 STS_PREP_STAGING = 7\n\ uint16 STS_MOUNT_STAGING = 8\n\ uint16 STS_EXTRACT_UPDATE = 9\n\ uint16 STS_LOAD_KEXEC = 10\n\ \n\ "; } static const char* value(const ::baxter_maintenance_msgs::UpdateStatus_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::baxter_maintenance_msgs::UpdateStatus_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.status); stream.next(m.progress); stream.next(m.long_description); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct UpdateStatus_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::baxter_maintenance_msgs::UpdateStatus_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::baxter_maintenance_msgs::UpdateStatus_<ContainerAllocator>& v) { s << indent << "status: "; Printer<uint16_t>::stream(s, indent + " ", v.status); s << indent << "progress: "; Printer<float>::stream(s, indent + " ", v.progress); s << indent << "long_description: "; Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.long_description); } }; } // namespace message_operations } // namespace ros #endif // BAXTER_MAINTENANCE_MSGS_MESSAGE_UPDATESTATUS_H
[ "julitosnchez@correo.ugr.es" ]
julitosnchez@correo.ugr.es
30741078216cbca399d39bb8799ff28844dbc804
60bd79d18cf69c133abcb6b0d8b0a959f61b4d10
/libraries/I2CKeyPad8x8/test/unit_test_001.cpp
9142ccc62cb2aa3688e6b6c80189886429da8e10
[ "MIT" ]
permissive
RobTillaart/Arduino
e75ae38fa6f043f1213c4c7adb310e91da59e4ba
48a7d9ec884e54fcc7323e340407e82fcc08ea3d
refs/heads/master
2023-09-01T03:32:38.474045
2023-08-31T20:07:39
2023-08-31T20:07:39
2,544,179
1,406
3,798
MIT
2022-10-27T08:28:51
2011-10-09T19:53:59
C++
UTF-8
C++
false
false
1,907
cpp
// // FILE: unit_test_001.cpp // AUTHOR: Rob Tillaart // DATE: 2022-09-28 // PURPOSE: unit tests for the I2CKeyPad8x8 library // https://github.com/RobTillaart/I2CKeyPad8x8 // https://github.com/Arduino-CI/arduino_ci/blob/master/REFERENCE.md // // supported assertions // https://github.com/Arduino-CI/arduino_ci/blob/master/cpp/unittest/Assertion.h#L33-L42 // ---------------------------- // assertEqual(expected, actual) // assertNotEqual(expected, actual) // assertLess(expected, actual) // assertMore(expected, actual) // assertLessOrEqual(expected, actual) // assertMoreOrEqual(expected, actual) // assertTrue(actual) // assertFalse(actual) // assertNull(actual) // assertNotNull(actual) #include <ArduinoUnitTests.h> #include "Arduino.h" #include "I2CKeyPad8x8.h" unittest_setup() { fprintf(stderr, "I2C_KEYPAD8x8_LIB_VERSION: %s\n", (char *) I2C_KEYPAD8x8_LIB_VERSION); } unittest_teardown() { } unittest(test_constants) { assertEqual(64, I2C_KEYPAD8x8_NOKEY); assertEqual(65, I2C_KEYPAD8x8_FAIL); } unittest(test_constructor) { const uint8_t KEYPAD_ADDRESS = 0x38; I2CKeyPad8x8 keyPad(KEYPAD_ADDRESS); assertEqual(I2C_KEYPAD8x8_NOKEY, keyPad.getLastKey()); // assertTrue(keyPad.begin()); // assertTrue(keyPad.isConnected()); } // unittest(test_KeyMap) // { // const uint8_t KEYPAD_ADDRESS = 0x38; // I2CKeyPad8x8 keyPad(KEYPAD_ADDRESS); // char keymap[66] = "123A456B789C*0#DNF"; // keyPad.loadKeyMap(keymap); // assertEqual('N', keyPad.getLastChar()); // } // Issues with Wire - to be investigated... // // unittest(test_read) // { // const uint8_t KEYPAD_ADDRESS = 0x38; // I2CKeyPad8x8 keyPad(KEYPAD_ADDRESS); // assertTrue(keyPad.isConnected()); // // assertTrue(keyPad.begin()); // // assertEqual(I2C_KEYPAD_NOKEY, keyPad.getKey()); // // assertFalse(keyPad.isPressed()); // } unittest_main() // --------
[ "rob.tillaart@gmail.com" ]
rob.tillaart@gmail.com
ffb1c8f3d7e98cabd880a0370912b84db608fff5
c0a23a5cb6b1c2ea3855c2537d0df6c08e5e00d5
/code/header/block/pd_block.h
d31cf2d18280df3c3b775c4db000e7a90c6608a9
[ "MIT" ]
permissive
1217720084/steps
e73c9cf051d8a77f228b0dde58089037c1bde6dc
4d6ebf909abb0b41162088e7e68e7e3b486ccfe6
refs/heads/master
2021-02-14T09:05:55.745624
2020-02-23T13:22:34
2020-02-23T13:22:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
868
h
#ifndef PD_BLOCK_H #define PD_BLOCK_H #include "header/block/block.h" #include "header/block/proportional_block.h" #include "header/block/differential_block.h" class PD_BLOCK : public BLOCK { // Kp+sKd/(1+sTd) public: PD_BLOCK(STEPS& toolkit); ~PD_BLOCK(); void set_Kp(double K); void set_Kd(double K); void set_Td_in_s(double T); double get_Kp() const; double get_Kd() const; double get_Td_in_s() const; double get_differentiator_state() const; double get_differentiator_store() const; void initialize(); void run(DYNAMIC_MODE mode); virtual void check(); private: void integrate(); void update(); PROPORTIONAL_BLOCK p_block; DIFFERENTIAL_BLOCK d_block; }; #endif // PD_BLOCK_H
[ "lichgang@sdu.edu.cn" ]
lichgang@sdu.edu.cn
aacbc737b730fc9a69efe04e9613a6a4fa99587c
c3154e8620d3a97cdea9491b2cb37b152eb07d91
/Framework/Core/Src/StreamReader.cpp
7d60b5be115e3f1d5abbf12bcb176fe3e5eb984c
[ "MIT" ]
permissive
amyrhzhao/CooEngine
e9283e10f6f374b2420c7f20117850beb82f6a93
8d467cc53fd8fe3806d726cfe4d7482ad0aca06a
refs/heads/master
2020-12-24T03:43:35.021231
2020-09-19T00:18:43
2020-09-19T00:18:43
281,494,528
3
0
null
null
null
null
UTF-8
C++
false
false
687
cpp
#include "Precompiled.h" #include "StreamReader.h" #include "MemoryStream.h" using namespace Coo::Core; StreamReader::StreamReader(MemoryStream & memoryStream) : mMemoryStream{ memoryStream } { memoryStream.Rewind(); } void StreamReader::Read(std::string & data) { int stringLength; Read(stringLength); char* str = new char[stringLength]; Read(str, stringLength); data.assign(str, stringLength); } bool StreamReader::Read(void * data, uint32_t size) { if (mMemoryStream.mHead + size > mMemoryStream.mCapacity) { return false; } memcpy(data, mMemoryStream.mBuffer + mMemoryStream.mHead, size); mMemoryStream.mHead += size; return true; }
[ "ImportService@microsoft.com" ]
ImportService@microsoft.com
f34a4ecf6b9affb705ad71c4856cbbb19268c618
16d10131d74c47974eca2008fcdf3c36e534dc18
/oneflow/core/actor/acc_compute_actor.cpp
86fcf77523f668a11f2aae7e5f552edb92b0e909
[ "Apache-2.0" ]
permissive
wwd190906/oneflow
6674cae3228e7a6e32d3b12b9742770561f47eaa
37df98ae61c35976c5fc8f53513844110effdf3f
refs/heads/master
2023-07-06T11:22:39.647617
2021-08-05T05:32:49
2021-08-05T05:32:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,595
cpp
/* Copyright 2020 The OneFlow Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "oneflow/core/actor/compute_actor.h" namespace oneflow { class AccCompActor final : public CompActor { public: OF_DISALLOW_COPY_AND_MOVE(AccCompActor); AccCompActor() = default; ~AccCompActor() override = default; private: int64_t ActNumForEachOutput(int64_t regst_desc_id) const override; void Act() override; void VirtualAsyncSendNaiveProducedRegstMsgToConsumer() override; void VirtualCompActorInit(const TaskProto& proto) override; void Init(const TaskProto&, int32_t max_acc_cnt); std::function<void(DeviceCtx*, void* dst, const void* src, size_t)> cpy_func_; int32_t acc_cnt_; int32_t max_acc_cnt_; }; void AccCompActor::VirtualCompActorInit(const TaskProto& proto) { const Shape& in_time_shape = Global<RegstMgr>::Get() ->RegstDesc4RegstDescId(Name2SoleRegstDescId("in")) .data_regst_time_shape(); const Shape& out_time_shape = Global<RegstMgr>::Get() ->RegstDesc4RegstDescId(Name2SoleRegstDescId("out")) .data_regst_time_shape(); CHECK_GE(in_time_shape.elem_cnt(), out_time_shape.elem_cnt()); Init(proto, in_time_shape.elem_cnt() / out_time_shape.elem_cnt()); } void AccCompActor::Init(const TaskProto& task_proto, int32_t max_acc_cnt) { using namespace std::placeholders; if (GetDeviceType() == DeviceType::kCPU) { cpy_func_ = std::bind(Memcpy<DeviceType::kCPU>, _1, _2, _3, _4); } else { #ifdef WITH_CUDA cpy_func_ = std::bind(Memcpy<DeviceType::kGPU>, _1, _2, _3, _4); #else UNIMPLEMENTED(); #endif } OF_SET_MSG_HANDLER(&AccCompActor::HandlerNormal); acc_cnt_ = 0; max_acc_cnt_ = max_acc_cnt; } int64_t AccCompActor::ActNumForEachOutput(int64_t regst_desc_id) const { return regst_desc_id == Name2SoleRegstDescId("out") ? max_acc_cnt_ : 1; } void AccCompActor::Act() { Regst* out_regst = GetNaiveCurWriteable("out"); Regst* in_regst = GetNaiveCurReadable("in"); KernelCtx kernel_ctx = GenDefaultKernelCtx(); if (acc_cnt_ == 0) { const Blob* in_blob = in_regst->GetMutSoleBlob(); Blob* out_blob = out_regst->GetMutSoleBlob(); if (GetDeviceType() == DeviceType::kCPU) { Memcpy<DeviceType::kCPU>(kernel_ctx.device_ctx, out_blob->ForceMutDptr(), in_blob->dptr(), out_blob->ByteSizeOfBlobBody()); } else if (GetDeviceType() == DeviceType::kGPU) { #ifdef WITH_CUDA Memcpy<DeviceType::kGPU>(kernel_ctx.device_ctx, out_blob->ForceMutDptr(), in_blob->dptr(), out_blob->ByteSizeOfBlobBody()); #else UNIMPLEMENTED(); #endif } else { UNIMPLEMENTED(); } } else { AsyncLaunchKernel(kernel_ctx); } acc_cnt_ += 1; } void AccCompActor::VirtualAsyncSendNaiveProducedRegstMsgToConsumer() { if (acc_cnt_ == max_acc_cnt_) { HandleProducedNaiveDataRegstToConsumer(); acc_cnt_ = 0; } } REGISTER_ACTOR(TaskType::kAcc, AccCompActor); } // namespace oneflow
[ "noreply@github.com" ]
wwd190906.noreply@github.com
d93b2f71f91e39badf6f08f5114acf8676604182
e9450baebfcc751108b07e2c663d1e5a2a783fdb
/src/BB/Game.cpp
808eda3331831727879d4701ea1c2cc62645433a
[]
no_license
dymani/BrainBurst1
009e26c068bd959ec06f96d4a936d2b0ead9a4ea
7ea647b26f5aa81cbb430bb95b5b6af7243d97f0
refs/heads/master
2021-01-17T22:02:45.450106
2016-02-13T16:34:23
2016-02-13T16:34:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,613
cpp
#include "BB/Game.h" #include "BB/GameState/IGameState.h" namespace bb { Game::Game() { } Game::~Game() { while(!m_states.empty()) popState(); } int Game::run() { #if _DEBUG HWND hWnd = GetConsoleWindow(); ShowWindow(hWnd, SW_SHOW); #else HWND hWnd = GetConsoleWindow(); ShowWindow(hWnd, SW_HIDE); #endif clock_t previous, lag, current, elapsed; previous = clock(); lag = 0; bool isRunning = true; while(isRunning) { current = clock(); elapsed = current - previous; previous = current; lag += elapsed; if(peekState() == nullptr) continue; peekState()->handleInput(); while(lag >= MS_PER_UPDATE) { isRunning = peekState()->update(); lag -= MS_PER_UPDATE; } peekState()->draw(double(lag) / double(MS_PER_UPDATE)); } #if _DEBUG system("PAUSE"); #endif return 0; } void Game::pushState(IGameState* state) { m_states.push(state); return; } void Game::popState() { delete m_states.top(); m_states.pop(); return; } void Game::changeState(IGameState* state) { if(!m_states.empty()) { popState(); } pushState(state); return; } IGameState* Game::peekState() { if(m_states.empty()) return nullptr; return m_states.top(); } }
[ "auyf.g118@gmail.com" ]
auyf.g118@gmail.com
d538058a4fe911efe1746078833cbcef6757de72
601ed0172226dd5ea7366c7b20c521eb3df1e6b0
/6.cpp
5f43a7579f48737f6a661ae6f349429ceb0f92c6
[]
no_license
Beisenbek/PL2016_W3_G3_D1
5743d73c357a205859da7bcbe56773b168a23954
8d315bc1c5b36a0f8d95a3a335963531cb93c5b2
refs/heads/master
2020-12-05T20:21:41.000066
2016-09-07T09:45:51
2016-09-07T09:45:51
67,593,815
0
0
null
null
null
null
UTF-8
C++
false
false
167
cpp
#include <iostream> #include <cmath> using namespace std; int main(){ int a; cin >> a; cout << (char)a << endl; cout << char(a); cout << endl; return 0; }
[ "bsnbk@Beisenbeks-MacBook-Pro.local" ]
bsnbk@Beisenbeks-MacBook-Pro.local
31a59f08c41a7fbe98fa6a0c2b6100e16b726ce4
fcc4255330e54117e785fe4f9ad7f03f13e9b59f
/practice/cpp/sort/array_quadruplet.cpp
5a6cf196dd045092b1232bf193a2f06a71824fb6
[]
no_license
truongpt/warm_up
f5cc018e997e7edefe2802c6e346366e32c41b35
47c5694537fbe32ed389e82c862e283b90a9066d
refs/heads/master
2023-07-18T11:10:22.978036
2021-09-02T20:32:04
2021-09-02T20:32:04
242,413,021
4
0
null
null
null
null
ISO-8859-3
C++
false
false
3,749
cpp
/* - Problem: Array Quadruplet Given an unsorted array of integers arr and a number s, write a function findArrayQuadruplet that finds four numbers (quadruplet) in arr that sum up to s. Your function should return an array of these numbers in an ascending order. If such a quadruplet doesnft exist, return an empty array. Note that there may be more than one quadruplet in arr whose sum is s. Youfre asked to return the first one you encounter (considering the results are sorted). Explain and code the most efficient solution possible, and analyze its time and space complexities. - input: arr = [2, 7, 4, 0, 9, 5, 1, 3], s = 20 - output: [0, 4, 7, 9] - Solution 1. - Brute force -> 4 for loop - Time & Space. - TC: O(n^4) - SC: O(1) - Solution 2. - Start from sum 2 elements problem. -> https://www.youtube.com/watch?v=XKu_SEDAykw - Time complexity: O(n) - Space complexity: - O(n) for unsorted array - O(1) for sorted array - For sum 3 elements -> O(n^2) ``` For i = 0 -> n-3 { sum2( s - arr[i]) } ``` - Time complexity: O(n^2) - For sum 3 elements ``` For i = 0 -> n-4 { sum3( s - arr[i]) } ``` - Time complexity: O(n^3) - Space complexity: O(log n) <- memory for sorting array, assume sort algorithms is quick sort. - Comparing performance. - Use case at main function. - Result - Solution 1: 5.10503 (second) - Solution 2: 0.030944 (second) */ #include <iostream> #include <vector> #include <algorithm> #include <stdlib.h> #include "../utility/perf.h" using namespace std; vector<int> find4SumBF (vector<int>& arr, int s) { if (arr.size() < 4) return {}; int n = arr.size(); vector<int> res = {}; for (int i = 0; i < n-3; i++) { for (int j = i+1; j < n-2; j++) { for (int k = j+1; k < n-1; k++) { for (int h = k+1; h < n; h++) { if (s == arr[i] + arr[j] + arr[k] + arr[h]) { res.push_back(arr[i]); res.push_back(arr[j]); res.push_back(arr[k]); res.push_back(arr[h]); sort(res.begin(), res.end()); return res; } } } } } return {}; } vector<int> find4SumO (vector<int>& arr, int s) { if (arr.size() < 4) return {}; sort(arr.begin(), arr.end()); int n = arr.size(); vector<int> res = {}; for (int i = 0; i < n-3; i++) { for (int j = i+1; j < n-2; j++) { int l = j+1, r = n-1; int sum2 = s - arr[i] - arr[j]; while (l < r) { if (arr[l] + arr[r] < sum2) { l++; } else if (arr[l] + arr[r] > sum2) { r--; } else { return {arr[i], arr[j], arr[l], arr[r]}; } } } } return {}; } int main(void) { vector<int> arr1 = {}, arr2 = {}; int num = 1000; int s = 100*rand(); for (int i = 0; i < num; i++) { int temp = rand(); arr1.push_back(temp); arr2.push_back(temp); } vector<int> res; { TIME_SCOPE("find4SumBF"); res = find4SumBF(arr1, s); } // verify int sum = 0; for (auto it : res) { sum += it; } if (sum != s) { cout << "S1 Error" << endl; } { TIME_SCOPE("find4SumO"); res = find4SumO(arr2, s); } sum = 0; for (auto it : res) { sum += it; } if (sum != s) { cout << "S1 Error" << endl; } }
[ "truongptk30a3@gmail.com" ]
truongptk30a3@gmail.com
51283da3156ac51bd74f51dc94c03f0ee2a66576
12703a558be75704bf52c238a0d54f74168950c8
/Wali/Wali/233994/Release/WebCore.framework/Versions/A/PrivateHeaders/ReadableByteStreamInternalsBuiltins.h
6c465f40db6e218a9b1d80d5388c3ab5b80f246d
[]
no_license
FarhanQ7/Wali_
ef1dac5069af644456085bedb4f6ca2b6bc140d5
1c1997c374cdf3f815ef84dff53a3d98fd763f78
refs/heads/master
2020-03-23T11:22:07.908316
2018-07-23T02:07:39
2018-07-23T02:07:39
141,499,716
0
0
null
null
null
null
UTF-8
C++
false
false
35,194
h
/* * Copyright (c) 2016 Apple Inc. All rights reserved. * Copyright (c) 2016 Canon Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * */ // DO NOT EDIT THIS FILE. It is automatically generated from JavaScript files for // builtins by the script: Source/JavaScriptCore/Scripts/generate-js-builtins.py #pragma once #if ENABLE(STREAMS_API) #include <JavaScriptCore/BuiltinUtils.h> #include <JavaScriptCore/Identifier.h> #include <JavaScriptCore/JSFunction.h> #include <JavaScriptCore/UnlinkedFunctionExecutable.h> namespace JSC { class FunctionExecutable; } namespace WebCore { /* ReadableByteStreamInternals */ extern const char* s_readableByteStreamInternalsPrivateInitializeReadableStreamBYOBReaderCode; extern const int s_readableByteStreamInternalsPrivateInitializeReadableStreamBYOBReaderCodeLength; extern const JSC::ConstructAbility s_readableByteStreamInternalsPrivateInitializeReadableStreamBYOBReaderCodeConstructAbility; extern const char* s_readableByteStreamInternalsPrivateInitializeReadableByteStreamControllerCode; extern const int s_readableByteStreamInternalsPrivateInitializeReadableByteStreamControllerCodeLength; extern const JSC::ConstructAbility s_readableByteStreamInternalsPrivateInitializeReadableByteStreamControllerCodeConstructAbility; extern const char* s_readableByteStreamInternalsPrivateInitializeReadableStreamBYOBRequestCode; extern const int s_readableByteStreamInternalsPrivateInitializeReadableStreamBYOBRequestCodeLength; extern const JSC::ConstructAbility s_readableByteStreamInternalsPrivateInitializeReadableStreamBYOBRequestCodeConstructAbility; extern const char* s_readableByteStreamInternalsIsReadableByteStreamControllerCode; extern const int s_readableByteStreamInternalsIsReadableByteStreamControllerCodeLength; extern const JSC::ConstructAbility s_readableByteStreamInternalsIsReadableByteStreamControllerCodeConstructAbility; extern const char* s_readableByteStreamInternalsIsReadableStreamBYOBRequestCode; extern const int s_readableByteStreamInternalsIsReadableStreamBYOBRequestCodeLength; extern const JSC::ConstructAbility s_readableByteStreamInternalsIsReadableStreamBYOBRequestCodeConstructAbility; extern const char* s_readableByteStreamInternalsIsReadableStreamBYOBReaderCode; extern const int s_readableByteStreamInternalsIsReadableStreamBYOBReaderCodeLength; extern const JSC::ConstructAbility s_readableByteStreamInternalsIsReadableStreamBYOBReaderCodeConstructAbility; extern const char* s_readableByteStreamInternalsReadableByteStreamControllerCancelCode; extern const int s_readableByteStreamInternalsReadableByteStreamControllerCancelCodeLength; extern const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerCancelCodeConstructAbility; extern const char* s_readableByteStreamInternalsReadableByteStreamControllerErrorCode; extern const int s_readableByteStreamInternalsReadableByteStreamControllerErrorCodeLength; extern const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerErrorCodeConstructAbility; extern const char* s_readableByteStreamInternalsReadableByteStreamControllerCloseCode; extern const int s_readableByteStreamInternalsReadableByteStreamControllerCloseCodeLength; extern const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerCloseCodeConstructAbility; extern const char* s_readableByteStreamInternalsReadableByteStreamControllerClearPendingPullIntosCode; extern const int s_readableByteStreamInternalsReadableByteStreamControllerClearPendingPullIntosCodeLength; extern const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerClearPendingPullIntosCodeConstructAbility; extern const char* s_readableByteStreamInternalsReadableByteStreamControllerGetDesiredSizeCode; extern const int s_readableByteStreamInternalsReadableByteStreamControllerGetDesiredSizeCodeLength; extern const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerGetDesiredSizeCodeConstructAbility; extern const char* s_readableByteStreamInternalsReadableStreamHasBYOBReaderCode; extern const int s_readableByteStreamInternalsReadableStreamHasBYOBReaderCodeLength; extern const JSC::ConstructAbility s_readableByteStreamInternalsReadableStreamHasBYOBReaderCodeConstructAbility; extern const char* s_readableByteStreamInternalsReadableStreamHasDefaultReaderCode; extern const int s_readableByteStreamInternalsReadableStreamHasDefaultReaderCodeLength; extern const JSC::ConstructAbility s_readableByteStreamInternalsReadableStreamHasDefaultReaderCodeConstructAbility; extern const char* s_readableByteStreamInternalsReadableByteStreamControllerHandleQueueDrainCode; extern const int s_readableByteStreamInternalsReadableByteStreamControllerHandleQueueDrainCodeLength; extern const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerHandleQueueDrainCodeConstructAbility; extern const char* s_readableByteStreamInternalsReadableByteStreamControllerPullCode; extern const int s_readableByteStreamInternalsReadableByteStreamControllerPullCodeLength; extern const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerPullCodeConstructAbility; extern const char* s_readableByteStreamInternalsReadableByteStreamControllerShouldCallPullCode; extern const int s_readableByteStreamInternalsReadableByteStreamControllerShouldCallPullCodeLength; extern const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerShouldCallPullCodeConstructAbility; extern const char* s_readableByteStreamInternalsReadableByteStreamControllerCallPullIfNeededCode; extern const int s_readableByteStreamInternalsReadableByteStreamControllerCallPullIfNeededCodeLength; extern const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerCallPullIfNeededCodeConstructAbility; extern const char* s_readableByteStreamInternalsTransferBufferToCurrentRealmCode; extern const int s_readableByteStreamInternalsTransferBufferToCurrentRealmCodeLength; extern const JSC::ConstructAbility s_readableByteStreamInternalsTransferBufferToCurrentRealmCodeConstructAbility; extern const char* s_readableByteStreamInternalsReadableByteStreamControllerEnqueueCode; extern const int s_readableByteStreamInternalsReadableByteStreamControllerEnqueueCodeLength; extern const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerEnqueueCodeConstructAbility; extern const char* s_readableByteStreamInternalsReadableByteStreamControllerEnqueueChunkCode; extern const int s_readableByteStreamInternalsReadableByteStreamControllerEnqueueChunkCodeLength; extern const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerEnqueueChunkCodeConstructAbility; extern const char* s_readableByteStreamInternalsReadableByteStreamControllerRespondWithNewViewCode; extern const int s_readableByteStreamInternalsReadableByteStreamControllerRespondWithNewViewCodeLength; extern const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerRespondWithNewViewCodeConstructAbility; extern const char* s_readableByteStreamInternalsReadableByteStreamControllerRespondCode; extern const int s_readableByteStreamInternalsReadableByteStreamControllerRespondCodeLength; extern const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerRespondCodeConstructAbility; extern const char* s_readableByteStreamInternalsReadableByteStreamControllerRespondInternalCode; extern const int s_readableByteStreamInternalsReadableByteStreamControllerRespondInternalCodeLength; extern const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerRespondInternalCodeConstructAbility; extern const char* s_readableByteStreamInternalsReadableByteStreamControllerRespondInReadableStateCode; extern const int s_readableByteStreamInternalsReadableByteStreamControllerRespondInReadableStateCodeLength; extern const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerRespondInReadableStateCodeConstructAbility; extern const char* s_readableByteStreamInternalsReadableByteStreamControllerRespondInClosedStateCode; extern const int s_readableByteStreamInternalsReadableByteStreamControllerRespondInClosedStateCodeLength; extern const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerRespondInClosedStateCodeConstructAbility; extern const char* s_readableByteStreamInternalsReadableByteStreamControllerProcessPullDescriptorsCode; extern const int s_readableByteStreamInternalsReadableByteStreamControllerProcessPullDescriptorsCodeLength; extern const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerProcessPullDescriptorsCodeConstructAbility; extern const char* s_readableByteStreamInternalsReadableByteStreamControllerFillDescriptorFromQueueCode; extern const int s_readableByteStreamInternalsReadableByteStreamControllerFillDescriptorFromQueueCodeLength; extern const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerFillDescriptorFromQueueCodeConstructAbility; extern const char* s_readableByteStreamInternalsReadableByteStreamControllerShiftPendingDescriptorCode; extern const int s_readableByteStreamInternalsReadableByteStreamControllerShiftPendingDescriptorCodeLength; extern const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerShiftPendingDescriptorCodeConstructAbility; extern const char* s_readableByteStreamInternalsReadableByteStreamControllerInvalidateBYOBRequestCode; extern const int s_readableByteStreamInternalsReadableByteStreamControllerInvalidateBYOBRequestCodeLength; extern const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerInvalidateBYOBRequestCodeConstructAbility; extern const char* s_readableByteStreamInternalsReadableByteStreamControllerCommitDescriptorCode; extern const int s_readableByteStreamInternalsReadableByteStreamControllerCommitDescriptorCodeLength; extern const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerCommitDescriptorCodeConstructAbility; extern const char* s_readableByteStreamInternalsReadableByteStreamControllerConvertDescriptorCode; extern const int s_readableByteStreamInternalsReadableByteStreamControllerConvertDescriptorCodeLength; extern const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerConvertDescriptorCodeConstructAbility; extern const char* s_readableByteStreamInternalsReadableStreamFulfillReadIntoRequestCode; extern const int s_readableByteStreamInternalsReadableStreamFulfillReadIntoRequestCodeLength; extern const JSC::ConstructAbility s_readableByteStreamInternalsReadableStreamFulfillReadIntoRequestCodeConstructAbility; extern const char* s_readableByteStreamInternalsReadableStreamBYOBReaderReadCode; extern const int s_readableByteStreamInternalsReadableStreamBYOBReaderReadCodeLength; extern const JSC::ConstructAbility s_readableByteStreamInternalsReadableStreamBYOBReaderReadCodeConstructAbility; extern const char* s_readableByteStreamInternalsReadableByteStreamControllerPullIntoCode; extern const int s_readableByteStreamInternalsReadableByteStreamControllerPullIntoCodeLength; extern const JSC::ConstructAbility s_readableByteStreamInternalsReadableByteStreamControllerPullIntoCodeConstructAbility; extern const char* s_readableByteStreamInternalsReadableStreamAddReadIntoRequestCode; extern const int s_readableByteStreamInternalsReadableStreamAddReadIntoRequestCodeLength; extern const JSC::ConstructAbility s_readableByteStreamInternalsReadableStreamAddReadIntoRequestCodeConstructAbility; #define WEBCORE_FOREACH_READABLEBYTESTREAMINTERNALS_BUILTIN_DATA(macro) \ macro(privateInitializeReadableStreamBYOBReader, readableByteStreamInternalsPrivateInitializeReadableStreamBYOBReader, 1) \ macro(privateInitializeReadableByteStreamController, readableByteStreamInternalsPrivateInitializeReadableByteStreamController, 3) \ macro(privateInitializeReadableStreamBYOBRequest, readableByteStreamInternalsPrivateInitializeReadableStreamBYOBRequest, 2) \ macro(isReadableByteStreamController, readableByteStreamInternalsIsReadableByteStreamController, 1) \ macro(isReadableStreamBYOBRequest, readableByteStreamInternalsIsReadableStreamBYOBRequest, 1) \ macro(isReadableStreamBYOBReader, readableByteStreamInternalsIsReadableStreamBYOBReader, 1) \ macro(readableByteStreamControllerCancel, readableByteStreamInternalsReadableByteStreamControllerCancel, 2) \ macro(readableByteStreamControllerError, readableByteStreamInternalsReadableByteStreamControllerError, 2) \ macro(readableByteStreamControllerClose, readableByteStreamInternalsReadableByteStreamControllerClose, 1) \ macro(readableByteStreamControllerClearPendingPullIntos, readableByteStreamInternalsReadableByteStreamControllerClearPendingPullIntos, 1) \ macro(readableByteStreamControllerGetDesiredSize, readableByteStreamInternalsReadableByteStreamControllerGetDesiredSize, 1) \ macro(readableStreamHasBYOBReader, readableByteStreamInternalsReadableStreamHasBYOBReader, 1) \ macro(readableStreamHasDefaultReader, readableByteStreamInternalsReadableStreamHasDefaultReader, 1) \ macro(readableByteStreamControllerHandleQueueDrain, readableByteStreamInternalsReadableByteStreamControllerHandleQueueDrain, 1) \ macro(readableByteStreamControllerPull, readableByteStreamInternalsReadableByteStreamControllerPull, 1) \ macro(readableByteStreamControllerShouldCallPull, readableByteStreamInternalsReadableByteStreamControllerShouldCallPull, 1) \ macro(readableByteStreamControllerCallPullIfNeeded, readableByteStreamInternalsReadableByteStreamControllerCallPullIfNeeded, 1) \ macro(transferBufferToCurrentRealm, readableByteStreamInternalsTransferBufferToCurrentRealm, 1) \ macro(readableByteStreamControllerEnqueue, readableByteStreamInternalsReadableByteStreamControllerEnqueue, 2) \ macro(readableByteStreamControllerEnqueueChunk, readableByteStreamInternalsReadableByteStreamControllerEnqueueChunk, 4) \ macro(readableByteStreamControllerRespondWithNewView, readableByteStreamInternalsReadableByteStreamControllerRespondWithNewView, 2) \ macro(readableByteStreamControllerRespond, readableByteStreamInternalsReadableByteStreamControllerRespond, 2) \ macro(readableByteStreamControllerRespondInternal, readableByteStreamInternalsReadableByteStreamControllerRespondInternal, 2) \ macro(readableByteStreamControllerRespondInReadableState, readableByteStreamInternalsReadableByteStreamControllerRespondInReadableState, 3) \ macro(readableByteStreamControllerRespondInClosedState, readableByteStreamInternalsReadableByteStreamControllerRespondInClosedState, 2) \ macro(readableByteStreamControllerProcessPullDescriptors, readableByteStreamInternalsReadableByteStreamControllerProcessPullDescriptors, 1) \ macro(readableByteStreamControllerFillDescriptorFromQueue, readableByteStreamInternalsReadableByteStreamControllerFillDescriptorFromQueue, 2) \ macro(readableByteStreamControllerShiftPendingDescriptor, readableByteStreamInternalsReadableByteStreamControllerShiftPendingDescriptor, 1) \ macro(readableByteStreamControllerInvalidateBYOBRequest, readableByteStreamInternalsReadableByteStreamControllerInvalidateBYOBRequest, 1) \ macro(readableByteStreamControllerCommitDescriptor, readableByteStreamInternalsReadableByteStreamControllerCommitDescriptor, 2) \ macro(readableByteStreamControllerConvertDescriptor, readableByteStreamInternalsReadableByteStreamControllerConvertDescriptor, 1) \ macro(readableStreamFulfillReadIntoRequest, readableByteStreamInternalsReadableStreamFulfillReadIntoRequest, 3) \ macro(readableStreamBYOBReaderRead, readableByteStreamInternalsReadableStreamBYOBReaderRead, 2) \ macro(readableByteStreamControllerPullInto, readableByteStreamInternalsReadableByteStreamControllerPullInto, 2) \ macro(readableStreamAddReadIntoRequest, readableByteStreamInternalsReadableStreamAddReadIntoRequest, 1) \ #define WEBCORE_BUILTIN_READABLEBYTESTREAMINTERNALS_PRIVATEINITIALIZEREADABLESTREAMBYOBREADER 1 #define WEBCORE_BUILTIN_READABLEBYTESTREAMINTERNALS_PRIVATEINITIALIZEREADABLEBYTESTREAMCONTROLLER 1 #define WEBCORE_BUILTIN_READABLEBYTESTREAMINTERNALS_PRIVATEINITIALIZEREADABLESTREAMBYOBREQUEST 1 #define WEBCORE_BUILTIN_READABLEBYTESTREAMINTERNALS_ISREADABLEBYTESTREAMCONTROLLER 1 #define WEBCORE_BUILTIN_READABLEBYTESTREAMINTERNALS_ISREADABLESTREAMBYOBREQUEST 1 #define WEBCORE_BUILTIN_READABLEBYTESTREAMINTERNALS_ISREADABLESTREAMBYOBREADER 1 #define WEBCORE_BUILTIN_READABLEBYTESTREAMINTERNALS_READABLEBYTESTREAMCONTROLLERCANCEL 1 #define WEBCORE_BUILTIN_READABLEBYTESTREAMINTERNALS_READABLEBYTESTREAMCONTROLLERERROR 1 #define WEBCORE_BUILTIN_READABLEBYTESTREAMINTERNALS_READABLEBYTESTREAMCONTROLLERCLOSE 1 #define WEBCORE_BUILTIN_READABLEBYTESTREAMINTERNALS_READABLEBYTESTREAMCONTROLLERCLEARPENDINGPULLINTOS 1 #define WEBCORE_BUILTIN_READABLEBYTESTREAMINTERNALS_READABLEBYTESTREAMCONTROLLERGETDESIREDSIZE 1 #define WEBCORE_BUILTIN_READABLEBYTESTREAMINTERNALS_READABLESTREAMHASBYOBREADER 1 #define WEBCORE_BUILTIN_READABLEBYTESTREAMINTERNALS_READABLESTREAMHASDEFAULTREADER 1 #define WEBCORE_BUILTIN_READABLEBYTESTREAMINTERNALS_READABLEBYTESTREAMCONTROLLERHANDLEQUEUEDRAIN 1 #define WEBCORE_BUILTIN_READABLEBYTESTREAMINTERNALS_READABLEBYTESTREAMCONTROLLERPULL 1 #define WEBCORE_BUILTIN_READABLEBYTESTREAMINTERNALS_READABLEBYTESTREAMCONTROLLERSHOULDCALLPULL 1 #define WEBCORE_BUILTIN_READABLEBYTESTREAMINTERNALS_READABLEBYTESTREAMCONTROLLERCALLPULLIFNEEDED 1 #define WEBCORE_BUILTIN_READABLEBYTESTREAMINTERNALS_TRANSFERBUFFERTOCURRENTREALM 1 #define WEBCORE_BUILTIN_READABLEBYTESTREAMINTERNALS_READABLEBYTESTREAMCONTROLLERENQUEUE 1 #define WEBCORE_BUILTIN_READABLEBYTESTREAMINTERNALS_READABLEBYTESTREAMCONTROLLERENQUEUECHUNK 1 #define WEBCORE_BUILTIN_READABLEBYTESTREAMINTERNALS_READABLEBYTESTREAMCONTROLLERRESPONDWITHNEWVIEW 1 #define WEBCORE_BUILTIN_READABLEBYTESTREAMINTERNALS_READABLEBYTESTREAMCONTROLLERRESPOND 1 #define WEBCORE_BUILTIN_READABLEBYTESTREAMINTERNALS_READABLEBYTESTREAMCONTROLLERRESPONDINTERNAL 1 #define WEBCORE_BUILTIN_READABLEBYTESTREAMINTERNALS_READABLEBYTESTREAMCONTROLLERRESPONDINREADABLESTATE 1 #define WEBCORE_BUILTIN_READABLEBYTESTREAMINTERNALS_READABLEBYTESTREAMCONTROLLERRESPONDINCLOSEDSTATE 1 #define WEBCORE_BUILTIN_READABLEBYTESTREAMINTERNALS_READABLEBYTESTREAMCONTROLLERPROCESSPULLDESCRIPTORS 1 #define WEBCORE_BUILTIN_READABLEBYTESTREAMINTERNALS_READABLEBYTESTREAMCONTROLLERFILLDESCRIPTORFROMQUEUE 1 #define WEBCORE_BUILTIN_READABLEBYTESTREAMINTERNALS_READABLEBYTESTREAMCONTROLLERSHIFTPENDINGDESCRIPTOR 1 #define WEBCORE_BUILTIN_READABLEBYTESTREAMINTERNALS_READABLEBYTESTREAMCONTROLLERINVALIDATEBYOBREQUEST 1 #define WEBCORE_BUILTIN_READABLEBYTESTREAMINTERNALS_READABLEBYTESTREAMCONTROLLERCOMMITDESCRIPTOR 1 #define WEBCORE_BUILTIN_READABLEBYTESTREAMINTERNALS_READABLEBYTESTREAMCONTROLLERCONVERTDESCRIPTOR 1 #define WEBCORE_BUILTIN_READABLEBYTESTREAMINTERNALS_READABLESTREAMFULFILLREADINTOREQUEST 1 #define WEBCORE_BUILTIN_READABLEBYTESTREAMINTERNALS_READABLESTREAMBYOBREADERREAD 1 #define WEBCORE_BUILTIN_READABLEBYTESTREAMINTERNALS_READABLEBYTESTREAMCONTROLLERPULLINTO 1 #define WEBCORE_BUILTIN_READABLEBYTESTREAMINTERNALS_READABLESTREAMADDREADINTOREQUEST 1 #define WEBCORE_FOREACH_READABLEBYTESTREAMINTERNALS_BUILTIN_CODE(macro) \ macro(readableByteStreamInternalsPrivateInitializeReadableStreamBYOBReaderCode, privateInitializeReadableStreamBYOBReader, static_cast<const char*>(nullptr), s_readableByteStreamInternalsPrivateInitializeReadableStreamBYOBReaderCodeLength) \ macro(readableByteStreamInternalsPrivateInitializeReadableByteStreamControllerCode, privateInitializeReadableByteStreamController, static_cast<const char*>(nullptr), s_readableByteStreamInternalsPrivateInitializeReadableByteStreamControllerCodeLength) \ macro(readableByteStreamInternalsPrivateInitializeReadableStreamBYOBRequestCode, privateInitializeReadableStreamBYOBRequest, static_cast<const char*>(nullptr), s_readableByteStreamInternalsPrivateInitializeReadableStreamBYOBRequestCodeLength) \ macro(readableByteStreamInternalsIsReadableByteStreamControllerCode, isReadableByteStreamController, static_cast<const char*>(nullptr), s_readableByteStreamInternalsIsReadableByteStreamControllerCodeLength) \ macro(readableByteStreamInternalsIsReadableStreamBYOBRequestCode, isReadableStreamBYOBRequest, static_cast<const char*>(nullptr), s_readableByteStreamInternalsIsReadableStreamBYOBRequestCodeLength) \ macro(readableByteStreamInternalsIsReadableStreamBYOBReaderCode, isReadableStreamBYOBReader, static_cast<const char*>(nullptr), s_readableByteStreamInternalsIsReadableStreamBYOBReaderCodeLength) \ macro(readableByteStreamInternalsReadableByteStreamControllerCancelCode, readableByteStreamControllerCancel, static_cast<const char*>(nullptr), s_readableByteStreamInternalsReadableByteStreamControllerCancelCodeLength) \ macro(readableByteStreamInternalsReadableByteStreamControllerErrorCode, readableByteStreamControllerError, static_cast<const char*>(nullptr), s_readableByteStreamInternalsReadableByteStreamControllerErrorCodeLength) \ macro(readableByteStreamInternalsReadableByteStreamControllerCloseCode, readableByteStreamControllerClose, static_cast<const char*>(nullptr), s_readableByteStreamInternalsReadableByteStreamControllerCloseCodeLength) \ macro(readableByteStreamInternalsReadableByteStreamControllerClearPendingPullIntosCode, readableByteStreamControllerClearPendingPullIntos, static_cast<const char*>(nullptr), s_readableByteStreamInternalsReadableByteStreamControllerClearPendingPullIntosCodeLength) \ macro(readableByteStreamInternalsReadableByteStreamControllerGetDesiredSizeCode, readableByteStreamControllerGetDesiredSize, static_cast<const char*>(nullptr), s_readableByteStreamInternalsReadableByteStreamControllerGetDesiredSizeCodeLength) \ macro(readableByteStreamInternalsReadableStreamHasBYOBReaderCode, readableStreamHasBYOBReader, static_cast<const char*>(nullptr), s_readableByteStreamInternalsReadableStreamHasBYOBReaderCodeLength) \ macro(readableByteStreamInternalsReadableStreamHasDefaultReaderCode, readableStreamHasDefaultReader, static_cast<const char*>(nullptr), s_readableByteStreamInternalsReadableStreamHasDefaultReaderCodeLength) \ macro(readableByteStreamInternalsReadableByteStreamControllerHandleQueueDrainCode, readableByteStreamControllerHandleQueueDrain, static_cast<const char*>(nullptr), s_readableByteStreamInternalsReadableByteStreamControllerHandleQueueDrainCodeLength) \ macro(readableByteStreamInternalsReadableByteStreamControllerPullCode, readableByteStreamControllerPull, static_cast<const char*>(nullptr), s_readableByteStreamInternalsReadableByteStreamControllerPullCodeLength) \ macro(readableByteStreamInternalsReadableByteStreamControllerShouldCallPullCode, readableByteStreamControllerShouldCallPull, static_cast<const char*>(nullptr), s_readableByteStreamInternalsReadableByteStreamControllerShouldCallPullCodeLength) \ macro(readableByteStreamInternalsReadableByteStreamControllerCallPullIfNeededCode, readableByteStreamControllerCallPullIfNeeded, static_cast<const char*>(nullptr), s_readableByteStreamInternalsReadableByteStreamControllerCallPullIfNeededCodeLength) \ macro(readableByteStreamInternalsTransferBufferToCurrentRealmCode, transferBufferToCurrentRealm, static_cast<const char*>(nullptr), s_readableByteStreamInternalsTransferBufferToCurrentRealmCodeLength) \ macro(readableByteStreamInternalsReadableByteStreamControllerEnqueueCode, readableByteStreamControllerEnqueue, static_cast<const char*>(nullptr), s_readableByteStreamInternalsReadableByteStreamControllerEnqueueCodeLength) \ macro(readableByteStreamInternalsReadableByteStreamControllerEnqueueChunkCode, readableByteStreamControllerEnqueueChunk, static_cast<const char*>(nullptr), s_readableByteStreamInternalsReadableByteStreamControllerEnqueueChunkCodeLength) \ macro(readableByteStreamInternalsReadableByteStreamControllerRespondWithNewViewCode, readableByteStreamControllerRespondWithNewView, static_cast<const char*>(nullptr), s_readableByteStreamInternalsReadableByteStreamControllerRespondWithNewViewCodeLength) \ macro(readableByteStreamInternalsReadableByteStreamControllerRespondCode, readableByteStreamControllerRespond, static_cast<const char*>(nullptr), s_readableByteStreamInternalsReadableByteStreamControllerRespondCodeLength) \ macro(readableByteStreamInternalsReadableByteStreamControllerRespondInternalCode, readableByteStreamControllerRespondInternal, static_cast<const char*>(nullptr), s_readableByteStreamInternalsReadableByteStreamControllerRespondInternalCodeLength) \ macro(readableByteStreamInternalsReadableByteStreamControllerRespondInReadableStateCode, readableByteStreamControllerRespondInReadableState, static_cast<const char*>(nullptr), s_readableByteStreamInternalsReadableByteStreamControllerRespondInReadableStateCodeLength) \ macro(readableByteStreamInternalsReadableByteStreamControllerRespondInClosedStateCode, readableByteStreamControllerRespondInClosedState, static_cast<const char*>(nullptr), s_readableByteStreamInternalsReadableByteStreamControllerRespondInClosedStateCodeLength) \ macro(readableByteStreamInternalsReadableByteStreamControllerProcessPullDescriptorsCode, readableByteStreamControllerProcessPullDescriptors, static_cast<const char*>(nullptr), s_readableByteStreamInternalsReadableByteStreamControllerProcessPullDescriptorsCodeLength) \ macro(readableByteStreamInternalsReadableByteStreamControllerFillDescriptorFromQueueCode, readableByteStreamControllerFillDescriptorFromQueue, static_cast<const char*>(nullptr), s_readableByteStreamInternalsReadableByteStreamControllerFillDescriptorFromQueueCodeLength) \ macro(readableByteStreamInternalsReadableByteStreamControllerShiftPendingDescriptorCode, readableByteStreamControllerShiftPendingDescriptor, static_cast<const char*>(nullptr), s_readableByteStreamInternalsReadableByteStreamControllerShiftPendingDescriptorCodeLength) \ macro(readableByteStreamInternalsReadableByteStreamControllerInvalidateBYOBRequestCode, readableByteStreamControllerInvalidateBYOBRequest, static_cast<const char*>(nullptr), s_readableByteStreamInternalsReadableByteStreamControllerInvalidateBYOBRequestCodeLength) \ macro(readableByteStreamInternalsReadableByteStreamControllerCommitDescriptorCode, readableByteStreamControllerCommitDescriptor, static_cast<const char*>(nullptr), s_readableByteStreamInternalsReadableByteStreamControllerCommitDescriptorCodeLength) \ macro(readableByteStreamInternalsReadableByteStreamControllerConvertDescriptorCode, readableByteStreamControllerConvertDescriptor, static_cast<const char*>(nullptr), s_readableByteStreamInternalsReadableByteStreamControllerConvertDescriptorCodeLength) \ macro(readableByteStreamInternalsReadableStreamFulfillReadIntoRequestCode, readableStreamFulfillReadIntoRequest, static_cast<const char*>(nullptr), s_readableByteStreamInternalsReadableStreamFulfillReadIntoRequestCodeLength) \ macro(readableByteStreamInternalsReadableStreamBYOBReaderReadCode, readableStreamBYOBReaderRead, static_cast<const char*>(nullptr), s_readableByteStreamInternalsReadableStreamBYOBReaderReadCodeLength) \ macro(readableByteStreamInternalsReadableByteStreamControllerPullIntoCode, readableByteStreamControllerPullInto, static_cast<const char*>(nullptr), s_readableByteStreamInternalsReadableByteStreamControllerPullIntoCodeLength) \ macro(readableByteStreamInternalsReadableStreamAddReadIntoRequestCode, readableStreamAddReadIntoRequest, static_cast<const char*>(nullptr), s_readableByteStreamInternalsReadableStreamAddReadIntoRequestCodeLength) \ #define WEBCORE_FOREACH_READABLEBYTESTREAMINTERNALS_BUILTIN_FUNCTION_NAME(macro) \ macro(isReadableByteStreamController) \ macro(isReadableStreamBYOBReader) \ macro(isReadableStreamBYOBRequest) \ macro(privateInitializeReadableByteStreamController) \ macro(privateInitializeReadableStreamBYOBReader) \ macro(privateInitializeReadableStreamBYOBRequest) \ macro(readableByteStreamControllerCallPullIfNeeded) \ macro(readableByteStreamControllerCancel) \ macro(readableByteStreamControllerClearPendingPullIntos) \ macro(readableByteStreamControllerClose) \ macro(readableByteStreamControllerCommitDescriptor) \ macro(readableByteStreamControllerConvertDescriptor) \ macro(readableByteStreamControllerEnqueue) \ macro(readableByteStreamControllerEnqueueChunk) \ macro(readableByteStreamControllerError) \ macro(readableByteStreamControllerFillDescriptorFromQueue) \ macro(readableByteStreamControllerGetDesiredSize) \ macro(readableByteStreamControllerHandleQueueDrain) \ macro(readableByteStreamControllerInvalidateBYOBRequest) \ macro(readableByteStreamControllerProcessPullDescriptors) \ macro(readableByteStreamControllerPull) \ macro(readableByteStreamControllerPullInto) \ macro(readableByteStreamControllerRespond) \ macro(readableByteStreamControllerRespondInClosedState) \ macro(readableByteStreamControllerRespondInReadableState) \ macro(readableByteStreamControllerRespondInternal) \ macro(readableByteStreamControllerRespondWithNewView) \ macro(readableByteStreamControllerShiftPendingDescriptor) \ macro(readableByteStreamControllerShouldCallPull) \ macro(readableStreamAddReadIntoRequest) \ macro(readableStreamBYOBReaderRead) \ macro(readableStreamFulfillReadIntoRequest) \ macro(readableStreamHasBYOBReader) \ macro(readableStreamHasDefaultReader) \ macro(transferBufferToCurrentRealm) \ #define DECLARE_BUILTIN_GENERATOR(codeName, functionName, overriddenName, argumentCount) \ JSC::FunctionExecutable* codeName##Generator(JSC::VM&); WEBCORE_FOREACH_READABLEBYTESTREAMINTERNALS_BUILTIN_CODE(DECLARE_BUILTIN_GENERATOR) #undef DECLARE_BUILTIN_GENERATOR class ReadableByteStreamInternalsBuiltinsWrapper : private JSC::WeakHandleOwner { public: explicit ReadableByteStreamInternalsBuiltinsWrapper(JSC::VM* vm) : m_vm(*vm) WEBCORE_FOREACH_READABLEBYTESTREAMINTERNALS_BUILTIN_FUNCTION_NAME(INITIALIZE_BUILTIN_NAMES) #define INITIALIZE_BUILTIN_SOURCE_MEMBERS(name, functionName, overriddenName, length) , m_##name##Source(JSC::makeSource(StringImpl::createFromLiteral(s_##name, length), { })) WEBCORE_FOREACH_READABLEBYTESTREAMINTERNALS_BUILTIN_CODE(INITIALIZE_BUILTIN_SOURCE_MEMBERS) #undef INITIALIZE_BUILTIN_SOURCE_MEMBERS { } #define EXPOSE_BUILTIN_EXECUTABLES(name, functionName, overriddenName, length) \ JSC::UnlinkedFunctionExecutable* name##Executable(); \ const JSC::SourceCode& name##Source() const { return m_##name##Source; } WEBCORE_FOREACH_READABLEBYTESTREAMINTERNALS_BUILTIN_CODE(EXPOSE_BUILTIN_EXECUTABLES) #undef EXPOSE_BUILTIN_EXECUTABLES WEBCORE_FOREACH_READABLEBYTESTREAMINTERNALS_BUILTIN_FUNCTION_NAME(DECLARE_BUILTIN_IDENTIFIER_ACCESSOR) void exportNames(); private: JSC::VM& m_vm; WEBCORE_FOREACH_READABLEBYTESTREAMINTERNALS_BUILTIN_FUNCTION_NAME(DECLARE_BUILTIN_NAMES) #define DECLARE_BUILTIN_SOURCE_MEMBERS(name, functionName, overriddenName, length) \ JSC::SourceCode m_##name##Source;\ JSC::Weak<JSC::UnlinkedFunctionExecutable> m_##name##Executable; WEBCORE_FOREACH_READABLEBYTESTREAMINTERNALS_BUILTIN_CODE(DECLARE_BUILTIN_SOURCE_MEMBERS) #undef DECLARE_BUILTIN_SOURCE_MEMBERS }; #define DEFINE_BUILTIN_EXECUTABLES(name, functionName, overriddenName, length) \ inline JSC::UnlinkedFunctionExecutable* ReadableByteStreamInternalsBuiltinsWrapper::name##Executable() \ {\ if (!m_##name##Executable) {\ JSC::Identifier executableName = functionName##PublicName();\ if (overriddenName)\ executableName = JSC::Identifier::fromString(&m_vm, overriddenName);\ m_##name##Executable = JSC::Weak<JSC::UnlinkedFunctionExecutable>(JSC::createBuiltinExecutable(m_vm, m_##name##Source, executableName, s_##name##ConstructAbility), this, &m_##name##Executable);\ }\ return m_##name##Executable.get();\ } WEBCORE_FOREACH_READABLEBYTESTREAMINTERNALS_BUILTIN_CODE(DEFINE_BUILTIN_EXECUTABLES) #undef DEFINE_BUILTIN_EXECUTABLES inline void ReadableByteStreamInternalsBuiltinsWrapper::exportNames() { #define EXPORT_FUNCTION_NAME(name) m_vm.propertyNames->appendExternalName(name##PublicName(), name##PrivateName()); WEBCORE_FOREACH_READABLEBYTESTREAMINTERNALS_BUILTIN_FUNCTION_NAME(EXPORT_FUNCTION_NAME) #undef EXPORT_FUNCTION_NAME } class ReadableByteStreamInternalsBuiltinFunctions { public: explicit ReadableByteStreamInternalsBuiltinFunctions(JSC::VM& vm) : m_vm(vm) { } void init(JSC::JSGlobalObject&); void visit(JSC::SlotVisitor&); public: JSC::VM& m_vm; #define DECLARE_BUILTIN_SOURCE_MEMBERS(functionName) \ JSC::WriteBarrier<JSC::JSFunction> m_##functionName##Function; WEBCORE_FOREACH_READABLEBYTESTREAMINTERNALS_BUILTIN_FUNCTION_NAME(DECLARE_BUILTIN_SOURCE_MEMBERS) #undef DECLARE_BUILTIN_SOURCE_MEMBERS }; inline void ReadableByteStreamInternalsBuiltinFunctions::init(JSC::JSGlobalObject& globalObject) { #define EXPORT_FUNCTION(codeName, functionName, overriddenName, length)\ m_##functionName##Function.set(m_vm, &globalObject, JSC::JSFunction::create(m_vm, codeName##Generator(m_vm), &globalObject)); WEBCORE_FOREACH_READABLEBYTESTREAMINTERNALS_BUILTIN_CODE(EXPORT_FUNCTION) #undef EXPORT_FUNCTION } inline void ReadableByteStreamInternalsBuiltinFunctions::visit(JSC::SlotVisitor& visitor) { #define VISIT_FUNCTION(name) visitor.append(m_##name##Function); WEBCORE_FOREACH_READABLEBYTESTREAMINTERNALS_BUILTIN_FUNCTION_NAME(VISIT_FUNCTION) #undef VISIT_FUNCTION } } // namespace WebCore #endif // ENABLE(STREAMS_API)
[ "Farhan.q@live.com" ]
Farhan.q@live.com
b1a45b602d42d5964bd8da3401996a09c29ec075
df8a36d365956a30ff132c75fbff9f91bad994a3
/throwExcept.cpp
6a374530403066148189310d1fcd31cb05256ef8
[]
no_license
tecle/LeetCode
920d9e535b7061c5ac32daf66c20cfbe7d6f6945
4f525d149b2e27665157e61f49280ca55512a146
refs/heads/master
2016-09-05T18:41:01.905688
2014-04-28T01:05:22
2014-04-28T01:05:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
230
cpp
#include<iostream> #include<stdexcept> using namespace std; int showExcept(int i){ if(i==0){ throw runtime_error("zero!"); return 0; } return 2/i; } int main(){ cout<<showExcept(1)<<endl; cout<<showExcept(0)<<endl; }
[ "tecle@126.com" ]
tecle@126.com
91a62f23169f70b4bbce79e26683d81df1fb7cfb
65e0d33c4326e1d2206536603dac821617987b49
/main.cpp
720a08463ceb8061ed900461b41faa0f44d40a5d
[]
no_license
trevorstarick/aster
9ffee116b105809ba21c3a16cf87bf397a289dc9
e2bdb30903af882e74307c19c2bdb27ee0003b19
refs/heads/master
2021-01-12T20:54:34.213622
2015-11-24T07:42:23
2015-11-24T07:42:23
46,123,655
0
0
null
null
null
null
UTF-8
C++
false
false
104
cpp
#include "Aster.h" int main(int argc, char** argv) { Aster aster; aster.run(); return 0; }
[ "trevor.starick@gmail.com" ]
trevor.starick@gmail.com
cc0d10395fce4a9c0858801a30b1f1ef85046f3f
64e33ef0860a04a06c5ea7bd8b2159890f757d7d
/jni/art-kitkat-mr1.1-release/runtime/indirect_reference_table.cc
3017064e665fb9868795161bf99ec2578d469ed8
[ "Apache-2.0" ]
permissive
handgod/soma
a16d5547d1b3a028ead86bd3531c0526568c74f5
d64131f4d6f9543eacd1d4040b560df00555b2c8
refs/heads/master
2021-01-10T11:34:58.926723
2016-03-04T11:56:41
2016-03-04T11:56:41
53,018,560
0
0
null
null
null
null
UTF-8
C++
false
false
11,624
cc
/* * Copyright (C) 2009 The Android Open Source Project * * 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 "indirect_reference_table.h" #include "jni_internal.h" #include "reference_table.h" #include "runtime.h" #include "scoped_thread_state_change.h" #include "thread.h" #include "utils.h" #include <cstdlib> namespace art { static void AbortMaybe() { // If -Xcheck:jni is on, it'll give a more detailed error before aborting. if (!Runtime::Current()->GetJavaVM()->check_jni) { // Otherwise, we want to abort rather than hand back a bad reference. LOG(FATAL) << "JNI ERROR (app bug): see above."; } } IndirectReferenceTable::IndirectReferenceTable(size_t initialCount, size_t maxCount, IndirectRefKind desiredKind) { CHECK_GT(initialCount, 0U); CHECK_LE(initialCount, maxCount); CHECK_NE(desiredKind, kSirtOrInvalid); table_ = reinterpret_cast<const mirror::Object**>(malloc(initialCount * sizeof(const mirror::Object*))); CHECK(table_ != NULL); memset(table_, 0xd1, initialCount * sizeof(const mirror::Object*)); slot_data_ = reinterpret_cast<IndirectRefSlot*>(calloc(initialCount, sizeof(IndirectRefSlot))); CHECK(slot_data_ != NULL); segment_state_.all = IRT_FIRST_SEGMENT; alloc_entries_ = initialCount; max_entries_ = maxCount; kind_ = desiredKind; } IndirectReferenceTable::~IndirectReferenceTable() { free(table_); free(slot_data_); table_ = NULL; slot_data_ = NULL; alloc_entries_ = max_entries_ = -1; } // Make sure that the entry at "idx" is correctly paired with "iref". bool IndirectReferenceTable::CheckEntry(const char* what, IndirectRef iref, int idx) const { const mirror::Object* obj = table_[idx]; IndirectRef checkRef = ToIndirectRef(obj, idx); if (UNLIKELY(checkRef != iref)) { LOG(ERROR) << "JNI ERROR (app bug): attempt to " << what << " stale " << kind_ << " " << iref << " (should be " << checkRef << ")"; AbortMaybe(); return false; } return true; } IndirectRef IndirectReferenceTable::Add(uint32_t cookie, const mirror::Object* obj) { IRTSegmentState prevState; prevState.all = cookie; size_t topIndex = segment_state_.parts.topIndex; DCHECK(obj != NULL); // TODO: stronger sanity check on the object (such as in heap) DCHECK_ALIGNED(reinterpret_cast<uintptr_t>(obj), 8); DCHECK(table_ != NULL); DCHECK_LE(alloc_entries_, max_entries_); DCHECK_GE(segment_state_.parts.numHoles, prevState.parts.numHoles); if (topIndex == alloc_entries_) { // reached end of allocated space; did we hit buffer max? if (topIndex == max_entries_) { LOG(FATAL) << "JNI ERROR (app bug): " << kind_ << " table overflow " << "(max=" << max_entries_ << ")\n" << MutatorLockedDumpable<IndirectReferenceTable>(*this); } size_t newSize = alloc_entries_ * 2; if (newSize > max_entries_) { newSize = max_entries_; } DCHECK_GT(newSize, alloc_entries_); table_ = reinterpret_cast<const mirror::Object**>(realloc(table_, newSize * sizeof(const mirror::Object*))); slot_data_ = reinterpret_cast<IndirectRefSlot*>(realloc(slot_data_, newSize * sizeof(IndirectRefSlot))); if (table_ == NULL || slot_data_ == NULL) { LOG(FATAL) << "JNI ERROR (app bug): unable to expand " << kind_ << " table (from " << alloc_entries_ << " to " << newSize << ", max=" << max_entries_ << ")\n" << MutatorLockedDumpable<IndirectReferenceTable>(*this); } // Clear the newly-allocated slot_data_ elements. memset(slot_data_ + alloc_entries_, 0, (newSize - alloc_entries_) * sizeof(IndirectRefSlot)); alloc_entries_ = newSize; } // We know there's enough room in the table. Now we just need to find // the right spot. If there's a hole, find it and fill it; otherwise, // add to the end of the list. IndirectRef result; int numHoles = segment_state_.parts.numHoles - prevState.parts.numHoles; if (numHoles > 0) { DCHECK_GT(topIndex, 1U); // Find the first hole; likely to be near the end of the list. const mirror::Object** pScan = &table_[topIndex - 1]; DCHECK(*pScan != NULL); while (*--pScan != NULL) { DCHECK_GE(pScan, table_ + prevState.parts.topIndex); } UpdateSlotAdd(obj, pScan - table_); result = ToIndirectRef(obj, pScan - table_); *pScan = obj; segment_state_.parts.numHoles--; } else { // Add to the end. UpdateSlotAdd(obj, topIndex); result = ToIndirectRef(obj, topIndex); table_[topIndex++] = obj; segment_state_.parts.topIndex = topIndex; } if (false) { LOG(INFO) << "+++ added at " << ExtractIndex(result) << " top=" << segment_state_.parts.topIndex << " holes=" << segment_state_.parts.numHoles; } DCHECK(result != NULL); return result; } void IndirectReferenceTable::AssertEmpty() { if (UNLIKELY(begin() != end())) { ScopedObjectAccess soa(Thread::Current()); LOG(FATAL) << "Internal Error: non-empty local reference table\n" << MutatorLockedDumpable<IndirectReferenceTable>(*this); } } // Verifies that the indirect table lookup is valid. // Returns "false" if something looks bad. bool IndirectReferenceTable::GetChecked(IndirectRef iref) const { if (UNLIKELY(iref == NULL)) { LOG(WARNING) << "Attempt to look up NULL " << kind_; return false; } if (UNLIKELY(GetIndirectRefKind(iref) == kSirtOrInvalid)) { LOG(ERROR) << "JNI ERROR (app bug): invalid " << kind_ << " " << iref; AbortMaybe(); return false; } int topIndex = segment_state_.parts.topIndex; int idx = ExtractIndex(iref); if (UNLIKELY(idx >= topIndex)) { LOG(ERROR) << "JNI ERROR (app bug): accessed stale " << kind_ << " " << iref << " (index " << idx << " in a table of size " << topIndex << ")"; AbortMaybe(); return false; } if (UNLIKELY(table_[idx] == NULL)) { LOG(ERROR) << "JNI ERROR (app bug): accessed deleted " << kind_ << " " << iref; AbortMaybe(); return false; } if (UNLIKELY(!CheckEntry("use", iref, idx))) { return false; } return true; } static int Find(mirror::Object* direct_pointer, int bottomIndex, int topIndex, const mirror::Object** table) { for (int i = bottomIndex; i < topIndex; ++i) { if (table[i] == direct_pointer) { return i; } } return -1; } bool IndirectReferenceTable::ContainsDirectPointer(mirror::Object* direct_pointer) const { return Find(direct_pointer, 0, segment_state_.parts.topIndex, table_) != -1; } // Removes an object. We extract the table offset bits from "iref" // and zap the corresponding entry, leaving a hole if it's not at the top. // If the entry is not between the current top index and the bottom index // specified by the cookie, we don't remove anything. This is the behavior // required by JNI's DeleteLocalRef function. // This method is not called when a local frame is popped; this is only used // for explicit single removals. // Returns "false" if nothing was removed. bool IndirectReferenceTable::Remove(uint32_t cookie, IndirectRef iref) { IRTSegmentState prevState; prevState.all = cookie; int topIndex = segment_state_.parts.topIndex; int bottomIndex = prevState.parts.topIndex; DCHECK(table_ != NULL); DCHECK_LE(alloc_entries_, max_entries_); DCHECK_GE(segment_state_.parts.numHoles, prevState.parts.numHoles); int idx = ExtractIndex(iref); JavaVMExt* vm = Runtime::Current()->GetJavaVM(); if (GetIndirectRefKind(iref) == kSirtOrInvalid && Thread::Current()->SirtContains(reinterpret_cast<jobject>(iref))) { LOG(WARNING) << "Attempt to remove local SIRT entry from IRT, ignoring"; return true; } if (GetIndirectRefKind(iref) == kSirtOrInvalid && vm->work_around_app_jni_bugs) { mirror::Object* direct_pointer = reinterpret_cast<mirror::Object*>(iref); idx = Find(direct_pointer, bottomIndex, topIndex, table_); if (idx == -1) { LOG(WARNING) << "Trying to work around app JNI bugs, but didn't find " << iref << " in table!"; return false; } } if (idx < bottomIndex) { // Wrong segment. LOG(WARNING) << "Attempt to remove index outside index area (" << idx << " vs " << bottomIndex << "-" << topIndex << ")"; return false; } if (idx >= topIndex) { // Bad --- stale reference? LOG(WARNING) << "Attempt to remove invalid index " << idx << " (bottom=" << bottomIndex << " top=" << topIndex << ")"; return false; } if (idx == topIndex-1) { // Top-most entry. Scan up and consume holes. if (!vm->work_around_app_jni_bugs && !CheckEntry("remove", iref, idx)) { return false; } table_[idx] = NULL; int numHoles = segment_state_.parts.numHoles - prevState.parts.numHoles; if (numHoles != 0) { while (--topIndex > bottomIndex && numHoles != 0) { if (false) { LOG(INFO) << "+++ checking for hole at " << topIndex-1 << " (cookie=" << cookie << ") val=" << table_[topIndex - 1]; } if (table_[topIndex-1] != NULL) { break; } if (false) { LOG(INFO) << "+++ ate hole at " << (topIndex - 1); } numHoles--; } segment_state_.parts.numHoles = numHoles + prevState.parts.numHoles; segment_state_.parts.topIndex = topIndex; } else { segment_state_.parts.topIndex = topIndex-1; if (false) { LOG(INFO) << "+++ ate last entry " << topIndex - 1; } } } else { // Not the top-most entry. This creates a hole. We NULL out the // entry to prevent somebody from deleting it twice and screwing up // the hole count. if (table_[idx] == NULL) { LOG(INFO) << "--- WEIRD: removing null entry " << idx; return false; } if (!vm->work_around_app_jni_bugs && !CheckEntry("remove", iref, idx)) { return false; } table_[idx] = NULL; segment_state_.parts.numHoles++; if (false) { LOG(INFO) << "+++ left hole at " << idx << ", holes=" << segment_state_.parts.numHoles; } } return true; } void IndirectReferenceTable::VisitRoots(RootVisitor* visitor, void* arg) { for (auto ref : *this) { visitor(*ref, arg); } } void IndirectReferenceTable::Dump(std::ostream& os) const { os << kind_ << " table dump:\n"; std::vector<const mirror::Object*> entries(table_, table_ + Capacity()); // Remove NULLs. for (int i = entries.size() - 1; i >= 0; --i) { if (entries[i] == NULL) { entries.erase(entries.begin() + i); } } ReferenceTable::Dump(os, entries); } } // namespace art
[ "943488158@qq.com" ]
943488158@qq.com
159f4a80d7654033eca9aa6e0dbe7bbc5c81cf8a
26a23a87317b942e0f8ce75591394d35f3d4d353
/manmor.h
e27645720ef594aa907fda17a4cf58c16da4837d
[]
no_license
kodending/stoneAge
34f183e29ce9a58a179f60a1732b17163b1e00e7
357949d414fd493b0bfcbeb8ea19849cd3da1b59
refs/heads/master
2023-08-03T09:56:07.624103
2021-09-10T04:12:26
2021-09-10T04:12:26
404,947,562
0
0
null
null
null
null
UTF-8
C++
false
false
100
h
#pragma once #include "pet.h" class manmor : public pet { public: manmor() {}; ~manmor() {}; };
[ "codending@gmail.com" ]
codending@gmail.com
3ba1fec7973fd5dba659353af2812f1225809b82
7fc2415f07eed242ca9c141dce38153422cfd35c
/data_structure/heap/binary_heap.cpp
7b71973148f07c7e2bfb904abcef46df47ebc8dc
[ "CC-BY-4.0" ]
permissive
icyzeroice/head-for-algorithm
b0f726b7d03b20ccf55d9b08a624857fb8591901
47c813a4418bf0c83de3fc376fc1af3ca1ed5480
refs/heads/master
2021-06-07T05:23:28.700367
2020-06-22T15:07:05
2020-06-22T15:07:05
109,589,654
0
0
null
null
null
null
UTF-8
C++
false
false
2,853
cpp
#include<iostream> using namespace std; #define BINARY_HEAP_INITIAL_LENGTH 50 // max root binary heap class BinaryHeap { private: // data fragment int _queue[BINARY_HEAP_INITIAL_LENGTH + 1]; int _size; void static _swop(int *arr, int i, int j) { arr[i] = arr[i] + arr[j]; arr[j] = arr[i] - arr[j]; arr[i] = arr[i] - arr[j]; }; // private methods void _swim(int index) { int parentIndex; while (index > 1) { parentIndex = index / 2; if (_queue[parentIndex] < _queue[index]) { _swop(_queue, parentIndex, index); } index = parentIndex; } }; void _sink(int index) { int leftChild; int rightChild; // 左右节点都有 while (index * 2 < _size) { leftChild = index * 2; rightChild = leftChild + 1; // TODO: 这里的 if 条件应该能优化下 if (_queue[leftChild] > _queue[index] && _queue[rightChild] > _queue[index] && _queue[leftChild] >= _queue[rightChild]) { _swop(_queue, leftChild, index); index = leftChild; } else if (_queue[leftChild] > _queue[index] && _queue[rightChild] > _queue[index] && _queue[leftChild] < _queue[rightChild]) { _swop(_queue, rightChild, index); index = rightChild; } else if (_queue[leftChild] > _queue[index]) { _swop(_queue, leftChild, index); index = leftChild; } else if (_queue[rightChild] > _queue[index]) { _swop(_queue, rightChild, index); index = rightChild; } } // 只有左节点 if (index * 2 == _size && _queue[index * 2] > _queue[index]) { _swop(_queue, index * 2, index); } }; public: BinaryHeap(): _size(0) { // TODO: 数组 _queue 需要初始化 cout << "constructor initialized, set `_size` to " << _size << endl; }; ~BinaryHeap() { // delete[] _queue; cout << "instance is to be destroyed..."; }; int getLength() { return _size; }; bool insert(int item) { // TODO: need to extend the size of _queue? if (_size == BINARY_HEAP_INITIAL_LENGTH) { return false; } _size++; _queue[_size] = item; _swim(_size); return true; }; int delMax() { if (_size == 0) { return 0; } int max = _queue[1]; _queue[1] = _queue[_size]; // 将最大放置尾部,注意可以实现堆排序 _queue[_size] = max; _size--; _sink(1); return max; }; void print() { cout << "Queue is: " << *_queue << "\nSize is: " << _size << endl; }; }; int main(int argc, char const *argv[]) { BinaryHeap h; h.insert(3); h.insert(2); h.insert(4); h.print(); h.insert(5); h.insert(6); h.insert(7); h.print(); h.delMax(); h.print(); return 0; }
[ "ziv3@outlook.com" ]
ziv3@outlook.com
e5de55fcc1a8bdf71c7bf4a31208976246af77cc
5d24c201bc31e8cac61fae466e1c80be5d38b631
/external/boost/futures/boost/futures/future.hpp
2eceb5a4dd81cd0885b877fdd26a7aaeead01554
[ "BSL-1.0" ]
permissive
Fooway/saga-cpp
330196aec55642630eb1853363bc3cf8d53336db
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
refs/heads/master
2020-07-12T02:31:44.485713
2012-12-13T11:39:22
2012-12-13T11:39:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,354
hpp
// future class // Copyright (c) 2005 Hartmut Kaiser. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FUTURE_HPP #define BOOST_FUTURE_HPP 1 #include <boost/shared_ptr.hpp> #include <boost/futures/future_base.hpp> /////////////////////////////////////////////////////////////////////////////// namespace boost { namespace futures { /////////////////////////////////////////////////////////////////////////// namespace detail { template <typename FutureResult> struct future_impl_base { virtual ~future_impl_base() {}; virtual FutureResult get() = 0; virtual bool done() = 0; }; template <typename Future, typename FutureResult> struct future_impl : future_impl_base<FutureResult> { future_impl(Future const& f) : f(f) {} ~future_impl() {} FutureResult get() { return f(); } bool done() { return f.done(); } Future f; }; } /////////////////////////////////////////////////////////////////////////// template <typename FutureResult> struct future : future_base<future<FutureResult> > { typedef FutureResult result_type; future() {} template <typename Future> future(future_base<Future> const& f) : impl(new detail::future_impl<Future, FutureResult>(f.derived())) {} template <typename Future> future operator= (future_base<Future> const& f) { impl.reset(new detail::future_impl<Future, FutureResult>(f.derived())); return *this; } FutureResult operator()() { return impl->get(); } bool done() { return impl->done(); } boost::shared_ptr<detail::future_impl_base<FutureResult> > impl; }; /////////////////////////////////////////////////////////////////////////////// }} // namespace boost::futures #endif /* BOOST_FUTURIZED_HPP */
[ "oweidner@cct.lsu.edu" ]
oweidner@cct.lsu.edu
577d4452a47445f087454b1cdeef52d32ee933d8
19cd1f34da03edd1ddd60cc4044ba7d0f92de656
/fynet/fynet_config.hpp
8c29ff430ba9813529420759e5e3436bfc394aa8
[]
no_license
pass0a/fynet
260dc4c1b49d5e383097d7edb179afb21fa0ab8f
61ffb466d5cfdae19b9e564e36b40845c228317d
refs/heads/master
2020-12-31T23:44:49.672407
2020-02-08T06:35:09
2020-02-08T06:35:09
239,081,306
0
0
null
null
null
null
UTF-8
C++
false
false
163
hpp
#include <stdint.h> #ifdef USE_FLOAT32 typedef float_t data_type; #elif USE_FLOAT64 typedef double data_type; #elif USE_INT8 typedef int data_type; #endif
[ "liuwenjun@hangsheng.com.cn" ]
liuwenjun@hangsheng.com.cn
a9d3f600d1ec6c60d175bbefffd625e1e357c44a
988e0a3e05ca7298452dbb754bf73c4de4f0acf7
/1007.cpp
9d1fd8ed9da1697b92347dcfdbdd59a047e5bf27
[]
no_license
matheusrodrisantos/URI_EXERCICIOS
c5970d0fc53ebc2e91941e51bcd85c6491dd82d5
e24f3b2af862bea012c22efa9660e5e280138ada
refs/heads/master
2020-08-04T18:11:17.776952
2020-02-20T16:08:14
2020-02-20T16:08:14
212,233,178
0
0
null
null
null
null
UTF-8
C++
false
false
187
cpp
#include <iostream> using namespace std; int main() { int a,b,c,d,diferenca; cin>>a>>b>>c>>d; diferenca=(a*b-c*d); cout<<"DIFERENCA = "<<diferenca<<'\n'; return 0; }
[ "matheus.rodrisantos@bol.com.br" ]
matheus.rodrisantos@bol.com.br
690557c920ecd0e24f609986464547ba6bfb29ab
6cb70d123245b6ba59e4b502a214be645a161203
/c2c/CGenerator/TypeSorter.h
9aedb760aabc971c7c21675005611efd2b6dc884
[ "Apache-2.0" ]
permissive
Dandigit/c2compiler
6e85d77f1a56d7318f6c3e4fce7dbac33a714340
28d04225068f879243e82912d23ca7d593d1eb70
refs/heads/master
2020-04-12T22:02:14.492444
2018-12-21T08:10:21
2018-12-21T08:10:21
162,496,465
0
0
Apache-2.0
2018-12-19T22:14:48
2018-12-19T22:14:48
null
UTF-8
C++
false
false
1,396
h
/* Copyright 2013-2018 Bas van den Berg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CGENERATOR_TYPE_SORTER_H #define CGENERATOR_TYPE_SORTER_H #include <vector> #include <map> namespace C2 { class Decl; class DeclDep; class CTypeWriter { public: virtual ~CTypeWriter() {} virtual void forwardDecl(const Decl* D) = 0; virtual void fullDecl(const Decl* D) = 0; }; class TypeSorter { public: TypeSorter() {} ~TypeSorter(); void add(const Decl* D); void write(CTypeWriter& writer); private: typedef std::vector<DeclDep*> DeclDepList; typedef DeclDepList::const_iterator DeclDepListConstIter; typedef DeclDepList::iterator DeclDepListIter; DeclDepList depmap; typedef std::map<const Decl*, const Decl*> FunctionMap; typedef FunctionMap::const_iterator FunctionMapConstIter; FunctionMap functions; }; } #endif
[ "b.van.den.berg.nl@gmail.com" ]
b.van.den.berg.nl@gmail.com
fbc79603587a11056ecc23a4c97eabb4af916e4c
3d234bf166417451753dff067884c777e3666cb1
/src/modules/molvis/molvis.moddef
149449d7129b8ad0e90b64a2872eb58c30c6e84c
[ "MIT", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
biochem-fan/cuemol2
e0084875334389248f77ccf0f7c04fdd3d675659
a37c0e84d0718c7456f8cb5a3c94f5677e93864b
refs/heads/master
2020-04-06T06:51:17.854846
2014-11-13T04:11:14
2014-11-13T04:11:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
893
moddef
// -*-Mode: C++;-*- // // $Id: molvis.moddef,v 1.12 2010/12/03 16:40:41 rishitani Exp $ #include "BallStickRenderer.qif" #include "AnIsoURenderer.qif" #include "CPKRenderer.qif" #include "SplineRenderer.qif" #include "TubeRenderer.qif" #include "TubeSection.qif" #include "PaintColoring.qif" #include "RibbonRenderer.qif" #include "JctTable.qif" #include "NARenderer.qif" #include "AtomIntrRenderer.qif" #include "Ribbon2Renderer.qif" #include "RainbowColoring.qif" #include "DistPickDrawObj.qif" #include "DisoRenderer.qif" module molvis { init molvis::init(); fini molvis::fini(); BallStickRenderer; AnIsoURenderer; CPKRenderer; SplineRenderer; TubeRenderer; TubeSection; PaintColoring; RibbonRenderer; JctTable; NARenderer; AtomIntrRenderer; DisoRenderer; Ribbon2Renderer; RainbowColoring; DistPickDrawObj; };
[ "ryu.istn@gmail.com" ]
ryu.istn@gmail.com
65bfa0efbdd6701667dd09c191fed2fbf02ecb58
c05476255a08d014ee97eee946157bf9b5973102
/hellos/example/ios/Pods/Headers/Private/hellos/syslog.hpp
d36c490445bc1f349f41e83586257c28499fdb5d
[]
no_license
J844259756/WebSocketPPTest
c9a5f70baca8b8706e217ac7cf9eadd0afabfdba
099a919951c0bfc62f8757a9a8816c86d86d77a6
refs/heads/master
2022-12-08T07:19:12.895761
2020-09-08T14:06:52
2020-09-08T14:06:52
293,319,805
0
0
null
null
null
null
UTF-8
C++
false
false
78
hpp
../../../../.symlinks/plugins/hellos/ios/Classes/websocketpp/logger/syslog.hpp
[ "" ]
4560039c542a06cdb7a742872f350ba3a3df65cf
ba4114085975d862eb3c8f1a01958ff1289debcf
/tb_magazineLimitations.hpp
e0764e19bae4421b15a23162358370d35b746cff
[]
no_license
TacBF/tb_rhs_hard_target.saralite
0905bb55dff275706fd5efd2f82e4d9d354123af
61dd212150a059f84d9cc164bf6e074640c35a74
refs/heads/master
2021-01-19T20:31:28.140820
2017-04-17T14:40:47
2017-04-17T14:40:47
88,517,371
0
0
null
null
null
null
UTF-8
C++
false
false
1,723
hpp
class cfgMagazines { class magazineLimitations { /*--------------------------------------------------------------------------- Sets the amount of magazines you can have out of the following array (So in total!) You can specify a special number for resistance as well ---------------------------------------------------------------------------*/ class 40mm_HE { magazineArray[] = {"rhs_mag_M441_HE", "rhs_mag_M433_HEDP", "rhs_VOG25", "rhs_VOG25P","rhs_VG40TB"}; limit = 8; limtResistance = 8; categoryName = "40mm HE Grenades"; }; class 6x40mm_Grenades { magazineArray[] = {"rhsusf_mag_6Rnd_M441_HE","rhsusf_mag_6Rnd_M433_HEDP","rhsusf_mag_6Rnd_M576_Buckshot","rhsusf_mag_6Rnd_M781_Practice","rhsusf_mag_6Rnd_M714_white"}; limit = 2; limtResistance = 2; categoryName = "6x40mm Grenades"; }; class Grenade { magazineArray[] = {"rhs_mag_rgd5","rhs_mag_m67","rhs_mag_rgn"}; limit = 3; limtResistance = 3; categoryName = "HE Grenades"; }; class Stun_Grenade { magazineArray[] = {"rhs_mag_fakel", "rhs_mag_fakels", "rhs_mag_zarya2", "rhs_mag_plamyam", "rhs_mag_mk84", "rhs_mag_an_m14_th3", "rhs_mag_m7a3_cs", "rhs_mag_mk3a2"}; limit = 2; limtResistance = 2; categoryName = "Stun Grenades"; }; class HE_Rockets { magazineArray[] = {"rhs_rpg7_OG70V_mag","CUP_M136_M","CUP_SMAW_HEDP_M","CUP_RPG18_M"}; limit = 3; limtResistance = 3; categoryName = "HE Rockets"; }; class HE_Shotgun { magazineArray[] = {"rhsusf_8Rnd_FRAG", "rhsusf_5Rnd_FRAG", "rhsusf_8Rnd_HE", "rhsusf_5Rnd_HE"}; limit = 4; limtResistance = 4; categoryName = "HE Shotgun"; }; }; };
[ "ballista.milsim@gmail.com" ]
ballista.milsim@gmail.com
635f5b3a987157af75c6e81511697075bcaae5e1
894fd6ba0629786fd3baa07fe6026ba00d4f2c9a
/assignment.cpp
dd9c782e1e2c72daa5c757ced01c46909219f523
[]
no_license
officialngare/Calculator
e016e426cc3c0fe573043c474cae49bdcbda2475
f8956242fca801bd60f90bd68cb03ddba6d81662
refs/heads/main
2023-08-25T13:06:27.319327
2021-10-18T11:04:15
2021-10-18T11:04:15
418,460,596
0
0
null
null
null
null
UTF-8
C++
false
false
960
cpp
#include <stdio.h> #include <conio.h> int main(){ /* Variable declation */ int a,b, sum, difference, product, modulo; float quotient; /* Taking input from user and storing it in firstNumber and secondNumber */ printf("Enter First Number: "); scanf("%d", &a); printf("Enter Second Number: "); scanf("%d", &b); /* Adding two numbers */ sum = a + b; /* Subtracting two numbers */ difference = a - b; /* Multiplying two numbers*/ product = a * b; /* Dividing two numbers by typecasting one operand to float*/ quotient = (float)a/b; /* returns remainder of after an integer division */ modulo = a%b; printf("\nSum = %d", sum); printf("\nDifference = %d", difference); printf("\nMultiplication = %d", product); printf("\nDivision = %.3f", quotient); printf("\nRemainder = %d", modulo); getch(); return 0; }
[ "noreply@github.com" ]
officialngare.noreply@github.com
eb897675ad57e54f9e66b9fe72163cf4d27faad8
ee22fa7476a52f3fe2f9bc88d6c8f43f614cdba6
/Timus/1146.cpp
c22da54a645dab559fb4df695445c2700f9e13d1
[]
no_license
Sillyplus/Solution
704bff07a29709f64e3e1634946618170d426b72
48dcaa075852f8cda1db22ec1733600edea59422
refs/heads/master
2020-12-17T04:53:07.089633
2016-07-02T10:01:28
2016-07-02T10:01:28
21,733,756
0
0
null
null
null
null
UTF-8
C++
false
false
849
cpp
#include <iostream> #include <cmath> #include <algorithm> using namespace std; const int MN = 110; int a[MN][MN] = {0}; int sum[MN][MN] = {0}; int main() { int n, k; cin >> n; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { cin >> a[i][j]; sum[i][j] = sum[i-1][j] + sum[i][j-1] - sum[i-1][j-1] + a[i][j]; } } int ans = -2147483647; for (int i = 1; i <= n; i++) { for (int j = i; j <= n; j++) { int s = 0, temp; for (int k = 1; k <= n; k++) { temp = sum[j][k] - sum[j][k-1] - sum[i-1][k] + sum[i-1][k-1]; if (s > 0) s += temp; else s = temp; ans = max(ans, s); } } } cout << ans << endl; return 0; }
[ "oi_boy@sina.cn" ]
oi_boy@sina.cn
65a0a7e6be7c6c3969dbf160ee0ac0870e680464
f82106e56e348b5ee325c6a533f2bb1478a5c959
/src/KeyboardPlayer.cpp
00f8b9285fee62df50e5fe01a29ca55e42b6790e
[]
no_license
JoVsn/pianobeep
974d11bbe5df9e7076219d53f0c163add880df16
ac6d886df789d7ab5ae691ff19b5a03dfc5b1ea6
refs/heads/master
2020-03-11T05:19:24.973153
2018-04-16T20:13:58
2018-04-16T20:13:58
129,799,711
1
0
null
null
null
null
UTF-8
C++
false
false
3,697
cpp
// // Created by Jordan on 02/12/2017. // #include "../headers/KeyboardPlayer.hpp" // Constructors KeyboardPlayer::KeyboardPlayer(Instrument &myInstrument) : instrument(myInstrument), tempo(120) { keyboard.insert(std::make_pair("q", new Note('B', 3))); keyboard.insert(std::make_pair("s", new Note('C', 4))); keyboard.insert(std::make_pair("d", new Note('D', 4))); keyboard.insert(std::make_pair("f", new Note('E', 4))); keyboard.insert(std::make_pair("g", new Note('F', 4))); keyboard.insert(std::make_pair("h", new Note('G', 4))); keyboard.insert(std::make_pair("j", new Note('A', 4))); keyboard.insert(std::make_pair("k", new Note('B', 4))); keyboard.insert(std::make_pair("l", new Note('C', 5))); keyboard.insert(std::make_pair("m", new Note('D', 5))); keyboard.insert(std::make_pair("e", new Note('C', 4, 'd'))); keyboard.insert(std::make_pair("r", new Note('D', 4, 'd'))); keyboard.insert(std::make_pair("y", new Note('F', 4, 'd'))); keyboard.insert(std::make_pair("u", new Note('G', 4, 'd'))); keyboard.insert(std::make_pair("i", new Note('A', 4, 'd'))); keyboard.insert(std::make_pair("p", new Note('C', 5, 'd'))); } // Returns the attribute "instrument" Instrument &KeyboardPlayer::getInstrument() const { return instrument; } // Sets the attribute "instrument" void KeyboardPlayer::setInstrument(Instrument &instrument) { KeyboardPlayer::instrument = instrument; } // Returns the attribute "keyboard" const std::map<std::string, Note*> &KeyboardPlayer::getKeyboard() const { return keyboard; } // Sets the attribute "keyboard" void KeyboardPlayer::setKeyboard(const std::map<std::string, Note*> &keyboard) { KeyboardPlayer::keyboard = keyboard; } // Returns the attribute "tempo" int KeyboardPlayer::getTempo() const { return tempo; } // Sets the attribute "tempo" void KeyboardPlayer::setTempo(int tempo) { KeyboardPlayer::tempo = tempo; } // Returns the Note corresponding to the key given in parameter Note* KeyboardPlayer::getNote(std::string myKey) { if (keyboard.find(myKey) == keyboard.end()) { return new Note('N'); } return keyboard[myKey]; } // Returns the key/instruction corresponding to the key pressed by the user std::string KeyboardPlayer::detectKey() const { int c = getch(); switch(c) { case 'q': return "q"; case 's': return "s"; case 'd': return "d"; case 'f': return "f"; case 'g': return "g"; case 'h': return "h"; case 'j': return "j"; case 'k': return "k"; case 'l': return "l"; case 'm': return "m"; case 'e': return "e"; case 'r': return "r"; case 'y': return "y"; case 'u': return "u"; case 'i': return "i"; case 'p': return "p"; case 'w': return "leave"; case 'x': return "save"; case 'c': return "tempo"; default: return ""; } } // Plays the note corresponding to the key pressed by the user std::string KeyboardPlayer::play() { std::string keyPressed; keyPressed = detectKey(); Note* myNote = getNote(keyPressed); instrument.playNote(*myNote, tempo); return keyPressed; } // Deletes the Notes in the keyboard map from the memory void KeyboardPlayer::deleteNotes() { for(std::map<std::string, Note*>::iterator it = keyboard.begin(); it != keyboard.end(); ++it) { delete it->second; } }
[ "vilsaint.jordan@gmail.com" ]
vilsaint.jordan@gmail.com
0f5c3d1179157f704de6ef85d5d8c6a83fce9e64
607e8a82b91ce74a7aa374baf648a3bb4abfab1a
/jni - bug/pathogen/file.h
dd69a4ae7529e6f13171b3c20f580ec7c9a68aaa
[]
no_license
zhaozw/pathogenandroid
b53469f0d6b6dbcf599d6bd3499fbee550ac0109
7b0febc84a42c3e568f0c376a7b4a3531165eec5
refs/heads/master
2021-01-13T02:06:37.667990
2013-04-14T02:27:16
2013-04-14T02:27:16
9,426,097
2
0
null
null
null
null
UTF-8
C++
false
false
431
h
#ifndef FILE_H #define FILE_H #include <string> #include <sstream> #include <iostream> #include <android/asset_manager.h> #include <android/asset_manager_jni.h> using namespace std; class CFile { public: AAsset* mFile; CFile(); CFile(const char* filepath, int mode=AASSET_MODE_UNKNOWN); ~CFile(); int seek(int off, int origin=SEEK_SET); int read(void* to, int amt); int tell(); int remain(); void close(); }; #endif
[ "polyfrag@hotmail.com" ]
polyfrag@hotmail.com
81b9e9af6e2de790791cda4224413984f8e66906
f2fa39e10cf04739eb44a90089e360306aa39172
/magicFilter/src/main/jni/beautify/MagicBeautify.h
a11be38789d3ac7add457756dca7725005d458e7
[]
no_license
Anonybh/advancedPhotoEditor
9f3187e60964a49e01dcb08f8649c1aa15188fbd
44c47c0b9cf22bbf3d65d06fdf04254b8ea1c430
refs/heads/master
2022-12-24T22:39:15.486021
2020-10-10T14:12:53
2020-10-10T14:12:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
874
h
#ifndef _MAGIC_BEAUTIFY_H_ #define _MAGIC_BEAUTIFY_H_ #include "../bitmap/JniBitmap.h" class MagicBeautify { public: void initMagicBeautify(JniBitmap* jniBitmap); void unInitMagicBeautify(); void startSkinSmooth(float smoothlevel); void startWhiteSkin(float whitenlevel); static MagicBeautify* getInstance(); ~MagicBeautify(); private: static MagicBeautify * instance; MagicBeautify(); uint64_t *mIntegralMatrix; uint64_t *mIntegralMatrixSqr; uint32_t *storedBitmapPixels; uint32_t *mImageData_rgb; uint8_t *mImageData_yuv; uint8_t *mSkinMatrix; int mImageWidth; int mImageHeight; float mSmoothLevel; float mWhitenLevel; void initIntegral(); void initSkinMatrix(); void _startBeauty(float smoothlevel, float whitenlevel); void _startSkinSmooth(float smoothlevel); void _startWhiteSkin(float whitenlevel); }; #endif
[ "sinemaltinkilit@gmail.com" ]
sinemaltinkilit@gmail.com
c44ca087ff6e358a2ede93aea6a2f405881b8397
aa354c9318d71db93c625bbdfc6c014df2d59aec
/src/tracking/TLD.hpp
a8548e220321786dd59c501ffed4d8d2acdebe39
[]
no_license
Nfreewind/TLD-MOD
dcd19e92b7ed32a8bf5eaa1fa167fda8e681da41
a7790de2819a79ff16bb1551433d41b216c943da
refs/heads/master
2020-05-25T01:46:43.724294
2018-07-11T23:23:02
2018-07-11T23:23:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
389
hpp
#ifndef TLD_HPP_INCLUDED #define TLD_HPP_INCLUDED #include <iostream> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include "../common/utils.hpp" #include "Tracker.hpp" #include "Detector.hpp" #include "Integrator_Learning.hpp" using namespace std; using namespace cv; void TLD(char *parameters_path, char *saidaTemplates); #endif // TLD_HPP_INCLUDED
[ "hugo.lima.chaves@gmail.com" ]
hugo.lima.chaves@gmail.com
a054ee884d0d570d94a2d20ad52836ddacfde36d
2eecd3f38b0216df54a16a4e5467337f7a5bf429
/src/shaders/NormalMapShader.h
d289e1fbff8015fddf6b1cfb333122bc02388750
[]
no_license
centuryglass/raytracer
360008148b210eac7e71dbe1316527de97dee67f
5c5e9fb312523d577778f95a0dd3d934e038cf87
refs/heads/master
2020-08-16T05:57:53.573103
2019-10-16T05:30:10
2019-10-16T05:30:10
215,464,787
0
0
null
null
null
null
UTF-8
C++
false
false
1,079
h
/*NormalMapShader.h *Author: Anthony Brown *Produces color info using surface normals *primarily for debugging purposes */ #ifndef __NORMALMAPSHADER__ #define __NORMALMAPSHADER__ #include "Vector3D.h" #include "Scene.h" #include "HitStruct.h" using namespace sivelab; class NormalMapShader : public Shader { public: NormalMapShader() { type = "NormalMap"; } ~NormalMapShader() { } /** * Returns hit a hit color set to give information about the normal vector * at the intersect point. * @param scene The scene where the intersect occurs * @param hit the structure containing intersect data * @return the appropriate color value for the intersect point. */ Vector3D getHitColor(Scene* scene, HitStruct& hit); Vector3D mapLightRay(Scene* scene, HitStruct& hit, Vector3D light,int depth){ return getHitColor(scene, hit); } Vector3D getShadow(HitStruct &hit, Light * l, Scene * scene) { Vector3D s; return s; } }; #endif
[ "anthony0857@gmail.com" ]
anthony0857@gmail.com
ad1a64379ff655a8ae8f6a6b59575c71f1804925
3881f09455e97564764b30b1b612efb404c857f8
/Code/eCore/Include/FileSystem/Archive.h
6a659d044511986f9da25907b50ed770b41b9e37
[]
no_license
eloben/e3engine
345a8100b433103ce3edf312651dbfccba68f243
d14c967c1810360c394bc9bf335289042e3d1149
refs/heads/master
2021-01-01T05:47:52.280255
2014-12-14T20:27:31
2014-12-14T20:27:31
28,004,743
1
0
null
null
null
null
ISO-8859-1
C++
false
false
2,532
h
/*---------------------------------------------------------------------------------------------------------------------- This source file is part of the E3 Project Copyright (c) 2010-2014 Elías Lozada-Benavente 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. ----------------------------------------------------------------------------------------------------------------------*/ // Created 31-Aug-2014 by Elías Lozada-Benavente // Based on original created 12-Feb-2010 by Elías Lozada-Benavente // // $Revision: $ // $Date: $ // $Author: $ /** @file Archive.h This file declares the Archive class. */ #ifndef E3_ARCHIVE_H #define E3_ARCHIVE_H #include "Path.h" #include <fstream> namespace E { namespace FileSystem { /*---------------------------------------------------------------------------------------------------------------------- Archive ----------------------------------------------------------------------------------------------------------------------*/ class Archive { public: enum OpenMode { eOpenModeRead, eOpenModeWrite, eOpenModeAppend }; Archive(); ~Archive(); // Accessors const Path& GetPath() const; bool IsOpen() const; // Methods void Close(); bool Open(const Path& filePath, OpenMode openMode = eOpenModeRead); void Read(char* pTarget, size_t length); void Write(const char* pSource, size_t length); private: Path mFilePath; std::fstream mFileStream; E_DISABLE_COPY_AND_ASSSIGNMENT(Archive); }; } } #endif
[ "eloben@gmail.com" ]
eloben@gmail.com
97a4178e4bbea8594e683d5805fdccc327073ffb
33f59b1ba6b12c2dd3080b24830331c37bba9fe2
/Depend/Foundation/Distance/Wm4DistRay2Ray2.h
061e8d95258929645f01553a013a553b40132802
[]
no_license
daleaddink/flagship3d
4835c223fe1b6429c12e325770c14679c42ae3c6
6cce5b1ff7e7a2d5d0df7aa0594a70d795c7979a
refs/heads/master
2021-01-15T16:29:12.196094
2009-11-01T10:18:11
2009-11-01T10:18:11
37,734,654
1
0
null
null
null
null
UTF-8
C++
false
false
1,542
h
// Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // The Wild Magic Version 4 Foundation Library source code is supplied // under the terms of the license agreement // http://www.geometrictools.com/License/Wm4FoundationLicense.pdf // and may not be copied or disclosed except in accordance with the terms // of that agreement. #ifndef WM4DISTRAY2RAY2_H #define WM4DISTRAY2RAY2_H #include "Wm4FoundationLIB.h" #include "Wm4Distance.h" #include "Wm4Ray2.h" namespace Wm4 { template <class Real> class WM4_FOUNDATION_ITEM DistRay2Ray2 : public Distance<Real,Vector2<Real> > { public: DistRay2Ray2 (const Ray2<Real>& rkRay0, const Ray2<Real>& rkRay1); // object access const Ray2<Real>& GetRay0 () const; const Ray2<Real>& GetRay1 () const; // static distance queries virtual Real Get (); virtual Real GetSquared (); // function calculations for dynamic distance queries virtual Real Get (Real fT, const Vector2<Real>& rkVelocity0, const Vector2<Real>& rkVelocity1); virtual Real GetSquared (Real fT, const Vector2<Real>& rkVelocity0, const Vector2<Real>& rkVelocity1); private: using Distance<Real,Vector2<Real> >::m_kClosestPoint0; using Distance<Real,Vector2<Real> >::m_kClosestPoint1; const Ray2<Real>& m_rkRay0; const Ray2<Real>& m_rkRay1; }; typedef DistRay2Ray2<float> DistRay2Ray2f; typedef DistRay2Ray2<double> DistRay2Ray2d; } #endif
[ "yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa" ]
yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa
25a9b0b02548ac653dca8b11c3541a8d244f5bc0
2d2b852681caba926033541aab1431f66467d1d9
/MultiTask.cpp
45a85712482cd75aca4df837673c97e05c58496c
[]
no_license
alialshekarchee/Arduino_MultiTask
a9ab58f5ee0a63080339db2ce6197ae05f154644
1174e96b69a91bfe35159a60836d6cc6af6162ba
refs/heads/main
2023-04-23T02:51:36.280650
2021-05-15T04:43:45
2021-05-15T04:43:45
367,540,829
0
0
null
null
null
null
UTF-8
C++
false
false
616
cpp
#include "MultiTask.h" MultiTask::MultiTask() { } MultiTask::~MultiTask() { } void MultiTask::runTask(unsigned long miliseconds) { this->miliseconds = miliseconds; this->currentMicros = micros(); this->taskEnable = true; } bool MultiTask::isTaskDue() { if((micros() - this->currentMicros) / 1000 >= this->miliseconds && this->taskEnable) { this->currentMicros = micros(); this->taskEnable = false; return true; } else { if(micros() > 4294967000) { this->currentMicros = 0; } return false; } } void MultiTask::disableTask() { this->taskEnable = false; }
[ "alielshekarchee@gmail.com" ]
alielshekarchee@gmail.com
d7485ff84bd7fd245a4844ec9e26ebe824ab1330
0474d696c36cc2e2be35b15704c85dd9e0f375bf
/measure_backups/measure/measureDlg.cpp
683657511eff84f493c802e33953b3b4d31156b1
[]
no_license
nicedaylbl/ProjectsDemo
8dd9a5672b1614c41b471a8f73eca3d157ac8e9f
2f5316852330a146084704a0c982ec1410d845ec
refs/heads/master
2021-01-19T01:37:42.352974
2017-04-05T01:18:43
2017-04-05T01:18:43
87,251,081
0
0
null
null
null
null
GB18030
C++
false
false
15,119
cpp
// measureDlg.cpp : 实现文件 // #include "stdafx.h" #include "measure.h" #include "measureDlg.h" #include "ChartCtrl/ChartAxisLabel.h" #include "ChartCtrl/ChartLineSerie.h" #include <stdlib.h> #include <string.h> #include <locale> #include <time.h> #include <math.h> #ifdef _DEBUG #define new DEBUG_NEW #endif // 用于应用程序“关于”菜单项的 CAboutDlg 对话框 class CAboutDlg : public CDialog { public: CAboutDlg(); // 对话框数据 enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 // 实现 protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) END_MESSAGE_MAP() // CmeasureDlg 对话框 CmeasureDlg::CmeasureDlg(CWnd* pParent /*=NULL*/) : CDialog(CmeasureDlg::IDD, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); DeviceHandle = NULL; pLeftAxis = NULL; pBottomAxis = NULL; isDrawFlag = true; memset(myCurrentArray,0,sizeof(myCurrentArray)); memset(mySampleTime,0, sizeof(mySampleTime)); totalTimeCount = 0; myrealCurrent = 0; myCount = 1; maxCurrent = 0; minCurrent = 0; sumCurrent = 0; maxLeftAxis = 500; } void CmeasureDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_CHART, myChartCtrl); DDX_Control(pDX, IDC_STATIC_TOTALTIME, myTotalTime); DDX_Control(pDX, IDC_STATIC_RMSCURRENT,myRmsCurrent); DDX_Control(pDX, IDC_EDIT_GPIBADD2, m_GPIB); DDX_Control(pDX, IDC_EDIT_POWADD, m_addPower); DDX_Control(pDX, IDC_EDIT_VOLTAGE, m_voltage); DDX_Control(pDX, IDC_EDIT_SAMPLE, m_rate); DDX_Control(pDX, IDC_LIST_RESULT, myListCtrl); DDX_Control(pDX, IDC_STATIC_AXIS, m_StaticAxis); } BEGIN_MESSAGE_MAP(CmeasureDlg, CDialog) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() //}}AFX_MSG_MAP ON_BN_CLICKED(IDC_BUTTON_SAVEDATA, &CmeasureDlg::OnBnClickedButtonSavedata) ON_BN_CLICKED(IDC_BUTTON_START, &CmeasureDlg::OnBnClickedButtonStart) ON_WM_TIMER() ON_BN_CLICKED(IDC_BUTTON_OPENDIVECE, &CmeasureDlg::OnBnClickedButtonOpendivece) ON_BN_CLICKED(IDC_BUTTON_QUIT, &CmeasureDlg::OnBnClickedButtonQuit) END_MESSAGE_MAP() // CmeasureDlg 消息处理程序 BOOL CmeasureDlg::OnInitDialog() { CDialog::OnInitDialog(); // 将“关于...”菜单项添加到系统菜单中。 // IDM_ABOUTBOX 必须在系统命令范围内。 ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // 设置此对话框的图标。当应用程序主窗口不是对话框时,框架将自动 // 执行此操作 SetIcon(m_hIcon, TRUE); // 设置大图标 SetIcon(m_hIcon, FALSE); // 设置小图标 // TODO: 在此添加额外的初始化代码 myCurrentData = new VECTOR; m_GPIB.SetWindowText(_T("0")); m_addPower.SetWindowText(_T("5")); m_voltage.SetWindowText(_T("3.8")); m_rate.SetWindowText(_T("1")); // TODO: 在此添加额外的初始化代码 ((CButton*)GetDlgItem(IDC_CHECK_CORRENT))->SetCheck(1); ((CButton*)GetDlgItem(IDC_CHECK_DWENBLE))->SetCheck(1); //初始化曲线表 pLeftAxis = myChartCtrl.CreateStandardAxis(CChartCtrl::LeftAxis); pLeftAxis->SetAutomatic(false); pLeftAxis->SetMinMax(0,500); //pAxis->EnableScrollBar(true); pLeftAxis->SetPanZoomEnabled(false); pBottomAxis = myChartCtrl.CreateStandardAxis(CChartCtrl::BottomAxis); pBottomAxis->SetAutomatic(false); pBottomAxis->EnableScrollBar(true); pBottomAxis->SetMinMax(0,200); TChartString strtitle = _T("功耗图表"); myChartCtrl.GetTitle()->AddString(strtitle); TChartString strLeftAxis = _T("电流(mA)"); TChartString strBottomAxis = _T("时间(s)"); myChartCtrl.GetLeftAxis()->GetLabel()->SetText(strLeftAxis); myChartCtrl.GetBottomAxis()->GetLabel()->SetText(strBottomAxis); m_pLineSerie = myChartCtrl.CreateLineSerie(); CChartCrossHairCursor* pCrossHair = myChartCtrl.CreateCrossHairCursor(); myChartCtrl.ShowMouseCursor(true); CMyCursorListener* pCursorListener = new CMyCursorListener; pCrossHair->RegisterListener(pCursorListener); myStaticResultFont.CreateFont(30,0,0,0,FW_NORMAL,FALSE,FALSE,0,ANSI_CHARSET,\ OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS,DEFAULT_QUALITY, DEFAULT_PITCH | FF_SWISS,_T("Arial")); myRmsCurrent.SetFont(&myStaticResultFont); myRmsCurrent.SetBKColor(RGB(0,150,0)); myRmsCurrent.SetTextColor(RGB(0,0,255)); myRmsCurrent.SetWindowText(_T("0.0mA")); myTotalTime.SetFont(&myStaticResultFont); myTotalTime.SetBKColor(RGB(0,150,0)); myTotalTime.SetTextColor(RGB(0,0,255)); myTotalTime.SetWindowText(_T("00时00分00秒")); //设置myListResult结果显示 DWORD dwStyle =myListCtrl.GetExtendedStyle(); dwStyle = LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES ; myListCtrl.SetExtendedStyle(dwStyle);//设置扩展风格 myListCtrl.InsertColumn(0,_T("指标"),LVCFMT_CENTER,80); myListCtrl.InsertColumn(1,_T("数值(mA)"),LVCFMT_CENTER,110); myListCtrl.InsertItem(0,_T("当前电流值")); myListCtrl.InsertItem(1,_T("平均电流值")); myListCtrl.InsertItem(2,_T("最大电流值")); myListCtrl.InsertItem(3,_T("最小电流值")); return TRUE; // 除非将焦点设置到控件,否则返回 TRUE } void CmeasureDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } // 如果向对话框添加最小化按钮,则需要下面的代码 // 来绘制该图标。对于使用文档/视图模型的 MFC 应用程序, // 这将由框架自动完成。 void CmeasureDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // 用于绘制的设备上下文 SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // 使图标在工作区矩形中居中 int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // 绘制图标 dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } //当用户拖动最小化窗口时系统调用此函数取得光标 //显示。 HCURSOR CmeasureDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } void CmeasureDlg::OnBnClickedButtonSavedata() { // TODO: 在此添加控件通知处理程序代码 OPENFILENAME ofn; TCHAR szFile[MAX_PATH]; ZeroMemory(&ofn,sizeof(ofn)); ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = m_hWnd; ofn.lpstrFile = szFile; ofn.lpstrFile[0] = _T('\0'); ofn.nMaxFile = sizeof(szFile); ofn.lpstrFilter = _T("Text\0*.txt\0"); ofn.nFilterIndex = 1; ofn.lpstrFileTitle = NULL; ofn.nMaxFileTitle = 0; ofn.Flags = OFN_SHOWHELP | OFN_OVERWRITEPROMPT; CString strFile; if (GetSaveFileName(&ofn)) { strFile.Format(_T("%s"),szFile); } else return; if (strFile.Find(_T('.'))!= -1) { strFile = strFile.Left(strFile.Find(_T('.'))); } strFile+=_T(".txt"); CStdioFile File; CFileException fileException; if (File.Open(strFile,CFile::modeCreate | CFile::modeReadWrite | CFile::typeText)) { char* old_local = _strdup(setlocale(LC_CTYPE,NULL)); setlocale(LC_CTYPE, "chs"); File.WriteString(_T("序号 采样时间(s) 电流(mA)\n")); } int testNumber=0; VECTOR::iterator itt = myCurrentData->begin(); CString bufferData = _T(""); while( itt != myCurrentData->end()) { double tempCurret = (*itt).first; CString tempCurrentTime = (*itt).second; bufferData.Format(_T("%d %s %.3f\n"),testNumber+1,tempCurrentTime,tempCurret); File.WriteString(bufferData); ++testNumber; *itt++; } File.Close(); } void CmeasureDlg::OpenDevice() { viStatus = VI_SUCCESS; m_GPIB.GetWindowText(strGpib); m_addPower.GetWindowText(strPowerAddress); m_voltage.GetWindowText(strVoltage); double Voltage = _wtof(strVoltage.GetBuffer(0)); if (VI_SUCCESS > viOpenDefaultRM(&m_viDefaultRM) ) { AfxMessageBox(_T("打开电源DefaultRM失败!")); //return VI_FALSE; } else { sprintf(szCmdBuff,"GPIB%d::%d::INSTR",_ttoi(strGpib),_ttoi(strPowerAddress)); viStatus = viOpen(m_viDefaultRM, szCmdBuff, VI_NULL, VI_NULL, &DeviceHandle); if (!viStatus) { viStatus |= viSetAttribute(DeviceHandle,VI_ATTR_TMO_VALUE,20000); viStatus |= viQueryf(DeviceHandle,"*IDN?\n","%t",szCmdBuff); viStatus |= viPrintf(DeviceHandle,"*RST\n"); viStatus |= viPrintf(DeviceHandle,"INST:COUP:OUTP:STAT NONE\n");//指令只对其中某一路生效。 viStatus |= viPrintf(DeviceHandle,"VOLT %.5f;CURR 3\n",Voltage); viStatus |= viPrintf(DeviceHandle,"OUTP ON\n"); } else { AfxMessageBox(_T("打开电源失败!")); } } } void CmeasureDlg::OnSetBottomtAxisAuto(int rate) { //rate单位为ms int tempMinLeftAxis = 0; int tempSample = rate >= 1000 ? (rate/1000) : rate; if ( myCount == 1 ) { if (ceil(myrealCurrent) < 500) { maxLeftAxis = 500; } else if (ceil(myrealCurrent) < 1000 ) { maxLeftAxis = 1000; } else if (ceil(myrealCurrent) < 1500) { maxLeftAxis = 1500; } else maxLeftAxis = 2000; tempMinLeftAxis = (maxLeftAxis - 500) > 0 ? (maxLeftAxis - 500) : 0; pLeftAxis->SetMinMax(tempMinLeftAxis, maxLeftAxis); } if ( myCount <= MAXDWPONIT ) { pBottomAxis->SetMinMax(0,MAXDWPONIT*tempSample); } else { int startAxis = ((myCount-1)%MAXDWPONIT + (myCount-1)/MAXDWPONIT)*tempSample; int endAxis = ((myCount-1)%MAXDWPONIT+MAXDWPONIT + (myCount-1)/MAXDWPONIT)*tempSample; pBottomAxis->SetMinMax(startAxis,endAxis); } } void CmeasureDlg::OnDrawMoving() { int number = myCount<MAXNUM ?myCount:MAXNUM; m_pLineSerie->ClearSerie(); if ( myCount < MAXNUM ) { FillCurrentArray(myrealCurrent); } if ( myCount >= MAXNUM ) { LeftMoveArray(myCurrentArray,mySampleTime,number,myrealCurrent); } OnSetBottomtAxisAuto(mySampleRate); //LeftMoveArray(myCurrentArray,mySampleTime,number,myCurrentOnce); m_pLineSerie->AddPoints(mySampleTime,myCurrentArray,number); } void CmeasureDlg::LeftMoveArray(double* ptrCurrent,double* ptrSample,size_t length,double data) { for (size_t i=1;i<length;++i) { ptrCurrent[i-1] = ptrCurrent[i]; } ptrCurrent[length-1] = data; for (size_t j=1;j<length;++j) { ptrSample[j-1] = ptrSample[j]; } ptrSample[length-1] =myCount*mySampleRate ; } void CmeasureDlg::FillCurrentArray( double data) { int temp = mySampleRate >= 1000 ? mySampleRate/1000 : mySampleRate; myCurrentArray[myCount-1] = data; mySampleTime[myCount-1] =myCount*temp; } void CmeasureDlg::SetTotalTime() { ++totalTimeCount; int hour = 0 ; int minute = 0; int second = 0; CString temptotal = _T(""); hour = totalTimeCount/3600; minute = (totalTimeCount%3600)/60; second = (totalTimeCount%3600)%60; temptotal.Format(_T("%02d时%02d分%02d秒"),hour,minute,second); myTotalTime.SetWindowText(temptotal); } void CmeasureDlg::SetListResult() { CString itemText = _T(""); itemText.Format(_T("%03.3f mA"),sumCurrent/myCount); myRmsCurrent.SetWindowText(itemText); itemText.Format(_T("%.5f"),myrealCurrent); myListCtrl.SetItemText(0,1,itemText); itemText.Format(_T("%.5f"),sumCurrent/myCount); myListCtrl.SetItemText(1,1,itemText); itemText.Format(_T("%.5f"),maxCurrent); myListCtrl.SetItemText(2,1,itemText); itemText.Format(_T("%.5f"),minCurrent); myListCtrl.SetItemText(3,1,itemText); } void CmeasureDlg::CurrentMeasures() { if ( DeviceHandle != NULL ) { viStatus = viQueryf(DeviceHandle,"MEAS:CURR?\n","%lf",&myrealCurrent); } else myrealCurrent = 0; } void CmeasureDlg::OnBnClickedButtonStart() { // TODO: 在此添加控件通知处理程序代码 CString str; double voltage = 0; double current = 0; m_GPIB.GetWindowText(strGpib); m_addPower.GetWindowText(strPowerAddress); m_voltage.GetWindowText(strVoltage); m_rate.GetWindowText(strSample); mySampleRate = _ttoi(strSample);//采样时间为ms //OnSetBottomtAxisAuto(_ttoi(strSample)); str = mySampleRate >= 1000 ? _T("时间(s)") : _T("时间(ms)"); myChartCtrl.GetBottomAxis()->GetLabel()->SetText(str.GetBuffer(0)); GetDlgItem(IDC_BUTTON_START)->GetWindowText(str); if (!str.Compare(_T("开始"))) { myCurrentData->clear();// //判断是否画图 if ( BST_CHECKED == IsDlgButtonChecked( IDC_CHECK_DWENBLE )) { isDrawFlag = true; } else isDrawFlag = false; GetDlgItem(IDC_BUTTON_START)->SetWindowText(_T("结束")); DWORD begin = GetTickCount(); SetTimer(1,mySampleRate,NULL);//采样率 SetTimer(2,1000,NULL);//该计时器记录测试总时间ms为单位。 } if (!str.Compare(_T("结束"))) { GetDlgItem(IDC_BUTTON_START)->SetWindowText(_T("开始")); //结束之后重置测试相关的全局变量,以便开始下次测试。 memset(myCurrentArray,0,sizeof(myCurrentArray)); memset(mySampleTime,0, sizeof(mySampleTime)); totalTimeCount = 0; myrealCurrent = 0; myCount = 1; maxCurrent = 0; minCurrent = 0; sumCurrent = 0; KillTimer(1); KillTimer(2); } } void CmeasureDlg::OnTimer(UINT_PTR nIDEvent) { // TODO: 在此添加消息处理程序代码和/或调用默认值 if (1 == nIDEvent) { DWORD begin2 = GetTickCount(); CString strSystime; GetLocalTime(&st); strSystime.Format(_T("%02d-%02d_%02d:%02d:%02d:%02d"),st.wMonth,st.wDay,st.wHour,st.wMinute,st.wSecond,st.wMilliseconds); strSystime.ReleaseBuffer(); CurrentMeasures(); myrealCurrent = 1000*myrealCurrent;//直接取出来电流结果单位为A myCurrentData->push_back(make_pair(myrealCurrent,strSystime)); maxCurrent = maxCurrent > myrealCurrent ? maxCurrent:myrealCurrent; minCurrent = ( minCurrent < myrealCurrent ) && ( minCurrent > 0.000001) ? minCurrent:myrealCurrent; sumCurrent = sumCurrent + myrealCurrent; SetListResult(); if ( isDrawFlag ) { OnDrawMoving(); } myCount++; } if ( 2 == nIDEvent) { SetTotalTime(); } CDialog::OnTimer(nIDEvent); } void CmeasureDlg::OnBnClickedButtonOpendivece() { // TODO: 在此添加控件通知处理程序代码 CString str; GetDlgItem(IDC_BUTTON_OPENDIVECE)->GetWindowText(str); if (!str.Compare(_T("打开电源"))) { OpenDevice(); if (viStatus == VI_SUCCESS) { GetDlgItem(IDC_BUTTON_OPENDIVECE)->SetWindowText(_T("关闭电源")); } } if (!str.Compare(_T("关闭电源"))) { GetDlgItem(IDC_BUTTON_OPENDIVECE)->SetWindowText(_T("打开电源")); CloseDevice(); } } void CmeasureDlg::OnBnClickedButtonQuit() { // TODO: 在此添加控件通知处理程序代码 delete myCurrentData; AfxGetMainWnd()->SendMessage(WM_CLOSE); } void CmeasureDlg::CloseDevice() { if (DeviceHandle != NULL) { viPrintf(DeviceHandle,"OUTP OFF\n"); } viClose(m_viDefaultRM); viClose(DeviceHandle); }
[ "menxinghong@126.com" ]
menxinghong@126.com
2eb2d49646610b2de6d6aab3c0f2e06da6d4bf8e
2ce43dfc0cfcf187d76aef1a3e85001f0ba08fee
/cantera/include/cantera/thermo/MetalSHEelectrons.h
0cc76b6db8fc5f1c6722f2245057398122ee2421
[]
no_license
parkerclayton/python
2387b6e07b8dd2e65f215274c4d578da1309ea74
3b3c346b7039f5b83a2bc0dcf287ff01cbd6b716
refs/heads/master
2020-04-09T04:16:06.551172
2016-06-02T05:03:40
2016-06-02T05:03:40
51,048,280
0
0
null
null
null
null
UTF-8
C++
false
false
13,399
h
/** * @file MetalSHEelectrons.h * Header file for the MetalSHEElectrons class, which represents the * electrons in a metal that are consistent with the * SHE electrode (see \ref thermoprops and * class \link Cantera::MetalSHEelectrons MetalSHEelectrons\endlink) */ /* * Copyright (2005) Sandia Corporation. Under the terms of * Contract DE-AC04-94AL85000 with Sandia Corporation, the * U.S. Government retains certain rights in this software. */ #ifndef CT_METALSHEELECTRONS_H #define CT_METALSHEELECTRONS_H #include "SingleSpeciesTP.h" namespace Cantera { //! Class MetalSHEelectrons represents electrons within a metal, adjacent to an //! aqueous electrolyte, that are consistent with the SHE reference electrode. /*! * The class is based on the electron having a chemical potential equal to one- * half of the entropy of the H<SUP>2</SUP> gas at the system pressure * * <b> Specification of Species Standard State Properties </b> * * This class inherits from SingleSpeciesTP. It is assumed that the reference * state thermodynamics may be obtained by a pointer to a populated species * thermodynamic property manager class (see ThermoPhase::m_spthermo). How to * relate pressure changes to the reference state thermodynamics is resolved at * this level. * * The enthalpy function is given by the following relation. * * \f[ * h^o_k(T,P) = h^{ref}_k(T) * \f] * * The standard state constant-pressure heat capacity is independent of pressure: * * \f[ * Cp^o_k(T,P) = Cp^{ref}_k(T) * \f] * * The standard state entropy depends in the following fashion on pressure: * * \f[ * S^o_k(T,P) = S^{ref}_k(T) - R \ln(\frac{P}{P_{ref}}) * \f] * * The standard state Gibbs free energy is obtained from the enthalpy and * entropy functions: * * \f[ * \mu^o_k(T,P) = h^o_k(T,P) - S^o_k(T,P) T * \f] * * \f[ * \mu^o_k(T,P) = \mu^{ref}_k(T) + R T \ln( \frac{P}{P_{ref}}) * \f] * * where * \f[ * \mu^{ref}_k(T) = h^{ref}_k(T) - T S^{ref}_k(T) * \f] * * The standard state internal energy is obtained from the enthalpy function also * * \f[ * u^o_k(T,P) = h^o_k(T) - R T * \f] * * <b> Specification of Solution Thermodynamic Properties </b> * * All solution properties are obtained from the standard state species * functions, since there is only one species in the phase. * * <b> %Application within Kinetics Managers </b> * * The standard concentration is equal to 1.0. This means that the kinetics * operator works on an activities basis. Since this is a stoichiometric * substance, this means that the concentration of this phase drops out of * kinetics expressions since the activity is always equal to one. * * This is what is expected of electrons. The only effect that this class will * have on reactions is in terms of the standard state chemical potential, which * is equal to 1/2 of the H2 gas chemical potential, and the voltage assigned to * the electron, which is the voltage of the metal. * * <b> Instantiation of the Class </b> * * The constructor for this phase is located in the default ThermoFactory for * %Cantera. A new MetalSHEelectrons object may be created by the following code * snippets, where the file metalSHEelectrons.xml exists in a local directory: * * @code * MetalSHEelectrons *eMetal = new MetalSHEelectrons("metalSHEelectrons.xml", ""); * @endcode * * or by the following call to importPhase(): * * @code * XML_Node *xm = get_XML_NameID("phase", iFile + "#MetalSHEelectrons", 0); * MetalSHEelectrons eMetal; * importPhase(*xm, &eMetal); * @endcode * * @code * ThermoPhase *eMetal = newPhase("MetalSHEelectrons.xml", "MetalSHEelectrons"); * @endcode * * Additionally, this phase may be created without including an XML file with * the special command, where the default file is embedded into this object. * * @code * MetalSHEelectrons *eMetal = new MetalSHEelectrons("MetalSHEelectrons_default.xml", ""); * @endcode * * <b> XML Example </b> * * The phase model name for this is called MetalSHEelectrons. It must be * supplied as the model attribute of the thermo XML element entry. Within the * phase XML block, the density of the phase must be specified though it's not * used. An example of an XML file this phase is given below. * * @code * <?xml version="1.0"?> * <ctml> * <validate reactions="yes" species="yes"/> * * <phase dim="3" id="MetalSHEelectrons"> * <elementArray datasrc="elements.xml"> * E * </elementArray> * <speciesArray datasrc="#species_Metal_SHEelectrons"> she_electron </speciesArray> * <thermo model="metalSHEelectrons"> * <density units="g/cm3">2.165</density> * </thermo> * <transport model="None"/> * <kinetics model="none"/> * </phase> * * <!-- species definitions --> * <speciesData id="species_Metal_SHEelectrons"> * <species name="she_electron"> * <atomArray> E:1 </atomArray> * <charge> -1 </charge> * <thermo> * <NASA Tmax="1000.0" Tmin="200.0" P0="100000.0"> * <floatArray name="coeffs" size="7"> * 1.172165560E+00, 3.990260375E-03, -9.739075500E-06, 1.007860470E-08, * -3.688058805E-12, -4.589675865E+02, 3.415051190E-01 * </floatArray> * </NASA> * <NASA Tmax="6000.0" Tmin="1000.0" P0="100000.0"> * <floatArray name="coeffs" size="7"> * 1.466432895E+00, 4.133039835E-04, -7.320116750E-08, 7.705017950E-12, * -3.444022160E-16, -4.065327985E+02, -5.121644350E-01 * </floatArray> * </NASA> * </thermo> * <density units="g/cm3">2.165</density> * </species> * </speciesData> * </ctml> * @endcode * * The model attribute, "MetalSHEelectrons", on the thermo element identifies * the phase as being a MetalSHEelectrons object. * * @ingroup thermoprops */ class MetalSHEelectrons : public SingleSpeciesTP { public: //! Default constructor for the MetalSHEelectrons class MetalSHEelectrons(); //! Construct and initialize a MetalSHEelectrons ThermoPhase object //! directly from an ASCII input file /*! * @param infile name of the input file * @param id name of the phase id in the file. * If this is blank, the first phase in the file is used. */ MetalSHEelectrons(const std::string& infile, const std::string& id = ""); //! Construct and initialize a MetalSHEelectrons ThermoPhase object //! directly from an XML database /*! * @param phaseRef XML node pointing to a MetalSHEelectrons description * @param id Id of the phase. */ MetalSHEelectrons(XML_Node& phaseRef, const std::string& id = ""); MetalSHEelectrons(const MetalSHEelectrons& right); MetalSHEelectrons& operator=(const MetalSHEelectrons& right); virtual ThermoPhase* duplMyselfAsThermoPhase() const; /** * Equation of state flag. * * Returns the value cMetalSHEelectrons, defined in mix_defs.h. */ virtual int eosType() const; //! @name Mechanical Equation of State //! @{ //! Report the Pressure. Units: Pa. /*! * For an incompressible substance, the density is independent of pressure. * This method simply returns the stored pressure value. */ virtual doublereal pressure() const; //! Set the pressure at constant temperature. Units: Pa. /*! * For an incompressible substance, the density is independent of pressure. * Therefore, this method only stores the specified pressure value. It does * not modify the density. * * @param p Pressure (units - Pa) */ virtual void setPressure(doublereal p); virtual doublereal isothermalCompressibility() const; virtual doublereal thermalExpansionCoeff() const; //! @} //! @name Activities, Standard States, and Activity Concentrations //! //! This section is largely handled by parent classes, since there //! is only one species. Therefore, the activity is equal to one. //! @{ //! This method returns an array of generalized concentrations /*! * \f$ C^a_k\f$ are defined such that \f$ a_k = C^a_k / C^0_k, \f$ where * \f$ C^0_k \f$ is a standard concentration defined below and \f$ a_k \f$ * are activities used in the thermodynamic functions. These activity (or * generalized) concentrations are used by kinetics manager classes to * compute the forward and reverse rates of elementary reactions. * * For a stoichiometric substance, there is only one species, and the * generalized concentration is 1.0. * * @param c Output array of generalized concentrations. The units depend * upon the implementation of the reaction rate expressions within * the phase. */ virtual void getActivityConcentrations(doublereal* c) const; //! Return the standard concentration for the kth species /*! * The standard concentration \f$ C^0_k \f$ used to normalize the activity * (i.e., generalized) concentration. This phase assumes that the kinetics * operator works on an dimensionless basis. Thus, the standard * concentration is equal to 1.0. * * @param k Optional parameter indicating the species. The default * is to assume this refers to species 0. * @return * Returns The standard Concentration as 1.0 */ virtual doublereal standardConcentration(size_t k=0) const; //! Natural logarithm of the standard concentration of the kth species. /*! * @param k index of the species (defaults to zero) */ virtual doublereal logStandardConc(size_t k=0) const; //! Get the array of chemical potentials at unit activity for the species at //! their standard states at the current <I>T</I> and <I>P</I> of the //! solution. /*! * For a stoichiometric substance, there is no activity term in the chemical * potential expression, and therefore the standard chemical potential and * the chemical potential are both equal to the molar Gibbs function. * * These are the standard state chemical potentials \f$ \mu^0_k(T,P) \f$. * The values are evaluated at the current temperature and pressure of the * solution * * @param mu0 Output vector of chemical potentials. * Length: m_kk. */ virtual void getStandardChemPotentials(doublereal* mu0) const; //@} /// @name Properties of the Standard State of the Species in the Solution //@{ virtual void getEnthalpy_RT(doublereal* hrt) const; virtual void getEntropy_R(doublereal* sr) const; virtual void getGibbs_RT(doublereal* grt) const; virtual void getCp_R(doublereal* cpr) const; //! Returns the vector of nondimensional Internal Energies of the standard //! state species at the current <I>T</I> and <I>P</I> of the solution /*! * For an incompressible, stoichiometric substance, the molar internal * energy is independent of pressure. Since the thermodynamic properties are * specified by giving the standard-state enthalpy, the term \f$ P_{ref} * \hat v\f$ is subtracted from the specified reference molar enthalpy to * compute the standard state molar internal energy. * * @param urt output vector of nondimensional standard state * internal energies of the species. Length: m_kk. */ virtual void getIntEnergy_RT(doublereal* urt) const; //@} /// @name Thermodynamic Values for the Species Reference States //@{ virtual void getIntEnergy_RT_ref(doublereal* urt) const; // @} virtual void initThermoXML(XML_Node& phaseNode, const std::string& id); //! Make the default XML tree /*! * @returns a malloced XML tree containing the default info. */ static XML_Node* makeDefaultXMLTree(); //! Set the equation of state parameters /*! * @internal * * @param n number of parameters * @param c array of \a n coefficients * c[0] = density of phase [ kg/m3 ] */ virtual void setParameters(int n, doublereal* const c); //! Get the equation of state parameters in a vector /*! * @internal * * @param n number of parameters * @param c array of \a n coefficients * * For this phase: * - n = 1 * - c[0] = density of phase [ kg/m3 ] */ virtual void getParameters(int& n, doublereal* const c) const; //! Set equation of state parameter values from XML entries. /*! * For this phase, the density of the phase is specified in this block. * * @param eosdata An XML_Node object corresponding to * the "thermo" entry for this phase in the input file. * * eosdata points to the thermo block, and looks like this: * * @code * <phase id="stoichsolid" > * <thermo model="StoichSubstance"> * <density units="g/cm3">3.52</density> * </thermo> * </phase> * @endcode */ virtual void setParametersFromXML(const XML_Node& eosdata); }; } #endif
[ "parkerclayton@comcast.net" ]
parkerclayton@comcast.net
ec95c8995339865a56cf90e4d97ac16b89dda667
8fb12d96a857cd95c95d622e552d4d17ba4d9d02
/simpleShaders.cpp
2b8ee965ca0a9443369ec9294dcb4162300a4c97
[]
no_license
strykejern/strykejern-ShaderProject
4428776a32898e0e5b8ad5d69ac7e54e60553d7c
3f928ab5feb77cedb57178a85393cc38c2782de7
refs/heads/master
2021-01-10T03:30:54.679026
2013-02-24T12:29:46
2013-02-24T12:29:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,127
cpp
#ifdef __APPLE__ #include <glew.h> #include <GLUT/GLUT.h> #include <OpenGL/glext.h> #elif defined (_WIN32) #include <GL\glew.h> #include <GL\glut.h> #include <GL\GL.h> #endif #include "simpleShaders.h" #include <iostream> #include <fstream> using namespace std; simpleShaderProgram::simpleShaderProgram(void){ program = glCreateProgram(); } simpleShaderProgram::simpleShaderProgram(const char *vertexFile, const char *fragFile){ program = glCreateProgram(); attachVertexShader(vertexFile); attachFragmentShader(fragFile); linkShader(); } void simpleShaderProgram::loadShader(const GLchar *filename, GLint shader, GLuint program){ GLuint vshader = glCreateShader(shader); const char *vs = readTextFile(filename); glShaderSource(vshader, 1, &vs, NULL); char output[2000]; glCompileShader(vshader); glGetShaderInfoLog(vshader, 2000, NULL, output); cout << output << endl; glAttachShader(program,vshader); delete [] vs; } char *simpleShaderProgram::readTextFile(const char *filename){ ifstream TFile; TFile.open(filename); if (TFile.is_open()){ TFile.seekg(0, ios::end); int length = (int)TFile.tellg(); TFile.seekg(0, ios::beg); char *buffer = new char[length+1]; TFile.read(buffer, length); buffer[length] = '\0'; TFile.close(); return buffer; } else{ cout << "Error opening file" << endl; throw 404; } } void simpleShaderProgram::attachVertexShader(const char *filename){ loadShader(filename, GL_VERTEX_SHADER, program); } void simpleShaderProgram::attachFragmentShader(const char *filename){ loadShader(filename, GL_FRAGMENT_SHADER, program); } void simpleShaderProgram::enable(void){ glUseProgram(program); } void simpleShaderProgram::disable(void){ glUseProgram(NULL); } void simpleShaderProgram::linkShader(void){ glLinkProgram(program); } GLint simpleShaderProgram::getProgram(void){ return program; }
[ "strykejernene@gmail.com" ]
strykejernene@gmail.com
2aac4d4a8a28714a1fc85f9676f1e21ad512b56d
7bfc60c56b4c12957c53657d0549a136b6e6cdb2
/index_tuple.cpp
d2045ca22437ba1ac789ae040dd997a7708407be
[ "BSL-1.0" ]
permissive
bolero-MURAKAMI/CEL---ConstExpr-Library
867ef5656ff531ececaf5747594f8b948d872f34
1ad865dd8845c63e473a132870347e913ff91c1c
refs/heads/master
2021-01-17T22:03:25.021662
2011-11-26T12:59:00
2011-11-26T12:59:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,024
cpp
// Copyright (C) 2011 RiSK (sscrisk) // // 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<cassert> #include<sscrisk/cel/array.hpp> #include<sscrisk/cel/index_tuple.hpp> template<std::size_t... Indexes> constexpr sscrisk::cel::array<int, sizeof...(Indexes)> f(sscrisk::cel::index_tuple<Indexes...>) { return {{Indexes...}}; } int main() { using namespace sscrisk::cel; constexpr auto a = f(index_tuple<>()); assert(a.size() == 0); constexpr auto b = f(index_tuple<42>()); assert(b.size() == 1); assert(b[0] == 42); constexpr auto c = f(index_tuple<42, 64>()); assert(c.size() == 2); assert(c[0] == 42); assert(c[1] == 64); constexpr auto d = f(index_range<0, 10>::type()); assert(d.size() == 10); assert(d[0] == 0); assert(d[9] == 9); constexpr auto e = f(index_range<0, 10, 3>::type()); assert(e.size() == 4); assert(e[0] == 0); assert(e[3] == 9); }
[ "sscrisk@gmail.com" ]
sscrisk@gmail.com
c79b25335ed2b0d4da5639664db8e5274171b38f
bfe485ed1bac4deace37e8c0a64608abfcebc1ca
/autoPilot.cpp
d44fc6deeeb0a25fcb532734ba96003820cfd249
[]
no_license
cb1986ster/miniCopterPro
9ed2e5085c6d533a36250106fe4a67556d54dcd5
a677a1902e4b8a5e0d7ef827934ceb55f87579ea
refs/heads/master
2021-01-10T21:21:34.781290
2016-09-25T21:23:07
2016-09-25T21:23:07
31,960,143
3
0
null
null
null
null
UTF-8
C++
false
false
3,860
cpp
#include "autoPilot.h" #include "miniCopterPro.h" #define copter ((miniCopterPro*)copterPointer) //------------------------------------------------------------------------------ void autoPilot::init(){ copter->io.sendMesgNoNl(ioText_pilotInit); pidDataPointers[0][0]=copter->sensors.getPitchPointer(); pidDataPointers[0][1]=copter->getPitchTargetPointer(); pidDataPointers[1][0]=copter->sensors.getRollPointer(); pidDataPointers[1][1]=copter->getRollTargetPointer(); pidDataPointers[2][0]=copter->sensors.getYawPointer(); pidDataPointers[2][1]=copter->getYawTargetPointer(); pidDataPointers[3][0]=copter->sensors.getPitchPointer(); pidDataPointers[3][1]=copter->getPitchTargetPointer(); workMode = PILOT_MODE_GIMBAL_RUN; initPID(); copter->io.sendMesgNoStart(ioText_OK); } //------------------------------------------------------------------------------ void autoPilot::fixGimbal(){ copter->effectors.setGimbalArc(0,copter->sensors.getRoll()+copter->getGimbalTarget(0)); copter->effectors.setGimbalArc(1,copter->sensors.getPitch()+copter->getGimbalTarget(1)); } //------------------------------------------------------------------------------ void autoPilot::tunePID(int pidNo,double* pidK){ uint8_t i; for(i=0;i<12;i++) saveInEEPROM(i+(pidNo*12), *((byte*)(&pidK)+i) ); initPID(); } void autoPilot::initPID(){ double pidK[3] = {1.0,0.5,0.1}; uint8_t pidNo,i; for(pidNo=0;pidNo<4;pidNo++){ // Free on reload if(pids[pidNo]) free(pids[pidNo]); // Load from EEPROM if( 170 == getEEPROM(3) && 170 == getEEPROM(2) && 170 == getEEPROM(1) && 170 == getEEPROM(0) ) for(i=0;i<12;i++) *(((byte*)pidK)+i) = getEEPROM(4 + i + (pidNo*12)); // Create PID pids[pidNo] = new PID( // Input pidDataPointers[pidNo][0], // Output pidsOut+pidNo, // Target pidDataPointers[pidNo][2], pidK[0], // P pidK[1], // I pidK[2], // D DIRECT ); } } //------------------------------------------------------------------------------ void autoPilot::fixPlatform(){ static double throtle = 0 ; pids[CPID_ROLL]->Compute(); pids[CPID_ROT]->Compute(); pids[CPID_PITCH]->Compute(); // pids[CPID_THROTLE]->Compute(); throtle = copter->getAltChangeTarget(); copter->effectors.setMotorSpeed(0, pidsOut[CPID_ROT] + pidsOut[CPID_ROLL] + pidsOut[CPID_PITCH] + throtle ); copter->effectors.setMotorSpeed(1, -pidsOut[CPID_ROT] + pidsOut[CPID_ROLL] - pidsOut[CPID_PITCH] + throtle ); copter->effectors.setMotorSpeed(2, pidsOut[CPID_ROT] - pidsOut[CPID_ROLL] - pidsOut[CPID_PITCH] + throtle ); copter->effectors.setMotorSpeed(3, -pidsOut[CPID_ROT] - pidsOut[CPID_ROLL] + pidsOut[CPID_PITCH] + throtle ); } //------------------------------------------------------------------------------ void autoPilot::doJob(){ switch(workMode){ case PILOT_MODE_FLY: /*********************************************/ fixPlatform(); fixGimbal(); /*###########################################*/ break; case PILOT_MODE_IDLE: /*********************************************/ copter->effectors.stopMotors(); copter->effectors.setGimbalArc(0,0); copter->effectors.setGimbalArc(0,1); /*###########################################*/ break; case PILOT_MODE_GIMBAL_RUN: /*********************************************/ fixGimbal(); copter->effectors.stopMotors(); /*###########################################*/ break; case PILOT_MODE_MOTOR_TEST: /*********************************************/ copter->effectors.setMotorSpeed(0, copter->getPitchTarget() ); copter->effectors.setMotorSpeed(1, copter->getPitchTarget() ); copter->effectors.setMotorSpeed(2, copter->getPitchTarget() ); copter->effectors.setMotorSpeed(3, copter->getPitchTarget() ); /*###########################################*/ break; } }
[ "cb1986ster@gmail.com" ]
cb1986ster@gmail.com
e0887fb45c844f866dc98e0ab04d4d07cc637e78
b2f375c56a26f3df263f5078dd1589a1e2d2c644
/include/mats.hpp
d6f71260420665d7a93c4bc70ef3feeea564dc86
[]
no_license
JYLeeLYJ/GAMES101Final_StableFluid
b76e04cdf5ec399ffaae4815b908778d447c9e4f
646fd23385685ad474d356e488406344f3e6681a
refs/heads/master
2023-08-05T18:38:47.146718
2021-09-24T11:27:40
2021-09-24T11:27:40
410,040,496
0
0
null
null
null
null
UTF-8
C++
false
false
2,686
hpp
#pragma once #include <cassert> #include <concepts> #include <Eigen/Eigen> #include <span> #include <algorithm> using Vec2f = Eigen::Array2f; using Vec3f = Eigen::Array3f; using Vec3u8= Eigen::Array<uint8_t , 3 , 1>; using Vec4u8= Eigen::Array<uint8_t , 4 , 1>; static_assert(sizeof(Vec2f) == sizeof(float) * 2); struct Index2D{ int i , j ; }; template<class V> requires (std::is_standard_layout_v<V>) class Field{ public: explicit Field(std::size_t shape_x , std::size_t shape_y) :m_shape_x(shape_x) , m_shape_y(shape_y) ,m_maxi(shape_x - 1) , m_maxj(shape_y - 1) ,m_data(shape_x * shape_y){} std::size_t XSize() const noexcept {return m_shape_x;} std::size_t YSize() const noexcept {return m_shape_y;} template<std::invocable<V & , Index2D> F> void ForEach(F && f) noexcept(noexcept(std::forward<F>(f)(m_data[0] , {0,0}))) { // coord (i, j) should be signed integer #pragma omp parallel for schedule (dynamic , 8) for(int i = 0; i < m_shape_x ; ++i) { auto index = Index2D{i, 0}; for(int pos = i * m_shape_y; index.j < m_shape_y ; ++index.j , ++pos) { std::forward<F>(f)(m_data[pos] , index); } } } V & operator[] (const Index2D & index) noexcept{ auto pos = index.i * m_shape_y + index.j ; assert(pos < m_data.size()); return m_data[pos]; } std::span<const V> Span() const noexcept { return std::span{m_data.data() , m_data.size()}; } // clamp sample , no extrapolate V Sample(Index2D index) noexcept { index.i = std::clamp<int>(index.i , 0 , m_maxi ); index.j = std::clamp<int>(index.j , 0 , m_maxj ); return this->operator[](index); } //requires V += V{} V NeighborSum(const Index2D & index) noexcept requires requires (V & v){ v += std::declval<V>(); }{ auto pos = index.i * m_shape_y + index.j ; assert(pos < m_data.size()); auto mid = m_data[pos]; auto ans = V{}; ans += index.i > 0 ? m_data[pos - m_shape_y] : mid; ans += index.i < m_maxi ? m_data[pos + m_shape_y]: mid; ans += index.j > 0 ? m_data[pos - 1] : mid; ans += index.j < m_maxj ? m_data[pos + 1] : mid; return ans; } void Fill(const V & val) { std::fill(m_data.begin() , m_data.end() , val); } void SwapWith(Field & f) noexcept{ std::swap(m_shape_x , f.m_shape_x); std::swap(m_shape_y , f.m_shape_y); std::swap(m_data, f.m_data); } private: std::size_t m_shape_x; std::size_t m_shape_y; int m_maxi; int m_maxj; std::vector<V> m_data{}; };
[ "JYLeeLYJ@qq.com" ]
JYLeeLYJ@qq.com
3db2f673c9fa3c4f580a5fcedff007e0aa5f8852
e71551968ccc826f536c13ce5ef68e7f6d3c2b83
/src/SETTINGS/Settings.cpp
d5f9e73f34f48619ce9fa9cc15a6430a4fcd1538
[]
no_license
FCHcap/Cubator
2c77cc3ec4db06c2f26d81acd2ef2cc4e06a75c6
cfac8d3e8b86c9c5a43e7f5dd1ac01b0cb4edca6
refs/heads/master
2020-04-11T07:19:36.865124
2018-06-14T09:31:39
2018-06-14T09:31:39
30,690,083
0
0
null
null
null
null
UTF-8
C++
false
false
8,452
cpp
#include <Settings.h> Settings * Settings::_settings = NULL; Settings::Settings() : QSettings("Fch", "Cubator"){ } Settings::~Settings(){ } Settings * Settings::getInstance(){ if(_settings == NULL){ _settings = new Settings(); } return _settings; } void Settings::kill(){ if(_settings != NULL){ delete _settings; _settings = NULL; } } void Settings::setSettingsMaps(SettingsMaps settings){ QMutexLocker locker(&_mutex); // Writing maps settings beginGroup("MapsFiles"); QList<QString> slMaps = settings.maps().keys(); for(int i=0; i<slMaps.count(); i++){ setValue(slMaps[i],settings.maps()[slMaps[i]]); } endGroup(); beginGroup("Maps"); setValue("centering_gps", settings.centeringGps()); setValue("enable_changes", settings.enableChanges()); setValue("default_map", settings.defaultMap()); setValue("enable_center_view", settings.enableCenterView()); setValue("x_center_view", settings.centerView().x()); setValue("y_center_view", settings.centerView().y()); endGroup(); } SettingsMaps Settings::settingsMaps(){ QMutexLocker locker(&_mutex); SettingsMaps settings; beginGroup("MapsFiles"); QMap<QString, QString> maps; QStringList keys = allKeys(); QString key; foreach(key, keys) maps.insert(key, value(key).toString()); settings.setMaps(maps); endGroup(); beginGroup("Maps"); settings.setCenteringGps(value("centering_gps", 0).toBool()); settings.setEnableChanges(value("enable_changes", 0).toBool()); settings.setDefaultMap(value("default_map", "").toString()); settings.setEnableCenterView(value("enable_center_view", 0).toBool()); QPointF pcv; pcv.setX(value("x_center_view", 0).toDouble()); pcv.setY(value("y_center_view", 0).toDouble()); settings.setCenterView(pcv); endGroup(); return settings; } void Settings::setSettingsGps(SettingsGps settings){ QMutexLocker locker(&_mutex); beginGroup("Gps"); setSettingsDevice(settings); setValue("projection", settings.projection()); endGroup(); } SettingsGps Settings::settingsGps(){ QMutexLocker locker(&_mutex); SettingsGps settings; beginGroup("Gps"); settings = settingsDevice(); settings.setProjection(value("projection").toString()); endGroup(); return settings; } void Settings::setSettingsSonar(SettingsSonar settings){ QMutexLocker locker(&_mutex); beginGroup("Sonar"); setSettingsDevice(settings); endGroup(); } SettingsSonar Settings::settingsSonar(){ QMutexLocker locker(&_mutex); SettingsSonar settings; beginGroup("Sonar"); settings = (SettingsSonar) settingsDevice(); endGroup(); return settings; } void Settings::setSettingsBoats(SettingsBoats settings){ QMutexLocker locker(&_mutex); // Writing settings boats files beginGroup("BoatsFiles"); QList<QString> slBoats = settings.boats().keys(); for(int i=0; i<slBoats.count(); i++){ setValue(slBoats[i],settings.boats()[slBoats[i]]); } endGroup(); } SettingsBoats Settings::settingsBoats(){ QMutexLocker locker(&_mutex); SettingsBoats settings; beginGroup("BoatsFiles"); QMap<QString, QString> boats; QStringList keys = allKeys(); QString key; foreach(key, keys) boats.insert(key, value(key).toString()); settings.setBoats(boats); endGroup(); return settings; } void Settings::setSettingsGeo(SettingsGeo settings){ QMutexLocker locker(&_mutex); // Save the ellipsoids beginGroup("Ellipsoids"); GeoEllipsoids ellipsoids = settings.ellipsoids(); foreach(QString ellName, ellipsoids.keys()){ beginGroup(ellName); GeoEllipsoid ellipsoid = ellipsoids.value(ellName); setValue("a", (double) ellipsoid.a()); setValue("b", (double) ellipsoid.b()); endGroup(); } endGroup(); // Save the datums beginGroup("Datums"); GeoDatums datums = settings.datums(); foreach(QString datName, datums.keys()){ beginGroup(datName); GeoDatum datum = datums.value(datName); setValue("ellipsoid", (QString) datum.ellipsoid()); setValue("tx", (double) datum.tx()); setValue("ty", (double) datum.ty()); setValue("tz", (double) datum.tz()); setValue("rx", (double) datum.rx()); setValue("ry", (double) datum.ry()); setValue("rz", (double) datum.rz()); endGroup(); } endGroup(); // Save the projections beginGroup("Projections"); GeoProjections projections = settings.projections(); foreach(QString projName, projections.keys()){ beginGroup(projName); GeoProjection projection = projections.value(projName); setValue("datum", (QString) projection.datum()); setValue("n", (double) projection.n()); setValue("c", (double) projection.c()); setValue("lg0", (double) projection.lg0()); setValue("xs", (double) projection.xs()); setValue("ys", (double) projection.ys()); endGroup(); } endGroup(); } SettingsGeo Settings::settingsGeo(){ QMutexLocker locker(&_mutex); SettingsGeo settings; // Load the ellipsoids beginGroup("Ellipsoids"); GeoEllipsoids ellipsoids; foreach(QString ellName, GeoConvers::listEllipsoids()){ beginGroup(ellName); GeoEllipsoid ellipsoid; ellipsoid.setA(value("a", 0).toDouble()); ellipsoid.setB(value("b", 0).toDouble()); endGroup(); ellipsoids.insert(ellName, ellipsoid); } endGroup(); settings.setEllipsoids(ellipsoids); // Load the datums beginGroup("Datums"); GeoDatums datums; foreach(QString datName, GeoConvers::listDatums()){ beginGroup(datName); GeoDatum datum; datum.setEllipsoid(value("ellipsoid", "").toString()); datum.setTx(value("tx", 0).toDouble()); datum.setTy(value("ty", 0).toDouble()); datum.setTz(value("tz", 0).toDouble()); datum.setRx(value("rx", 0).toDouble()); datum.setRy(value("ry", 0).toDouble()); datum.setRz(value("rz", 0).toDouble()); endGroup(); datums.insert(datName, datum); } endGroup(); settings.setDatums(datums); // Load the projections beginGroup("Projections"); GeoProjections projections; foreach(QString projName, GeoConvers::listProjections()){ beginGroup(projName); GeoProjection projection; projection.setDatum(value("datum", "").toString()); projection.setN(value("n", 0).toDouble()); projection.setC(value("c", 0).toDouble()); projection.setLg0(value("lg0", 0).toDouble()); projection.setXs(value("xs", 0).toDouble()); projection.setYs(value("ys", 0).toDouble()); endGroup(); projections.insert(projName, projection); } endGroup(); settings.setProjections(projections); return settings; } void Settings::setSettingsStatusBar(SettingsStatusBar settings){ QMutexLocker locker(&_mutex); beginGroup("StatusBar"); setValue("projection", settings.projection()); setValue("gpsFormat", settings.gpsFormat()); endGroup(); } SettingsStatusBar Settings::settingsStatusBar(){ QMutexLocker locker(&_mutex); SettingsStatusBar statusBar; beginGroup("StatusBar"); statusBar.setProjection(value("projection", "").toString()); statusBar.setGpsFormat(value("gpsFormat", "").toString()); endGroup(); return statusBar; } void Settings::setSettingsDevice(const SettingsDevice &settings){ setValue("name", settings.name()); setValue("bauds", settings.rate()); setValue("databits", settings.dataBits()); setValue("parity", settings.parity()); setValue("stopbit", settings.stopBit()); setValue("flowcontrol", settings.flowControl()); setValue("enabled", settings.enabled()); } SettingsDevice Settings::settingsDevice(){ SettingsDevice settings; settings.setName(value("name").toString()); settings.setRate(value("bauds").toString()); settings.setDataBits(value("databits").toString()); settings.setParity(value("parity").toString()); settings.setStopBit(value("stopbit").toString()); settings.setFlowControl(value("flowcontrol").toString()); settings.setEnabled(value("enabled").toBool()); return settings; }
[ "olive.emmanuel@gmail.com" ]
olive.emmanuel@gmail.com
30b5bc17ad540a3661a09bbb2878b86716920749
b93d6ebceab031ac0f5002815fc4812af0a47c78
/TimeSheetDynamicUpload/Test/Test.cpp
faaffa12c61069ddcc806d5726050d0fc84f4e4c
[]
no_license
radtek/PayrollTimeAttendSystem
ac83226d44d5b0869f03687f4efc0aaf0d39814f
b6fa31230a4d57b578dde2ff614ae1ffedf50c77
refs/heads/master
2020-06-13T20:05:11.720503
2018-11-10T10:54:54
2018-11-10T10:54:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
178
cpp
// Test.cpp : main project file. #include "stdafx.h" using namespace System; int main(array<System::String ^> ^args) { Console::WriteLine(L"Hello World"); return 0; }
[ "lerouxerrol@gmail.com" ]
lerouxerrol@gmail.com
b96ec97112b3ab311a54f7793ee06f565a5c0b17
e9ff87a95ff78df99049dfabcf122324391923c8
/submit.ino
e15938091c7d67ac87f155fe12125350d0ae2692
[]
no_license
mhasansagor/Vault-Security-System
a48f3bba9784dbf3e0d1475a677aa0be3046f861
c653b5fd67bfc8aafd56799027124beae2faec6b
refs/heads/main
2022-12-26T03:47:00.130214
2020-10-07T21:58:34
2020-10-07T21:58:34
302,169,330
0
0
null
null
null
null
UTF-8
C++
false
false
2,023
ino
/*project_____Door Controlled System with card punch machine Devolped by GM Rakibul Kabir, Hasan Mahamud Sagor , Majharul Islam Devolped with Arduino_HC-SRO4_SRD-05vdc-sl-c TrigPin EchoPin GND VCC ------- ------- --- --- 13 12 GND 5v */ #include <Ultrasonic.h> Ultrasonic ultrasonic1(13, 12); // An ultrasonic sensor HC-04 Ultrasonic ultrasonic2(11,10); // An ultrasonic sensor PING))) Ultrasonic ultrasonic3(9,8); // An Seeed Studio ultrasonic sensor Ultrasonic ultrasonic4(7,6); // An ultrasonic sensor PING))) Ultrasonic ultrasonic5(5,4); // An Seeed Studio ultrasonic sensor void setup() { Serial.begin(9600); pinMode(14,OUTPUT); } void loop() { delay(10); Serial.print("Sensor 01: "); Serial.print(ultrasonic1.read(CM)); // Prints the distance on the default unit (centimeters) Serial.println("cm"); Serial.print("Sensor 02: "); Serial.print(ultrasonic2.read(CM)); // Prints the distance making the unit explicit Serial.println("cm"); Serial.print("Sensor 03: "); Serial.print(ultrasonic3.read(CM)); // Prints the distance in inches Serial.println("cm"); Serial.print("Sensor 04: "); Serial.print(ultrasonic4.read(CM)); // Prints the distance making the unit explicit Serial.println("cm"); Serial.print("Sensor 05: "); Serial.print(ultrasonic5.read(CM)); // Prints the distance in inches Serial.println("cm"); if (ultrasonic1.read(CM)>=6 ) {digitalWrite(14,LOW); delay(4000); } else if (ultrasonic2.read(CM)>=6 ) {digitalWrite(14,LOW); delay(4000); } else if (ultrasonic3.read(CM)>=6 ) {digitalWrite(14,LOW); delay(4000); } else if (ultrasonic4.read(CM)>=6 ) {digitalWrite(14,LOW); delay(4000); } else if (ultrasonic5.read(CM)>=6 ) {digitalWrite(14,LOW); delay(4000); } else { digitalWrite(14,HIGH); delay(1000); } }
[ "noreply@github.com" ]
mhasansagor.noreply@github.com
d3535454d5a3ca48a8a53ed20f4c13e59fce169a
f33ef12c417f792fe1b411d559c169783d6ba2db
/ppg_and_imu_readings/ppg_and_imu_readings.ino
db79f2c5dc506f3d272a33df27ac727840500f86
[]
no_license
kimtxn/URECA_2020-2021
e34bd85c2790e4e9e1881008d653e25e833ce2bb
835b6514edce3bc88be6a0819011a434d0baa4a1
refs/heads/main
2023-06-10T02:24:51.336056
2021-06-30T16:17:01
2021-06-30T16:17:01
381,680,473
0
0
null
null
null
null
UTF-8
C++
false
false
6,641
ino
/* Optical SP02 Detection (SPK Algorithm) using the MAX30105 Breakout By: Nathan Seidle @ SparkFun Electronics Date: October 19th, 2016 https://github.com/sparkfun/MAX30105_Breakout This demo shows heart rate and SPO2 levels. It is best to attach the sensor to your finger using a rubber band or other tightening device. Humans are generally bad at applying constant pressure to a thing. When you press your finger against the sensor it varies enough to cause the blood in your finger to flow differently which causes the sensor readings to go wonky. This example is based on MAXREFDES117 and RD117_LILYPAD.ino from Maxim. Their example was modified to work with the SparkFun MAX30105 library and to compile under Arduino 1.6.11 Please see license file for more info. Hardware Connections (Breakoutboard to Arduino): -5V = 5V (3.3V is allowed) -GND = GND -SDA = A4 (or SDA) -SCL = A5 (or SCL) -INT = Not connected The MAX30105 Breakout can handle 5V or 3.3V I2C logic. We recommend powering the board with 5V but it will also run at 3.3V. */ #include <Arduino.h> #include <Wire.h> #include "MAX30105.h" #include "spo2_algorithm_new.h" #include <Adafruit_Sensor.h> #include <Adafruit_BNO055.h> #include <utility/imumaths.h> #include <math.h> MAX30105 particleSensor; #define MAX_BRIGHTNESS 255 uint32_t elapsedTime,timeStart; uint32_t irBuffer[100]; //infrared LED sensor data uint32_t redBuffer[100]; //red LED sensor data int32_t bufferLength; //data length int32_t old_n_spo2=0; int32_t n_spo2=0; float ratio,correl; int8_t validSPO2=0; //indicator to show if the SPO2 calculation is valid int32_t heartRate=0; //heart rate value int8_t validHeartRate=0; //indicator to show if the heart rate calculation is valid byte pulseLED = 11; //Must be on PWM pin byte readLED = 13; //Blinks with each data read uint8_t k; Adafruit_BNO055 myIMU = Adafruit_BNO055(55,0x29); long ax,ay,az,mx,my,mz,gx,gy,gz=0; void setup() { Serial.begin(115200); // initialize serial communication at 115200 bits per second: pinMode(pulseLED, OUTPUT); pinMode(readLED, OUTPUT); // Initialize sensor if (!particleSensor.begin(Wire, I2C_SPEED_FAST)) //Use default I2C port, 400kHz speed { Serial.println(F("MAX30105 was not found. Please check wiring/power.")); while (1); } Serial.read(); byte ledBrightness = 40; //Options: 0=Off to 255=50mA byte sampleAverage = 4; //Options: 1, 2, 4, 8, 16, 32 byte ledMode = 2; //Options: 1 = Red only, 2 = Red + IR, 3 = Red + IR + Green byte sampleRate = 100; //Options: 50, 100, 200, 400, 800, 1000, 1600, 3200 int pulseWidth = 411; //Options: 69, 118, 215, 411 int adcRange = 4096; //Options: 2048, 4096, 8192, 16384 myIMU.begin(); particleSensor.setup(ledBrightness, sampleAverage, ledMode, sampleRate, pulseWidth, adcRange); //Configure sensor with these settings timeStart=millis(); } void loop() { bufferLength = 100; //buffer length of 100 stores 4 seconds of samples running at 25sps //read the first 100 samples, and determine the signal range for (byte i = 0 ; i < bufferLength ; i++) { while (particleSensor.available() == false) //do we have new data? particleSensor.check(); //Check the sensor for new data redBuffer[i] = particleSensor.getFIFORed(); irBuffer[i] = particleSensor.getFIFOIR(); particleSensor.nextSample(); //We're finished with this sample so move to next sample Serial.print(F("red ")); Serial.print(redBuffer[i], DEC); Serial.print(F(" ir ")); Serial.print(irBuffer[i], DEC); Serial.println(" HR 0 SPO2 0 0 0 0 0 0 0 0 0 0"); } //calculate heart rate and SpO2 after first 100 samples (first 4 seconds of samples) maxim_heart_rate_and_oxygen_saturation(irBuffer, bufferLength, redBuffer, &n_spo2, &validSPO2, &heartRate, &validHeartRate, &ratio, &correl); //Continuously taking samples from MAX30102. Heart rate and SpO2 are calculated every 2 second while (1) { //dumping the first 25 sets of samples in the memory and shift the last 75 sets of samples to the top for (byte i = 50; i < 100; i++) { redBuffer[i - 50] = redBuffer[i]; irBuffer[i - 50] = irBuffer[i]; } //take 25 sets of samples before calculating the heart rate. for (byte i = 50; i < 100; i++) { while (particleSensor.available() == false) //do we have new data? particleSensor.check(); //Check the sensor for new data //digitalWrite(readLED, !digitalRead(readLED)); //Blink onboard LED with every data read redBuffer[i] = particleSensor.getFIFORed(); irBuffer[i] = particleSensor.getFIFOIR(); particleSensor.nextSample(); //We're finished with this sample so move to next sample imu::Quaternion quat=myIMU.getQuat(); imu::Vector<3> acc = myIMU.getVector(Adafruit_BNO055::VECTOR_ACCELEROMETER); imu::Vector<3> gyr = myIMU.getVector(Adafruit_BNO055::VECTOR_GYROSCOPE); imu::Vector<3> mag = myIMU.getVector(Adafruit_BNO055::VECTOR_MAGNETOMETER); ax=acc.x(); ay=acc.y(); az=acc.z(); mx=mag.x(); my=mag.y(); mz=mag.z(); gx=gyr.x(); gy=gyr.y(); gz=gyr.z(); //send samples and calculation result to terminal program through UART Serial.print(F("red ")); Serial.print(redBuffer[i], DEC); Serial.print(F(" ir ")); Serial.print(irBuffer[i], DEC); Serial.print(F(" HR ")); Serial.print(heartRate, DEC); // Serial.print(F(" HRvalid ")); // Serial.print(validHeartRate, DEC); Serial.print(F(" SPO2 ")); Serial.print(n_spo2, DEC); // Serial.print(F(" SPO2Valid ")); // Serial.print(validSPO2, DEC); Serial.print(" "); Serial.print(acc.x()); Serial.print(" "); Serial.print(acc.y()); Serial.print(" "); Serial.print(acc.z()); Serial.print(" "); Serial.print(mag.x()); Serial.print(" "); Serial.print(mag.y()); Serial.print(" "); Serial.print(mag.z()); Serial.print(" "); Serial.print(gyr.x()); Serial.print(" "); Serial.print(gyr.y()); Serial.print(" "); Serial.println(gyr.z()); } //After gathering 50 new samples recalculate HR and SP02 maxim_heart_rate_and_oxygen_saturation(irBuffer, bufferLength, redBuffer, &n_spo2, &validSPO2, &heartRate, &validHeartRate, &ratio, &correl); } }
[ "noreply@github.com" ]
kimtxn.noreply@github.com
d70201a98456404a86f43445945db5bede8c5348
80f0f7860fa16d3d4209bb21035dc8804700c277
/public/smppparser/submit_sm.hpp
d8bdecd59b5be854a4ffbc6597706e5df6f39e52
[ "MIT" ]
permissive
dotphoenix/smpp-server-client
5db0b5c9260693ddbdf5d8acae717cfc6d4e817d
c5186172ef6f0607d330588f6e19363808c61236
refs/heads/master
2020-03-27T12:49:46.985799
2019-09-11T08:08:12
2019-09-11T08:08:12
146,572,520
3
2
null
null
null
null
UTF-8
C++
false
false
11,363
hpp
/* * SMPP Encoder/Decoder * Copyright (C) 2006 redtaza@users.sourceforge.net * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef __SMPP_SUBMIT_SM_HPP__ #define __SMPP_SUBMIT_SM_HPP__ /// @file submit_sm.hpp /// @brief An SMPP submit_sm PDU. #include "aux_types.hpp" #include "header.hpp" namespace Smpp { /// @class SubmitSm /// @brief Definition of an SMPP submit_sm, derived from a Request. class SubmitSm : public Request { ServiceType service_type_; SmeAddress source_addr_; SmeAddress destination_addr_; EsmClass esm_class_; ProtocolId protocol_id_; PriorityFlag priority_flag_; Time schedule_delivery_time_; Time validity_period_; RegisteredDelivery registered_delivery_; ReplaceIfPresentFlag replace_if_present_flag_; DataCoding data_coding_; SmDefaultMsgId sm_default_msg_id_; ShortMessage short_message_; Smpp::Buffer buff_; public: /** submit_sm minimum length in octets */ const static int MinLength = 33; /** @brief Default constructor. */ SubmitSm(); /** @brief Constructor requiring all mandatory parameters. */ SubmitSm( const SequenceNumber& sequenceNumber, const ServiceType& serviceType, const SmeAddress& sourceAddr, const SmeAddress& destinationAddr, const EsmClass& esmClass, const ProtocolId& protocolId, const PriorityFlag& priorityFlag, const Time& scheduleDeliveryTime, const Time& validityPeriod, const RegisteredDelivery& registeredDelivery, const ReplaceIfPresentFlag& replaceIfPresentFlag, const DataCoding& dataCoding, const SmDefaultMsgId& smDefaultMsgId, const ShortMessage& shortMessage); /// @brief Construct from a buffer. SubmitSm(const Smpp::Uint8* b); /// @brief Destructor - does nothing. ~SubmitSm(); // // Mutating // /// @brief Set the service type. /// @param p The new service type. void service_type(const ServiceType& p) { int diff = p.length() - service_type_.length(); service_type_ = p; Header::update_length(diff); } /// @brief Set the service type. /// @param p The new service type. void service_type(const Smpp::Char* p) { int diff = strlen(p) - service_type_.length(); service_type_ = p; Header::update_length(diff); } /// @brief Set the source address using an SmeAddress object. /// @param p The new source address. void source_addr(const SmeAddress& p) { int diff = p.address().length() - source_addr_.address().length(); source_addr_ = p; Header::update_length(diff); } /// @brief Set the source address using just the address. /// @param p The source address characters. void source_addr(const Address& p) { int diff = p.length() - source_addr_.address().length(); source_addr_ = SmeAddress(Smpp::Ton(Smpp::Ton::Unknown), Smpp::Npi(Smpp::Npi::Unknown), p); Header::update_length(diff); } /// @brief Set the destination address using an SmeAddress object. /// @param p The new destination address. void destination_addr(const SmeAddress& p) { int diff = p.address().length() - destination_addr_.address().length(); destination_addr_ = p; Header::update_length(diff); } /// @brief Set the destination address using just the address. /// @param p The destination address characters. void destination_addr(const Address& p) { int diff = p.length() - destination_addr_.address().length(); destination_addr_ = SmeAddress(Smpp::Ton(Smpp::Ton::Unknown), Smpp::Npi(Smpp::Npi::Unknown), p); Header::update_length(diff); } /// @brief Set the esm class. /// @param p The new esm class. void esm_class(const int& p) { esm_class_ = p; } /// @brief Set the protocol Id. /// @param p The new protocol id. void protocol_id(const int& p) { protocol_id_ = p; } /// @brief Set the priority flag. /// @param p The new priority flag. void priority_flag(const int& p) { priority_flag_ = p; } /// @brief Set the schedule delivery time. /// @param p The new schedule delivery time. void schedule_delivery_time(const Time& p) { int diff = p.length() - schedule_delivery_time_.length(); schedule_delivery_time_ = p; Header::update_length(diff); } /// @brief Set the schedule delivery time. /// @param p The new schedule delivery time. void schedule_delivery_time(const Smpp::Char* p) { int diff = strlen(p) - schedule_delivery_time_.length(); schedule_delivery_time_ = p; Header::update_length(diff); } /// @brief Set the validity period. /// @param p The new validity period. void validity_period(const Time& p) { int diff = p.length() - validity_period_.length(); validity_period_ = p; Header::update_length(diff); } /// @brief Set the validity period. /// @param p The new validity period. void validity_period(const Smpp::Char* p) { int diff = strlen(p) - validity_period_.length(); validity_period_ = p; Header::update_length(diff); } /// @brief Set the registered delivery. /// @param p The new registered delivery. void registered_delivery(const RegisteredDelivery& p) { registered_delivery_ = p; } /// @brief Set the replace if present flag. /// @param p The new replace if present flag. void replace_if_present_flag(const ReplaceIfPresentFlag& p) { replace_if_present_flag_ = p; } /// @brief Set the data coding. /// @param p The new data coding. void data_coding(const DataCoding& p) { data_coding_ = p; } /// @brief Set the SM default message Id. /// @param p The new SM default message Id. void sm_default_msg_id(const SmDefaultMsgId& p) { sm_default_msg_id_ = p; } /// @brief Set the short message and sm length. /// @param p The new short message. /// @param l The new short message length. void short_message(const Smpp::Uint8* p, Smpp::Uint8 l) { int diff = l - short_message_.length(); short_message_ = ShortMessage(p, l); Header::update_length(diff); } // // Accessing // /// @brief Access the service type. /// @return The service type. const ServiceType& service_type() const { return service_type_; } /// @brief Access the source address. /// @return The source address. const SmeAddress& source_addr() const { return source_addr_; } /// @brief Access the destination address. /// @return The destination address. const SmeAddress& destination_addr() const { return destination_addr_; } /// @brief Access the esm class. /// @return The esm class. const EsmClass& esm_class() const { return esm_class_; } /// @brief Access the protocol id. /// @return The protocol id. const ProtocolId& protocol_id() const { return protocol_id_; } /// @brief Access the priority flag. /// @return The priority flag. const PriorityFlag& priority_flag() const { return priority_flag_; } /// @brief Access the schedule delivery time. /// @return The schedule delivery time. const Time& schedule_delivery_time() const { return schedule_delivery_time_; } /// @brief Access the validity period. /// @return The validity period. const Time& validity_period() const { return validity_period_; } /// @brief Access the registered delivery. /// @return The registered delivery. const RegisteredDelivery& registered_delivery() const { return registered_delivery_; } /// @brief Access the replace if present flag. /// @return The replace if present flag. const ReplaceIfPresentFlag& replace_if_present_flag() const { return replace_if_present_flag_; } /// @brief Access the data coding. /// @return The data coding. const DataCoding& data_coding() const { return data_coding_; } /// @brief Access the SM default message id. /// @return The SM default message id. const SmDefaultMsgId& sm_default_msg_id() const { return sm_default_msg_id_; } /// @brief Access the short message length. /// @return The short message length. const Smpp::String::size_type sm_length() const { return short_message_.length(); } /// @brief Access the short message. /// @return The short message. const ShortMessage& short_message() const { return short_message_; } /// @brief Serialize the PDU. /// @note The length is taken from the command_length(). /// @return The PDU as an octet array, suitable for outputting. const Smpp::Uint8* encode(); /// @brief Populates the PDU from an array of octets. /// @param buff containing PDU as octet array. void decode(const Smpp::Uint8* buff); }; } // namespace Smpp #endif
[ "noreply@github.com" ]
dotphoenix.noreply@github.com
ac869fce0eeaf551537bf105cd2e852ac594f0cd
f4dc3450a1cfedf352774cba95dc68b32cbfbf11
/Sources/Emulator/src/mame/includes/jpmsys5.h
e703b9e5af5ebc0bc24fa03d621ed54ad8b29639
[]
no_license
Jaku2k/MAMEHub
ae85696aedf3f1709b98090c843c752d417874a9
faa98abc278cd52dd599584f7de5e2dd39cf6f87
refs/heads/master
2021-01-18T07:48:32.570205
2013-10-10T01:42:06
2013-10-10T01:42:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,336
h
#include "cpu/m68000/m68000.h" #include "machine/6840ptm.h" #include "machine/6850acia.h" #include "sound/2413intf.h" #include "sound/upd7759.h" #include "video/tms34061.h" #include "machine/nvram.h" #include "video/awpvid.h" #include "machine/steppers.h" #include "machine/roc10937.h" class jpmsys5_state : public driver_device { public: jpmsys5_state(const machine_config &mconfig, device_type type, const char *tag) : driver_device(mconfig, type, tag), m_vfd(*this, "vfd"), m_maincpu(*this, "maincpu") { } UINT8 m_palette[16][3]; int m_pal_addr; int m_pal_idx; int m_touch_state; emu_timer *m_touch_timer; int m_touch_data_count; int m_touch_data[3]; int m_touch_shift_cnt; int m_lamp_strobe; int m_mpxclk; int m_muxram[255]; int m_alpha_clock; optional_device<roc10937_t> m_vfd; UINT8 m_a0_acia_dcd; UINT8 m_a0_data_out; UINT8 m_a0_data_in; UINT8 m_a1_acia_dcd; UINT8 m_a1_data_out; UINT8 m_a1_data_in; UINT8 m_a2_acia_dcd; UINT8 m_a2_data_out; UINT8 m_a2_data_in; DECLARE_WRITE16_MEMBER(sys5_tms34061_w); DECLARE_READ16_MEMBER(sys5_tms34061_r); DECLARE_WRITE16_MEMBER(ramdac_w); DECLARE_WRITE16_MEMBER(rombank_w); DECLARE_READ16_MEMBER(coins_r); DECLARE_WRITE16_MEMBER(coins_w); DECLARE_READ16_MEMBER(unk_r); DECLARE_WRITE16_MEMBER(mux_w); DECLARE_READ16_MEMBER(mux_r); DECLARE_INPUT_CHANGED_MEMBER(touchscreen_press); DECLARE_WRITE16_MEMBER(jpm_upd7759_w); DECLARE_READ16_MEMBER(jpm_upd7759_r); DECLARE_WRITE_LINE_MEMBER(ptm_irq); DECLARE_WRITE8_MEMBER(u26_o1_callback); DECLARE_WRITE_LINE_MEMBER(acia_irq); DECLARE_READ_LINE_MEMBER(a0_rx_r); DECLARE_WRITE_LINE_MEMBER(a0_tx_w); DECLARE_READ_LINE_MEMBER(a0_dcd_r); DECLARE_READ_LINE_MEMBER(a1_rx_r); DECLARE_WRITE_LINE_MEMBER(a1_tx_w); DECLARE_READ_LINE_MEMBER(a1_dcd_r); DECLARE_READ_LINE_MEMBER(a2_rx_r); DECLARE_WRITE_LINE_MEMBER(a2_tx_w); DECLARE_READ_LINE_MEMBER(a2_dcd_r); DECLARE_READ16_MEMBER(mux_awp_r); DECLARE_READ16_MEMBER(coins_awp_r); void sys5_draw_lamps(); DECLARE_MACHINE_START(jpmsys5v); DECLARE_MACHINE_RESET(jpmsys5v); DECLARE_VIDEO_START(jpmsys5v); DECLARE_MACHINE_START(jpmsys5); DECLARE_MACHINE_RESET(jpmsys5); UINT32 screen_update_jpmsys5v(screen_device &screen, bitmap_rgb32 &bitmap, const rectangle &cliprect); TIMER_CALLBACK_MEMBER(touch_cb); required_device<cpu_device> m_maincpu; };
[ "jgmath2000@gmail.com" ]
jgmath2000@gmail.com
14ab4313975d4f175563c8e7b2114d85d7b1dde5
abf04a2b2220435f1fb305367d47604e28b86d2b
/controller/admin_gu/rmusr.cpp
0e9dfb8667b280e2ebfff5bf2a4e3bd59f1dc1c3
[]
no_license
ldecast/Proyecto1-Archivos-2S2021
2da71f96e1d074243dcbd692691b6b2e95c89b6e
2cf2f561f5cd19dd354eafedf0fe36a04e89550f
refs/heads/master
2023-08-24T23:50:59.296052
2021-09-16T17:55:17
2021-09-16T17:56:26
407,946,214
0
1
null
null
null
null
UTF-8
C++
false
false
4,056
cpp
#include <iostream> #include <string.h> #include "../../model/filesystem.h" #include "../../model/users_groups.h" #include "../handler.h" #include "func.h" using std::string; int rmusr(string _name) { if (_name == "") return coutError("Error: faltan parámetros obligatorios.", NULL); if (_user_logged.logged_in == false || _user_logged.nombre != "root") return coutError("Error: solamente se puede ejecutar el comando rmgrp con el usuario root.", NULL); if (_name == "root") return coutError("Error: No se puede eliminar el usuario root.", NULL); Users user_to_remove; user_to_remove.nombre = _name; Users user_tmp; FILE *file = fopen((_user_logged.mounted.path).c_str(), "rb"); /* Lectura del superbloque */ Superbloque super_bloque; fseek(file, startByteSuperBloque(_user_logged.mounted), SEEK_SET); fread(&super_bloque, sizeof(Superbloque), 1, file); /* Lectura del inodo de usuarios */ InodosTable users_inode; fseek(file, super_bloque.s_inode_start, SEEK_SET); // Mover el puntero al inicio de la tabla de inodos fseek(file, sizeof(InodosTable), SEEK_CUR); // Mover el puntero al segundo inodo que corresponde al archivo de users.txt fread(&users_inode, sizeof(InodosTable), 1, file); // Leer el inodo fclose(file); file = NULL; /* Obtener todo el archivo concatenado */ string content_file = GetAllFile(users_inode, super_bloque.s_block_start, _user_logged.mounted.path); file = fopen((_user_logged.mounted.path).c_str(), "rb+"); /* LEER LÍNEA POR LÍNEA EL ARCHIVO USERS.TXT */ std::istringstream f(content_file); int uid = 1; string line, tmp = ""; while (getline(f, line)) { int count = 0; for (int i = 0; (i = line.find(',', i)) != std::string::npos; i++) count++; switch (count) { case 4: uid++; user_tmp.UID = std::stoi(line.substr(0, line.find_first_of(','))); line = line.substr(line.find_first_of(',') + 1); user_tmp.tipo = line.substr(0, line.find_first_of(','))[0]; line = line.substr(line.find_first_of(',') + 1); user_tmp.grupo = line.substr(0, line.find_first_of(',')); line = line.substr(line.find_first_of(',') + 1); user_tmp.nombre = line.substr(0, line.find_first_of(',')); line = line.substr(line.find_first_of(',') + 1); user_tmp.contrasena = line.substr(0, line.find_first_of('\n')); if (user_tmp.nombre == user_to_remove.nombre && user_tmp.UID != 0) { tmp = std::to_string(user_tmp.UID) + ",U," + user_tmp.grupo + "," + user_tmp.nombre + "," + user_tmp.contrasena + "\n"; } break; default: break; } } if (tmp == "") return coutError("Error: No existe ningún usuario activo con el nombre: '" + _name + "'.", file); content_file.replace(content_file.find(tmp), tmp.find_first_of(','), "0"); users_inode.i_size = content_file.length(); /* REESCRITURA */ for (int i = 0; i < 15 && content_file.length() > 0; i++) //falta agregar indirectos { ArchivosBlock fblock; if (content_file.length() > 64) { strcpy(fblock.b_content, (content_file.substr(0, 64).c_str())); content_file = content_file.substr(64); } else { strcpy(fblock.b_content, content_file.c_str()); content_file = ""; } if (users_inode.i_block[i] != -1) { fseek(file, super_bloque.s_block_start, SEEK_SET); fseek(file, users_inode.i_block[i] * 64, SEEK_CUR); fwrite(&fblock, 64, 1, file); } } users_inode.i_mtime = getCurrentTime(); fseek(file, super_bloque.s_inode_start, SEEK_SET); fseek(file, sizeof(InodosTable), SEEK_CUR); fwrite(&users_inode, sizeof(InodosTable), 1, file); fclose(file); file = NULL; return 1; }
[ "3006240180101@ingenieria.usac.edu.gt" ]
3006240180101@ingenieria.usac.edu.gt
eff1c6b86b091b7e69f963a9d81f169c9b73c737
9ce6d56b1f200bf2cf04e04867ddc6ae32b72207
/projects/esp_wroober_armver2/src/main.cpp
c6f93847dd9bb282f4bd0f1452479b7ce9749b37
[]
no_license
SiChiTong/ESP32
222745b9f8be9a2a662e872fe5090a6441787a1b
6dce96613701204e3e700ec1e974e4fbfc25c6f3
refs/heads/master
2023-07-01T23:37:12.546539
2021-08-04T08:14:37
2021-08-04T08:14:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,680
cpp
#include <Arduino.h> #include "ESP32mother.h" #include "ESP32Servo.h" #define MIN_PULSE 500 #define MAX_PULSE 2400 #define Step (MAX_PULSE - MIN_PULSE) / 180 Servo s[4]; Timer st[4],dt; const int servopin[4] = {18,19,21,22}; void Servobegin() { for (int i = 0; i < 4; i++) { s[i].setPeriodHertz(50); s[i].attach(servopin[i]); } } void setup() { Serial.begin(115200); Servobegin(); PS3init(); Serial.println("End setup"); } volatile int angle[4]; uint8_t ST[4]; bool hold=false; Chattering HOLD(3,120); void PS3Controller() { PS3Debug=""; uint16_t PS3button=PS3Button(); for(int i=0;i<16;i++) { switch((int)PS3button&1ull<<i)//0b/select/start/l3/r3/l1/r1/l2/r2/up/down/right/left/△/〇/×/□/ { case 0b1000000000000000:St.addprintf(&PS3Debug,"select\n");break; case 0b0100000000000000:St.addprintf(&PS3Debug,"start\n");break; case 0b0010000000000000:St.addprintf(&PS3Debug,"l3\n");break; case 0b0001000000000000:St.addprintf(&PS3Debug,"r3\n");break; case 0b0000100000000000:St.addprintf(&PS3Debug,"l1\n");break; case 0b0000010000000000:St.addprintf(&PS3Debug,"r1\n");break; case 0b0000001000000000:St.addprintf(&PS3Debug,"l2\n");HOLD<=1;break; case 0b0000000100000000:St.addprintf(&PS3Debug,"r2\n");break; case 0b0000000010000000:St.addprintf(&PS3Debug,"up\n");break; case 0b0000000001000000:St.addprintf(&PS3Debug,"down\n");break; case 0b0000000000100000:St.addprintf(&PS3Debug,"right\n");break; case 0b0000000000010000:St.addprintf(&PS3Debug,"left\n");break; case 0b0000000000001000:St.addprintf(&PS3Debug,"triangle\n");break; case 0b0000000000000100:St.addprintf(&PS3Debug,"circle\n");break; case 0b0000000000000010:St.addprintf(&PS3Debug,"cross\n");break; case 0b0000000000000001:St.addprintf(&PS3Debug,"square\n");break; default:break; } } if(HOLD==1) hold=!hold; if(hold) ST[3]=1; else ST[3]=75; HOLD<=0; ST[0] = (PS3stick(lX)>0)?128-PS3stick(lX):255-PS3stick(lX)+128; ST[1] = (PS3stick(lY)>0)?128-PS3stick(lY):255-PS3stick(lY)+128; ST[2] = (PS3stick(rY)>0)?128-PS3stick(rY):255-PS3stick(rY)+128; //ST[3] = (PS3stick(rX)>0)?128-PS3stick(rX):255-PS3stick(rX)+128; } void loop() { PS3Controller(); if (dt.stand_by(0.5)) { ESP_SERIAL.printf("%f/%f/%f/lx=%d/ly=%d/rx=%d/ry=%d,hold %d\n\r",Vx,Vy,Angular,ST[0],ST[1],ST[2],ST[3],hold); ESP_SERIAL.print(PS3Debug); } for(int i=0;i<4;i++) { angle[i]=map(ST[i],0,255,MIN_PULSE,MAX_PULSE); s[i].writeMicroseconds(angle[i]); } PS3Update(); delay(20); }
[ "eieioeiji0501@gmail.com" ]
eieioeiji0501@gmail.com
8bb8bd98a513b91a874dbeafb68d9d7f9123530d
95f5abc9ec8f1b7ac3f29509f4e32b705366e69a
/libraries/RTC/DS1307.h
740fc1da65095c03de66ace59d4be9ec11623688
[]
no_license
LucaSmerea/arduino
21db631d82100fced706d91e0c3dc889e33e3de9
3325685f809cfc3f29808d4946f0ae92c6fa6054
refs/heads/master
2023-03-20T21:28:15.175028
2015-07-20T20:21:35
2015-07-20T20:21:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,524
h
/* DS1307.h - library for DS1307 rtc */ //fix for Arduino 1.00 #if defined(ARDUINO) && ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif // ensure this library description is only included once #ifndef DS1307_h #define DS1307_h // include types & constants of Wiring core API #include <WConstants.h> // include types & constants of Wire ic2 lib #include <../Wire/Wire.h> #define DS1307_SEC 0 #define DS1307_MIN 1 #define DS1307_HR 2 #define DS1307_DOW 3 #define DS1307_DATE 4 #define DS1307_MTH 5 #define DS1307_YR 6 #define DS1307_BASE_YR 2000 #define DS1307_CTRL_ID B1101000 //DS1307 // Define register bit masks #define DS1307_CLOCKHALT B10000000 #define DS1307_LO_BCD B00001111 #define DS1307_HI_BCD B11110000 #define DS1307_HI_SEC B01110000 #define DS1307_HI_MIN B01110000 #define DS1307_HI_HR B00110000 #define DS1307_LO_DOW B00000111 #define DS1307_HI_DATE B00110000 #define DS1307_HI_MTH B00110000 #define DS1307_HI_YR B11110000 // library interface description class DS1307 { // user-accessible "public" interface public: DS1307(); void get(int *, boolean); int get(int, boolean); int min_of_day(boolean); void set(int, int); void start(void); void stop(void); // library-accessible "private" interface private: byte rtc_bcd[7]; // used prior to read/set ds1307 registers; void read(void); void save(void); }; extern DS1307 RTC; #endif
[ "kyle.bowerman@gmail.com" ]
kyle.bowerman@gmail.com
188058e321968b7532959a916345ed67d1b6088a
8bbaa558480442c7c680719008819922130f3225
/Project1/Main.cpp
a0f1271d9bdbcdc55d836160d4e9ebedd2bf21b9
[]
no_license
jeanhadrien/ISEN-Projects-NoisedATPH
ecd894a2435d0828337ce72e9d02b45016f66656
3bd65c5ff980417e9513be5e1f49da37f55bf309
refs/heads/master
2022-02-25T11:58:27.400585
2019-10-14T10:41:39
2019-10-14T10:41:39
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
386
cpp
#include "SceneOpenGL.h" int main(int argc, char **argv) { // Création de la sène (fenêtre) SceneOpenGL scene("Courbe ATPH", 800, 600); // Initialisation de la scène (fenêtre) if (scene.initialiserFenetre() == false) return -1; if (scene.initGL() == false) return -1; // Boucle Principale qui gére l'affichage scene.affichage(); // Fin du programme return 0; }
[ "40248338+jeanhadrien@users.noreply.github.com" ]
40248338+jeanhadrien@users.noreply.github.com
edc47c79317e4747c2529a85e73415a2f1a51dca
c1ce8fa1976b4db87d137ce7541afdafbee01793
/old/include/box_monitor.h
18561a3972c4e475cebeb545f10756aa810bff91
[ "MIT" ]
permissive
johnaparker/Qbox
0b4a2b4c76248122c59e8da844d81ab5854d63fa
7b8daf42dcc140448b2fa9e3ba7122bd69bbcb01
refs/heads/master
2021-05-23T20:39:46.605662
2020-09-09T02:40:47
2020-09-09T02:40:47
52,501,700
2
2
null
null
null
null
UTF-8
C++
false
false
1,281
h
#ifndef GUARD_box_monitor_h #define GUARD_box_monitor_h #include <string> #include <memory> #include "monitor.h" #include "surface_monitor.h" namespace qbox { class Field2D; //*** There is memory redunancy here....is it worth it for using a templated add_monitor function instead??? //box monitor: monitors all points inside 4 surface monitors class box_monitor: public monitor { public: //various constructors box_monitor(std::string name, const volume &vol, const freq_data &freq, bool extendable=false); box_monitor(const volume &vol, const freq_data &freq, bool extendable=false); //same as surface_monitor void set_F(Field2D *newF); void update(); Array compute_flux() const override; ComplexArray ntff(const vec &p) const; ComplexTensor ntff_sphere(double radius, int N) const; void write_flux_sides(); //call write for all surface_monitors void write_ntff_sphere(double radius, int N) const; void operator-=(const box_monitor& other) { for (int i = 0; i != 4; i++) monitors[i] -= other.monitors[i]; } private: surface_monitor monitors[4]; //4 surface monitors volume vol; }; } #endif
[ "japarker@uchicago.edu" ]
japarker@uchicago.edu
66387e52388db5a8a86a3320c6d93d0b4e895f9f
34d88b26a5bbd92d947f04c099da1478420ec4fa
/rpg_2D_string_game_c++/Dungeon/GameEngine.cpp
9df4662bd92ae5ff3b7690edb6837ba35e5fb27d
[]
no_license
Arousde/hda_projects
3e911e7e44a4a5161348d790fd0d04079def4f82
d38a217210a8da8bd3517034dfc22d234ce1c3ff
refs/heads/main
2023-01-12T01:19:13.971143
2020-11-12T22:27:38
2020-11-12T22:27:38
312,403,560
0
0
null
null
null
null
UTF-8
C++
false
false
9,303
cpp
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ #include "GameEngine.h" #include "Trap.h" #include "Lever.h" #include "StationaryController.h" #include "AttackController.h" #include <iostream> #include <sstream> using namespace std; GameEngine::GameEngine(int height, int width, const std::vector<std::string>& data, std::vector<std::string>& v) { m_welt = new DungeonMap(height, width, data, v); weiter = true; int Reihe, Spalte, Strength, Stamina, RReihe, RSpalte; std::string key, controller, LeveroderSwitch, itemm; char zeichen; for (int j = 0; j < v.size(); j++) { std::stringstream tada(v[j]), tadaba(v[j]); Controller* c; tada>> key; if (key == "Character") { tadaba >> key >> zeichen >> Strength >> Stamina >> controller >> Reihe>>Spalte; if (controller == "ConsoleController") c = new ConsoleController; else if (controller == "StationaryController") c = new StationaryController; else c = new AttackController(m_welt); Character* character = new Character(zeichen, Stamina, Strength, c); c->setAttak(character); m_vector.push_back(character); m_welt->place({Reihe, Spalte}, m_vector[m_vector.size() - 1]); } else if (key == "Door") { tadaba >> key >> Reihe >> Spalte >> LeveroderSwitch >> RReihe>>RSpalte; Door* d = new Door; DungeonMap::Position doorPos; doorPos.Reihe = Reihe; doorPos.Spalte = Spalte; m_welt->placeT(doorPos, d); if (LeveroderSwitch == "Switch") { Switch* s = new Switch; s->Set_Ptr_passive(d); DungeonMap::Position switchPos; switchPos.Reihe = RReihe; switchPos.Spalte = RSpalte; m_welt->placeT(switchPos, s); } else if (LeveroderSwitch == "Lever") { Lever* l = new Lever; l->Set_Ptr_passive(d); DungeonMap::Position LeverPos; LeverPos.Reihe = RReihe; LeverPos.Spalte = RSpalte; m_welt->placeT(LeverPos, l); } } else if (key == "Trap") { tadaba >> key >> Reihe>>Spalte; Trap* t = new Trap; DungeonMap::Position trapPos; trapPos.Reihe = Reihe; trapPos.Spalte = Spalte; m_welt->placeT(trapPos, t); } else { tadaba >> itemm >> Reihe>>Spalte; if (itemm == "ArmingSword") { Item* item = new ArmingSword; DungeonMap::Position itemPos; itemPos.Reihe = Reihe; itemPos.Spalte = Spalte; Floor* f; f = dynamic_cast<Floor*> (m_welt->findTile(itemPos)); f->setItem(item); } else if (itemm == "Greatsword") { Item* item = new Greatsword; DungeonMap::Position itemPos; itemPos.Reihe = Reihe; itemPos.Spalte = Spalte; Floor* f; f = dynamic_cast<Floor*> (m_welt->findTile(itemPos)); f->setItem(item); } else if (itemm == "Club") { Item* item = new Club; DungeonMap::Position itemPos; itemPos.Reihe = Reihe; itemPos.Spalte = Spalte; Floor* f; f = dynamic_cast<Floor*> (m_welt->findTile(itemPos)); f->setItem(item); } else if (itemm == "RapierUndDagger") { Item* item = new RapierUndDagger; DungeonMap::Position itemPos; itemPos.Reihe = Reihe; itemPos.Spalte = Spalte; Floor* f; f = dynamic_cast<Floor*> (m_welt->findTile(itemPos)); f->setItem(item); } else if (itemm == "Gambeson") { Item* item = new Gambeson; DungeonMap::Position itemPos; itemPos.Reihe = Reihe; itemPos.Spalte = Spalte; Floor* f; f = dynamic_cast<Floor*> (m_welt->findTile(itemPos)); f->setItem(item); } else if (itemm == "MailArmour") { Item* item = new MailArmour; DungeonMap::Position itemPos; itemPos.Reihe = Reihe; itemPos.Spalte = Spalte; Floor* f; f = dynamic_cast<Floor*> (m_welt->findTile(itemPos)); f->setItem(item); } else if (itemm == "Shield") { Item* item = new Shield; DungeonMap::Position itemPos; itemPos.Reihe = Reihe; itemPos.Spalte = Spalte; Floor* f; f = dynamic_cast<Floor*> (m_welt->findTile(itemPos)); f->setItem(item); } else if (itemm == "FullPlateArmour") { Item* item = new FullPlateArmour; DungeonMap::Position itemPos; itemPos.Reihe = Reihe; itemPos.Spalte = Spalte; Floor* f; f = dynamic_cast<Floor*> (m_welt->findTile(itemPos)); f->setItem(item); std::cout << "item mriguel" << std::endl; } } } Character* opfer = nullptr; Character* angreifer = nullptr; for (Character* p : m_vector) { if (p->GetController()->typ() == "control") opfer = p; if (p->GetController()->typ() == "attak") angreifer = p; } Controller* c_angreifer; angreifer->GetController()->setOpfer(opfer); } void GameEngine::menue(int i) { cout << " Spielerinfos 1 // return 2 // beneden 3 // " << endl; int wahl; cin>>wahl; switch (wahl) { case 1: m_vector[i]->showInfo(); break; case 2: break; case 3: weiter = false; break; } } GameEngine::~GameEngine() { delete m_welt; } void GameEngine::turn() { Tile* neu_t; m_welt->print(); while (weiter) { // if( m_vector[m_vector.size()-1]->GetController()->getOpfer()->GetHitpoints()<=0){ //// m_vector[m_vector.size()-1]->GetController()->getOpfer()->~Character(); // cout<<"game over"<<endl; // ende = false ; // return; // } // // for (int i = 0; i < m_vector.size(); i++) { // repeat: if (m_vector.empty()) { weiter = false; return; } if (m_vector[i]->GetHitpoints() < 0) { m_vector.erase(m_vector.begin() + i - 1); return; } int controller= 0; for (Character* c : m_vector) { if ((c->GetController()->typ() == "control")) { controller++; } } if(controller == 0){ weiter = false; return; } int a = m_vector[i]->GetController()->move(); DungeonMap::Position p = m_welt->findCharacter(m_vector[i]); Tile* t = m_welt->findTile(p); DungeonMap::Position p_neu; int r = p.Reihe; int s = p.Spalte; if (a == 1) { p_neu.Reihe = r + 1; p_neu.Spalte = s - 1; } else if (a == 2) { p_neu.Reihe = r + 1; p_neu.Spalte = s; } else if (a == 3) { p_neu.Reihe = r + 1; p_neu.Spalte = s + 1; } else if (a == 4) { p_neu.Reihe = r; p_neu.Spalte = s - 1; } else if (a == 5) { p_neu.Reihe = r; p_neu.Spalte = s; std::cout << " stehen bleiben" << std::endl; } else if (a == 6) { p_neu.Reihe = r; p_neu.Spalte = s + 1; } else if (a == 7) { p_neu.Reihe = r - 1; p_neu.Spalte = s - 1; } else if (a == 8) { p_neu.Reihe = r - 1; p_neu.Spalte = s; } else if (a == 9) { p_neu.Reihe = r - 1; p_neu.Spalte = s + 1; } else if (a == 0) { menue(i); m_welt->print(); if (weiter == false) return; else goto repeat; } else { std::cout << "1/2/3/4/5/6/7/8/9" << std::endl; m_welt->print(); //// goto repeat; return; } neu_t = m_welt->findTile(p_neu); t->onLeave(neu_t); m_welt->print(); } } }
[ "oussema.arous@stud.h-da.de" ]
oussema.arous@stud.h-da.de
4f1de31eb77f70d3a56686988fbd07654a1233a6
e82960a354947128aba7be51d12f04d57fe45624
/dbmse/include/utils/Algebraic_tree_node.h
8a3477cbfc2c6e6da206caaba5296721c8e4b2c5
[]
no_license
dvaosta/dbmse
f3d43880f56a9a423a86bdcdb01f8810ef234004
b0177ab27b2c8083aa701723befa1386d8535c30
refs/heads/master
2021-01-10T12:24:32.330293
2015-10-21T15:52:12
2015-10-21T15:52:12
44,162,997
0
0
null
null
null
null
UTF-8
C++
false
false
262
h
#pragma once #include "Binary_tree_node.h" template<typename T> class Algebraic_tree_node : public Binary_tree_node<T> { private: Algebraic_tree_node parent; public: Algebraic_tree_node(); void set_parent(Algebraic_tree_node &); ~Algebraic_tree_node(); };
[ "davide.visentin@studenti.polito.it" ]
davide.visentin@studenti.polito.it
e04665f2a1bd89b480767943c89f46fe89ccc3b6
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_repos_function_1643_httpd-2.4.25.cpp
538ee9b8beb8646f7b42677ab9cabe95ed89c267
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,146
cpp
static void set_neg_headers(request_rec *r, negotiation_state *neg, int alg_result) { apr_table_t *hdrs; var_rec *avail_recs = (var_rec *) neg->avail_vars->elts; const char *sample_type = NULL; const char *sample_language = NULL; const char *sample_encoding = NULL; const char *sample_charset = NULL; char *lang; char *qstr; apr_off_t len; apr_array_header_t *arr; int max_vlist_array = (neg->avail_vars->nelts * 21); int first_variant = 1; int vary_by_type = 0; int vary_by_language = 0; int vary_by_charset = 0; int vary_by_encoding = 0; int j; /* In order to avoid O(n^2) memory copies in building Alternates, * we preallocate a apr_table_t with the maximum substrings possible, * fill it with the variant list, and then concatenate the entire array. * Note that if you change the number of substrings pushed, you also * need to change the calculation of max_vlist_array above. */ if (neg->send_alternates && neg->avail_vars->nelts) arr = apr_array_make(r->pool, max_vlist_array, sizeof(char *)); else arr = NULL; /* Put headers into err_headers_out, since send_http_header() * outputs both headers_out and err_headers_out. */ hdrs = r->err_headers_out; for (j = 0; j < neg->avail_vars->nelts; ++j) { var_rec *variant = &avail_recs[j]; if (variant->content_languages && variant->content_languages->nelts) { lang = apr_array_pstrcat(r->pool, variant->content_languages, ','); } else { lang = NULL; } /* Calculate Vary by looking for any difference between variants */ if (first_variant) { sample_type = variant->mime_type; sample_charset = variant->content_charset; sample_language = lang; sample_encoding = variant->content_encoding; } else { if (!vary_by_type && strcmp(sample_type ? sample_type : "", variant->mime_type ? variant->mime_type : "")) { vary_by_type = 1; } if (!vary_by_charset && strcmp(sample_charset ? sample_charset : "", variant->content_charset ? variant->content_charset : "")) { vary_by_charset = 1; } if (!vary_by_language && strcmp(sample_language ? sample_language : "", lang ? lang : "")) { vary_by_language = 1; } if (!vary_by_encoding && strcmp(sample_encoding ? sample_encoding : "", variant->content_encoding ? variant->content_encoding : "")) { vary_by_encoding = 1; } } first_variant = 0; if (!neg->send_alternates) continue; /* Generate the string components for this Alternates entry */ *((const char **) apr_array_push(arr)) = "{\""; *((const char **) apr_array_push(arr)) = ap_escape_path_segment(r->pool, variant->file_name); *((const char **) apr_array_push(arr)) = "\" "; qstr = (char *) apr_palloc(r->pool, 6); apr_snprintf(qstr, 6, "%1.3f", variant->source_quality); /* Strip trailing zeros (saves those valuable network bytes) */ if (qstr[4] == '0') { qstr[4] = '\0'; if (qstr[3] == '0') { qstr[3] = '\0'; if (qstr[2] == '0') { qstr[1] = '\0'; } } } *((const char **) apr_array_push(arr)) = qstr; if (variant->mime_type && *variant->mime_type) { *((const char **) apr_array_push(arr)) = " {type "; *((const char **) apr_array_push(arr)) = variant->mime_type; *((const char **) apr_array_push(arr)) = "}"; } if (variant->content_charset && *variant->content_charset) { *((const char **) apr_array_push(arr)) = " {charset "; *((const char **) apr_array_push(arr)) = variant->content_charset; *((const char **) apr_array_push(arr)) = "}"; } if (lang) { *((const char **) apr_array_push(arr)) = " {language "; *((const char **) apr_array_push(arr)) = lang; *((const char **) apr_array_push(arr)) = "}"; } if (variant->content_encoding && *variant->content_encoding) { /* Strictly speaking, this is non-standard, but so is TCN */ *((const char **) apr_array_push(arr)) = " {encoding "; *((const char **) apr_array_push(arr)) = variant->content_encoding; *((const char **) apr_array_push(arr)) = "}"; } /* Note that the Alternates specification (in rfc2295) does * not require that we include {length x}, so we could omit it * if determining the length is too expensive. We currently * always include it though. * * If the variant is a CGI script, find_content_length would * return the length of the script, not the output it * produces, so we check for the presence of a handler and if * there is one we don't add a length. * * XXX: TODO: This check does not detect a CGI script if we * get the variant from a type map. This needs to be fixed * (without breaking things if the type map specifies a * content-length, which currently leads to the correct result). */ if (!(variant->sub_req && variant->sub_req->handler) && (len = find_content_length(neg, variant)) >= 0) { *((const char **) apr_array_push(arr)) = " {length "; *((const char **) apr_array_push(arr)) = apr_off_t_toa(r->pool, len); *((const char **) apr_array_push(arr)) = "}"; } *((const char **) apr_array_push(arr)) = "}"; *((const char **) apr_array_push(arr)) = ", "; /* trimmed below */ } if (neg->send_alternates && neg->avail_vars->nelts) { arr->nelts--; /* remove last comma */ apr_table_mergen(hdrs, "Alternates", apr_array_pstrcat(r->pool, arr, '\0')); } if (neg->is_transparent || vary_by_type || vary_by_language || vary_by_charset || vary_by_encoding) { apr_table_mergen(hdrs, "Vary", 2 + apr_pstrcat(r->pool, neg->is_transparent ? ", negotiate" : "", vary_by_type ? ", accept" : "", vary_by_language ? ", accept-language" : "", vary_by_charset ? ", accept-charset" : "", vary_by_encoding ? ", accept-encoding" : "", NULL)); } if (neg->is_transparent) { /* Create TCN response header */ apr_table_setn(hdrs, "TCN", alg_result == alg_list ? "list" : "choice"); } }
[ "993273596@qq.com" ]
993273596@qq.com
e50f34c75cb6fb35c13dfe11da9da3715185db57
67745f64c337cf364dbcf25bf8455c27842210de
/11466.cpp
b2904dd24270cf38f84bd4466d74db6ed0cdb4f7
[]
no_license
lidaiqing/UVA
1b1466df4b8f0a5952f629132a421eb0c75462dc
fbf280aa5031c68c8a6c460e42ed2d266bcdddcf
refs/heads/master
2021-01-16T17:47:49.116122
2017-01-14T04:38:59
2017-01-14T04:38:59
78,913,321
0
0
null
null
null
null
UTF-8
C++
false
false
1,329
cpp
#include <bits/stdc++.h> using namespace std; long long _sieve_size; bitset<400001000> bs; vector<long long> primes; void sieve(long long upperbound) { _sieve_size = upperbound + 1; bs.set(); bs[0] = bs[1] = 0; for (long long i = 2; i <= _sieve_size; i++) if (bs[i]) { for (long long j = i * i; j <= _sieve_size; j += i) bs[j] = 0; primes.push_back((int)i); } } bool isPrime(long long N) { if (N <= _sieve_size) return bs[N]; for (int i = 0; i < primes.size(); i++) if (N % primes[i] == 0) return false; return true; } long long primeFactors(long long N) { vector<long long> factors; long long PF_idx = 0, PF = primes[PF_idx]; while (PF * PF <= N) { if (N % PF == 0) factors.push_back(PF); while (N % PF == 0) {N /= PF;} PF = primes[++PF_idx]; } if (N != 1) factors.push_back(N); if (factors.size() >= 2) return factors[factors.size()-1]; else return -1; } int main() { sieve(10000000); // memset(memo,-1,sizeof(memo)); while (1) { long long N; cin>>N; if (N < 0) N *= -1; if (N == 0) break; else { if ( (N < _sieve_size && bs[N]) || (isPrime(N))) cout<<"-1"<<endl; else cout<<primeFactors(N)<<endl; } } }
[ "lidaiqing1993@gmail.com" ]
lidaiqing1993@gmail.com
7e8b48fc0d39f41192f00b92d45cea8735144aba
11ead08ef49582ad2c79833cfafdf9f7ef557d73
/client/resourceaccess.h
09df61416fcdc9a66c82c5681c0dd72e6610f283
[]
no_license
aseigo/toynadi
1d2123a519e4ff54a0603ff71c5cbcae178fec00
cd99c2a9649d1e1639dfa9fc7590f2e5af89335a
refs/heads/master
2016-09-05T15:22:08.139291
2014-12-02T10:18:11
2014-12-02T10:18:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
799
h
#pragma once #include <QLocalSocket> #include <QObject> #include <QTimer> class ResourceAccess : public QObject { Q_OBJECT public: ResourceAccess(const QString &resourceName, QObject *parent = 0); ~ResourceAccess(); QString resourceName() const; bool isReady() const; public Q_SLOTS: void open(); void close(); Q_SIGNALS: void ready(bool isReady); void revisionChanged(unsigned long long revision); private Q_SLOTS: void connected(); void disconnected(); void connectionError(QLocalSocket::LocalSocketError error); void readResourceMessage(); bool processMessageBuffer(); private: QString m_resourceName; QLocalSocket *m_socket; QTimer *m_tryOpenTimer; bool m_startingProcess; QByteArray m_partialMessageBuffer; };
[ "aseigo@kde.org" ]
aseigo@kde.org
82b0954664051399989c268ed774c1d5f45daddf
6b60258775bae97209e6f0369edd91a946f6915d
/driving_parameters_analysis_system.ino
49114af2931e49eca85fd48340c874c9e923d650
[]
no_license
mountenergy/Hackster-Smart-City-Contest
9fb7d76454810866cdfe50c6e3b926d0de5634e8
8319d5f7614434f7111d5699f851e0ce64c0762a
refs/heads/master
2021-05-31T21:44:47.933920
2016-06-10T18:50:50
2016-06-10T18:50:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,395
ino
// Instructables link : // http://www.instructables.com/id/Driving-Parameters-Analysis-System/ // Driving Parameters Analysis System //Header files required //If not available, make sure to find them in Github repositories #include <HttpClient.h> #include <LTask.h> #include <LWiFi.h> #include <LWiFiClient.h> #include <LDateTime.h> #include <LGPRS.h> #include <LGPRSClient.h> #include <LGPRSServer.h> #include <LGPS.h> //Customize the data needed as per your specifications #define WIFI_AP "your wifi name" #define WIFI_PASSWORD "your wifi password" #define DEVICEID "your device id" #define DEVICEKEY "your device key" #define SITE_URL "api.mediatek.com" #define WIFI_AUTH LWIFI_WPA #define per 50 #define per1 3 gpsSentenceInfoStruct info; char buff[256]; double latitude; double longitude; double spd; char buffer_latitude[8]; char buffer_longitude[8]; char buffer_spd[8]; char buffer_sensor[8]; static unsigned char getComma(unsigned char num,const char *str) { unsigned char i,j = 0; int len=strlen(str); for(i = 0;i < len;i ++) { if(str[i] == ',') j++; if(j == num) return i + 1; } return 0; } static double getDoubleNumber(const char *s) { char buf[10]; unsigned char i; double rev; i=getComma(1, s); i = i - 1; strncpy(buf, s, i); buf[i] = 0; rev=atof(buf); return rev; } static double getIntNumber(const char *s) { char buf[10]; unsigned char i; double rev; i=getComma(1, s); i = i - 1; strncpy(buf, s, i); buf[i] = 0; rev=atoi(buf); return rev; } //Esssential part of code //GPS data processing //Determining quantities latitude,longitude and speed void parseDPAS(const char* DPASstr) { int tmp, hour, minute, second, num ; if(DPASstr[0] == '$') { tmp = getComma(1, DPASstr); hour = (DPASstr[tmp + 0] - '0') * 10 + (DPASstr[tmp + 1] - '0'); minute = (DPASstr[tmp + 2] - '0') * 10 + (DPASstr[tmp + 3] - '0'); second = (DPASstr[tmp + 4] - '0') * 10 + (DPASstr[tmp + 5] - '0'); sprintf(buff, "UTC timer %2d-%2d-%2d", hour, minute, second); tmp = getComma(2, DPASstr); latitude = getDoubleNumber(&DPASstr[tmp])/100.0; int latitude_int=floor(latitude); double latitude_decimal=(latitude-latitude_int)*100.0/60.0; latitude=latitude_int+latitude_decimal; tmp = getComma(4, DPASstr); longitude = getDoubleNumber(&DPASstr[tmp])/100.0; int longitude_int=floor(longitude); double longitude_decimal=(longitude-longitude_int)*100.0/60.0; longitude=longitude_int+longitude_decimal; sprintf(buff, "latitude = %10.4f, longitude = %10.4f", latitude, longitude); tmp = getComma(7, DPASstr); spd = getDoubleNumber(&DPASstr[tmp]); sprintf(buff, "speed = %F", spd); } else { Serial.println("Not get data"); } } void recdat() { LGPS.getData(&info); //Serial.println((char*)info.DPAS); parseDPAS((const char*)info.DPAS); } //AP connection void AP_connect() { Serial.print("Connecting to AP..."); while (0 == LWiFi.connect(WIFI_AP, LWiFiLoginInfo(WIFI_AUTH, WIFI_PASSWORD))) { Serial.print("."); delay(500); } Serial.println("Success!"); Serial.print("Connecting site..."); while (!drivepar.connect(SITE_URL, 80)) { Serial.print("."); delay(500); } Serial.println("Success!"); delay(100); } void getconnectInfo() { drivepar.print("GET /mcs/v2/devices/"); drivepar.print(DEVICEID); drivepar.println("/connections.csv HTTP/1.1"); drivepar.print("Host: "); drivepar.println(SITE_URL); drivepar.print("deviceKey: "); drivepar.println(DEVICEKEY); drivepar.println("Connection: close"); drivepar.println(); delay(500); int errorcount = 0; Serial.print("waiting for HTTP response..."); while (!drivepar.available()) { Serial.print("."); errorcount += 1; delay(150); } Serial.println(); int err = http.skipResponseHeaders(); int bodyLen = http.contentLength(); char c; int ipcount = 0; int count = 0; int separater = 0; while (drivepar) { int v = (int)drivepar.read(); if (v != -1) { c = v; //Serial.print(c); connection_info[ipcount]=c; if(c==',') separater=ipcount; ipcount++; } else { Serial.println("no more content, disconnect"); drivepar.stop(); } } int i; for(i=0;i<separater;i++) { ip[i]=connection_info[i]; } int j=0; separater++; for(i=separater;i<21 && j<5 && i < ipcount;i++) { port[j]=connection_info[i]; j++; } portnum = atoi (port); } void connectTCP() { c.stop(); Serial.print("Connecting to TCP..."); while (0 == c.connect(ip, portnum)) { Serial.println("Re-Connecting to TCP"); delay(1000); } c.println(tcpdata); c.println(); Serial.println("Success!"); } void heartBeat() { Serial.println("send TCP heartBeat"); c.println(tcpdata); c.println(); } void uploadstatus() { while (!drivepar.connect(SITE_URL, 80)) { Serial.print("."); delay(500); } delay(100); if(digitalRead(13)==1) upload_led = "ENGINE_MODE_DISPLAY,,1"; else upload_led = "ENGINE_MODE_DISPLAY,,0"; int thislength = upload_led.length(); HttpClient http(drivepar); drivepar.print("POST /mcs/v2/devices/"); drivepar.print(DEVICEID); drivepar.println("/datapoints.csv HTTP/1.1"); drivepar.print("Host: "); drivepar.println(SITE_URL); drivepar.print("deviceKey: "); drivepar.println(DEVICEKEY); drivepar.print("Content-Length: "); drivepar.println(thislength); drivepar.println("Content-Type: text/csv"); drivepar.println("Connection: close"); drivepar.println(); drivepar.println(upload_led); delay(500); int errorcount = 0; while (!drivepar.available()) { Serial.print("."); delay(100); } int err = http.skipResponseHeaders(); int bodyLen = http.contentLength(); while (drivepar) { int v = drivepar.read(); if (v != -1) { Serial.print(char(v)); } else { Serial.println("no more content, disconnect"); drivepar.stop(); } } Serial.println(); } //Data streaming to Mediatek Cloud Sandbox void transdat(){ while (!drivepar.connect(SITE_URL, 80)) { Serial.print("."); delay(500); } delay(100); float sensor = analogRead(A0); Serial.printf("latitude=%.4f\tlongitude=%.4f\tspd=%.4f\tsensor=%.4f\n",latitude,longitude,spd,sensor); if(latitude>-90 && latitude<=90 && longitude>=0 && longitude<360) { sprintf(buffer_latitude, "%.4f", latitude); sprintf(buffer_longitude, "%.4f", longitude); sprintf(buffer_spd, "%.4f", spd); sprintf(buffer_sensor, "%.4f", sensor); } String upload_GPS = "GPS,,"+String(buffer_latitude)+","+String(buffer_longitude)+","+String(buffer_spd)+","+String(buffer_sensor)+","+"0"+"\n"+"LATITUDE,,"+buffer_latitude+"\n"+"LONGITUDE,,"+buffer_longitude+"\n"+"SPEED,,"+buffer_spd+"\n"+"STEERING_ANGLE,,"+buffer_sensor; int GPS_length = upload_GPS.length(); HttpClient http(drivepar); drivepar.print("POST /mcs/v2/devices/"); drivepar.print(DEVICEID); drivepar.println("/datapoints.csv HTTP/1.1"); drivepar.print("Host: "); drivepar.println(SITE_URL); drivepar.print("deviceKey: "); drivepar.println(DEVICEKEY); drivepar.print("Content-Length: "); drivepar.println(GPS_length); drivepar.println("Content-Type: text/csv"); drivepar.println("Connection: close"); drivepar.println(); drivepar.println(upload_GPS); delay(500); int errorcount = 0; while (!drivepar.available()) { Serial.print("."); delay(100); } int err = http.skipResponseHeaders(); int bodyLen = http.contentLength(); while (drivepar) { int v = drivepar.read(); if (v != -1) { Serial.print(char(v)); } else { Serial.println("no more content, disconnect"); drivepar.stop(); } } Serial.println(); } LGPRSClient c; unsigned int rtc; unsigned int lrtc; unsigned int rtc1; unsigned int lrtc1; char port[4]={0}; char connection_info[21]={0}; char ip[15]={0}; int portnum; int val = 0; String tcpdata = String(DEVICEID) + "," + String(DEVICEKEY) + ",0"; String tcpcmd_led_on = "ENGINE_MODE_CONTROL,1"; String tcpcmd_led_off = "ENGINE_MODE_CONTROL,0"; String upload_led; LGPRSClient drivepar; HttpClient http(drivepar); //Setup void setup() { pinMode(13, OUTPUT); LTask.begin(); LWiFi.begin(); Serial.begin(115200); LGPS.powerOn(); AP_connect(); getconnectInfo(); connectTCP(); Serial.println("..."); } //Loop void loop() { String tcpcmd=""; while (c.available()) { int v = c.read(); if (v != -1) { Serial.print((char)v); tcpcmd += (char)v; if (tcpcmd.substring(40).equals(tcpcmd_led_on)){ digitalWrite(13, HIGH); Serial.print("Switch LED ON "); tcpcmd=""; } else if(tcpcmd.substring(40).equals(tcpcmd_led_off)){ digitalWrite(13, LOW); Serial.print("Switch LED OFF"); tcpcmd=""; } } } LDateTime.getRtc(&rtc); if ((rtc - lrtc) >= per) { heartBeat(); lrtc = rtc; } LDateTime.getRtc(&rtc1); if ((rtc1 - lrtc1) >= per1) { uploadstatus(); recdat(); transdat(); lrtc1 = rtc1; } }
[ "noreply@github.com" ]
mountenergy.noreply@github.com
c894ed75a4eaf837ed50177a072fddd82d04590d
367d2670c75d385d122bca60b9f550ca5b3888c1
/gem5/src/cpu/o3/lsq_unit.cc
6b3a6529f25b14a53501db195557d1fd6fdd52ab
[ "BSD-3-Clause", "LicenseRef-scancode-proprietary-license", "LGPL-2.0-or-later", "MIT" ]
permissive
Anish-Saxena/aqua_rowhammer_mitigation
4f060037d50fb17707338a6edcaa0ac33c39d559
3fef5b6aa80c006a4bd6ed4bedd726016142a81c
refs/heads/main
2023-04-13T05:35:20.872581
2023-01-05T21:10:39
2023-01-05T21:10:39
519,395,072
4
3
Unlicense
2023-01-05T21:10:40
2022-07-30T02:03:02
C++
UTF-8
C++
false
false
1,770
cc
/* * Copyright (c) 2004-2006 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "cpu/o3/isa_specific.hh" #include "cpu/o3/lsq_unit_impl.hh" // Force the instantiation of LDSTQ for all the implementations we care about. template class LSQUnit<O3CPUImpl>;
[ "asaxena317@krishna-srv4.ece.gatech.edu" ]
asaxena317@krishna-srv4.ece.gatech.edu
951b128373367ef2ed7b044b8c44116d0b2b2796
7fd38f45d53f527fe933c565902301b5f79f26ea
/Software/Rad Studio/Ultra_Sound_Tracker/Main.h
4b9f0cd879cd0dc4aa7e12d9214fb352991dc3e5
[]
no_license
Aleksandrovas/NavSys
82137479f0530c182c7aaaa14c4bee31beafa92b
31345a3dc613315ed8846c989e219858f8ef2106
refs/heads/master
2020-12-24T18:33:20.651805
2019-07-22T17:58:32
2019-07-22T17:58:32
56,809,354
0
1
null
null
null
null
UTF-8
C++
false
false
1,948
h
//--------------------------------------------------------------------------- #ifndef MainH #define MainH //--------------------------------------------------------------------------- #include <Classes.hpp> #include <Controls.hpp> #include <StdCtrls.hpp> #include <Forms.hpp> #include <ExtCtrls.hpp> #include <Math.hpp> #include <Dialogs.hpp> //--------------------------------------------------------------------------- class TForm1 : public TForm { __published: // IDE-managed Components TButton *Button3; TTimer *ConTimer; TLabel *Label1; TOpenDialog *OpenDialog1; TMemo *Memo5; TButton *Button1; TTimer *Timer1; TButton *Button7; TButton *Button8; TLabel *Label2; TButton *Button2; TButton *Button4; TButton *Button5; TButton *Button6; TLabel *Label3; TLabel *Label4; TLabel *Label5; TMemo *Memo1; TButton *Button9; void __fastcall FormClose(TObject *Sender, TCloseAction &Action); void __fastcall Button3Click(TObject *Sender); void __fastcall ConTimerTimer(TObject *Sender); void __fastcall FormCreate(TObject *Sender); void __fastcall Button1Click(TObject *Sender); void __fastcall Button5Click(TObject *Sender); void __fastcall Button6Click(TObject *Sender); void __fastcall Timer1Timer(TObject *Sender); void __fastcall Button7Click(TObject *Sender); void __fastcall Button8Click(TObject *Sender); void __fastcall Button2Click(TObject *Sender); void __fastcall Button4Click(TObject *Sender); void __fastcall Button9Click(TObject *Sender); private: // User declarations public: // User declarations __fastcall TForm1(TComponent* Owner); unsigned int VID,PID,Ilgiss,Plotiss,Aukstiss; int X,Y,Z; float Xxy,Yxy,k,Kp[4]; bool XY,YZ,XZ; String pos_File; //static unsigned char pos0=0; }; //--------------------------------------------------------------------------- extern PACKAGE TForm1 *Form1; //--------------------------------------------------------------------------- #endif
[ "arturas.aleksandrovas@gmail.com" ]
arturas.aleksandrovas@gmail.com
4f0c087b1080c1f89513b51bc5022d71c40a3a65
a2475d8c8a1b343e6a0eb01b246362d9029218f7
/include/decoder.h
d75ae5a2a31ccc65a8b15ed93eb27ce3626d1a46
[]
no_license
marinajordao/LinkPlanner
68ddf0aee1428876678b7964a56d2470678a8d93
f248307ec9b652a6299e35c871d897e70f06015e
refs/heads/R2017-0
2020-03-21T00:29:12.979266
2018-06-21T09:21:48
2018-06-21T09:21:48
137,896,079
0
0
null
2018-07-11T17:31:50
2018-06-19T13:34:38
Matlab
UTF-8
C++
false
false
858
h
# ifndef PROGRAM_INCLUDE_DECODER_H_ # define PROGRAM_INCLUDE_DECODER_H_ # include "netxpto.h" # include <vector> // Implements a IQ Decoder. class Decoder : public Block { /* Input Parameters */ t_integer m{ 4 }; vector<t_complex> iqAmplitudes{ { 1.0, 1.0 },{ -1.0, 1.0 },{ -1.0, -1.0 },{ 1.0, -1.0 } }; /* State Variables */ bool firstTime{ true }; public: /* Methods */ Decoder() {}; Decoder(vector<Signal *> &InputSig, vector<Signal *> &OutputSig) :Block(InputSig, OutputSig) {}; void initialize(void); bool runBlock(void); void setM(int mValue); int getM() { return m; }; void setIqAmplitudes(vector<t_iqValues> iqAmplitudesValues); vector<t_iqValues> getIqAmplitudes() { return iqAmplitudes; } /*void setIqValues(vector<t_complex> iq) { iqValues = iq; }; vector<t_complex> getIqValues() { return iqValues; }*/ }; # endif
[ "netxpto@gmail.com" ]
netxpto@gmail.com
78d075d2a768df9e7c0e92c56f891e31b7f30933
cae01bde9c62bce6fe5ea31e456841b172d4ea7d
/src/main.cpp
b9268e04b7222b26f4bc3247fc367e5841c380a5
[]
no_license
Dakoth/RShell-CS100
50dda97f85b19c464825f0374f8840adadb34d02
daccffc5d5a80c930baf0ad0e74a80c6e9255536
refs/heads/main
2023-02-27T03:21:19.481975
2021-02-03T20:37:03
2021-02-03T20:37:03
335,747,449
0
0
null
null
null
null
UTF-8
C++
false
false
9,874
cpp
//things to fix for next time: quotes, exit function behaving bizarrely sometimes, and google unit test behaving wierdly #include <stdio.h> #include <unistd.h> #include <sys/wait.h> #include <sys/types.h> #include <stdlib.h> #include "Command.hpp" #include "Command.cpp" #include "Or.hpp" #include "Or.cpp" #include "And.hpp" #include "And.cpp" #include "Semicolon.hpp" #include "Semicolon.cpp" #include <cstring> #include <string.h> using namespace std; Executable* breakupCommand(string str){ vector<string> c; string strProcessed = str; bool firstQuoteSet = false; string theFirstStringInQuotes = ""; unsigned indexOfFirstQuote = 0; unsigned indexOfSecondQuote = 0; //checks if there are any comments in the input and removes them //checks if there are quotes in the input and if there are, the index of the first and second occurance of the character '"' is taken for(unsigned i = 0; i < strProcessed.size(); i++){ if(strProcessed[i] == '"' && !firstQuoteSet){ firstQuoteSet = true; indexOfFirstQuote = i; } else if(strProcessed[i] == '"' && firstQuoteSet){ indexOfSecondQuote = i; } } if(indexOfFirstQuote != 0 && indexOfSecondQuote != 0){ //im just assuming that theres only one set of quotes in a given command and that it is always the last argument for a command theFirstStringInQuotes = strProcessed.substr(indexOfFirstQuote + 1, indexOfSecondQuote - indexOfFirstQuote-1); strProcessed = strProcessed.substr(0, indexOfFirstQuote); } //creates an array of characters that has the same values as strProcessed because strtok only takes in an array of chars terminated by a null char int stringlength = strProcessed.length(); char array[strProcessed.length()+1]; strcpy(array, strProcessed.c_str()); array[stringlength] = 0; //after the array is made, breaks up the string every time there is a spacce and puts it into vector c, for example if str is "echo hello", c.at(0) = "echo" and c.at(1) = "hello" char* ptr = strtok(array, " "); while(ptr != NULL){ //converts the char pointer to a string before adding it to the vector string x(ptr); c.push_back(x); ptr = strtok(NULL, " "); } //if theFirstStringInQuotes is not empty, then there was a quote in this output, so we add it back if(theFirstStringInQuotes != ""){ c.push_back(theFirstStringInQuotes); } return new Command(c); } //helper function for Get_List_Commands to figure out if the current index is in a set of quotes bool inQuotes(string str, int index){ int quotes = 0; for(int i = 0; i < index; i++){ if(str[i] == '"'){ quotes++; } } //if there is an odd number of quotes behind the index, it will be in quotes if there is a quote after index if(quotes % 2 == 0){ return false; } for(int i = index + 1; i < str.size(); ++i){ if(str[i] == '"'){ return true; } } return false; } /* //Gets the string and separates it by connectors, then it uses the breackupCommand function to break up the command into its arguments vector<vector<string> > Get_List_Commands(string str){ vector<vector<string> > c; //vector<string> temp; //begin deonotes the place where to start parsing each individual command unsigned begin = 0; for(unsigned i = 0; i < str.size(); i++){ if(!inQuotes(str, i)){ if(str[i] == '|' && str[i+1] == '|'){ c.push_back(breakupCommand(str.substr(begin, i- begin))); //temp.push_back(str.substr(begin, i-begin)); begin = i+2; } else if(str[i] == '&' && str[i+1] == '&'){ c.push_back(breakupCommand(str.substr(begin, i- begin))); //temp.push_back(str.substr(begin, i-begin)); begin = i+2; } else if(str[i] == ';' && str[i+1] == ' '){ c.push_back(breakupCommand(str.substr(begin, i- begin))); //temp.push_back(str.substr(begin, i-begin)); begin = i+2; } } } c.push_back(breakupCommand(str.substr(begin))); //temp.push_back(str.substr(begin)); return c; } vector<string> List_Connectors(string str){ vector<string> c; for(unsigned i = 0; i < str.size(); i++){ if(!inQuotes(str, i)){ if(str[i] == '|' && str[i+1] == '|'){ c.push_back("||"); } else if(str[i] == '&' && str[i+1] == '&'){ c.push_back("&&"); } else if(str[i] == ';' && str[i+1] == ' '){ c.push_back("; "); } } } return c; } Executable* createtree(vector<vector<char*> > commands, vector<string> connectors){ Executable* root = new Command(commands.at(0)); commands.erase(commands.begin()); if(connectors.size() == 0){ return root; } Executable* temp; while(connectors.size() != 0){ if(connectors.at(0) == "||"){ Executable* right = new Command(commands.at(0)); temp = new Or(root, right); root = temp; commands.erase(commands.begin()); connectors.erase(connectors.begin()); } else if(connectors.at(0) == "&&"){ Executable* right = new Command(commands.at(0)); temp = new And(root, right); root = temp; commands.erase(commands.begin()); connectors.erase(connectors.begin()); } else if(connectors.at(0) == "; "){ Executable* right = new Command(commands.at(0)); temp = new Semicolon(root, right); root = temp; commands.erase(commands.begin()); connectors.erase(connectors.begin()); } } return root; } */ string removeComments(string str){ for(unsigned i = 0; i < str.size(); i++){ if(str.at(i) == '#'){ return str.substr(0, i); } } return str; } bool no_connectors(string str){ for(int i = 0; i < str.size(); i++){ if(!inQuotes(str, i)){ if(str.at(i) == ';' && str.at(i+1)== ' '){ return false; } if(str.at(i) == '|' && str.at(i+1) == '|'){ return false; } if(str.at(i) == '&' && str.at(i+1) == '&'){ return false; } } } return true; } //new function int getIndexOfNextConnector(string str, int index) { //If index never found, return str.size() int indexOfNC; //Give this index, find the next connector for (indexOfNC = index; indexOfNC < str.size(); indexOfNC++) { if (!inQuotes(str, indexOfNC)) { if (str.at(indexOfNC) == ';') { return indexOfNC; } else if (str.at(indexOfNC) == '|' && str.at(indexOfNC + 1) == '|') { return indexOfNC; } else if (str.at(indexOfNC) == '&' && str.at(indexOfNC + 1) == '&') { return indexOfNC; } } } return indexOfNC; } //new funct 2 int getIndexOfMatchingParenthesis(string str, int index) { int numLeftP = 0; int numRightP = 0; int i; for (i = index; i < str.size(); i++) { //returns if same number of left and right parentheses if(!inQuotes(str, i)){ if (str.at(i) == '(') { numLeftP++; } if (str.at(i) == ')') { numRightP++; if (numLeftP == numRightP) { return i; } } } } //if no closing thing return i; } Executable* createtree(string str1){ string str = removeComments(str1); if(no_connectors(str)){ return breakupCommand(str); } string connector = ""; string whatsleft; Executable* root = 0; Executable* temp = 0; int begin = 0; int i = 0; if(str.at(i) == '('){ i = getIndexOfMatchingParenthesis(str, i); root = createtree(str.substr(begin+1, i-1)); while(i != str.size() && (str.at(i) == ')' || str.at(i) == ' ')){ i++; } if(i == str.size()){ return root; } } else{ i = getIndexOfNextConnector(str, i); root = createtree(str.substr(begin, i)); } while(i != str.size()){ if(str.at(i) == '&' && str.at(i+1) == '&'){ connector = "&&"; } else if(str.at(i) == '|' && str.at(i+1) == '|'){ connector = "||"; } else if(str.at(i) == ';' && str.at(i+1) == ' '){ connector = "; "; } while(str.at(i) == '|' || str.at(i) == '&' || str.at(i) == ';' || str.at(i) == ' '){ i++; } begin = i; if(str.at(i) == '('){ i = getIndexOfMatchingParenthesis(str, i); temp = createtree(str.substr(begin+1, i-1)); if(connector == "&&"){ root = new And(root, temp); } else if(connector == "||"){ root = new Or(root, temp); } else if(connector == "; "){ root = new Semicolon(root, temp); } while(i != str.size() && (str.at(i) == ')' || str.at(i) == ' ')){ i++; } if(i == str.size()){ return root; } } else{ i = getIndexOfNextConnector(str,i); temp = createtree(str.substr(begin, i)); if(connector == "&&"){ root = new And(root, temp); } else if(connector == "||"){ root = new Or(root, temp); } else if(connector == "; "){ root = new Semicolon(root, temp); } if(i == str.size()){ return root; } } } return root; } int main(){ while(1){ cout << "$ "; string input; getline(cin, input); //vector<vector<string> > commands = Get_List_Commands(input); //vector<vector<char*> > commandsChar; //vector<string> connectors = List_Connectors(input); /* for(int i = 0; i < connectors.size(); i++){ cout << connectors.at(i) << endl; } */ /* for(int j = 0; j < commands.size(); j++) { vector<char*> tempCharCommand; vector<string> tempCommand = commands.at(j); for(int i = 0; i < tempCommand.size(); ++i){ tempCharCommand.push_back((char*)tempCommand.at(i).c_str()); } commandsChar.push_back(tempCharCommand); tempCharCommand.clear(); } */ /* for(int i = 0; i < commandsChar.size(); ++i){ for(int j = 0; j < commandsChar.at(i).size(); ++j){ cout << "Vector " << i << ": \"" << commandsChar.at(i).at(j) << "\" "; } cout << endl; } */ Executable* x = createtree(input); x->execute(); } return 0; }
[ "noreply@github.com" ]
Dakoth.noreply@github.com
5e2c0ff35df6c955fd0da6c054f10b81382aee14
c88ac73cdd5dcd0d2d8a849f1d3ac30d751c49de
/v1/consumer.cpp
6f60afd6851f8799910d126e6b870efd52d49ef4
[]
no_license
wjj710/E-commerce-platform
acceec7881957c49276344368f35561c0bab0cb3
76d3ba522985007ab28413138d3603b67ceb201e
refs/heads/master
2023-08-30T17:19:15.690472
2021-10-25T09:59:19
2021-10-25T09:59:19
369,121,027
5
0
null
null
null
null
UTF-8
C++
false
false
161
cpp
#include "consumer.h" Consumer::Consumer(QString a, QString p, double b, int t):User(a,p,b,t) { } int Consumer::getUserType()const{ return 0; }
[ "1691826460@qq.com" ]
1691826460@qq.com
c2b139b7bd3f7f52524c7d3fa9b884bef378a764
db3d1ed55140248301aecd0853f6f592a5b89723
/Homework 3/include/global.h
69b47fdf812c85a55819d6e660bc495f6745f1a4
[]
no_license
jimmychenn/EE569-Repo
7d2526919ec920ba066aedad79215666b0315034
374d5710f9045c902b3ce50b2d68d31422302ba1
refs/heads/master
2020-12-02T09:43:30.356858
2016-12-01T22:57:22
2016-12-01T23:05:36
67,261,518
0
0
null
null
null
null
UTF-8
C++
false
false
2,561
h
#ifndef GLOBAL_H #define GLOBAL_H #include <opencv2/opencv.hpp> #include <cstdlib> #include <iostream> #include <cstdio> using namespace cv; char P1A_IN1[] = "P1/res/Texture1.raw"; char P1A_IN2[] = "P1/res/Texture2.raw"; char P1A_IN3[] = "P1/res/Texture3.raw"; char P1A_IN4[] = "P1/res/Texture4.raw"; char P1A_IN5[] = "P1/res/Texture5.raw"; char P1A_IN6[] = "P1/res/Texture6.raw"; char P1A_IN7[] = "P1/res/Texture7.raw"; char P1A_IN8[] = "P1/res/Texture8.raw"; char P1A_IN9[] = "P1/res/Texture9.raw"; char P1A_IN10[] = "P1/res/Texture10.raw"; char P1A_IN11[] = "P1/res/Texture11.raw"; char P1A_IN12[] = "P1/res/Texture12.raw"; char P1B_IN1[] = "P1/res/comb_1.raw"; char P1B_IN2[] = "P1/res/comb_2.raw"; char P2A_IN1[] = "P2/res/jeep.jpg"; char P2A_IN2[] = "P2/res/bus.jpg"; char P2B_IN1[] = "P2/res/rav4_1.jpg"; char P2B_IN2[] = "P2/res/rav4_2.jpg"; char P3A_IN1[] = "P3/res/zebra.raw"; class Global { public: Global(); char P1A_IN1[19]; char P1A_IN2[19]; char P1A_IN3[19]; char P1A_IN4[19]; char P1A_IN5[19]; char P1A_IN6[19]; char P1A_IN7[19]; char P1A_IN8[19]; char P1A_IN9[19]; char P1A_IN10[20]; char P1A_IN11[20]; char P1A_IN12[20]; //char* P1A_IN_ar[12]; char P1A_OUT; char P1B_OUT; char P1C_OUT; char P2A_OUT; char P2B_OUT; char P3A_OUT; }; Global::Global() { //In file names char P1A_IN1[] = "P1/res/Texture1.raw"; char P1A_IN2[] = "P1/res/Texture2.raw"; char P1A_IN3[] = "P1/res/Texture3.raw"; char P1A_IN4[] = "P1/res/Texture4.raw"; char P1A_IN5[] = "P1/res/Texture5.raw"; char P1A_IN6[] = "P1/res/Texture6.raw"; char P1A_IN7[] = "P1/res/Texture7.raw"; char P1A_IN8[] = "P1/res/Texture8.raw"; char P1A_IN9[] = "P1/res/Texture9.raw"; char P1A_IN10[] = "P1/res/Texture10.raw"; char P1A_IN11[] = "P1/res/Texture11.raw"; char P1A_IN12[] = "P1/res/Texture12.raw"; /* char P1A_IN[] = "P1/res/Texture"; for(int i = 1; i <= 12; i++) { char str[20]; strcpy(str, P1A_IN); if(i <= 9) { char num[2]; num[0] = '0' + i; num[1] = '\0'; strcat(str, num); } else { char num[3]; num[0] = '1'; num[1] = '0' + i-10; num[2] = '\0'; strcat(str, num); } char raw_suff[] = ".raw"; strcat(str, raw_suff); strcpy(P1A_IN_ar[i-1], str); std::cout << P1A_IN_ar[i-1] << std::endl; } */ //Out file names char P1A_OUT[] = "P1/out/P1A_out"; char P1B_OUT[] = "P1/out/P1B_out"; char P1C_OUT[] = "P1/out/P1C_out"; char P2A_OUT[] = "P2/out/P2A_out"; char P2B_OUT[] = "P2/out/P2B_out"; char P3A_OUT[] = "P3/out/P3A_out_"; } #endif
[ "jimmylch@usc.edu" ]
jimmylch@usc.edu
e894f27e3344b6674d9e3ccd75e3df975ba3fb94
51a36d41b60827056a6c60132089cb9733c4b577
/src/core/linalg/linalg.h
ee461da4aec214f5c8d8076f2c0af78610f38e5d
[]
no_license
jingchangshi/CppLibrary
f35884ec3f2dfff8586fa351167fbab17256578f
4a6863653968e46c0f98e5b7ffec837018057024
refs/heads/master
2021-09-07T08:52:36.326998
2018-02-20T16:47:12
2018-02-20T16:47:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
421
h
#ifndef LINALG_H #define LINALG_H template <typename T> inline int sgn(T val) { return (val>T(0))-(val<T(0)); } // sgn template<typename T> void linspace(T* lin_arr,T min,T max,int n_pts); template<typename T> void logspace(T* log_arr,T min,T max,int n_pts); template<typename T> void LUdcmp(T** a,int n,int* indx,T* d); template<typename T> void LUbksb(T** a,int n,int* indx,T* b); #endif
[ "jingchangshi@gmail" ]
jingchangshi@gmail
7ce8ed0d5de4ea8494486bd133e3a085d14651dc
5ac13fa1746046451f1989b5b8734f40d6445322
/minimangalore/Nebula2/code/nebula2/src/tools/nnpkbuilder.cc
510e47d51bde03f3686b08ba6bd8bf83dc89f99a
[]
no_license
moltenguy1/minimangalore
9f2edf7901e7392490cc22486a7cf13c1790008d
4d849672a6f25d8e441245d374b6bde4b59cbd48
refs/heads/master
2020-04-23T08:57:16.492734
2009-08-01T09:13:33
2009-08-01T09:13:33
35,933,330
0
0
null
null
null
null
UTF-8
C++
false
false
11,377
cc
//------------------------------------------------------------------------------ // nnpkbuilder.cc // (C) 2004 RadonLabs GmbH //------------------------------------------------------------------------------ #include "tools/nnpkbuilder.h" #include "kernel/nfileserver2.h" //------------------------------------------------------------------------------ /** */ nNpkBuilder::nNpkBuilder() : tocObject(0), npkFile(0), fileOffset(0), dataBlockStart(0), dataBlockOffset(0), dataSize(0), errorCode(NoError) { // empty } //------------------------------------------------------------------------------ /** */ nNpkBuilder::~nNpkBuilder() { n_assert(0 == this->tocObject); n_assert(0 == this->npkFile); } //------------------------------------------------------------------------------ /** Recursively fill the nNpkToc object with the contents of a filesystem directory. */ bool nNpkBuilder::GenerateToc(nDirectory* dir, const nString& dirName) { n_assert(dir); n_assert(!dirName.IsEmpty()); n_assert(this->tocObject); nFileServer2* fileServer = nFileServer2::Instance(); // add the directory itself to the tocObject nString dirNameLowerCase = dirName; dirNameLowerCase.ToLower(); this->tocObject->BeginDirEntry(dirNameLowerCase.Get()); // for each directory entry... if (!dir->IsEmpty()) do { // get current directory entry, and convert to lower case nString fullEntryName = dir->GetEntryName(); fullEntryName.ToLower(); nString entryName = fullEntryName.ExtractFileName(); // add new entry to toc nDirectory::EntryType entryType = dir->GetEntryType(); if (nDirectory::FILE == entryType) { // get length of file nFile* file = fileServer->NewFileObject(); n_assert(file); int fileLength = 0; bool fileOk = false; if (file->Open(fullEntryName, "rb")) { fileLength = file->GetSize(); file->Close(); fileOk = true; } file->Release(); if (fileOk) { this->tocObject->AddFileEntry(entryName.Get(), this->fileOffset, fileLength); this->fileOffset += fileLength; } else { // FIXME: issue a warning because file could not be opened? } } else if (nDirectory::DIRECTORY == entryType) { // start a new subdirectory entry nDirectory* subDir = fileServer->NewDirectoryObject(); n_assert(subDir); bool subDirOk = false; if (subDir->Open(fullEntryName)) { // recurse this->GenerateToc(subDir, fullEntryName); subDir->Close(); subDirOk = true; } n_delete(subDir); subDir = 0; if (!subDirOk) { // FIXME: issue a warning? } } } while (dir->SetToNextEntry()); // finish current directory entry this->tocObject->EndDirEntry(); return true; } //------------------------------------------------------------------------------ /** Recursively write a toc entry (recurses if the toc entry is a directory entry. */ bool nNpkBuilder::WriteTocEntry(nNpkTocEntry* tocEntry, bool noTopLevelName) { n_assert(this->npkFile); n_assert(tocEntry); nNpkTocEntry::Type entryType = tocEntry->GetType(); nString entryName; if (noTopLevelName) { entryName = "<noname>"; } else { entryName = tocEntry->GetName(); } int entryNameLen = entryName.Length(); int entryFileOffset = tocEntry->GetFileOffset(); int entryFileLength = tocEntry->GetFileLength(); if (nNpkTocEntry::DIR == entryType) { // write directory entry, and recurse int blockLen = sizeof(short) + entryNameLen; this->npkFile->PutInt('DIR_'); this->npkFile->PutInt(blockLen); this->npkFile->PutShort(entryNameLen); this->npkFile->Write(entryName.Get(), entryNameLen); nNpkTocEntry* curSubEntry = tocEntry->GetFirstEntry(); while (curSubEntry) { this->WriteTocEntry(curSubEntry, false); curSubEntry = tocEntry->GetNextEntry(curSubEntry); } // write a final directory end marker this->npkFile->PutInt('DEND'); this->npkFile->PutInt(0); } else { // write a file entry int blockLen = 2 * sizeof(int) + sizeof(short) + entryNameLen; this->npkFile->PutInt('FILE'); this->npkFile->PutInt(blockLen); this->npkFile->PutInt(entryFileOffset); this->npkFile->PutInt(entryFileLength); this->npkFile->PutShort(entryNameLen); this->npkFile->Write(entryName.Get(), entryNameLen); } return true; } //------------------------------------------------------------------------------ /** Recursively write the table of contents to the file. */ bool nNpkBuilder::WriteToc(bool noTopLevelName) { n_assert(this->tocObject); n_assert(this->npkFile); // write header this->npkFile->PutInt('NPK0'); // magic number this->npkFile->PutInt(4); // block len this->npkFile->PutInt(0); // the data offset (fixed later) // recursively write toc entries return this->WriteTocEntry(this->tocObject->GetRootEntry(), noTopLevelName); } //------------------------------------------------------------------------------ /** Write the data for an entry into the file, and recurse on directory entries. */ bool nNpkBuilder::WriteEntryData(nNpkTocEntry* tocEntry) { n_assert(this->npkFile); n_assert(tocEntry); nFileServer2* fileServer = nFileServer2::Instance(); nNpkTocEntry::Type entryType = tocEntry->GetType(); const char* entryName = tocEntry->GetName(); int entryFileOffset = tocEntry->GetFileOffset(); int entryFileLength = tocEntry->GetFileLength(); if (nNpkTocEntry::DIR == entryType) { // a dir entry, just recurse nNpkTocEntry* curSubEntry = tocEntry->GetFirstEntry(); while (curSubEntry) { if (!this->WriteEntryData(curSubEntry)) { return false; } curSubEntry = tocEntry->GetNextEntry(curSubEntry); } } else if (nNpkTocEntry::FILE == entryType) { // make sure the file is still consistent with the toc data n_assert(this->npkFile->Tell() == (this->dataBlockOffset + entryFileOffset)); // get the full source path name nString fileName = tocEntry->GetFullName(); // read source file data nFile* srcFile = fileServer->NewFileObject(); n_assert(srcFile); if (srcFile->Open(fileName, "rb")) { // allocate buffer for file and file contents char* buffer = n_new_array(char, entryFileLength); int bytesRead = srcFile->Read(buffer, entryFileLength); n_assert(bytesRead == entryFileLength); srcFile->Close(); // write buffer to target file int bytesWritten = this->npkFile->Write(buffer, entryFileLength); n_assert(bytesWritten == entryFileLength); n_delete(buffer); this->dataSize += entryFileLength; } else { n_error("nNpkBuilder::WriteEntryData(): failed to open src file '%s'!", fileName); } srcFile->Release(); } return true; } //------------------------------------------------------------------------------ /** Write the data block to the file, and fix the data start offset in the file header... */ bool nNpkBuilder::WriteData() { n_assert(this->npkFile); n_assert(this->tocObject); this->dataBlockStart = this->npkFile->Tell(); this->dataBlockOffset = this->dataBlockStart + 8; this->npkFile->PutInt('DATA'); int dataSizeOffset = this->npkFile->Tell(); this->npkFile->PutInt(0); // fix later... this->dataSize = 0; if (!this->WriteEntryData(this->tocObject->GetRootEntry())) { return false; } // fix block lengths this->npkFile->Seek(8, nFile::START); this->npkFile->PutInt(this->dataBlockStart); this->npkFile->Seek(dataSizeOffset, nFile::START); this->npkFile->PutInt(this->dataSize); this->npkFile->Seek(0, nFile::END); return true; } //------------------------------------------------------------------------------ /** Parse a directory and create a new NPK file from it. @param rootPath path to the directory where directory to pack is located @param dirName directory name inside rootPath (only one path component!) @param npkName full pathname to output npk file @param noTopLevelName if true, no root directory name will be stored in the file, so that the npk file's name (without extension) serves as the name of the root directory (use with care, default should be false) @return true, if all ok, false on error, call GetError() for details */ bool nNpkBuilder::Pack(const nString& rootPath, const nString& dirName, const nString& npkName, bool noTopLevelName) { n_assert(!rootPath.IsEmpty()); n_assert(!dirName.IsEmpty()); n_assert(!npkName.IsEmpty()); n_assert(0 == this->npkFile); bool success = false; this->SetError(NoError); nFileServer2* fileServer = nFileServer2::Instance(); // open source directory nString absDirName = rootPath; absDirName.Append("/"); absDirName.Append(dirName); nDirectory* dir = fileServer->NewDirectoryObject(); if (!dir->Open(absDirName)) { this->SetError(CannotOpenSourceDirectory); n_delete(dir); return success; } // open target file this->npkFile = fileServer->NewFileObject(); if (!this->npkFile->Open(npkName.Get(), "w")) { this->SetError(CannotOpenNpkFile); n_delete(dir); this->npkFile->Release(); this->npkFile = 0; return success; } // create table of contents this->tocObject = n_new(nNpkToc); this->tocObject->SetRootPath(rootPath.Get()); this->fileOffset = 0; if (this->GenerateToc(dir, dirName)) { // write header and toc file... if (this->WriteToc(noTopLevelName)) { // write data block if (this->WriteData()) { // all done success = true; } } } // cleanup n_delete(this->tocObject); this->tocObject = 0; this->npkFile->Release(); this->npkFile = 0; dir->Close(); n_delete(dir); return success; }
[ "BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c" ]
BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c
64a40dbf1fbf69a64d8c0035238a522474f9cd35
aff4c6d67714c1df504c7c2e9bf3143cb32826a9
/vthirug_Projects/Project5/tracker/smartSprite.h
6e45f4a61066235034127fdab9beaedf93b7a473
[]
no_license
VishnuPrabhuT/2D-Game-Engine
8dc31a8f8c56f8a37f67580ac0713ce505354c66
2b20170c67851ce8148956a4997829c78e91129e
refs/heads/master
2021-01-22T01:42:43.077187
2017-12-13T01:06:25
2017-12-13T01:06:25
102,225,197
0
0
null
null
null
null
UTF-8
C++
false
false
749
h
#ifndef SMARTSPRITE__H #define SMARTSPRITE__H #include <string> #include "twowaymultisprite.h" class ExplodingSprite; class SmartSprite : public TwoWayMultiSprite { public: SmartSprite(const std::string&, const Vector2f& pos, int w, int h); SmartSprite(const std::string&, const Vector2f& pos, const Vector2f& vel, const Image*); SmartSprite(const SmartSprite&); virtual ~SmartSprite() { } virtual void explode(); virtual void update(Uint32 ticks); void setPlayerPos(const Vector2f& p) { playerPos = p; } private: enum LOOK {LEFT, RIGHT}; Vector2f playerPos; int playerWidth; int playerHeight; LOOK currentMode; float safeDistance; void goLeft(); void goRight(); void goUp(); void goDown(); }; #endif
[ "vishnuprabhut@gmail.com" ]
vishnuprabhut@gmail.com
2d1afa15cfcb82bb764658beeab2e1f304017d08
4503b4ec29e9a30d26c433bac376f2bddaefd9e5
/XtreamToolkit/v16.4.0/Source/Chart/Styles/Point/XTPChartMarker.cpp
352f3309d3a12a583f59dda3f0897608d10076de
[]
no_license
SwunZH/ecocommlibs
0a872e0bbecbb843a0584fb787cf0c5e8a2a270b
4cff09ff1e479f5f519f207262a61ee85f543b3a
refs/heads/master
2021-01-25T12:02:39.067444
2018-02-23T07:04:43
2018-02-23T07:04:43
123,447,012
1
0
null
2018-03-01T14:37:53
2018-03-01T14:37:53
null
UTF-8
C++
false
false
7,190
cpp
// XTPChartMarker.cpp // // This file is a part of the XTREME TOOLKIT PRO MFC class library. // (c)1998-2013 Codejock Software, All Rights Reserved. // // THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE // RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN // CONSENT OF CODEJOCK SOFTWARE. // // THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED // IN THE XTREME TOOLKIT PRO LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO // YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A // SINGLE COMPUTER. // // CONTACT INFORMATION: // support@codejock.com // http://www.codejock.com // ///////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include <math.h> #include <Common/XTPPropExchange.h> #include "../../Types/XTPChartTypes.h" #include "../../XTPChartDefines.h" #include "../../XTPChartElement.h" #include <Chart/XTPChartLegendItem.h> #include "../../XTPChartSeriesStyle.h" #include "../../Drawing/XTPChartDeviceCommand.h" #include "../../Drawing/XTPChartCircleDeviceCommand.h" #include "../../Drawing/XTPChartRectangleDeviceCommand.h" #include "../../Drawing/XTPChartPolygonDeviceCommand.h" #include "../../Appearance/XTPChartFillStyle.h" #include "XTPChartMarker.h" IMPLEMENT_DYNAMIC(CXTPChartMarker, CXTPChartElement) CXTPChartMarker::CXTPChartMarker(CXTPChartSeriesStyle* pOwner) { m_pOwner = pOwner; m_nSize = 8; m_bVisible = TRUE; m_nType = xtpChartMarkerCircle; m_clrColor = CXTPChartColor::Empty; m_clrBorderColor = CXTPChartColor::Empty; m_bBorderVisible = TRUE; m_pFillStyle = new CXTPChartFillStyle(this); m_pFillStyle->SetFillMode(xtpChartFillGradient); m_pFillStyle->SetGradientAngle(xtpChartGradientAngle315); #ifdef _XTP_ACTIVEX EnableAutomation(); EnableTypeLib(); #endif } CXTPChartMarker::~CXTPChartMarker() { SAFE_RELEASE(m_pFillStyle); } CXTPChartDeviceCommand* CXTPChartMarker::CreateDeviceCommand(CXTPChartDeviceContext* pDC, const CXTPChartPointF& point, CXTPChartColor color, CXTPChartColor color2, CXTPChartColor colorBorder) { return CreateDeviceCommand(pDC, point, m_nSize, color, color2, colorBorder); } CXTPChartDeviceCommand* CXTPChartMarker::CreateDeviceCommand(CXTPChartDeviceContext* pDC, const CXTPChartPointF& point, int nWidth, CXTPChartColor color, CXTPChartColor color2, CXTPChartColor colorBorder) { if (!m_bVisible) return NULL; UNREFERENCED_PARAMETER(pDC); CXTPChartDeviceCommand* pCommand = new CXTPChartPolygonAntialiasingDeviceCommand(); if (m_nType == xtpChartMarkerCircle) { pCommand->AddChildCommand(m_pFillStyle->CreateCircleDeviceCommand(point, nWidth / 2, color, color2)); if (m_bBorderVisible) { pCommand->AddChildCommand(new CXTPChartBoundedCircleDeviceCommand(point, nWidth / 2, colorBorder, 1)); } } else if (m_nType == xtpChartMarkerSquare) { CXTPChartPoints arrPoints; arrPoints.Add(CXTPChartPointF(point.X - nWidth / 2, point.Y - nWidth / 2)); arrPoints.Add(CXTPChartPointF(point.X + nWidth / 2, point.Y - nWidth / 2)); arrPoints.Add(CXTPChartPointF(point.X + nWidth / 2, point.Y + nWidth / 2)); arrPoints.Add(CXTPChartPointF(point.X - nWidth / 2, point.Y + nWidth / 2)); pCommand->AddChildCommand(m_pFillStyle->CreateDeviceCommand(arrPoints, color, color2)); if (m_bBorderVisible) { pCommand->AddChildCommand(new CXTPChartBoundedPolygonDeviceCommand(arrPoints, colorBorder, 1)); } } else if (m_nType == xtpChartMarkerDiamond) { CXTPChartPoints arrPoints; float d = nWidth / (float)sqrt(2.0) - 1; arrPoints.Add(CXTPChartPointF(point.X - d, point.Y)); arrPoints.Add(CXTPChartPointF(point.X, point.Y - d)); arrPoints.Add(CXTPChartPointF(point.X + d, point.Y)); arrPoints.Add(CXTPChartPointF(point.X, point.Y + d)); pCommand->AddChildCommand(m_pFillStyle->CreateDeviceCommand(arrPoints, color, color2)); if (m_bBorderVisible) { pCommand->AddChildCommand(new CXTPChartBoundedPolygonDeviceCommand(arrPoints, colorBorder, 1)); } } else if (m_nType == xtpChartMarkerTriangle || m_nType == xtpChartMarkerPentagon || m_nType == xtpChartMarkerHexagon) { int nSide = m_nType == xtpChartMarkerTriangle ? 3 : m_nType == xtpChartMarkerPentagon ? 5 : 6; CXTPChartPoints arrPoints; double d = nWidth / (float)sqrt(2.0) - 1; const double PI = acos(-1.0); for (int i = 0; i < nSide; i++) { arrPoints.Add(CXTPChartPointF(point.X + d * cos(PI / 2 + i * 2 * PI / nSide), point.Y - d * sin(PI / 2 + i * 2 * PI / nSide))); } pCommand->AddChildCommand(m_pFillStyle->CreateDeviceCommand(arrPoints, color, color2)); if (m_bBorderVisible) { pCommand->AddChildCommand(new CXTPChartBoundedPolygonDeviceCommand(arrPoints, colorBorder, 1)); } } else if (m_nType == xtpChartMarkerStar) { int nSide = 5; CXTPChartPoints arrPoints; double d = nWidth / (float)sqrt(2.0) - 1; const double PI = acos(-1.0); double angle = 2 * PI / nSide; for (int i = 0; i < nSide; i++) { arrPoints.Add(CXTPChartPointF(point.X + d * cos(PI / 2 + i * angle), point.Y - d * sin(PI / 2 + i * angle))); arrPoints.Add(CXTPChartPointF(point.X + d / 2 * cos(PI / 2 + i * angle + angle/ 2), point.Y - d / 2 * sin(PI / 2 + i * angle + angle / 2))); } pCommand->AddChildCommand(m_pFillStyle->CreateDeviceCommand(arrPoints, color, color2)); if (m_bBorderVisible) { pCommand->AddChildCommand(new CXTPChartBoundedPolygonDeviceCommand(arrPoints, colorBorder, 1)); } } return pCommand; } void CXTPChartMarker::DoPropExchange(CXTPPropExchange* pPX) { PX_Bool(pPX, _T("BorderVisible"), m_bBorderVisible, TRUE); PX_Color(pPX, _T("BorderColor"), m_clrBorderColor); PX_Color(pPX, _T("Color"), m_clrColor); PX_Enum(pPX, _T("Type"), m_nType, xtpChartMarkerCircle); PX_Int(pPX, _T("Size"), m_nSize, 0); PX_Bool(pPX, _T("Visible"), m_bVisible, TRUE); CXTPPropExchangeSection secFillStyle(pPX->GetSection(_T("FillStyle"))); m_pFillStyle->DoPropExchange(&secFillStyle); } #ifdef _XTP_ACTIVEX BEGIN_DISPATCH_MAP(CXTPChartMarker, CXTPChartElement) DISP_PROPERTY_EX_ID(CXTPChartMarker, "Size", 1, GetSize, SetSize, VT_I4) DISP_PROPERTY_EX_ID(CXTPChartMarker, "Type", 2, GetType, SetType, VT_I4) DISP_PROPERTY_EX_ID(CXTPChartMarker, "FillStyle", 3, OleGetFillStyle, SetNotSupported, VT_DISPATCH) DISP_PROPERTY_EX_ID(CXTPChartMarker, "BorderVisible", 4, GetBorderVisible, SetBorderVisible, VT_BOOL) DISP_PROPERTY_EX_ID(CXTPChartMarker, "Visible", 5, GetVisible, SetVisible, VT_BOOL) END_DISPATCH_MAP() // {456BCC77-27BF-4cb1-9ABF-4558D9835223} static const GUID IID_IChartMarker = { 0x456bcc77, 0x27bf, 0x4cb1, { 0x9a, 0xbf, 0x45, 0x58, 0xd9, 0x83, 0x52, 0x23 } }; BEGIN_INTERFACE_MAP(CXTPChartMarker, CXTPChartElement) INTERFACE_PART(CXTPChartMarker, IID_IChartMarker, Dispatch) END_INTERFACE_MAP() IMPLEMENT_OLETYPELIB_EX(CXTPChartMarker, IID_IChartMarker) LPDISPATCH CXTPChartMarker::OleGetFillStyle() { return XTPGetDispatch(m_pFillStyle); } #endif
[ "kwkang@3e9e098e-e079-49b3-9d2b-ee27db7392fb" ]
kwkang@3e9e098e-e079-49b3-9d2b-ee27db7392fb
c4807ab665c61701be9b9f0877986c8ecd62fe2e
dc8e32a44df4617e8f4eab58e95733846e0cad6e
/Implementation/src/controller/av/StartAVController.cpp
cf288010200f92ecd210938c85c4b9fa4eff866a
[]
no_license
eBabiano/TegraK1_Performance
33a4ee528bd4bc2d926d26eb11252b78b45b39c6
1b615c332fcf02c0cf8ed134a6574c83ac5a4eb3
refs/heads/master
2020-04-03T02:11:43.005908
2018-12-06T08:39:58
2018-12-06T08:39:58
154,949,685
0
0
null
null
null
null
UTF-8
C++
false
false
838
cpp
#include <src/controller/av/StartAVController.hpp> #include <src/model/av/AVTypes.hpp> #include <iostream> namespace src { namespace controller { namespace av { StartAVController::StartAVController(src::model::av::AVManager& avManager) : mAVManager(&avManager) { } void StartAVController::observableUpdated(const view::gui::events::StartAVEvent &event) { if (event.isStarting()) { std::cout << "Start av algorithm" << std::endl; mAVManager->play(); } else { std::cout << "Stop av algorithm" << std::endl; mAVManager->stop(); } } } } }
[ "emib570@gmail.com" ]
emib570@gmail.com
55240289fb8e2a1506b336991292b5df9d42a823
93020fcc267a0ae3494907a5d8f325e55ddb0e30
/e_12_02/src/e_12_02.h
21940cf775d59055c427fecf2222dfa770e6f832
[]
no_license
ddt-narita/meikai_c-_narita
7f27d854f03241ab6706d89dd2e837ae98585538
e923a2489a181cbd61868ba09fee8d72d479a7b1
refs/heads/master
2021-01-20T07:23:31.846324
2019-05-21T11:37:16
2019-05-21T11:37:16
89,997,124
0
0
null
null
null
null
UTF-8
C++
false
false
1,436
h
/* 演習12-02 * クラスbooleanに対してvがFalseならbool型のtrueを、trueならbool型のfalseを * 返却する演算子関数!の追加 * 作成日:5月23日 * 作成者:成田修之 */ //インクルードガード #ifndef ___Class_Boolean #define ___Class_Boolean #include<iostream> //クラスBoolean class Boolean { public: //列挙帯を設定 enum boolean {False,True}; private: //データメンバ boolean v; public: //Falseで初期化するデフォルトコンストラクタ Boolean() : v(False) { } //引数が0ならFalse、それ以外ならTrueで初期化するコンストラクタ Boolean(int val) : v(val == 0? False: True) { } //int型への変換関数 operator int() const { //データメンバを0か1で返却 return v; } //const char*型への変換関数 operator const char*() const { //データメンバを文字列表現にして返却する return v == False ? "False" : "True"; } //論理演算子!の多重定義 bool operator! () { //データメンバvがFalseならbool型のtrueを、Trueならbool型のfalseを返却 return v == False ? true : false; } }; //挿入子の多重定義 inline std::ostream& operator<< (std::ostream& s, Boolean& x) { //Boolean型をconst char*型に静的にキャストする出力ストリームを返却 return s <<static_cast<const char*>(x); } //インクルードの終わり #endif
[ "ddt.jissyusei1@gmail.com" ]
ddt.jissyusei1@gmail.com
463f2407716c1560a97589513896c2e072a37123
4dc9caed5cb3f4639587d3d596a82cd748254045
/lib/Parser/ParseTreeComparer.h
6bcd32610987b73f14c979d76ced3de452bc4af3
[ "MIT" ]
permissive
jkrems/ChakraCore
2e68c27a8a278c36bfa144f77dbd79398279c52b
59b31e5821b7b8df3ed1f5021ed971da82cde9e1
refs/heads/master
2021-01-18T04:42:10.298111
2016-01-22T23:45:30
2016-01-22T23:45:30
50,215,307
2
0
null
2016-01-23T00:06:01
2016-01-23T00:06:00
null
UTF-8
C++
false
false
19,976
h
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #pragma once #ifdef EDIT_AND_CONTINUE namespace Js { class SyntaxEquivalenceBase; template <class Allocator> class SyntaxEquivalence; //----------------------------------------------------------------------------- // TreeComparer for ParseNode TreeMatch. //----------------------------------------------------------------------------- template <class SubClass, class Allocator> class ParseTreeComparer : public TreeComparerBase<SubClass, ParseNode> { private: static const int TOKENLIST_MAXDIFF_SHIFT = 3; // Used to detect lists of significantly different lengths SyntaxEquivalence<Allocator> syntaxEquivalence; // 2 lists used in GetDistance. (Can mark isLeaf because they don't own the nodes.) typedef JsUtil::List<PNode, Allocator, /*isLeaf*/true> NodeList; NodeList leftList, rightList; public: ParseTreeComparer(Allocator* alloc) : syntaxEquivalence(alloc), leftList(alloc), rightList(alloc) {} ParseTreeComparer(const ParseTreeComparer& other) : syntaxEquivalence(other.GetAllocator()), leftList(other.GetAllocator()), rightList(other.GetAllocator()) {} Allocator* GetAllocator() const { return leftList.GetAllocator(); } int LabelCount() const { return ::OpCode::knopLim; } int GetLabel(PNode x) const { return x->nop; } PNode GetParent(PNode x) const { return x->parent; } template <class Func> void MapChildren(PNode x, const Func& func) const { Js::MapChildren(x, func); } // Map (sub)tree nodes to compute distance. Child class can re-implement to control which nodes participate in // distance computing. template <class Func> void MapTreeToComputeDistance(PNode x, const Func& func) const { pThis()->MapTree(x, func); } double GetDistance(PNode left, PNode right) { Assert(pThis()->GetLabel(left) == pThis()->GetLabel(right)); // Only called for nodes of same label return ComputeValueDistance(left, right); } bool ValuesEqual(PNode oldNode, PNode newNode) { // This determines if we emit Update edit for matched nodes. If ValuesEqual, don't need update edit. return !(syntaxEquivalence.IsToken(oldNode) || syntaxEquivalence.HasToken(oldNode)) || syntaxEquivalence.AreEquivalent(oldNode, newNode); } private: double ComputeValueDistance(PNode left, PNode right) { // If 2 nodes are equivalent trees, consider them exact match. if (syntaxEquivalence.AreEquivalent(left, right)) { return ExactMatchDistance; } double distance = ComputeDistance(left, right); // We don't want to return an exact match, because there // must be something different, since we got here return (distance == ExactMatchDistance) ? EpsilonDistance : distance; } // // Computer distance the same as Roslyn: // * For token nodes, use their string LCS distance. // * Otherwise, flatten the tree to get all tokens, use token list LCS distance. // // However, our parser are significantly different to Roslyn. Roslyn uses "full fidelity" parser, // keeping every token scanned from source. e.g., "var a = 1" -> "var","a","=","1". Our parser keeps // much less tokens. Thus our LCS distance will be quite different, which may affect diff accuracy. // double ComputeDistance(PNode left, PNode right) { // For token nodes, use their string LCS distance if (syntaxEquivalence.IsToken(left)) { return ComputeTokenDistance(left, right); } // Otherwise, flatten the tree to get all tokens, use token list LCS distance Flatten(left, leftList); Flatten(right, rightList); // If token list lengths are significantly different, consider they are quite different. { int leftLen = leftList.Count(); int rightLen = rightList.Count(); int minLen = min(leftLen, rightLen); int maxLen = max(leftLen, rightLen); if (minLen < (maxLen >> TOKENLIST_MAXDIFF_SHIFT)) { // Assuming minLen are all matched, distance > 0.875 (7/8). These two nodes shouldn't be a match. return 1.0 - (double)minLen / (double)maxLen; } } return ComputeLongestCommonSubsequenceDistance(GetAllocator(), leftList.Count(), rightList.Count(), [this](int indexA, int indexB) { return AreNodesTokenEquivalent(leftList.Item(indexA), rightList.Item(indexB)); }); } // Flatten IsToken/HasToken nodes in the (sub)tree into given list to compute distance. void Flatten(PNode root, NodeList& list) { list.Clear(); pThis()->MapTreeToComputeDistance(root, [&](PNode child) { if (syntaxEquivalence.IsToken(child) || syntaxEquivalence.HasToken(child)) { list.Add(child); } }); } // Check if IsToken/HasToken nodes are equivalent bool AreNodesTokenEquivalent(PNode left, PNode right) { if (left->nop == right->nop) { return syntaxEquivalence.IsToken(left) ? syntaxEquivalence.AreTokensEquivalent(left, right) : syntaxEquivalence.HaveEquivalentTokens(left, right); } return false; } double ComputeTokenDistance(PNode left, PNode right) const { Assert(syntaxEquivalence.IsToken(left)); switch (left->nop) { case knopName: case knopStr: return ComputeDistance(left->sxPid.pid, right->sxPid.pid); case knopInt: return left->sxInt.lw == right->sxInt.lw ? ExactMatchDistance : 1.0; case knopFlt: return left->sxFlt.dbl == right->sxFlt.dbl ? ExactMatchDistance : 1.0; case knopRegExp: //TODO: sxPid.regexPattern break; } // Other token nodes with fixed strings, e.g. "true", "null", always match exactly return ExactMatchDistance; } // Compute distance of 2 PIDs as their string LCS distance double ComputeDistance(IdentPtr left, IdentPtr right) const { Allocator* alloc = leftList.GetAllocator(); return ComputeLongestCommonSubsequenceDistance(alloc, left->Cch(), right->Cch(), [=](int indexA, int indexB) { return left->Psz()[indexA] == right->Psz()[indexB]; }); } }; //----------------------------------------------------------------------------- // Function TreeComparer for TreeMatch at function level. View the parse tree as a hierarchy of functions. // Ignore statement details. //----------------------------------------------------------------------------- template <class Allocator> class FunctionTreeComparer : public ParseTreeComparer<FunctionTreeComparer<Allocator>, Allocator> { public: FunctionTreeComparer(Allocator* alloc) : ParseTreeComparer(alloc) {} FunctionTreeComparer(const FunctionTreeComparer& other) : ParseTreeComparer(other) {} // We only have 1 kind of node in this view -- FuncDecl int LabelCount() const { return 1; } int GetLabel(PNode x) const { return 0; } PNode GetParent(PNode x) const { while (true) { x = __super::GetParent(x); if (!x || x->nop == knopFncDecl || x->nop == knopProg) { break; } } return x; } template <class Func> void MapChildren(PNode x, const Func& func) const { __super::MapChildren(x, [&](PNode child) { if (child->nop == knopFncDecl) { func(child); } else { pThis()->MapChildren(child, func); } }); } // To compute function node distance, only use their direct child nodes. Do not include descendant nodes // under nested child functions. template <class Func> void MapTreeToComputeDistance(PNode x, const Func& func) const { func(x); __super::MapChildren(x, [&](PNode child) { if (child->nop == knopFncDecl) { func(child); // For child func, output the node itself but don't map its descendants } else { pThis()->MapTreeToComputeDistance(child, func); // recursive into other nodes } }); } }; //----------------------------------------------------------------------------- // Full TreeComparer for TreeMatch full parse tree. Used for test only. //----------------------------------------------------------------------------- template <class Allocator> class FullTreeComparer : public ParseTreeComparer<FullTreeComparer<Allocator>, Allocator> { public: FullTreeComparer(Allocator* alloc) : ParseTreeComparer(alloc) {} FullTreeComparer(const FullTreeComparer& other) : ParseTreeComparer(other) {} }; //----------------------------------------------------------------------------- // Visit every node of a parse (sub)tree in preorder. Delegates to Preorder/Postorder of PreorderContext. //----------------------------------------------------------------------------- template <class PreorderContext> void ParseTreePreorder(ParseNode* root, PreorderContext* context) { class ParseTreePreorderVisitorPolicy : public VisitorPolicyBase<PreorderContext*> { protected: bool Preorder(ParseNode* pnode, Context context) { context->Preorder(pnode); return true; } void Postorder(ParseNode* pnode, Context context) { context->Postorder(pnode); } }; ParseNodeVisitor<ParseTreePreorderVisitorPolicy> visitor; visitor.Visit(root, context); } template <class Func> void ParseTreePreorder(ParseNode* root, const Func& func) { class PreorderContext { private: const Func& func; public: PreorderContext(const Func& func) : func(func) {} void Preorder(ParseNode* pnode) { func(pnode); } void Postorder(ParseNode* pnode) {} }; PreorderContext context(func); ParseTreePreorder(root, &context); } // TEMP: Consider setting parent at parse time. Temporarily traverse the whole tree to fix parent links. template <class Allocator> void FixParentLinks(ParseNodePtr root, Allocator* alloc) { class FixAstParentVisitorContext { private: JsUtil::Stack<ParseNodePtr, Allocator, /*isLeaf*/true> stack; public: FixAstParentVisitorContext(Allocator* alloc) : stack(alloc) {}; void Preorder(ParseNode* pnode) { pnode->parent = !stack.Empty() ? stack.Top() : nullptr; stack.Push(pnode); } void Postorder(ParseNode* pnode) { Assert(pnode == stack.Peek()); stack.Pop(); } }; FixAstParentVisitorContext fixAstParentVisitorContext(alloc); ParseTreePreorder(root, &fixAstParentVisitorContext); } //----------------------------------------------------------------------------- // Map child nodes of a parse node. //----------------------------------------------------------------------------- template <class Func> void MapChildren(ParseNode* pnode, const Func& func) { struct ChildrenWalkerPolicy : public WalkerPolicyBase<bool, const Func&> { ResultType WalkChildChecked(ParseNode *pnode, Context context) { // Some of Walker code calls with null ParseNode. e.g., a for loop with null init child. if (pnode) { context(pnode); } return true; } ResultType WalkFirstChild(ParseNode *pnode, Context context) { return WalkChildChecked(pnode, context); } ResultType WalkSecondChild(ParseNode *pnode, Context context) { return WalkChildChecked(pnode, context); } ResultType WalkNthChild(ParseNode *pparentnode, ParseNode *pnode, Context context) { return WalkChildChecked(pnode, context); } }; ParseNodeWalker<ChildrenWalkerPolicy> walker; walker.Walk(pnode, func); } //----------------------------------------------------------------------------- // Helpers for testing ParseNode equivalence //----------------------------------------------------------------------------- class SyntaxEquivalenceBase { public: // // Check if a node is a token node (leaf only, can never have child nodes). e.g., "123" (number literal). // static bool IsToken(ParseNode* pnode) { // TODO: We may use a new flag fnopToken return (ParseNode::Grfnop(pnode->nop) & fnopLeaf) && pnode->nop != knopFncDecl && pnode->nop != knopClassDecl; } // // Check if a node has token (node type ownning an implicit token, e.g. "var x" (var declaration)). // static bool HasToken(ParseNode* pnode) { // TODO: We may use a new flag fnopHasToken return pnode->nop == knopVarDecl || pnode->nop == knopFncDecl; // TODO: other nodes with data } // // Check if 2 IsToken nodes (of the same type) are equivalent. // static bool AreTokensEquivalent(ParseNodePtr left, ParseNodePtr right) { Assert(IsToken(left) && left->nop == right->nop); switch (left->nop) { case knopName: case knopStr: return AreEquivalent(left->sxPid.pid, right->sxPid.pid); case knopInt: return left->sxInt.lw == right->sxInt.lw; case knopFlt: return left->sxFlt.dbl == right->sxFlt.dbl; case knopRegExp: //TODO: sxPid.regexPattern break; } // Other tokens have fixed strings and are always equivalent, e.g. "true", "null" return true; } // // Check if 2 HasToken nodes (of the same type) have equivalent tokens. // static bool HaveEquivalentTokens(ParseNodePtr left, ParseNodePtr right) { Assert(HasToken(left) && left->nop == right->nop); switch (left->nop) { case knopVarDecl: return AreEquivalent(left->sxVar.pid, right->sxVar.pid); case knopFncDecl: return AreEquivalent(left->sxFnc.pid, right->sxFnc.pid); //TODO: other nodes with data } Assert(false); return false; } private: // Test if 2 PIDs refer to the same text. static bool AreEquivalent(IdentPtr pid1, IdentPtr pid2) { if (pid1 && pid2) { // Optimize: If we can have both trees (scanner/parser) share Ident dictionary, this can become pid1 == pid2. return pid1->Hash() == pid2->Hash() && pid1->Cch() == pid2->Cch() && wcsncmp(pid1->Psz(), pid2->Psz(), pid1->Cch()) == 0; } // PIDs may be null, e.g. anonymous function declarations return pid1 == pid2; } }; template <class Allocator> class SyntaxEquivalence : public SyntaxEquivalenceBase { private: // 2 stacks used during equivalence test. (Can mark isLeaf because they don't own the nodes.) JsUtil::Stack<ParseNode*, Allocator, /*isLeaf*/true> leftStack, rightStack; public: SyntaxEquivalence(Allocator* alloc) : leftStack(alloc), rightStack(alloc) {} // // Tests if 2 parse (sub)trees are equivalent. // bool AreEquivalent(ParseNode* left, ParseNode* right) { bool result; if (TryTestEquivalenceFast(left, right, &result)) { return result; } Reset(); // Clear possible remaining nodes in leftStack/rightStack PushChildren(left, right); while (!leftStack.Empty() && leftStack.Count() == rightStack.Count()) { left = leftStack.Pop(); right = rightStack.Pop(); if (TryTestEquivalenceFast(left, right, &result)) { if (!result) { return false; } } else { PushChildren(left, right); // Sub-pair is ok, but need to compare children } } return leftStack.Empty() && rightStack.Empty(); } private: void Reset() { leftStack.Clear(); rightStack.Clear(); } void PushChildren(ParseNode* left, ParseNode* right) { Assert(leftStack.Count() == rightStack.Count()); MapChildren(left, [&](ParseNode* child) { leftStack.Push(child); }); MapChildren(right, [&](ParseNode* child) { rightStack.Push(child); }); } // // Try to test 2 nodes for equivalence. Return true if we can determine the pair equivalence. // Otherwise return false, which means the pair test is ok but we need further child nodes comparison. // static bool TryTestEquivalenceFast(ParseNode* left, ParseNode* right, _Out_ bool* result) { Assert(left && right); if (left == right) { *result = true; // Same node return true; } if (left->nop != right->nop) { *result = false; // Different node type return true; } if (IsToken(left)) { *result = AreTokensEquivalent(left, right); // Token comparison suffices return true; } if (HasToken(left) && !HaveEquivalentTokens(left, right)) { *result = false; // Different implicit tokens, e.g. "var x" vs "var y" return true; } return false; // This pair is ok, but not sure about children } }; } // namespace Js #endif
[ "chakrabot@users.noreply.github.com" ]
chakrabot@users.noreply.github.com
34c9d4f9e119e6b65658ea1cae2e2a11beff9209
e958f28dac770f7d7f50c6fabb8812567f29939e
/quadratic-errors.cpp
95c96e02745421746b03216f7ea525ed896371a3
[]
no_license
Karinliu/quadraticformula
0181d2172482c386987c9bd4fd30a2891e3cdc9f
0e7fd4a50e3b8e0a81b4b7e6a24a22a26a5e2d28
refs/heads/main
2023-08-18T08:50:58.807303
2021-10-12T10:26:40
2021-10-12T10:26:40
416,288,867
0
0
null
null
null
null
UTF-8
C++
false
false
2,273
cpp
#include <iostream> #include <cmath> #include <stdexcept> #include <sstream> double discriminantFormula(double a, double b, double c) { double discriminant; discriminant = b * b - 4 * a * c; return discriminant; } int quadraticFormula(double a, double b, double c){ double solution1, solution2; double d = discriminantFormula(a, b, c); if (d > 0){ solution1 = (-b + sqrt(d)) / (2 * a); solution2 = (-b - sqrt(d)) / (2 * a); std::cout << "There are 2 solutions." << std::endl; std::cout << "The solutions are: " << solution1 << " and " << solution2 << std::endl; } else if (d == 0){ solution1 = -b / (2 * a); std::cout << "There is 1 solution." << std::endl; std::cout << "The solution is: " << solution1 << std::endl; } else{ std::cout << "There is no solution." << std::endl; } return 0; } bool isNumber(const std::string &STR){ for (int i = 0; i < STR.size(); i++){ char emptyString = ' '; char dotString = '.'; if (std::isdigit(STR[i]) == false && (STR[i] != emptyString) && (STR[i] != dotString)){ return false; } } return true; } bool countInput(const std::string &STR){ std::stringstream counterInputs(STR); std::string individualInput; int count = 0; while (counterInputs >> individualInput){ count++; if (count == 3){ return true; } } return false; } void validateInput(){ std::string line; getline(std::cin, line); std::stringstream stringInput(line); stringInput << line; double a, b, c; stringInput >> a >> b >> c; if (countInput(line) == false){ throw std::runtime_error("Malformed user input"); } if (isNumber(line) == false){ throw std::runtime_error("Malformed user input"); } if (a == 0){ throw std::runtime_error("a must not be zero"); } quadraticFormula(a, b, c); } int main(){ try{ std::cout << "Please enter the values of a, b, and c: " << std::endl; validateInput(); } catch (std::runtime_error &excpt){ std::cout << "An error occurred: " << excpt.what() << std::endl; } return 0; }
[ "noreply@github.com" ]
Karinliu.noreply@github.com
4ee2f55d2166b6df6697319712621fe24eb44e48
e12c9e71676c9cd44c0d201ef6b3eb97898bd77f
/MyFramework/SourceCommon/Helpers/MyTweener.h
ccacd591b14831ff9bba1d031fc4a166dbdf63df
[]
no_license
jaccen/MyFramework
8757e689dbd4f1a160307dd9f952e4edfa7da327
2a9b55e01a0afc33d5b8d682b9e2c4f7252a2095
refs/heads/master
2021-01-20T08:35:00.127208
2015-11-15T19:53:48
2015-11-15T19:53:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,104
h
// // Copyright (c) 2012-2014 Jimmy Lord http://www.flatheadgames.com // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. #ifndef __MyTweener_H__ #define __MyTweener_H__ class MyTweenPool; extern MyTweenPool* g_pTweenPool; // http://rechneronline.de/function-graphs/ // Sine Ease in, out, in/out //a0=2&a1=-5 * cos(x * 3.1415927/2) + 5&a2=5 * sin(x * 3.1415927/2)&a3=-5/2 * (cos(x * 3.1415927)-1)&a4=5&a5=4&a6=24&a7=&a8=&a9=&b0=500&b1=500&b2=0&b3=1&b4=0&b5=5&b6=4&b7=4&b8=5&b9=5&c0=3&c1=0&c2=1&c3=1&c4=1&c5=1&c6=1&c7=0&c8=0&c9=0&d0=1&d1=10&d2=10&d3=0&d4=0&d5=1&d6=0&d7=1&d8=0&d9=1&e0=&e1=&e2=&e3=&e4=14&e5=14&e6=13&e7=12&e8=0&e9=0&f0=0&f1=1&f2=1&f3=0&f4=0&f5=&f6=&f7=&f8=&f9=&g0=&g1=1&g2=1&g3=0&g4=0&g5=0&g6=Y&g7=ffffff&g8=a0b0c0&g9=6080a0&h0=1&z enum MyTweenVarType { MTVT_UnsignedChar, MTVT_Char, MTVT_Int, MTVT_Float, }; enum MyTweenType { MTT_Linear, MTT_SineEaseIn, MTT_SineEaseOut, MTT_SineEaseInOut, MTT_BounceEaseIn, MTT_BounceEaseOut, MTT_BounceEaseInOut, MTT_ElasticEaseIn, MTT_ElasticEaseOut, MTT_ElasticEaseInOut, }; class TweenVar { public: MyTweenVarType m_VarType; MyTweenType m_TweenType; bool m_UseStartValueWhileWaitingForDelay; double m_TweenTime; double m_Delay; float m_Elasticity; unsigned int m_ID; // to more easily cancel a bunch tweened values. bool m_Done; }; class TweenUnsignedChar : public TweenVar { public: unsigned char* m_pVariable; unsigned char m_StartValue; unsigned char m_EndValue; TweenUnsignedChar() { m_VarType = MTVT_UnsignedChar; m_pVariable = 0; m_StartValue = 0; m_EndValue = 0; } }; class TweenChar : public TweenVar { public: char* m_pVariable; char m_StartValue; char m_EndValue; TweenChar() { m_VarType = MTVT_Char; m_pVariable = 0; m_StartValue = 0; m_EndValue = 0; } }; class TweenInt : public TweenVar { public: int* m_pVariable; int m_StartValue; int m_EndValue; TweenInt() { m_VarType = MTVT_Int; m_pVariable = 0; m_StartValue = 0; m_EndValue = 0; } }; class TweenFloat : public TweenVar { public: float* m_pVariable; float m_StartValue; float m_EndValue; TweenFloat() { m_VarType = MTVT_Float; m_pVariable = 0; m_StartValue = 0; m_EndValue = 0; } }; class MyTweener { public: //protected: MyList<TweenVar*> m_ListOfVars; bool m_Done; bool m_HoldPositionWhenDone; bool m_HoldVarPositionsWhenIndividualVarsAreDone; bool m_ExternalAllocations; //bool m_PlayInReverse; double m_TimePassed; public: MyTweener(); MyTweener(int numvars); ~MyTweener(); bool IsDone(); void Reset(bool removeallvariables); void AddUnsignedChar(unsigned char* var, unsigned char startvalue, unsigned char endvalue, double tweentime, MyTweenType tweentype, double delay, bool updatewhiledelayed = false, unsigned int id = 0); void AddChar(char* var, char startvalue, char endvalue, double tweentime, MyTweenType tweentype, double delay, bool updatewhiledelayed = false, unsigned int id = 0); void AddInt(int* var, int startvalue, int endvalue, double tweentime, MyTweenType tweentype, double delay, bool updatewhiledelayed = false, unsigned int id = 0); void AddFloat(float* var, float startvalue, float endvalue, double tweentime, MyTweenType tweentype, double delay, bool updatewhiledelayed = false, unsigned int id = 0); void SetUnsignedChar(int index, unsigned char startvalue, unsigned char endvalue); void SetChar(int index, char startvalue, char endvalue); void SetInt(int index, int startvalue, int endvalue); void SetFloat(int index, float startvalue, float endvalue); void SetUnsignedChar(int index, unsigned char* var, unsigned char startvalue, unsigned char endvalue, double tweentime, MyTweenType tweentype, double delay, bool updatewhiledelayed = false, unsigned int id = 0); void SetChar(int index, char* var, char startvalue, char endvalue, double tweentime, MyTweenType tweentype, double delay, bool updatewhiledelayed = false, unsigned int id = 0); void SetInt(int index, int* var, int startvalue, int endvalue, double tweentime, MyTweenType tweentype, double delay, bool updatewhiledelayed = false, unsigned int id = 0); void SetFloat(int index, float* var, float startvalue, float endvalue, double tweentime, MyTweenType tweentype, double delay, bool updatewhiledelayed = false, unsigned int id = 0); void Tick(double timepassed); }; class MyTweenPool { public: TweenFloat* m_FloatBlockAlloc; MyTweener m_UnsignedChars; MyTweener m_Chars; MyTweener m_Ints; MyTweener m_Floats; unsigned int m_NumUnsignedCharsInUse; unsigned int m_NumCharsInUse; unsigned int m_NumIntsInUse; unsigned int m_NumFloatsInUse; public: MyTweenPool(int numuchars, int numchars, int numints, int numfloats); ~MyTweenPool(); void Tick(double timepassed); void AddFloat(float* var, float startvalue, float endvalue, double tweentime, MyTweenType tweentype, double delay, bool updatewhiledelayed = false, int id = 0); void CancelAllWithID(unsigned int id); }; #endif //__MyTweener_H__
[ "jimmylord@gmail.com" ]
jimmylord@gmail.com
10a92f0b99c49a3e5a615d3dad01dfe2efb573b4
5df2cc9a40045eb1d2f3251d385fc36c063a5e15
/plugins/Quasars/src/Quasars-static_automoc.cpp
792bb1b68b8e2deb004148eeda2ee5354962bd98
[]
no_license
jeffwitthuhn/StelUnity
8ed88ed183acd09b78cbe8cdb127f1a055895f1e
f93a326bacaa5d9ba481359f1102df290c16cba0
refs/heads/master
2020-12-31T07:20:29.823699
2017-01-31T20:11:08
2017-01-31T20:11:08
80,552,054
0
1
null
null
null
null
UTF-8
C++
false
false
189
cpp
/* This file is autogenerated, do not edit*/ #include "Quasars-static_automoc.dir/moc_Quasars_HFILF2FFVYXFZP.cpp" #include "Quasars-static_automoc.dir/moc_QuasarsDialog_BZ62WOCC6V4HPL.cpp"
[ "jmkelzenberg@stcloudstate.edu" ]
jmkelzenberg@stcloudstate.edu
d341bf2407b734f5f0acef1337a627bcfe2e8fa2
4a4781f2dcf159cefd4d6a8fe9135e96c4591776
/lab/lab05/code/src/tree.h
2371dfcd5f0b41809dca3659cfd943f177a3481a
[]
no_license
supremacey/cpp-hans
34cf0a6752ee023aeb8ee67dd790d79b2c291972
317c500a171804980c2d75c135ef1b6d1d4873b9
refs/heads/master
2021-01-20T03:34:22.798614
2017-06-06T11:00:36
2017-06-06T11:00:36
83,833,120
0
0
null
null
null
null
UTF-8
C++
false
false
2,202
h
#ifndef TREE_INCLUDED #define TREE_INCLUDED 1 #include <iostream> #include <vector> #include "string.h" class tree; // struct trnode should be invisible to the user of tree. This can be // obtained by making it a private number of tree. // In this exercise, we leave it like this, because it is simpler. // In real code, trnode should be defined inside tree. struct trnode { string f; std::vector< tree > subtrees; size_t refcnt; // how many times I am refere to :)? // The reference counter: Counts how often this trnode is referred to. trnode( const string& f, const std::vector< tree > & subtrees, size_t refcnt ) : f{f}, subtrees{ subtrees }, refcnt{ refcnt } { } trnode( const string& f, std::vector< tree > && subtrees, size_t refcnt ) : f{f}, subtrees{ std::move( subtrees )}, refcnt{ refcnt } { } }; class tree { trnode* pntr; public: tree( const string& f ) : pntr( new trnode( f, { }, 1 )) { } tree( const string& f, const std::vector< tree > & subtrees ) : pntr( new trnode( f, subtrees, 1 )) { } tree( const string& f, std::vector< tree > && subtrees ) : pntr( new trnode( f, std::move( subtrees ), 1 )) { } tree( const tree& t ); // There is no need to write tree( tree&& t ), // because we cannot improve. void operator = ( tree&& t ); void operator = ( const tree& t ); const string& functor( ) const; // string& functor( ); const tree& operator [ ] ( size_t i ) const; // tree& operator [ ] ( size_t i ); size_t nrsubtrees( ) const; size_t getaddress() const; // replaces i-th subtree void replacesubtree(size_t i, const tree& t); // replaces the functor void replacefunctor(const string& s); ~tree( ); private: //public: // Delete public, when the thing is tested: void ensure_not_shared( ); }; tree subst(const tree& t, const string& var, const tree& val); std::ostream& operator << ( std::ostream& stream, const tree& t ); // Doesn't need to be friend, because it uses only functor( ), // nrsubtrees( ) and [ ]. #endif // TREE_INCLUDED
[ "supremacey@icloud.com" ]
supremacey@icloud.com
91492de20fd1a03c15c823fb19b4e81c7a1d7a7d
264d4734c618f5f7cab5cae88d1044dc2942a367
/sketch.cpp
a09fdc45bc7298d8ba98d0bd8774cd41788ec7d5
[]
no_license
MrJadaml/temp-humidity-dashboard
b9bf728817a325a10c581f4ea52a57f6de4a5558
6a21214e48725b31aa5a050047a22599e050ccb3
refs/heads/master
2021-01-20T00:19:55.534122
2017-05-20T19:37:57
2017-05-20T19:37:57
89,110,720
0
0
null
null
null
null
UTF-8
C++
false
false
511
cpp
#include <SimpleDHT.h> // for DHT11, // VCC: 5V or 3V // GND: GND // DATA: 2 int pinDHT11 = 2; SimpleDHT11 dht11; void setup() { Serial.begin(9600); } void loop() { byte temperature = 0; byte humidity = 0; byte data[40] = {0}; if (dht11.read(pinDHT11, &temperature, &humidity, data)) { Serial.print("Read DHT11 failed"); return; } Serial.print("tempCel,"); Serial.print((int)temperature); Serial.print(",humidity,"); Serial.println((int)humidity); delay(5000); }
[ "mrjadaml@gmail.com" ]
mrjadaml@gmail.com
c1c7dbf4a77579e4e0d2c9bd2dc39be5526fa342
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/collectd/gumtree/collectd_repos_function_496_collectd-4.5.1.cpp
a871c1fd3e2ddbe3d2010e1f6273f83672e50145
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,736
cpp
static int pplugin_dispatch_values (pTHX_ HV *values) { value_list_t list = VALUE_LIST_INIT; value_t *val = NULL; SV **tmp = NULL; int ret = 0; if (NULL == values) return -1; if (NULL == (tmp = hv_fetch (values, "type", 4, 0))) { log_err ("pplugin_dispatch_values: No type given."); return -1; } sstrncpy (list.type, SvPV_nolen (*tmp), sizeof (list.type)); if ((NULL == (tmp = hv_fetch (values, "values", 6, 0))) || (! (SvROK (*tmp) && (SVt_PVAV == SvTYPE (SvRV (*tmp)))))) { log_err ("pplugin_dispatch_values: No valid values given."); return -1; } { AV *array = (AV *)SvRV (*tmp); int len = av_len (array) + 1; if (len <= 0) return -1; val = (value_t *)smalloc (len * sizeof (value_t)); list.values_len = av2value (aTHX_ list.type, (AV *)SvRV (*tmp), val, len); list.values = val; if (-1 == list.values_len) { sfree (val); return -1; } } if (NULL != (tmp = hv_fetch (values, "time", 4, 0))) { list.time = (time_t)SvIV (*tmp); } else { list.time = time (NULL); } if (NULL != (tmp = hv_fetch (values, "host", 4, 0))) { sstrncpy (list.host, SvPV_nolen (*tmp), sizeof (list.host)); } else { sstrncpy (list.host, hostname_g, sizeof (list.host)); } if (NULL != (tmp = hv_fetch (values, "plugin", 6, 0))) sstrncpy (list.plugin, SvPV_nolen (*tmp), sizeof (list.plugin)); if (NULL != (tmp = hv_fetch (values, "plugin_instance", 15, 0))) sstrncpy (list.plugin_instance, SvPV_nolen (*tmp), sizeof (list.plugin_instance)); if (NULL != (tmp = hv_fetch (values, "type_instance", 13, 0))) sstrncpy (list.type_instance, SvPV_nolen (*tmp), sizeof (list.type_instance)); ret = plugin_dispatch_values (&list); sfree (val); return ret; }
[ "993273596@qq.com" ]
993273596@qq.com
f67e931fa7d697c380a4123a4001983c8632eac6
4f7466a8aba90dd237d30bf33c42c63f72875628
/src/engine.cc
fed49d75a19bdf2d958b2035c80c142ddad02fbd
[]
no_license
Videodr0me/leela-chess-experimental
2993f1a912eb14d03ba5194bb3f6e293b8f60a7b
d2088837fff01779dbf8fc606af6e92c98c1a449
refs/heads/master
2020-03-19T04:14:17.427499
2018-07-23T20:43:49
2018-07-23T20:43:49
135,808,631
7
0
null
null
null
null
UTF-8
C++
false
false
7,820
cc
/* This file is part of Leela Chess Zero. Copyright (C) 2018 The LCZero Authors Leela Chess is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Leela Chess 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 Leela Chess. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <functional> #include "engine.h" #include "mcts/search.h" #include "neural/factory.h" #include "neural/loader.h" namespace lczero { namespace { // TODO(mooskagh) Move threads parameter handling to search. const int kDefaultThreads = 2; const char* kThreadsOption = "Number of worker threads"; const char* kDebugLogStr = "Do debug logging into file"; // TODO(mooskagh) Move weights/backend/backend-opts parameter handling to // network factory. const char* kWeightsStr = "Network weights file path"; const char* kNnBackendStr = "NN backend to use"; const char* kNnBackendOptionsStr = "NN backend parameters"; const char* kSlowMoverStr = "Scale thinking time"; const char* kAutoDiscover = "<autodiscover>"; } // namespace EngineController::EngineController(BestMoveInfo::Callback best_move_callback, ThinkingInfo::Callback info_callback, const OptionsDict& options) : options_(options), best_move_callback_(best_move_callback), info_callback_(info_callback) {} void EngineController::PopulateOptions(OptionsParser* options) { using namespace std::placeholders; options->Add<StringOption>(kWeightsStr, "weights", 'w') = kAutoDiscover; options->Add<IntOption>(kThreadsOption, 1, 128, "threads", 't') = kDefaultThreads; options->Add<IntOption>( "NNCache size", 0, 999999999, "nncache", '\0', std::bind(&EngineController::SetCacheSize, this, _1)) = 200000; const auto backends = NetworkFactory::Get()->GetBackendsList(); options->Add<ChoiceOption>(kNnBackendStr, backends, "backend") = backends.empty() ? "<none>" : backends[0]; options->Add<StringOption>(kNnBackendOptionsStr, "backend-opts"); options->Add<FloatOption>(kSlowMoverStr, 0.0, 100.0, "slowmover") = 2.5; Search::PopulateUciParams(options); } SearchLimits EngineController::PopulateSearchLimits(int /*ply*/, bool is_black, const GoParams& params) { SearchLimits limits; limits.visits = params.nodes; limits.time_ms = params.movetime; int64_t time = (is_black ? params.btime : params.wtime); if (params.infinite || time < 0) return limits; int increment = std::max(int64_t(0), is_black ? params.binc : params.winc); int movestogo = params.movestogo < 0 ? 50 : params.movestogo; // Fix non-standard uci command. if (movestogo == 0) movestogo = 1; // How to scale moves time. float slowmover = options_.Get<float>(kSlowMoverStr); // Total time till control including increments. auto total_moves_time = (time + (increment * (movestogo - 1))); const int kSmartPruningToleranceMs = 200; // Compute the move time without slowmover. int64_t this_move_time = total_moves_time / movestogo; // Only extend thinking time with slowmover if smart pruning can potentially // reduce it. if (slowmover < 1.0 || this_move_time > kSmartPruningToleranceMs) { // Budget X*slowmover for current move, X*1.0 for the rest. this_move_time = slowmover ? total_moves_time / (movestogo - 1 + slowmover) * slowmover : 20; } // Make sure we don't exceed current time limit with what we calculated. limits.time_ms = std::min(this_move_time, static_cast<int64_t>(time * 0.95)); return limits; } void EngineController::UpdateNetwork() { SharedLock lock(busy_mutex_); std::string network_path = options_.Get<std::string>(kWeightsStr); std::string backend = options_.Get<std::string>(kNnBackendStr); std::string backend_options = options_.Get<std::string>(kNnBackendOptionsStr); if (network_path == network_path_ && backend == backend_ && backend_options == backend_options_) return; network_path_ = network_path; backend_ = backend; backend_options_ = backend_options; std::string net_path = network_path; if (net_path == kAutoDiscover) { net_path = DiscoveryWeightsFile(); } Weights weights = LoadWeightsFromFile(net_path); OptionsDict network_options = OptionsDict::FromString(backend_options, &options_); network_ = NetworkFactory::Get()->Create(backend, weights, network_options); } void EngineController::SetCacheSize(int size) { cache_.SetCapacity(size); } void EngineController::NewGame() { SharedLock lock(busy_mutex_); cache_.Clear(); search_.reset(); tree_.reset(); UpdateNetwork(); } void EngineController::SetPosition(const std::string& fen, const std::vector<std::string>& moves_str) { SharedLock lock(busy_mutex_); search_.reset(); if (!tree_) tree_ = std::make_unique<NodeTree>(); std::vector<Move> moves; for (const auto& move : moves_str) moves.emplace_back(move); tree_->ResetToPosition(fen, moves); UpdateNetwork(); } void EngineController::Go(const GoParams& params) { if (!tree_) { SetPosition(ChessBoard::kStartingFen, {}); } auto limits = PopulateSearchLimits(tree_->GetPlyCount(), tree_->IsBlackToMove(), params); search_ = std::make_unique<Search>(*tree_, network_.get(), best_move_callback_, info_callback_, limits, options_, &cache_); search_->StartThreads(options_.Get<int>(kThreadsOption)); } void EngineController::Stop() { if (search_) { search_->Stop(); search_->Wait(); } } EngineLoop::EngineLoop() : engine_(std::bind(&UciLoop::SendBestMove, this, std::placeholders::_1), std::bind(&UciLoop::SendInfo, this, std::placeholders::_1), options_.GetOptionsDict()) { engine_.PopulateOptions(&options_); options_.Add<StringOption>( kDebugLogStr, "debuglog", 'l', [this](const std::string& filename) { SetLogFilename(filename); }) = ""; } void EngineLoop::RunLoop() { if (!options_.ProcessAllFlags()) return; UciLoop::RunLoop(); } void EngineLoop::CmdUci() { SendResponse("id name The Lc0 chess engine."); SendResponse("id author The LCZero Authors."); for (const auto& option : options_.ListOptionsUci()) { SendResponse(option); } SendResponse("uciok"); } void EngineLoop::CmdIsReady() { engine_.EnsureReady(); SendResponse("readyok"); } void EngineLoop::CmdSetOption(const std::string& name, const std::string& value, const std::string& context) { options_.SetOption(name, value, context); if (options_sent_) { options_.SendOption(name); } } void EngineLoop::EnsureOptionsSent() { if (!options_sent_) { options_.SendAllOptions(); options_sent_ = true; } } void EngineLoop::CmdUciNewGame() { EnsureOptionsSent(); engine_.NewGame(); } void EngineLoop::CmdPosition(const std::string& position, const std::vector<std::string>& moves) { EnsureOptionsSent(); std::string fen = position; if (fen.empty()) fen = ChessBoard::kStartingFen; engine_.SetPosition(fen, moves); } void EngineLoop::CmdGo(const GoParams& params) { EnsureOptionsSent(); engine_.Go(params); } void EngineLoop::CmdStop() { engine_.Stop(); } } // namespace lczero
[ "noreply@github.com" ]
Videodr0me.noreply@github.com
4e5be12da196b8ae185fb6e0b9208aaf9ce09b2a
f878c7a63f668b9bd811f9c79a01814d7d63becd
/data_dir/dev/86735
6ad6816df13624a60b07d2f8728530992e554957
[ "MIT" ]
permissive
AliOsm/AI-SOCO
f8d7428f4570577e7e8d4dddecb4fed5cfbed11c
c7b285cd8a094f09a294e17af77d3cb254537801
refs/heads/master
2023-05-24T09:15:43.769045
2020-11-06T12:58:16
2020-11-06T12:58:16
265,671,705
18
8
null
null
null
null
UTF-8
C++
false
false
1,142
#include<bits/stdc++.h> using namespace std; vector<pair<int,int>> edge; vector<pair<int,int>> qs[10235]; int ans[20004],djs[555]; int F(int x){return x==djs[x]?x:djs[x]=F(djs[x]);} bool u(int x,int y){ x=F(x); y=F(y); if(x==y)return 0; djs[x]=y; return 1; } int main(){ ios_base::sync_with_stdio(0); cin.tie(0); int n,m; cin>>n>>m; edge.resize(m); for(int i=0;i<m;++i){ cin>>edge[i].first>>edge[i].second; } int q; cin>>q; for(int i=0;i<q;++i){ int l,r; cin>>l>>r; --l,--r; qs[l].push_back({r,i}); } for(int i=0;i<m;++i){ if(qs[i].empty())continue; sort(qs[i].begin(),qs[i].end()); reverse(qs[i].begin(),qs[i].end()); for(int i=1;i<=n;++i)djs[i]=i; int tot=n; for(int j=0;j<i;++j){ if(u(edge[j].first,edge[j].second))--tot; } int ptr=m-1; for(auto q:qs[i]){ while(ptr>q.first){ if(u(edge[ptr].first,edge[ptr].second))--tot; --ptr; } ans[q.second]=tot; } } for(int i=0;i<q;++i)cout<<ans[i]<<'\n'; }
[ "aliosm1997@gmail.com" ]
aliosm1997@gmail.com
d38e7ddf681df57a7f8332a6e4cb5336b575bb07
79c01c26ad4c0d4460d529126d01c7b97a6173b6
/src/VulkanApplication.h
ea83f54e0fb6854d0eb0bce6f33b37160cf1a267
[]
no_license
SSSSSolution/RealityCreator
7b4ca78290ab11ca29ff59dc01993d40444be61d
a0062d1c7ead3877612d746dbccc64ea46fd95eb
refs/heads/master
2020-11-28T00:04:29.329066
2020-03-23T15:01:48
2020-03-23T15:01:48
229,654,535
0
0
null
null
null
null
UTF-8
C++
false
false
1,024
h
#ifndef VULKANAPPLICATION_H #define VULKANAPPLICATION_H #include "VulkanInstance.h" #include "VulkanDevice.h" class VulkanDevice; class VulkanRenderer; class VulkanApplication { public: static VulkanApplication* getInstance(); ~VulkanApplication(); void initialize(); void prepare(); void render(); private: VulkanApplication(); VkResult createVulkanInstance(std::vector<const char *>layers, std::vector<const char *>extensions, const char *appName); VkResult createVulkanDevice(std::vector<const char *> layers, std::vector<const char *> extensions); VkResult createVulkanRenderer(); public: VulkanInstance vulkanInstance; VulkanDevice vulkanDevice; VulkanRenderer *vulkanRenderer; private: static std::unique_ptr<VulkanApplication> instance; static std::once_flag onlyOnce; std::vector<VkCommandBuffer> drawCmdList; }; #endif // VULKANAPPLICATION_H
[ "1845739048@qq.com" ]
1845739048@qq.com
647265a4aca57a21410c5176c5400c66451a8d40
1d9b1b78887bdff6dd5342807c4ee20f504a2a75
/lib/libcxx/include/__algorithm/includes.h
c64194a2c8269beea39a0022e51b9e1317cb33ae
[ "MIT", "LicenseRef-scancode-other-permissive", "NCSA", "LLVM-exception", "Apache-2.0" ]
permissive
mikdusan/zig
86831722d86f518d1734ee5a1ca89d3ffe9555e8
b2ffe113d3fd2835b25ddf2de1cc8dd49f5de722
refs/heads/master
2023-08-31T21:29:04.425401
2022-11-13T15:43:29
2022-11-13T15:43:29
173,955,807
1
0
MIT
2021-11-02T03:19:36
2019-03-05T13:52:53
Zig
UTF-8
C++
false
false
2,758
h
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #ifndef _LIBCPP___ALGORITHM_INCLUDES_H #define _LIBCPP___ALGORITHM_INCLUDES_H #include <__algorithm/comp.h> #include <__algorithm/comp_ref_type.h> #include <__config> #include <__functional/identity.h> #include <__functional/invoke.h> #include <__iterator/iterator_traits.h> #include <__type_traits/is_callable.h> #include <__utility/move.h> #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) # pragma GCC system_header #endif _LIBCPP_BEGIN_NAMESPACE_STD template <class _Iter1, class _Sent1, class _Iter2, class _Sent2, class _Comp, class _Proj1, class _Proj2> _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 bool __includes(_Iter1 __first1, _Sent1 __last1, _Iter2 __first2, _Sent2 __last2, _Comp&& __comp, _Proj1&& __proj1, _Proj2&& __proj2) { for (; __first2 != __last2; ++__first1) { if (__first1 == __last1 || std::__invoke( __comp, std::__invoke(__proj2, *__first2), std::__invoke(__proj1, *__first1))) return false; if (!std::__invoke(__comp, std::__invoke(__proj1, *__first1), std::__invoke(__proj2, *__first2))) ++__first2; } return true; } template <class _InputIterator1, class _InputIterator2, class _Compare> _LIBCPP_NODISCARD_EXT inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 bool includes( _InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2, _Compare __comp) { static_assert(__is_callable<_Compare, decltype(*__first1), decltype(*__first2)>::value, "Comparator has to be callable"); typedef typename __comp_ref_type<_Compare>::type _Comp_ref; return std::__includes( std::move(__first1), std::move(__last1), std::move(__first2), std::move(__last2), static_cast<_Comp_ref>(__comp), __identity(), __identity()); } template <class _InputIterator1, class _InputIterator2> _LIBCPP_NODISCARD_EXT inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_AFTER_CXX17 bool includes(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _InputIterator2 __last2) { return std::includes( std::move(__first1), std::move(__last1), std::move(__first2), std::move(__last2), __less<typename iterator_traits<_InputIterator1>::value_type, typename iterator_traits<_InputIterator2>::value_type>()); } _LIBCPP_END_NAMESPACE_STD #endif // _LIBCPP___ALGORITHM_INCLUDES_H
[ "andrew@ziglang.org" ]
andrew@ziglang.org
8214f1a88d59ac018b7ede23924fa23469ce7698
df2b9eaee2aefc34dcc3037406ea4a13358db354
/precsucc.cpp
33fdd3c1969c89d3ec809b480c8a7b2836cce332
[]
no_license
rob3d/Programmi.Scolastici
dbfef07638c9c3331bf29725577ff736708302bf
8d394b117057e835476c2490ccb8b90c3f5efd36
refs/heads/master
2021-01-21T03:02:19.418430
2016-05-03T20:01:45
2016-05-03T20:01:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
444
cpp
//ATTENZIONE! NON SONO RESPONSABILE PER L USO CHE VERRA' FATTO CON QUESTO CODICE! //https://github.com/santoroberto00/Programmi.Scolastici/blob/master/DISCLAIMER-LIBERATORIA.txt //Autore: Roberto Santo #include <stdio.h> #include <stdlib.h> main(){ int numero; printf("Inserisci il valore del numero intero:"); scanf("%i",&numero); printf("Il suo precedente e'' %i e il suo successivo e' %i.\n",numero-1,numero+1); system("PAUSE"); }
[ "santoroberto00@gmail.com" ]
santoroberto00@gmail.com
95c0f487e441004bba6226d337046632ebe7d91d
4043f78994d68efc7d0fe9805cd91ec46a4d16f4
/src/dxt_img.h
8ee7b74ca973796629938a6eba1c49d120b860f7
[ "Apache-2.0" ]
permissive
fanvanzh/3dtiles
d08d30956e790e451beab79c82acddc42a051e02
a7c3000c794f5fbcf0defe72cabd0465dbf9df6e
refs/heads/master
2023-09-03T14:08:09.905715
2023-08-30T02:30:02
2023-08-30T02:30:02
120,919,743
1,713
555
Apache-2.0
2023-08-30T02:30:03
2018-02-09T15:07:43
C++
UTF-8
C++
false
false
145
h
#ifndef DXT_IMG_H #define DXT_IMG_H void fill_4BitImage(std::vector<unsigned char>& jpeg_buf, osg::Image* img, int& width, int& height); #endif
[ "fanvanzh@sina.com" ]
fanvanzh@sina.com
ff20d603e2e479dc22fc364b97dae0db54052afc
18764973fb6947c80114c95e52f5e20ff1c7eda4
/src/components/application_manager/include/application_manager/commands/mobile/set_interior_vehicle_data_response.h
ecc8fd0904af9fd9702304af779a55234bf4dd0d
[]
no_license
FaridJafarov-l/sdl_core
a75ff5f13572d92f09c995bc5e979c8815aaeb52
11d6463b47a00334a23e8e7cadea4ab818d54f60
refs/heads/master
2023-09-04T08:55:16.628093
2016-12-19T12:33:47
2016-12-19T12:33:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,496
h
/* * Copyright (c) 2013, Ford Motor Company * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the * distribution. * * Neither the name of the Ford Motor Company 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. */ #ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_MOBILE_SET_INTERIOR_VEHICLE_DATA_RESPONSE_H_ #define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_MOBILE_SET_INTERIOR_VEHICLE_DATA_RESPONSE_H_ #include "application_manager/commands/command_response_impl.h" #include "application_manager/message.h" #include "utils/macro.h" namespace application_manager { namespace commands { class SetInteriorVehicleDataResponse : public CommandResponseImpl { public: explicit SetInteriorVehicleDataResponse(const MessageSharedPtr& message); virtual ~SetInteriorVehicleDataResponse(); virtual void Run(); private: DISALLOW_COPY_AND_ASSIGN(SetInteriorVehicleDataResponse); }; } // namespace commands } // namespace application_manager #endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_MOBILE_SET_INTERIOR_VEHICLE_DATA_RESPONSE_H_
[ "jack@livio.io" ]
jack@livio.io