blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
sequencelengths
1
1
author_id
stringlengths
0
158
4fe2ed9c3539072ef73041b7227554bd90bd4a63
7abbbef9590f9c4b9469adcbae5ea8907478bf03
/chromium_git/chromium/src/out/Release/gen/protoc_out/sync/protocol/attachments.pb.h
a5499e865da8cdaa4ae838dcb7c74c19ee0c46aa
[ "BSD-3-Clause" ]
permissive
GiorgiGagnidze/CEF
845bdc2f54833254b3454ba8f6c61449431c7884
fbfc30b5d60f1ea7157da449e34dd9ba9c50f360
refs/heads/master
2021-01-10T17:32:27.640882
2016-03-23T07:43:04
2016-03-23T07:43:04
54,463,340
0
1
null
null
null
null
UTF-8
C++
false
true
19,052
h
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: attachments.proto #ifndef PROTOBUF_attachments_2eproto__INCLUDED #define PROTOBUF_attachments_2eproto__INCLUDED #include <string> #include <google/protobuf/stubs/common.h> #if GOOGLE_PROTOBUF_VERSION < 2005000 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif #if 2005000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif #include <google/protobuf/generated_message_util.h> #include <google/protobuf/message_lite.h> #include <google/protobuf/repeated_field.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/unknown_field_set.h> #include <google/protobuf/unknown_field_set.h> // @@protoc_insertion_point(includes) #include "sync/protocol/sync_proto_export.h" namespace sync_pb { // Internal implementation detail -- do not call these. void SYNC_PROTO_EXPORT protobuf_AddDesc_attachments_2eproto(); void protobuf_AssignDesc_attachments_2eproto(); void protobuf_ShutdownFile_attachments_2eproto(); class AttachmentIdProto; class AttachmentMetadataRecord; class AttachmentMetadata; // =================================================================== class SYNC_PROTO_EXPORT AttachmentIdProto : public ::google::protobuf::MessageLite { public: AttachmentIdProto(); virtual ~AttachmentIdProto(); AttachmentIdProto(const AttachmentIdProto& from); inline AttachmentIdProto& operator=(const AttachmentIdProto& from) { CopyFrom(from); return *this; } inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { return _unknown_fields_; } inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { return &_unknown_fields_; } static const AttachmentIdProto& default_instance(); #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER // Returns the internal default instance pointer. This function can // return NULL thus should not be used by the user. This is intended // for Protobuf internal code. Please use default_instance() declared // above instead. static inline const AttachmentIdProto* internal_default_instance() { return default_instance_; } #endif void Swap(AttachmentIdProto* other); // implements Message ---------------------------------------------- AttachmentIdProto* New() const; void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from); void CopyFrom(const AttachmentIdProto& from); void MergeFrom(const AttachmentIdProto& from); void Clear(); bool IsInitialized() const; int ByteSize() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; public: ::std::string GetTypeName() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // optional string unique_id = 1; inline bool has_unique_id() const; inline void clear_unique_id(); static const int kUniqueIdFieldNumber = 1; inline const ::std::string& unique_id() const; inline void set_unique_id(const ::std::string& value); inline void set_unique_id(const char* value); inline void set_unique_id(const char* value, size_t size); inline ::std::string* mutable_unique_id(); inline ::std::string* release_unique_id(); inline void set_allocated_unique_id(::std::string* unique_id); // optional uint64 size_bytes = 2; inline bool has_size_bytes() const; inline void clear_size_bytes(); static const int kSizeBytesFieldNumber = 2; inline ::google::protobuf::uint64 size_bytes() const; inline void set_size_bytes(::google::protobuf::uint64 value); // optional uint32 crc32c = 3; inline bool has_crc32c() const; inline void clear_crc32c(); static const int kCrc32CFieldNumber = 3; inline ::google::protobuf::uint32 crc32c() const; inline void set_crc32c(::google::protobuf::uint32 value); // @@protoc_insertion_point(class_scope:sync_pb.AttachmentIdProto) private: inline void set_has_unique_id(); inline void clear_has_unique_id(); inline void set_has_size_bytes(); inline void clear_has_size_bytes(); inline void set_has_crc32c(); inline void clear_has_crc32c(); ::google::protobuf::UnknownFieldSet _unknown_fields_; ::std::string* unique_id_; ::google::protobuf::uint64 size_bytes_; ::google::protobuf::uint32 crc32c_; mutable int _cached_size_; ::google::protobuf::uint32 _has_bits_[(3 + 31) / 32]; #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER friend void SYNC_PROTO_EXPORT protobuf_AddDesc_attachments_2eproto_impl(); #else friend void SYNC_PROTO_EXPORT protobuf_AddDesc_attachments_2eproto(); #endif friend void protobuf_AssignDesc_attachments_2eproto(); friend void protobuf_ShutdownFile_attachments_2eproto(); void InitAsDefaultInstance(); static AttachmentIdProto* default_instance_; }; // ------------------------------------------------------------------- class SYNC_PROTO_EXPORT AttachmentMetadataRecord : public ::google::protobuf::MessageLite { public: AttachmentMetadataRecord(); virtual ~AttachmentMetadataRecord(); AttachmentMetadataRecord(const AttachmentMetadataRecord& from); inline AttachmentMetadataRecord& operator=(const AttachmentMetadataRecord& from) { CopyFrom(from); return *this; } inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { return _unknown_fields_; } inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { return &_unknown_fields_; } static const AttachmentMetadataRecord& default_instance(); #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER // Returns the internal default instance pointer. This function can // return NULL thus should not be used by the user. This is intended // for Protobuf internal code. Please use default_instance() declared // above instead. static inline const AttachmentMetadataRecord* internal_default_instance() { return default_instance_; } #endif void Swap(AttachmentMetadataRecord* other); // implements Message ---------------------------------------------- AttachmentMetadataRecord* New() const; void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from); void CopyFrom(const AttachmentMetadataRecord& from); void MergeFrom(const AttachmentMetadataRecord& from); void Clear(); bool IsInitialized() const; int ByteSize() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; public: ::std::string GetTypeName() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // optional .sync_pb.AttachmentIdProto id = 1; inline bool has_id() const; inline void clear_id(); static const int kIdFieldNumber = 1; inline const ::sync_pb::AttachmentIdProto& id() const; inline ::sync_pb::AttachmentIdProto* mutable_id(); inline ::sync_pb::AttachmentIdProto* release_id(); inline void set_allocated_id(::sync_pb::AttachmentIdProto* id); // optional bool is_on_server = 2; inline bool has_is_on_server() const; inline void clear_is_on_server(); static const int kIsOnServerFieldNumber = 2; inline bool is_on_server() const; inline void set_is_on_server(bool value); // @@protoc_insertion_point(class_scope:sync_pb.AttachmentMetadataRecord) private: inline void set_has_id(); inline void clear_has_id(); inline void set_has_is_on_server(); inline void clear_has_is_on_server(); ::google::protobuf::UnknownFieldSet _unknown_fields_; ::sync_pb::AttachmentIdProto* id_; bool is_on_server_; mutable int _cached_size_; ::google::protobuf::uint32 _has_bits_[(2 + 31) / 32]; #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER friend void SYNC_PROTO_EXPORT protobuf_AddDesc_attachments_2eproto_impl(); #else friend void SYNC_PROTO_EXPORT protobuf_AddDesc_attachments_2eproto(); #endif friend void protobuf_AssignDesc_attachments_2eproto(); friend void protobuf_ShutdownFile_attachments_2eproto(); void InitAsDefaultInstance(); static AttachmentMetadataRecord* default_instance_; }; // ------------------------------------------------------------------- class SYNC_PROTO_EXPORT AttachmentMetadata : public ::google::protobuf::MessageLite { public: AttachmentMetadata(); virtual ~AttachmentMetadata(); AttachmentMetadata(const AttachmentMetadata& from); inline AttachmentMetadata& operator=(const AttachmentMetadata& from) { CopyFrom(from); return *this; } inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { return _unknown_fields_; } inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { return &_unknown_fields_; } static const AttachmentMetadata& default_instance(); #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER // Returns the internal default instance pointer. This function can // return NULL thus should not be used by the user. This is intended // for Protobuf internal code. Please use default_instance() declared // above instead. static inline const AttachmentMetadata* internal_default_instance() { return default_instance_; } #endif void Swap(AttachmentMetadata* other); // implements Message ---------------------------------------------- AttachmentMetadata* New() const; void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from); void CopyFrom(const AttachmentMetadata& from); void MergeFrom(const AttachmentMetadata& from); void Clear(); bool IsInitialized() const; int ByteSize() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; public: ::std::string GetTypeName() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // repeated .sync_pb.AttachmentMetadataRecord record = 1; inline int record_size() const; inline void clear_record(); static const int kRecordFieldNumber = 1; inline const ::sync_pb::AttachmentMetadataRecord& record(int index) const; inline ::sync_pb::AttachmentMetadataRecord* mutable_record(int index); inline ::sync_pb::AttachmentMetadataRecord* add_record(); inline const ::google::protobuf::RepeatedPtrField< ::sync_pb::AttachmentMetadataRecord >& record() const; inline ::google::protobuf::RepeatedPtrField< ::sync_pb::AttachmentMetadataRecord >* mutable_record(); // @@protoc_insertion_point(class_scope:sync_pb.AttachmentMetadata) private: ::google::protobuf::UnknownFieldSet _unknown_fields_; ::google::protobuf::RepeatedPtrField< ::sync_pb::AttachmentMetadataRecord > record_; mutable int _cached_size_; ::google::protobuf::uint32 _has_bits_[(1 + 31) / 32]; #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER friend void SYNC_PROTO_EXPORT protobuf_AddDesc_attachments_2eproto_impl(); #else friend void SYNC_PROTO_EXPORT protobuf_AddDesc_attachments_2eproto(); #endif friend void protobuf_AssignDesc_attachments_2eproto(); friend void protobuf_ShutdownFile_attachments_2eproto(); void InitAsDefaultInstance(); static AttachmentMetadata* default_instance_; }; // =================================================================== // =================================================================== // AttachmentIdProto // optional string unique_id = 1; inline bool AttachmentIdProto::has_unique_id() const { return (_has_bits_[0] & 0x00000001u) != 0; } inline void AttachmentIdProto::set_has_unique_id() { _has_bits_[0] |= 0x00000001u; } inline void AttachmentIdProto::clear_has_unique_id() { _has_bits_[0] &= ~0x00000001u; } inline void AttachmentIdProto::clear_unique_id() { if (unique_id_ != &::google::protobuf::internal::GetEmptyString()) { unique_id_->clear(); } clear_has_unique_id(); } inline const ::std::string& AttachmentIdProto::unique_id() const { return *unique_id_; } inline void AttachmentIdProto::set_unique_id(const ::std::string& value) { set_has_unique_id(); if (unique_id_ == &::google::protobuf::internal::GetEmptyString()) { unique_id_ = new ::std::string; } unique_id_->assign(value); } inline void AttachmentIdProto::set_unique_id(const char* value) { set_has_unique_id(); if (unique_id_ == &::google::protobuf::internal::GetEmptyString()) { unique_id_ = new ::std::string; } unique_id_->assign(value); } inline void AttachmentIdProto::set_unique_id(const char* value, size_t size) { set_has_unique_id(); if (unique_id_ == &::google::protobuf::internal::GetEmptyString()) { unique_id_ = new ::std::string; } unique_id_->assign(reinterpret_cast<const char*>(value), size); } inline ::std::string* AttachmentIdProto::mutable_unique_id() { set_has_unique_id(); if (unique_id_ == &::google::protobuf::internal::GetEmptyString()) { unique_id_ = new ::std::string; } return unique_id_; } inline ::std::string* AttachmentIdProto::release_unique_id() { clear_has_unique_id(); if (unique_id_ == &::google::protobuf::internal::GetEmptyString()) { return NULL; } else { ::std::string* temp = unique_id_; unique_id_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyString()); return temp; } } inline void AttachmentIdProto::set_allocated_unique_id(::std::string* unique_id) { if (unique_id_ != &::google::protobuf::internal::GetEmptyString()) { delete unique_id_; } if (unique_id) { set_has_unique_id(); unique_id_ = unique_id; } else { clear_has_unique_id(); unique_id_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyString()); } } // optional uint64 size_bytes = 2; inline bool AttachmentIdProto::has_size_bytes() const { return (_has_bits_[0] & 0x00000002u) != 0; } inline void AttachmentIdProto::set_has_size_bytes() { _has_bits_[0] |= 0x00000002u; } inline void AttachmentIdProto::clear_has_size_bytes() { _has_bits_[0] &= ~0x00000002u; } inline void AttachmentIdProto::clear_size_bytes() { size_bytes_ = GOOGLE_ULONGLONG(0); clear_has_size_bytes(); } inline ::google::protobuf::uint64 AttachmentIdProto::size_bytes() const { return size_bytes_; } inline void AttachmentIdProto::set_size_bytes(::google::protobuf::uint64 value) { set_has_size_bytes(); size_bytes_ = value; } // optional uint32 crc32c = 3; inline bool AttachmentIdProto::has_crc32c() const { return (_has_bits_[0] & 0x00000004u) != 0; } inline void AttachmentIdProto::set_has_crc32c() { _has_bits_[0] |= 0x00000004u; } inline void AttachmentIdProto::clear_has_crc32c() { _has_bits_[0] &= ~0x00000004u; } inline void AttachmentIdProto::clear_crc32c() { crc32c_ = 0u; clear_has_crc32c(); } inline ::google::protobuf::uint32 AttachmentIdProto::crc32c() const { return crc32c_; } inline void AttachmentIdProto::set_crc32c(::google::protobuf::uint32 value) { set_has_crc32c(); crc32c_ = value; } // ------------------------------------------------------------------- // AttachmentMetadataRecord // optional .sync_pb.AttachmentIdProto id = 1; inline bool AttachmentMetadataRecord::has_id() const { return (_has_bits_[0] & 0x00000001u) != 0; } inline void AttachmentMetadataRecord::set_has_id() { _has_bits_[0] |= 0x00000001u; } inline void AttachmentMetadataRecord::clear_has_id() { _has_bits_[0] &= ~0x00000001u; } inline void AttachmentMetadataRecord::clear_id() { if (id_ != NULL) id_->::sync_pb::AttachmentIdProto::Clear(); clear_has_id(); } inline const ::sync_pb::AttachmentIdProto& AttachmentMetadataRecord::id() const { #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER return id_ != NULL ? *id_ : *default_instance().id_; #else return id_ != NULL ? *id_ : *default_instance_->id_; #endif } inline ::sync_pb::AttachmentIdProto* AttachmentMetadataRecord::mutable_id() { set_has_id(); if (id_ == NULL) id_ = new ::sync_pb::AttachmentIdProto; return id_; } inline ::sync_pb::AttachmentIdProto* AttachmentMetadataRecord::release_id() { clear_has_id(); ::sync_pb::AttachmentIdProto* temp = id_; id_ = NULL; return temp; } inline void AttachmentMetadataRecord::set_allocated_id(::sync_pb::AttachmentIdProto* id) { delete id_; id_ = id; if (id) { set_has_id(); } else { clear_has_id(); } } // optional bool is_on_server = 2; inline bool AttachmentMetadataRecord::has_is_on_server() const { return (_has_bits_[0] & 0x00000002u) != 0; } inline void AttachmentMetadataRecord::set_has_is_on_server() { _has_bits_[0] |= 0x00000002u; } inline void AttachmentMetadataRecord::clear_has_is_on_server() { _has_bits_[0] &= ~0x00000002u; } inline void AttachmentMetadataRecord::clear_is_on_server() { is_on_server_ = false; clear_has_is_on_server(); } inline bool AttachmentMetadataRecord::is_on_server() const { return is_on_server_; } inline void AttachmentMetadataRecord::set_is_on_server(bool value) { set_has_is_on_server(); is_on_server_ = value; } // ------------------------------------------------------------------- // AttachmentMetadata // repeated .sync_pb.AttachmentMetadataRecord record = 1; inline int AttachmentMetadata::record_size() const { return record_.size(); } inline void AttachmentMetadata::clear_record() { record_.Clear(); } inline const ::sync_pb::AttachmentMetadataRecord& AttachmentMetadata::record(int index) const { return record_.Get(index); } inline ::sync_pb::AttachmentMetadataRecord* AttachmentMetadata::mutable_record(int index) { return record_.Mutable(index); } inline ::sync_pb::AttachmentMetadataRecord* AttachmentMetadata::add_record() { return record_.Add(); } inline const ::google::protobuf::RepeatedPtrField< ::sync_pb::AttachmentMetadataRecord >& AttachmentMetadata::record() const { return record_; } inline ::google::protobuf::RepeatedPtrField< ::sync_pb::AttachmentMetadataRecord >* AttachmentMetadata::mutable_record() { return &record_; } // @@protoc_insertion_point(namespace_scope) } // namespace sync_pb // @@protoc_insertion_point(global_scope) #endif // PROTOBUF_attachments_2eproto__INCLUDED
9ff3df2f24aa59f5e48a06136b291efada665fa6
24a0c4835a70f852c2a5c0f1890afeedd6573e19
/logging/logd/SerializedLogChunk.cpp
a512bf33b82d47ea04dc78b5ab3d5fe4f5a47216
[]
no_license
jiangshide/android-system
cbe903883b4334be718f98b47910640515f1190e
ef92d4e47f51e84d2e7ed3affbeadabeafde2cd2
refs/heads/main
2023-06-09T01:52:12.061540
2021-06-21T03:00:05
2021-06-21T03:00:05
378,790,086
0
0
null
null
null
null
UTF-8
C++
false
false
4,441
cpp
/* * Copyright (C) 2020 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 "SerializedLogChunk.h" #include <android-base/logging.h> #include "CompressionEngine.h" #include "SerializedFlushToState.h" SerializedLogChunk::~SerializedLogChunk() { CHECK_EQ(reader_ref_count_, 0U); } void SerializedLogChunk::Compress() { CHECK_EQ(compressed_log_.size(), 0U); CompressionEngine::GetInstance().Compress(contents_, write_offset_, compressed_log_); LOG(VERBOSE) << "Compressed Log, buffer max size: " << contents_.size() << " size used: " << write_offset_ << " compressed size: " << compressed_log_.size(); } // TODO: Develop a better reference counting strategy to guard against the case where the writer is // much faster than the reader, and we needlessly compess / decompress the logs. void SerializedLogChunk::IncReaderRefCount() { if (++reader_ref_count_ != 1 || writer_active_) { return; } contents_.Resize(write_offset_); CompressionEngine::GetInstance().Decompress(compressed_log_, contents_); } void SerializedLogChunk::DecReaderRefCount() { CHECK_NE(reader_ref_count_, 0U); if (--reader_ref_count_ != 0) { return; } if (!writer_active_) { contents_.Resize(0); } } void SerializedLogChunk::AttachReader(SerializedFlushToState* reader) { readers_.emplace_back(reader); IncReaderRefCount(); } void SerializedLogChunk::DetachReader(SerializedFlushToState* reader) { auto it = std::find(readers_.begin(), readers_.end(), reader); CHECK(readers_.end() != it); readers_.erase(it); DecReaderRefCount(); } void SerializedLogChunk::NotifyReadersOfPrune(log_id_t log_id) { // Readers will call DetachReader() in their Prune() call, so we make a copy of the list first. auto readers = readers_; for (auto& reader : readers) { reader->Prune(log_id); } } bool SerializedLogChunk::ClearUidLogs(uid_t uid, log_id_t log_id, LogStatistics* stats) { CHECK_EQ(reader_ref_count_, 0U); if (write_offset_ == 0) { return true; } IncReaderRefCount(); int read_offset = 0; int new_write_offset = 0; while (read_offset < write_offset_) { const auto* entry = log_entry(read_offset); if (entry->uid() == uid) { read_offset += entry->total_len(); if (stats != nullptr) { stats->Subtract(entry->ToLogStatisticsElement(log_id)); } continue; } size_t entry_total_len = entry->total_len(); if (read_offset != new_write_offset) { memmove(contents_.data() + new_write_offset, contents_.data() + read_offset, entry_total_len); } read_offset += entry_total_len; new_write_offset += entry_total_len; } if (new_write_offset == 0) { DecReaderRefCount(); return true; } // Clear the old compressed logs and set write_offset_ appropriately to compress the new // partially cleared log. if (new_write_offset != write_offset_) { write_offset_ = new_write_offset; if (!writer_active_) { compressed_log_.Resize(0); Compress(); } } DecReaderRefCount(); return false; } bool SerializedLogChunk::CanLog(size_t len) { return write_offset_ + len <= contents_.size(); } SerializedLogEntry* SerializedLogChunk::Log(uint64_t sequence, log_time realtime, uid_t uid, pid_t pid, pid_t tid, const char* msg, uint16_t len) { auto new_log_address = contents_.data() + write_offset_; auto* entry = new (new_log_address) SerializedLogEntry(uid, pid, tid, sequence, realtime, len); memcpy(entry->msg(), msg, len); write_offset_ += entry->total_len(); highest_sequence_number_ = sequence; return entry; }
d4ff2d61107d0c5304437f99fea203da88ec7afe
5470644b5f0834b9646649da365c96101a2f9b2a
/Sources/Elastos/Frameworks/Droid/Base/Core/src/text/style/CTypefaceSpan.cpp
e4eb112303fd6c6b393bbdd0130dd608dc6a9037
[]
no_license
dothithuy/ElastosRDK5_0
42372da3c749170581b5ee9b3884f4a27ae81608
2cf231e9f09f8b3b8bcacb11080b4a87d047833f
refs/heads/master
2021-05-13T15:02:22.363934
2015-05-25T01:54:38
2015-05-25T01:54:38
116,755,452
1
0
null
2018-01-09T02:33:06
2018-01-09T02:33:06
null
UTF-8
C++
false
false
987
cpp
#include "text/style/CTypefaceSpan.h" #include "ext/frameworkext.h" namespace Elastos { namespace Droid { namespace Text { namespace Style { ICHARACTERSTYLE_METHODS_IMPL(CTypefaceSpan, TypefaceSpan, TypefaceSpan) IMETRICAFFECTINGSPAN_METHODS_IMPL(CTypefaceSpan, TypefaceSpan, TypefaceSpan) IPARCELABLESPAN_METHODS_IMPL(CTypefaceSpan, TypefaceSpan, TypefaceSpan) PInterface CTypefaceSpan::Probe( /* [in] */ REIID riid) { return _CTypefaceSpan::Probe(riid); } ECode CTypefaceSpan::GetFamily( /* [out] */ String* ret) { VALIDATE_NOT_NULL(ret); *ret = TypefaceSpan::GetFamily(); return NOERROR; } ECode CTypefaceSpan::constructor( /* [in] */ const String& family) { Init(family); return NOERROR; } ECode CTypefaceSpan::constructor() { return NOERROR; } ECode CTypefaceSpan::constructor( /* [in] */ IParcel* src) { Init(src); return NOERROR; } } // namespace Style } // namespace Text } // namepsace Droid } // namespace Elastos
da74998ee77dca890f14c13553f198e01da77915
25a04e5bd2ebc3af032471cb07c885aacdb78e73
/XVideoEdit/src/XVideoEdit/XVideoUI.cpp
6b95fe53dd45d082ffce185a3cfe3ce932ca009f
[]
no_license
wuchuanrui/Test
7f2491e208ee12ddb10d58aadbebd89d863e476f
d85ab91e3fac109bbcf234ed14d5f7d2ff37682d
refs/heads/master
2020-05-27T00:17:53.614861
2019-09-02T12:06:33
2019-09-02T12:34:28
188,416,275
0
0
null
null
null
null
GB18030
C++
false
false
11,468
cpp
#include "XVideoUI.h" #include<QFileDialog> #include<string> #include<QMessageBox> #include<opencv2/core.hpp> #include<opencv2/imgcodecs.hpp> #include<opencv2/imgproc.hpp> #include<opencv2/highgui.hpp> #include <QMouseEvent> #include"XVideoThread.h" #include"XVideoFilter.h" #include"XAudio.h" using namespace std; // flag: 维护按下滑动条的状态 static bool pressSlider = false; // 根据标志位:调用不同的函数 static bool isExport = false; // 默认是 RGB static bool isGray = true; // 标示: 是否添加水印 static bool isMark = false; // 标示: 是否添加视频融合 static bool isBlend = false; // 视频合并 static bool isMerge = false; XVideoUI::XVideoUI(QWidget *parent) : QWidget(parent) { ui.setupUi(this); // 将 窗口的标题栏 去掉 setWindowFlags(Qt::FramelessWindowHint); // Qt 中默认不支持 Mat 类型作为信号 传输,需要注册 qRegisterMetaType<cv::Mat>("cv::Mat"); // 关联 相应的信号和槽函数 // SetImage(cv::Mat) 绘制图像到 ui.src1Video 中 QObject::connect(XVideoThread::GetInstance(), SIGNAL(ViewImage1(cv::Mat)), ui.src1Video, SLOT(SetImage(cv::Mat))); QObject::connect(XVideoThread::GetInstance(), SIGNAL(ViewImage2(cv::Mat)), ui.src02Video, SLOT(SetImage(cv::Mat))); // SetImage(cv::Mat) 绘制图像到 ui.desVideo 中 QObject::connect(XVideoThread::GetInstance(), SIGNAL(ViewDes(cv::Mat)), ui.desVideo, SLOT(SetImage(cv::Mat))); QObject::connect(XVideoThread::GetInstance(), SIGNAL(saveEnd()), this, SLOT(exportEnd())); startTimer(40); // 开启定时器,每四十秒调用定时器事件,刷新进度条 } // 重载 定时器事件 void XVideoUI::timerEvent(QTimerEvent* e) { // 滑动条被按下,不刷新播放视频界面 if (pressSlider) return; double pos = XVideoThread::GetInstance()->getPos(); // 设置 滑动条的值 ui.playSlider->setValue(pos * 1000); } // 点击 "打开" 按钮,触发信号,调用槽函数 void XVideoUI::Open() { // 点击打开按钮,弹出选择文件对话框,让用户选择文件 // this 表示 XVideoUI.ui 主界面 fromLocal8Bit 中文转码 QString name = QFileDialog::getOpenFileName(this, QString::fromLocal8Bit("请选择要播放的视频文件!")); if (name.isEmpty()) return; string fileName = name.toLocal8Bit().data(); // 将 name 中文转码 // 打开视频文件 if (!XVideoThread::GetInstance()->OpenSrc1(fileName)) { QMessageBox::information(this, "error", QString::fromLocal8Bit("打开文件失败!")); return; } XVideoUI::Play(); // 打开视频默认播放 } // 视频开始播放 void XVideoUI::Play() { // 点击 "开始" ,显示 "暂停" 按钮,隐藏"开始"按钮 ui.pauseButton->show(); ui.pauseButton->setGeometry(ui.playButton->geometry()); ui.playButton->hide(); XVideoThread::GetInstance()->Play(); } // 视频暂停播放 void XVideoUI::Pause() { // 点击 "暂停" ,显示 "开始" 按钮,隐藏"暂停"按钮 ui.playButton->show(); ui.pauseButton->hide(); XVideoThread::GetInstance()->Pause(); } // 按下滑动条,不刷新播放视频界面 void XVideoUI::sliderPress() { pressSlider = true; } // 释放滑动条,才刷新播放视频界面 void XVideoUI::sliderRelease() { pressSlider = false; } // 滑动条拖动:pos 获取当前位置 void XVideoUI::setPos(int pos) { // 1000:滑动条的总长度 pos/1000.0: 比例 XVideoThread::GetInstance()->seek((double)pos / 1000.0); } // "设置" 按钮槽函数 void XVideoUI::set() { XVideoFilter::get()->clear(); // Bug 要清一下 isGray = true; // 添加水印 if (isMark) { double x = ui.markXspin->value(); double y = ui.markYspin->value(); double a = ui.markAspin->value(); XVideoFilter::get()->Add({ XTASK_MARK ,{ x,y,a } }); } // 视频裁剪 bool isClip = false; double cx = ui.XClipSpin->value(); double cy = ui.YClipSpin->value(); double cw = ui.widthSpin->value(); double ch = ui.heightSpin->value(); if (cx + cy + cw + ch > 0.0001) { isClip = true; XVideoFilter::get()->Add(XTask{ XTASK_CLIP,{ cx,cy,cw,ch } }); double cWidth = XVideoThread::GetInstance()->width; double cHeight = XVideoThread::GetInstance()->height; // 将 裁剪过后的图像 放大到与原图像大小一致 // 不然会发生冲突,无法导出视频 XVideoFilter::get()->Add(XTask{ XTASK_RESIZE,{ cWidth,cHeight } }); } // 图像金字塔 bool isPy = false;// 维护着:如果做图像金字塔就不要做 图像尺寸调整 int downValue = ui.pyDownSpinBox->value(); int upValue = ui.pyUpSpinBox->value(); // 原图大小 int w = XVideoThread::GetInstance()->width; int h = XVideoThread::GetInstance()->height; // 拉普拉斯金字塔 if (upValue > 0) { isPy = true; XVideoFilter::get()->Add(XTask { XTASK_PYUP,{ (double)upValue } }); for (int i = 0; i < upValue; i++) { // 拉普拉斯金字塔 向上采样 w = w * 2; h = h * 2; } ui.widthSpinBox->setValue(w); ui.heightSpinBox->setValue(h); } // 高斯金字塔 if (downValue > 0) { isPy = true; XVideoFilter::get()->Add(XTask { XTASK_PYDOWN,{(double)downValue }}); for (int i = 0; i < downValue; i++) { // 高斯金字塔 向下采样 w = w / 2; h = h / 2; } ui.widthSpinBox->setValue(w); ui.heightSpinBox->setValue(h); } // 设置 图像尺寸 double width = ui.widthSpinBox->value(); double height = ui.heightSpinBox->value(); if (!isMerge && !isClip && !isPy && ui.widthSpinBox->value() > 0 && ui.heightSpinBox->value() > 0 ) { XVideoFilter::get()->Add(XTask{ XTASK_RESIZE,{ width,height }}); } // 设置 对比度 和 亮度 if (ui.brightSpinBox->value()<0|| ui.brightSpinBox->value()>100 || ui.contrastSpinBox->value()<0.0|| ui.contrastSpinBox->value()>3.0) { return; } // 添加一个任务 C++ 11 的写法 XVideoFilter::get()->Add(XTask{ XTASK_GAIN, { (double)ui.brightSpinBox->value(), (double)ui.contrastSpinBox->value() } }); // 设置 灰度图 if (1 == ui.grayComboBox->currentIndex()) { XVideoFilter::get()->Add(XTask{ XTASK_GRAY }); isGray = false; } // 设置 图像旋转 if (1 == ui.rotateCombo->currentIndex()) { XVideoFilter::get()->Add(XTask{ XTASK_ROTATE_90 }); } if (2 == ui.rotateCombo->currentIndex()) { XVideoFilter::get()->Add(XTask{ XTASK_ROTATE_180 }); } if (3 == ui.rotateCombo->currentIndex()) { XVideoFilter::get()->Add(XTask{ XTASK_ROTATE_270 }); } // 设置 镜像 if (1 == ui.flipCombo->currentIndex()) { XVideoFilter::get()->Add(XTask{ XTASK_FLIP_X }); } if (2 == ui.flipCombo->currentIndex()) { XVideoFilter::get()->Add(XTask{ XTASK_FLIP_Y }); } if (3 == ui.flipCombo->currentIndex()) { XVideoFilter::get()->Add(XTask{ XTASK_FLIP_XY }); } // 视频融合 if (isBlend) { double a = ui.blendDoubleSpin->value(); XVideoFilter::get()->Add(XTask{ XTASK_BLEND,{a} }); } // 视频合并 if (isMerge) { double h2 = XVideoThread::GetInstance()->height02; double h1 = XVideoThread::GetInstance()->height; // 求出 src02 的宽 按比例缩放 int w = XVideoThread::GetInstance()->width02 * (h2 / h1); XVideoFilter::get()->Add(XTask{ XTASK_MERGE }); // 图像尺寸调整,为了能够导出视频文件 ui.widthSpinBox->setValue(XVideoThread::GetInstance()->width + w); ui.heightSpinBox->setValue(h1); } } // "导出" 按钮 槽函数 void XVideoUI::Export() { if (isExport) { // 为 true 是停止导出视频 XVideoThread::GetInstance()->stopSave(); // 下一次点击按钮,导出视频 isExport = false; ui.exportButton->setText(QString::fromLocal8Bit("导出视频")); return; } QString name = QFileDialog::getSaveFileName(this, QString::fromLocal8Bit("保存视频"),"out01.avi"); // 不要忘了 边界检测 if (name.isEmpty()) return; std::string fileName = name.toLocal8Bit().data(); int width = ui.widthSpinBox->value(); int height = ui.heightSpinBox->value(); if(XVideoThread::GetInstance()->startSave(fileName, width, height,isGray)) { isExport = true; ui.exportButton->setText(QString::fromLocal8Bit("停止导出")); } } // 导出到视频结尾位置: Text 发生改变提示 void XVideoUI::exportEnd() { isExport = false; ui.exportButton->setText(QString::fromLocal8Bit("导出视频")); // 导出 视频结束 , 抽取音频,然后合并 音频 和 视频文件 // 选择打开的 音视频文件名 string src = XVideoThread::GetInstance()->src01File; // 导出时指定的 音视频文件名 string des = XVideoThread::GetInstance()->desFile; int ss = 0; int t = 0; ss = XVideoThread::GetInstance()->totalMs * ((double)ui.leftHorizontalSlider->value() / 1000.); int end = XVideoThread::GetInstance()->totalMs * ((double)ui.rightHorizontalSlider->value() / 1000.); t = end - ss; XAudio::getInstance()->ExportA(src, src + ".mp3",ss,t); string tmp = des + ".avi"; QFile::remove(tmp.c_str()); QFile::rename(des.c_str(), tmp.c_str()); XAudio::getInstance()->Merge(tmp, src + ".mp3", des); } // 点击"添加水印" 按钮,弹出文件对话框 void XVideoUI::Mark() { isBlend = false; // 添加水印,就不要添加视频融合了 QString name = QFileDialog::getOpenFileName(this, QString::fromLocal8Bit("请选择添加水印的图片")); if (name.isEmpty()) { return; } std::string fileName = name.toLocal8Bit().data(); cv::Mat mark = cv::imread(fileName); if (mark.empty()) return; XVideoThread::GetInstance()->setMarkMat(mark); isMark = true; } // "视频融合" 槽函数 void XVideoUI::Blend() { isMark = false; // 添加视频融合,就不要添加水印了 QString name = QFileDialog::getOpenFileName(this, QString::fromLocal8Bit("请选择添加融合的视频文件")); if (name.isEmpty()) { return; } std::string fileName = name.toLocal8Bit().data(); // 打开 二号视频源文件 isBlend = XVideoThread::GetInstance()->OpenSrc02(fileName); } // 合并视频 void XVideoUI::Merge() { isMark = false; // 添加合并视频,就不要添加水印了 isBlend = false; // 添加合并视频,就不要添加视频融合了 QString name = QFileDialog::getOpenFileName(this, QString::fromLocal8Bit("请选择添加合并的视频文件")); if (name.isEmpty()) { return; } std::string fileName = name.toLocal8Bit().data(); // 打开 二号视频源文件 isMerge = XVideoThread::GetInstance()->OpenSrc02(fileName); } //剪辑 视频 start位置 void XVideoUI::Left(int pos) { XVideoThread::GetInstance()->setBegin((double)pos / 1000); setPos(pos); // 让 播放进度的滑动条 跟 left 滑动条位置一致 } // 剪辑 视频 end 位置 void XVideoUI::Right(int pos) { XVideoThread::GetInstance()->setEnd((double)pos / 1000); } void XVideoUI::mousePressEvent(QMouseEvent *event) { //当鼠标左键点击时. if (event->button() == Qt::LeftButton) { m_move = true; //记录鼠标的世界坐标. m_startPoint = event->globalPos(); //记录窗体的世界坐标. m_windowPoint = this->frameGeometry().topLeft(); } } void XVideoUI::mouseMoveEvent(QMouseEvent *event) { if (event->buttons() & Qt::LeftButton) { //移动中的鼠标位置相对于初始位置的相对位置. QPoint relativePos = event->globalPos() - m_startPoint; //然后移动窗体即可. this->move(m_windowPoint + relativePos); } } void XVideoUI::mouseReleaseEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) { //改变移动状态. m_move = false; } }
1ad1f2905f101c0650a6521fc45c6df8a3dbd2e4
6a15cee126402eb8550ff91119d10a41c128c8fb
/src/lib/SIMD_Optimized_Kernels/Kernels/Muscle_Differential/Muscle_Differential.cpp
d647c1a0629957544b4a989c41b1d6038948e97f
[]
no_license
thecsapprentice/SBSS_Public
da407dcf53285e969108a2f7f696a6d1ccf478a1
057296aa11b2934fb3d6ea0d636139c5d93f96a4
refs/heads/master
2020-06-07T05:55:33.295414
2017-04-13T15:17:57
2017-04-13T15:17:57
192,942,024
0
0
null
null
null
null
UTF-8
C++
false
false
2,954
cpp
//##################################################################### // Copyright (c) 2011-2013 Nathan Mitchell, Eftychios Sifakis. // This file is covered by the FreeBSD license. Please refer to the // license.txt file for more information. //##################################################################### #ifndef SUBROUTINE_Muscle_Differential #include <assert.h> #include "KernelCommon.h" #else namespace { #endif template<class Tw,class T_DATA=void,class I_DATA=void> #ifdef SUBROUTINE_Muscle_Differential inline #endif void Muscle_Differential(T_DATA (&dP_fiber)[9], const T_DATA (&dF)[9], const T_DATA (&fiber)[3], const T_DATA (&Ffiber)[3], const T_DATA (&c1), const T_DATA (&c2) ) { #define M_I(x,y) (y * 3 + x ) typedef Number<Tw> Tn; Tn fiber0; Tn fiber1; Tn fiber2; Tn F_fiber0; Tn F_fiber1; Tn F_fiber2; Tn dF0; Tn dF1; Tn dF2; Tn dw0; Tn dw1; Tn dw2; Tn q0; Tn q1; Tn q2; Tn dw_dp; Tn temp; Tn C1; Tn C2; Tn dP_fiber0; Tn dP_fiber1; Tn dP_fiber2; Vector3<Tn> vdF_r; Vector3<Tn> vfiber; Vector3<Tn> vdw; Vector3<Tn> vF_fiber; Vector3<Tn> vq; Vector3<Tn> vdP_fiber; vfiber.Load_Aligned(fiber); // // TV dw = dF*fiber; // // Load first row of dF vdF_r.Load_Aligned(dF[M_I(0,0)],dF[M_I(0,1)],dF[M_I(0,2)]); vdw.x = vdF_r.DotProduct(vfiber); // Load second row of dF vdF_r.Load_Aligned(dF[M_I(1,0)],dF[M_I(1,1)],dF[M_I(1,2)]); vdw.y = vdF_r.DotProduct(vfiber); // Load third row of dF vdF_r.Load_Aligned(dF[M_I(2,0)],dF[M_I(2,1)],dF[M_I(2,2)]); vdw.z = vdF_r.DotProduct(vfiber); // // TV q = c1 * dw + c2 * VECTOR<T,d>::Dot_Product(dw,F_fiber) * F_fiber; // vF_fiber.Load_Aligned(Ffiber); C1.Load(c1); C2.Load(c2); //-- //-- TV q = C1 * dw + C2 * VECTOR<T,d>::Dot_Product(dw,F_fiber) * F_fiber; //-- vq = (vdw * C1) + (vF_fiber * (C2 * vdw.DotProduct(vF_fiber))); // // MATRIX<T,d> dP_fiber=MATRIX<T,d>::Outer_Product(q,fiber); // vdP_fiber = vfiber*vq.x; vdP_fiber.Store( dP_fiber[M_I(0,0)], dP_fiber[M_I(0,1)], dP_fiber[M_I(0,2)] ); vdP_fiber = vfiber*vq.y; vdP_fiber.Store( dP_fiber[M_I(1,0)], dP_fiber[M_I(1,1)], dP_fiber[M_I(1,2)] ); vdP_fiber = vfiber*vq.z; vdP_fiber.Store( dP_fiber[M_I(2,0)], dP_fiber[M_I(2,1)], dP_fiber[M_I(2,2)] ); } #ifdef SUBROUTINE_Muscle_Differential } #else #define INSTANCE_KERNEL_Muscle_Differential(WIDTH) WIDETYPE(float,WIDTH) (&dP_fiber)[9], const WIDETYPE(float,WIDTH) (&dF)[9], const WIDETYPE(float,WIDTH) (&fiber)[3], const WIDETYPE(float,WIDTH) (&Ffiber)[3], const WIDETYPE(float,WIDTH) (&c1), const WIDETYPE(float,WIDTH) (&c2) INSTANCE_KERNEL(Muscle_Differential); #undef INSTANCE_KERNEL_Muscle_Differential #endif
b2cce29f74c4a0c00ff34bdda67fbb8f2623727b
fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd
/third_party/WebKit/Source/platform/network/ParsedContentDisposition.h
7cb7686cf820f62db93cbc7865ade65e96704aae
[ "BSD-3-Clause", "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft" ]
permissive
wzyy2/chromium-browser
2644b0daf58f8b3caee8a6c09a2b448b2dfe059c
eb905f00a0f7e141e8d6c89be8fb26192a88c4b7
refs/heads/master
2022-11-23T20:25:08.120045
2018-01-16T06:41:26
2018-01-16T06:41:26
117,618,467
3
2
BSD-3-Clause
2022-11-20T22:03:57
2018-01-16T02:09:10
null
UTF-8
C++
false
false
1,330
h
// 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. #ifndef ParsedContentDisposition_h #define ParsedContentDisposition_h #include "platform/PlatformExport.h" #include "platform/network/ParsedContentHeaderFieldParameters.h" #include "platform/wtf/Allocator.h" #include "platform/wtf/HashMap.h" #include "platform/wtf/text/StringHash.h" namespace blink { // Parses the content of a Content-Disposition header field into disposition // type and parameters and stores them. class PLATFORM_EXPORT ParsedContentDisposition final { STACK_ALLOCATED(); public: using Mode = ParsedContentHeaderFieldParameters::Mode; explicit ParsedContentDisposition(const String&, Mode = Mode::kNormal); String Type() const { return type_; } String Filename() const; // Note that in the case of multiple values for the same name, the last value // is returned. String ParameterValueForName(const String& name) const { return parameters_.ParameterValueForName(name); } size_t ParameterCount() const { return parameters_.ParameterCount(); } bool IsValid() const { return parameters_.IsValid(); } private: String type_; ParsedContentHeaderFieldParameters parameters_; }; } // namespace blink #endif
b9a24c3fcf67d921d06d1cbdf1992dcfea984d66
90801f3b268270b21b5de8065cdbdbf4c0147e39
/Source/Common/Game/Projectile.h
34e955fb885d302c7777337928112e2b6d342c48
[]
no_license
gord0185/FINAL_ASSIGNMENT
9d6f69da57807971c83ff5f31697fbc3e678f6f7
d9b6f99be353e266cc26eee4ddcf7bc9618d1d48
refs/heads/master
2020-05-17T12:32:32.929169
2013-12-12T20:46:41
2013-12-12T20:46:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
934
h
// // Projectile.h // GAM-1532 OSX Game // // Created by Ryan Gordon on 2013-11-28. // Copyright (c) 2013 Algonquin College. All rights reserved. // #ifndef PROJECTILE_H #define PROJECTILE_H #include "GameObject.h" class ProjectileListener; class Projectile : public GameObject { public: Projectile(ProjectileListener* listener, int damage, float velocity); virtual ~Projectile(); virtual void update(double delta); virtual void paint(); virtual void reset(); virtual const char* getType(); virtual void setTarget(float x, float y); virtual int getDamage(); protected: ProjectileListener* m_Listener; int m_Damage; float m_Velocity; float m_Angle; float m_TargetX; float m_TargetY; private: OpenGLTexture* m_ProjectileTexture; }; class ProjectileListener { public: virtual void handlePlayerCollision(Projectile* projectile) = 0; virtual void handleBoundsCollision(Projectile* projectile) = 0; }; #endif
b7d3ef3bde475539c215ab3624d292c7e66ce994
8dc84558f0058d90dfc4955e905dab1b22d12c08
/chrome/browser/renderer_context_menu/render_view_context_menu_browsertest_util.cc
67e7041f0182cb77b096725619db584cd9fdd5c6
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
meniossin/src
42a95cc6c4a9c71d43d62bc4311224ca1fd61e03
44f73f7e76119e5ab415d4593ac66485e65d700a
refs/heads/master
2022-12-16T20:17:03.747113
2020-09-03T10:43:12
2020-09-03T10:43:12
263,710,168
1
0
BSD-3-Clause
2020-05-13T18:20:09
2020-05-13T18:20:08
null
UTF-8
C++
false
false
2,237
cc
// Copyright 2014 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/renderer_context_menu/render_view_context_menu_browsertest_util.h" #include "base/bind.h" #include "base/location.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/browser/renderer_context_menu/render_view_context_menu.h" #include "content/public/test/test_utils.h" ContextMenuNotificationObserver::ContextMenuNotificationObserver( int command_to_execute) : command_to_execute_(command_to_execute) { RenderViewContextMenu::RegisterMenuShownCallbackForTesting(base::BindOnce( &ContextMenuNotificationObserver::MenuShown, base::Unretained(this))); } ContextMenuNotificationObserver::~ContextMenuNotificationObserver() { } void ContextMenuNotificationObserver::MenuShown( RenderViewContextMenu* context_menu) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&ContextMenuNotificationObserver::ExecuteCommand, base::Unretained(this), context_menu)); } void ContextMenuNotificationObserver::ExecuteCommand( RenderViewContextMenu* context_menu) { context_menu->ExecuteCommand(command_to_execute_, 0); context_menu->Cancel(); } ContextMenuWaiter::ContextMenuWaiter() { RenderViewContextMenu::RegisterMenuShownCallbackForTesting( base::BindOnce(&ContextMenuWaiter::MenuShown, base::Unretained(this))); } ContextMenuWaiter::~ContextMenuWaiter() { } void ContextMenuWaiter::MenuShown(RenderViewContextMenu* context_menu) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&ContextMenuWaiter::Cancel, base::Unretained(this), context_menu)); } void ContextMenuWaiter::WaitForMenuOpenAndClose() { run_loop_.Run(); } content::ContextMenuParams& ContextMenuWaiter::params() { return params_; } void ContextMenuWaiter::Cancel(RenderViewContextMenu* context_menu) { params_ = context_menu->params(); context_menu->Cancel(); run_loop_.Quit(); }
fa47380c045f3559a7f62429a22feedb4932db17
ce8bcdce184888ce53d9544ede34e77b408e3c1b
/Unused/CJ60Lib/Include/CJFlatHeaderCtrl.h
7c1aa915537da61ffa4cf4631b1822c44763e628
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
bolabola/gh0st
2637bd5f720faf49e86cafc9bcd8baa6845c3b48
ef5e362bb1ac22c0fc1353083e9b67e551aa9212
refs/heads/master
2020-07-29T08:50:04.546341
2019-09-20T07:51:36
2019-09-20T08:14:49
209,735,698
24
16
null
null
null
null
UTF-8
C++
false
false
3,825
h
// CJHeaderCtrl.h : header file // // Copyright ?1998-99 Kirk Stowell // mailto:[email protected] // http://www.codejockeys.com/kstowell/ // // This source code may be used in compiled form in any way you desire. // Source file(s) may be redistributed unmodified by any means PROVIDING // they are not sold for profit without the authors expressed written consent, // and providing that this notice and the authors name and all copyright // notices remain intact. If the source code is used in any commercial // applications then a statement along the lines of: // // "Portions Copyright ?1998-99 Kirk Stowell" must be included in the // startup banner, "About" box or printed documentation. An email letting // me know that you are using it would be nice as well. That's not much to ask // considering the amount of work that went into this. // // This software is provided "as is" without express or implied warranty. Use // it at your own risk! The author accepts no liability for any damage/loss of // business that this product may cause. // // ========================================================================== // // Acknowledgements: // <> Many thanks to all of you, who have encouraged me to update my articles // and code, and who sent in bug reports and fixes. // <> Many thanks Zafir Anjum ([email protected]) for the tremendous job that // he has done with codeguru, enough can not be said, and for his article // 'Indicating sort order in header control' which is where the code for // the sorting arrows in the header comes from. // <> Many thanks to Microsoft for making the source code availiable for MFC. // Since most of this work is a modification from existing classes and // methods, this library would not have been possible. // // ========================================================================== // HISTORY: // ========================================================================== // 1.00 16 Jan 1999 - Initial release. // 1.01 31 Jan 1999 - Fixed problem with sort arrow drawn. If hditem // has an associated bitmap, the arrow is not drawn. // 1.02 24 Feb 1999 - Fixed repainting problem when header is moved or // window is resized. The class now uses log font // instead of hard coded Tahoma font. // ========================================================================== // ///////////////////////////////////////////////////////////////////////////// #ifndef __CJFLATHEADERCTRL_H__ #define __CJFLATHEADERCTRL_H__ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 ///////////////////////////////////////////////////////////////////////////// // CCJFlatHeaderCtrl window class AFX_EXT_CLASS CCJFlatHeaderCtrl : public CHeaderCtrl { // Construction public: CCJFlatHeaderCtrl(); // Attributes public: BOOL m_bFlatHeader; BOOL m_bBoldFont; CFont m_HeaderFont; int m_nOffset; BOOL m_bLBtnDown; // Operations public: void FlatHeader(BOOL bBoldFont = TRUE); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CCJFlatHeaderCtrl) public: virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct); //}}AFX_VIRTUAL // Implementation public: void DrawFlatBorder(); int SetSortImage( int nCol, BOOL bAsc ); virtual ~CCJFlatHeaderCtrl(); // Generated message map functions protected: //{{AFX_MSG(CCJFlatHeaderCtrl) afx_msg void OnPaint(); afx_msg void OnWindowPosChanging(WINDOWPOS FAR* lpwndpos); //}}AFX_MSG DECLARE_MESSAGE_MAP() protected: int m_nSortCol; BOOL m_bSortAsc; }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Developer Studio will insert additional declarations immediately before the previous line. #endif // __CJFLATHEADERCTRL_H__
59081aeecd9ce243417eae6272eba14759bdec0e
f974b7130eb913ef9abd114947f5844002f00481
/Source/Math/Matrix4.h
05cbb0884cbbe41fc01a011d1e21aa65bb273301
[]
no_license
criptych/RE
3b56ec379eb14ba0fc39e44992aec5e81a21f6ab
6f852e17f64b42a9c3d4c79358bf18deb61c1502
refs/heads/master
2020-04-26T06:41:33.733633
2018-12-15T18:25:33
2018-12-15T18:25:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
24,771
h
#pragma once #include "MathUtil.h" #include "Vector4.h" #define MATRIX_COLUMN_MAJOR 1 struct Matrix4; // matrix 4x4 // column major by default, can toggle MATRIX_COLUMN_MAJOR // comments are mostly based on column major version __declspec(align(16)) struct Matrix4 { public: union { float m[4][4]; Vec128 m128[4]; // rows or columns based on which one we choose Vector4 mLine[4]; struct { Vector4 mScaledAxisX; Vector4 mScaledAxisY; Vector4 mScaledAxisZ; Vector4 mTranslation; }; }; Matrix4() {}; Matrix4(const Vector4& line0, const Vector4& line1, const Vector4& line2, const Vector4& line3) { mLine[0] = line0; mLine[1] = line1; mLine[2] = line2; mLine[3] = line3; } //Matrix4(Vec128 vec0, Vec128 vec1, Vec128 vec2, Vec128 vec3) //{ // m128[0] = vec0; // m128[1] = vec1; // m128[2] = vec2; // m128[3] = vec3; //} // const getter static __forceinline Matrix4 Identity() { const Matrix4 identity( VecSet(1.f, 0.f, 0.f, 0.f), VecSet(0.f, 1.f, 0.f, 0.f), VecSet(0.f, 0.f, 1.f, 0.f), VecSet(0.f, 0.f, 0.f, 1.f) ); return identity; } static __forceinline Matrix4 Zero() { const Matrix4 zero( VecZero(), VecZero(), VecZero(), VecZero() ); return zero; } // add inline Matrix4 operator+(const Matrix4& m) const { Matrix4 r; r.m128[0] = VecAdd(m128[0], m.m128[0]); r.m128[1] = VecAdd(m128[1], m.m128[1]); r.m128[2] = VecAdd(m128[2], m.m128[2]); r.m128[3] = VecAdd(m128[3], m.m128[3]); return r; } inline Matrix4& operator+=(const Matrix4& m) { m128[0] = VecAdd(m128[0], m.m128[0]); m128[1] = VecAdd(m128[1], m.m128[1]); m128[2] = VecAdd(m128[2], m.m128[2]); m128[3] = VecAdd(m128[3], m.m128[3]); return *this; } inline Matrix4& operator+=(float f) { Vec128 t = VecSet1(f); m128[0] = VecAdd(m128[0], t); m128[1] = VecAdd(m128[1], t); m128[2] = VecAdd(m128[2], t); m128[3] = VecAdd(m128[3], t); return *this; } // sub inline Matrix4 operator-(const Matrix4& m) const { Matrix4 r; r.m128[0] = VecSub(m128[0], m.m128[0]); r.m128[1] = VecSub(m128[1], m.m128[1]); r.m128[2] = VecSub(m128[2], m.m128[2]); r.m128[3] = VecSub(m128[3], m.m128[3]); return r; } inline Matrix4& operator-=(const Matrix4& m) { m128[0] = VecSub(m128[0], m.m128[0]); m128[1] = VecSub(m128[1], m.m128[1]); m128[2] = VecSub(m128[2], m.m128[2]); m128[3] = VecSub(m128[3], m.m128[3]); return *this; } // mul scalar inline Matrix4 operator*(float f) const { Matrix4 r; Vec128 t = VecSet1(f); r.m128[0] = VecMul(m128[0], t); r.m128[1] = VecMul(m128[1], t); r.m128[2] = VecMul(m128[2], t); r.m128[3] = VecMul(m128[3], t); return r; } inline Matrix4& operator*=(float f) { Vec128 t = VecSet1(f); m128[0] = VecMul(m128[0], t); m128[1] = VecMul(m128[1], t); m128[2] = VecMul(m128[2], t); m128[3] = VecMul(m128[3], t); return *this; } // div scalar inline Matrix4 operator/(float f) const { Matrix4 r; Vec128 t = VecSet1(f); r.m128[0] = VecDiv(m128[0], t); r.m128[1] = VecDiv(m128[1], t); r.m128[2] = VecDiv(m128[2], t); r.m128[3] = VecDiv(m128[3], t); return r; } inline Matrix4& operator/=(float f) { Vec128 t = VecSet1(f); m128[0] = VecDiv(m128[0], t); m128[1] = VecDiv(m128[1], t); m128[2] = VecDiv(m128[2], t); m128[3] = VecDiv(m128[3], t); return *this; } // mul vector inline Vector4 operator*(const Vector4& v) const { Vec128 r; r = VecMul(m128[0], VecSwizzle1(v.m128,0)); r = VecAdd(r, VecMul(m128[1], VecSwizzle1(v.m128,1))); r = VecAdd(r, VecMul(m128[2], VecSwizzle1(v.m128,2))); r = VecAdd(r, VecMul(m128[3], VecSwizzle1(v.m128,3))); return r; } // mul matrix inline Matrix4 operator*(const Matrix4& m) const { #if MATRIX_COLUMN_MAJOR const Vec128* vecA = m128; const Vec128* vecB = m.m128; #else const Vec128* vecA = m.m128; const Vec128* vecB = m128; #endif Matrix4 r; // line 0 r.m128[0] = VecMul(vecA[0], VecSwizzle1(vecB[0], 0)); r.m128[0] = VecAdd(r.m128[0], VecMul(vecA[1], VecSwizzle1(vecB[0], 1))); r.m128[0] = VecAdd(r.m128[0], VecMul(vecA[2], VecSwizzle1(vecB[0], 2))); r.m128[0] = VecAdd(r.m128[0], VecMul(vecA[3], VecSwizzle1(vecB[0], 3))); // line 1 r.m128[1] = VecMul(vecA[0], VecSwizzle1(vecB[1], 0)); r.m128[1] = VecAdd(r.m128[1], VecMul(vecA[1], VecSwizzle1(vecB[1], 1))); r.m128[1] = VecAdd(r.m128[1], VecMul(vecA[2], VecSwizzle1(vecB[1], 2))); r.m128[1] = VecAdd(r.m128[1], VecMul(vecA[3], VecSwizzle1(vecB[1], 3))); // line 2 r.m128[2] = VecMul(vecA[0], VecSwizzle1(vecB[2], 0)); r.m128[2] = VecAdd(r.m128[2], VecMul(vecA[1], VecSwizzle1(vecB[2], 1))); r.m128[2] = VecAdd(r.m128[2], VecMul(vecA[2], VecSwizzle1(vecB[2], 2))); r.m128[2] = VecAdd(r.m128[2], VecMul(vecA[3], VecSwizzle1(vecB[2], 3))); // line 3 r.m128[3] = VecMul(vecA[0], VecSwizzle1(vecB[3], 0)); r.m128[3] = VecAdd(r.m128[3], VecMul(vecA[1], VecSwizzle1(vecB[3], 1))); r.m128[3] = VecAdd(r.m128[3], VecMul(vecA[2], VecSwizzle1(vecB[3], 2))); r.m128[3] = VecAdd(r.m128[3], VecMul(vecA[3], VecSwizzle1(vecB[3], 3))); return r; } // compose two matrix A,B as transform by A then B. // for column major returns B*A // for row major return A*B inline Matrix4 Compose(const Matrix4& m) const { #if MATRIX_COLUMN_MAJOR return m * (*this); #else return (*this) * m; #endif } // compose two matrix A,B as transform by A then B. // for column major returns B*A // for row major return A*B static inline Matrix4 Compose(const Matrix4& m1, const Matrix4& m2) { return m1.Compose(m2); } inline Matrix4 GetTransposed() const { // from _MM_TRANSPOSE4_PS() Matrix4 r; Vec128 t0 = VecShuffle_0101(m128[0], m128[1]); // 00, 01, 10, 11 Vec128 t1 = VecShuffle_0101(m128[2], m128[3]); // 20, 21, 30, 31 Vec128 t2 = VecShuffle_2323(m128[0], m128[1]); // 02, 03, 12, 13 Vec128 t3 = VecShuffle_2323(m128[2], m128[3]); // 22, 23, 32, 33 r.m128[0] = VecShuffle(t0, t1, 0, 2, 0, 2); // 00, 10, 20, 30 r.m128[1] = VecShuffle(t0, t1, 1, 3, 1, 3); // 01, 11, 21, 31 r.m128[2] = VecShuffle(t2, t3, 0, 2, 0, 2); // 02, 12, 22, 32 r.m128[3] = VecShuffle(t2, t3, 1, 3, 1, 3); // 03, 13, 23, 33 return r; } // transpose but don't process last line // returns (00, 10, 20, 30), (01, 11, 21, 31), (02, 12, 22, 32), (undefined) inline Matrix4 GetTransposed43() const { // from _MM_TRANSPOSE4_PS() Matrix4 r; Vec128 t0 = VecShuffle_0101(m128[0], m128[1]); // 00, 01, 10, 11 Vec128 t1 = VecShuffle_0101(m128[2], m128[3]); // 20, 21, 30, 31 Vec128 t2 = VecShuffle_2323(m128[0], m128[1]); // 02, 03, 12, 13 Vec128 t3 = VecShuffle_2323(m128[2], m128[3]); // 22, 23, 32, 33 r.m128[0] = VecShuffle(t0, t1, 0, 2, 0, 2); // 00, 10, 20, 30 r.m128[1] = VecShuffle(t0, t1, 1, 3, 1, 3); // 01, 11, 21, 31 r.m128[2] = VecShuffle(t2, t3, 0, 2, 0, 2); // 02, 12, 22, 32 return r; } // returns (00, 10, 20, 23), (01, 11, 21, 23), (02, 12, 22, 23) __forceinline void Internal_GetTransposed3(Vec128& outTLine0, Vec128& outTLine1, Vec128& outTLine2) const { Vec128 t0 = VecShuffle_0101(m128[0], m128[1]); // 00, 01, 10, 11 Vec128 t1 = VecShuffle_2323(m128[0], m128[1]); // 02, 03, 12, 13 outTLine0 = VecShuffle(t0, m128[2], 0, 2, 0, 3); // 00, 10, 20, 23 outTLine1 = VecShuffle(t0, m128[2], 1, 3, 1, 3); // 01, 11, 21, 23 outTLine2 = VecShuffle(t1, m128[2], 0, 2, 2, 3); // 02, 12, 22, 23 } inline Matrix4 GetTransposed3() const { Matrix4 r; // transpose 3x3, we know m03 = m13 = m23 = 0 Internal_GetTransposed3(r.m128[0], r.m128[1], r.m128[2]); r.m128[3] = m128[3]; return r; } // inv(A) = Transpose(inv(Transpose(A))) // Inverse function is the same no matter column major or row major // this version treats it as column major inline Matrix4 GetInverse() const { // use block matrix method // A is a matrix, then i(A) or iA means inverse of A, A# (or A_ in code) means adjugate of A, |A| is determinant, tr(A) is trace // some properties: iA = A# / |A|, (AB)# = B#A#, (cA)# = c^(n-1)A#, |AB| = |A||B|, |cA| = c^n|A|, tr(AB) = tr(BA) // for 2x2 matrix: (A#)# = A, (cA)# = cA#, |-A| = |A|, |A+B| = |A| + |B| + tr(A#B), tr(A) = A0*A3 - A1*A2 // M is 4x4 matrix, we divide into 4 2x2 matrices // let M = | A B |, then iM = | i(A-BiDC) -iABi(D-CiAB) | = 1/|M| * | (|D|A - B(D#C))# (|B|C - D(A#B)#)# | // | C D | | -iDCi(A-BiDC) i(D-CiAB) | | (|C|B - A(D#C)#)# (|A|D - C(A#B))# | // we have property: |M| = |A|*|D-CiAB| = |D|*|A-BiDC| = |AD-BC| = |A||D| + |B||C| - tr((A#B)(D#C)) // we use __m128 to represent sub 2x2 column major matrix as A = | A0 A2 | // | A1 A3 | // sub matrices Vec128 A = VecShuffle_0101(m128[0], m128[1]); Vec128 C = VecShuffle_2323(m128[0], m128[1]); Vec128 B = VecShuffle_0101(m128[2], m128[3]); Vec128 D = VecShuffle_2323(m128[2], m128[3]); Vec128 detA = VecSet1(m[0][0] * m[1][1] - m[0][1] * m[1][0]); Vec128 detC = VecSet1(m[0][2] * m[1][3] - m[0][3] * m[1][2]); Vec128 detB = VecSet1(m[2][0] * m[3][1] - m[2][1] * m[3][0]); Vec128 detD = VecSet1(m[2][2] * m[3][3] - m[2][3] * m[3][2]); #if 0 // for determinant, float version is faster // determinant as (|A| |C| |B| |D|) Vec128 detSub = VecSub( VecMul(VecShuffle(m128[0], m128[2], 0,2,0,2), VecShuffle(m128[1], m128[3], 1,3,1,3)), VecMul(VecShuffle(m128[0], m128[2], 1,3,1,3), VecShuffle(m128[1], m128[3], 0,2,0,2)) ); Vec128 detA = VecSwizzle1(detSub, 0); Vec128 detC = VecSwizzle1(detSub, 1); Vec128 detB = VecSwizzle1(detSub, 2); Vec128 detD = VecSwizzle1(detSub, 3); #endif // let iM = 1/|M| * | X Y | // | Z W | // D#C Vec128 D_C = Mat2AdjMul_CM(D, C); // A#B Vec128 A_B = Mat2AdjMul_CM(A, B); // X# = |D|A - B(D#C) Vec128 X_ = VecSub(VecMul(detD, A), Mat2Mul_CM(B, D_C)); // W# = |A|D - C(A#B) Vec128 W_ = VecSub(VecMul(detA, D), Mat2Mul_CM(C, A_B)); // |M| = |A|*|D| + ... (continue later) Vec128 detM = VecMul(detA, detD); // Y# = |B|C - D(A#B)# Vec128 Y_ = VecSub(VecMul(detB, C), Mat2MulAdj_CM(D, A_B)); // Z# = |C|B - A(D#C)# Vec128 Z_ = VecSub(VecMul(detC, B), Mat2MulAdj_CM(A, D_C)); // |M| = |A|*|D| + |B|*|C| ... (continue later) detM = VecAdd(detM, VecMul(detB, detC)); // tr((A#B)(D#C)) Vec128 tr = VecDotV(A_B, VecSwizzle(D_C, 0,2,1,3)); // |M| = |A|*|D| + |B|*|C| - tr((A#B)(D#C)) detM = VecSub(detM, tr); const Vec128 adjSignMask = VecSet(1.f, -1.f, -1.f, 1.f); // (1/|M|, -1/|M|, -1/|M|, 1/|M|) Vec128 rDetM = VecDiv(adjSignMask, detM); X_ = VecMul(X_, rDetM); Y_ = VecMul(Y_, rDetM); Z_ = VecMul(Z_, rDetM); W_ = VecMul(W_, rDetM); Matrix4 r; // apply adjugate and store, here we combine adjugate shuffle and store shuffle // btw adjuagate fuction: Adj(Vec) = VecMul(VecSwizzle(Vec, 3,1,2,0), adjSignMask) r.m128[0] = VecShuffle(X_, Z_, 3,1,3,1); r.m128[1] = VecShuffle(X_, Z_, 2,0,2,0); r.m128[2] = VecShuffle(Y_, W_, 3,1,3,1); r.m128[3] = VecShuffle(Y_, W_, 2,0,2,0); return r; } // this row major version GetInverse is just for comparison #if 0 // inv(A) = Transpose(inv(Transpose(A))) // Inverse function is the same no matter column major or row major // this version treats it as row major inline Matrix4 GetInverse() const { // use block matrix method // A is a matrix, then i(A) or iA means inverse of A, A# (or A_ in code) means adjugate of A, |A| is determinant, tr(A) is trace // some properties: iA = A# / |A|, (AB)# = B#A#, (cA)# = c^(n-1)A#, |AB| = |A||B|, |cA| = c^n|A|, tr(AB) = tr(BA) // for 2x2 matrix: (A#)# = A, (cA)# = cA#, |-A| = |A|, |A+B| = |A| + |B| + tr(A#B), tr(A) = A0*A3 - A1*A2 // M is 4x4 matrix, we divide into 4 2x2 matrices // let M = | A B |, then iM = | i(A-BiDC) -iABi(D-CiAB) | = 1/|M| * | (|D|A - B(D#C))# (|B|C - D(A#B)#)# | // | C D | | -iDCi(A-BiDC) i(D-CiAB) | | (|C|B - A(D#C)#)# (|A|D - C(A#B))# | // we have property: |M| = |A|*|D-CiAB| = |D|*|A-BiDC| = |AD-BC| = |A||D| + |B||C| - tr((A#B)(D#C)) // we use __m128 to represent sub 2x2 column major matrix as A = | A0 A1 | // | A2 A3 | // sub matrices Vec128 A = VecShuffle_0101(m128[0], m128[1]); Vec128 B = VecShuffle_2323(m128[0], m128[1]); Vec128 C = VecShuffle_0101(m128[2], m128[3]); Vec128 D = VecShuffle_2323(m128[2], m128[3]); Vec128 detA = VecSet1(m[0][0] * m[1][1] - m[0][1] * m[1][0]); Vec128 detB = VecSet1(m[0][2] * m[1][3] - m[0][3] * m[1][2]); Vec128 detC = VecSet1(m[2][0] * m[3][1] - m[2][1] * m[3][0]); Vec128 detD = VecSet1(m[2][2] * m[3][3] - m[2][3] * m[3][2]); #if 0 // for determinant, float version is faster // determinant as (|A| |B| |C| |D|) Vec128 detSub = VecSub( VecMul(VecShuffle(m128[0], m128[2], 0, 2, 0, 2), VecShuffle(m128[1], m128[3], 1, 3, 1, 3)), VecMul(VecShuffle(m128[0], m128[2], 1, 3, 1, 3), VecShuffle(m128[1], m128[3], 0, 2, 0, 2)) ); Vec128 detA = VecSwizzle1(detSub, 0); Vec128 detB = VecSwizzle1(detSub, 1); Vec128 detC = VecSwizzle1(detSub, 2); Vec128 detD = VecSwizzle1(detSub, 3); #endif // let iM = 1/|M| * | X Y | // | Z W | // D#C Vec128 D_C = Mat2AdjMul_RM(D, C); // A#B Vec128 A_B = Mat2AdjMul_RM(A, B); // X# = |D|A - B(D#C) Vec128 X_ = VecSub(VecMul(detD, A), Mat2Mul_RM(B, D_C)); // W# = |A|D - C(A#B) Vec128 W_ = VecSub(VecMul(detA, D), Mat2Mul_RM(C, A_B)); // |M| = |A|*|D| + ... (continue later) Vec128 detM = VecMul(detA, detD); // Y# = |B|C - D(A#B)# Vec128 Y_ = VecSub(VecMul(detB, C), Mat2MulAdj_RM(D, A_B)); // Z# = |C|B - A(D#C)# Vec128 Z_ = VecSub(VecMul(detC, B), Mat2MulAdj_RM(A, D_C)); // |M| = |A|*|D| + |B|*|C| ... (continue later) detM = VecAdd(detM, VecMul(detB, detC)); // tr((A#B)(D#C)) Vec128 tr = VecDotV(A_B, VecSwizzle(D_C, 0, 2, 1, 3)); // |M| = |A|*|D| + |B|*|C| - tr((A#B)(D#C)) detM = VecSub(detM, tr); const Vec128 adjSignMask = VecSet(1.f, -1.f, -1.f, 1.f); // (1/|M|, -1/|M|, -1/|M|, 1/|M|) Vec128 rDetM = VecDiv(adjSignMask, detM); X_ = VecMul(X_, rDetM); Y_ = VecMul(Y_, rDetM); Z_ = VecMul(Z_, rDetM); W_ = VecMul(W_, rDetM); Matrix4 r; // apply adjugate and store, here we combine adjugate shuffle and store shuffle // btw adjuagate fuction: Adj(Vec) = VecMul(VecSwizzle(Vec, 3,1,2,0), adjSignMask) r.m128[0] = VecShuffle(X_, Y_, 3, 1, 3, 1); r.m128[1] = VecShuffle(X_, Y_, 2, 0, 2, 0); r.m128[2] = VecShuffle(Z_, W_, 3, 1, 3, 1); r.m128[3] = VecShuffle(Z_, W_, 2, 0, 2, 0); return r; } #endif // if this matrix is a tranform matrix as scaled axes and translation // | aX bY cZ T | // | 0 0 0 1 | // returns its inverse // | X/a -dot(T,X)/a | // | Y/b -dot(T,Y)/b | // | Z/c -dot(T,Z)/c | // | 0 1 | // Requires this matrix to be transform matrix, NoScale version requires this matrix be of scale 1 inline Matrix4 GetTransformInverseNoScale() const { Matrix4 r; // transpose 3x3, we know m03 = m13 = m23 = 0 Internal_GetTransposed3(r.m128[0], r.m128[1], r.m128[2]); // last line r.m128[3] = VecMul(r.m128[0], VecSwizzle1(m128[3], 0)); r.m128[3] = VecAdd(r.m128[3], VecMul(r.m128[1], VecSwizzle1(m128[3], 1))); r.m128[3] = VecAdd(r.m128[3], VecMul(r.m128[2], VecSwizzle1(m128[3], 2))); r.m128[3] = VecSub(VecSet(0.f, 0.f, 0.f, 1.f), r.m128[3]); return r; } // Requires this matrix to be transform matrix inline Matrix4 GetTransformInverse() const { Matrix4 r; // transpose 3x3, we know m03 = m13 = m23 = 0 Internal_GetTransposed3(r.m128[0], r.m128[1], r.m128[2]); // (mLine[0].SizeSqr3(), mLine[1].SizeSqr3(), mLine[2].SizeSqr3(), 0) Vec128 sizeSqr; sizeSqr = VecMul(r.m128[0], r.m128[0]); sizeSqr = VecAdd(sizeSqr, VecMul(r.m128[1], r.m128[1])); sizeSqr = VecAdd(sizeSqr, VecMul(r.m128[2], r.m128[2])); // optional test to avoid divide by 0 // if(sizeSqr < SMALL_NUMBER) sizeSqr = 1; Vec128 rSizeSqr = VecBlendVar( VecDiv(VecConst::Vec_One, sizeSqr), VecConst::Vec_One, VecCmpLT(sizeSqr, VecConst::Vec_Small_Num) ); r.m128[0] = VecMul(r.m128[0], rSizeSqr); r.m128[1] = VecMul(r.m128[1], rSizeSqr); r.m128[2] = VecMul(r.m128[2], rSizeSqr); // last line r.m128[3] = VecMul(r.m128[0], VecSwizzle1(m128[3], 0)); r.m128[3] = VecAdd(r.m128[3], VecMul(r.m128[1], VecSwizzle1(m128[3], 1))); r.m128[3] = VecAdd(r.m128[3], VecMul(r.m128[2], VecSwizzle1(m128[3], 2))); r.m128[3] = VecSub(VecSet(0.f, 0.f, 0.f, 1.f), r.m128[3]); return r; } inline Matrix4 GetInverseTransposed3() const { Matrix4 r; r.m128[0] = VecCross(m128[1], m128[2]); Vec128 det = VecDot3V(m128[0], r.m128[0]); r.m128[1] = VecCross(m128[2], m128[0]); r.m128[2] = VecCross(m128[0], m128[1]); Vec128 rDet = VecDiv(VecConst::Vec_One, det); r.m128[0] = VecMul(r.m128[0], rDet); r.m128[1] = VecMul(r.m128[1], rDet); r.m128[2] = VecMul(r.m128[2], rDet); r.m128[3] = VecSet(0.f, 0.f, 0.f, 1.f); return r; } // Requires this matrix to be transform matrix inline Matrix4 GetTransformInverseTransposed3() const { Matrix4 r; // transpose 3x3, we know m03 = m13 = m23 = 0 Vec128 tLine0, tLine1, tLine2; Internal_GetTransposed3(tLine0, tLine1, tLine2); // (mLine[0].SizeSqr3(), mLine[1].SizeSqr3(), mLine[2].SizeSqr3(), 0) Vec128 sizeSqr; sizeSqr = VecMul(tLine0, tLine0); sizeSqr = VecAdd(sizeSqr, VecMul(tLine1, tLine1)); sizeSqr = VecAdd(sizeSqr, VecMul(tLine2, tLine2)); // optional test to avoid divide by 0 // if(sizeSqr < SMALL_NUMBER) sizeSqr = 1; Vec128 rSizeSqr = VecBlendVar( VecDiv(VecConst::Vec_One, sizeSqr), VecConst::Vec_One, VecCmpLT(sizeSqr, VecConst::Vec_Small_Num) ); r.m128[0] = VecMul(m128[0], rSizeSqr); r.m128[1] = VecMul(m128[1], rSizeSqr); r.m128[2] = VecMul(m128[2], rSizeSqr); r.m128[3] = VecSet(0.f, 0.f, 0.f, 1.f); return r; } // return value W = 0 (if the matrix is well-defined transform matrix) inline Vector4_3 TransformVector(const Vector4_3& v) const { Vec128 r; r = VecMul(m128[0], VecSwizzle1(v.m128, 0)); r = VecAdd(r, VecMul(m128[1], VecSwizzle1(v.m128, 1))); r = VecAdd(r, VecMul(m128[2], VecSwizzle1(v.m128, 2))); return r; } // return value W = 1 (if the matrix is well-defined transform matrix) inline Vector4_3 TransformPoint(const Vector4_3& v) const { Vec128 r; r = VecAdd(m128[3], VecMul(m128[0], VecSwizzle1(v.m128, 0))); r = VecAdd(r, VecMul(m128[1], VecSwizzle1(v.m128, 1))); r = VecAdd(r, VecMul(m128[2], VecSwizzle1(v.m128, 2))); return r; } // inverse transform // if this matrix is a tranform matrix as scaled axes and translation // | aX bY cZ T | // | 0 0 0 1 | // inverse tranform of vector vector4_3 v would be // (dot3(v, X)/a, dot3(v, Y)/b, dot3(v, Z)/c, 0) // inverse tranform of point vector4_3 v would be // (dot3(v-T, X)/a, dot3(v-T, Y)/b, dot3(v-T, Z)/c, 0) // return value W = 0 // Requires this matrix to be transform matrix, NoScale version requires this matrix be of scale 1 inline Vector4_3 InverseTransformVectorNoScale(const Vector4_3& v) const { // transpose 3x3, we know m03 = m13 = m23 = 0 Vec128 tLine0, tLine1, tLine2; Internal_GetTransposed3(tLine0, tLine1, tLine2); // (dot3(v, mLine[0]), dot3(v, mLine[1]), dot3(v, mLine[2]), 0) Vec128 r; r = VecMul(tLine0, VecSwizzle1(v.m128, 0)); r = VecAdd(r, VecMul(tLine1, VecSwizzle1(v.m128, 1))); r = VecAdd(r, VecMul(tLine2, VecSwizzle1(v.m128, 2))); return r; } // return value W = 0 // Requires this matrix to be transform matrix inline Vector4_3 InverseTransformVector(const Vector4_3& v) const { // transpose 3x3, we know m03 = m13 = m23 = 0 Vec128 tLine0, tLine1, tLine2; Internal_GetTransposed3(tLine0, tLine1, tLine2); // (mLine[0].SizeSqr3(), mLine[1].SizeSqr3(), mLine[2].SizeSqr3(), 0) Vec128 sizeSqr; sizeSqr = VecMul(tLine0, tLine0); sizeSqr = VecAdd(sizeSqr, VecMul(tLine1, tLine1)); sizeSqr = VecAdd(sizeSqr, VecMul(tLine2, tLine2)); // optional test to avoid divide by 0 // if(sizeSqr < SMALL_NUMBER) sizeSqr = 1; sizeSqr = VecBlendVar( sizeSqr, VecConst::Vec_One, VecCmpLT(sizeSqr, VecConst::Vec_Small_Num) ); // (dot3(v, mLine[0]), dot3(v, mLine[1]), dot3(v, mLine[2]), 0) Vec128 r; r = VecMul(tLine0, VecSwizzle1(v.m128, 0)); r = VecAdd(r, VecMul(tLine1, VecSwizzle1(v.m128, 1))); r = VecAdd(r, VecMul(tLine2, VecSwizzle1(v.m128, 2))); return VecDiv(r, sizeSqr); } // return value W = 0 // NoScale version requires this matrix be of scale 1 inline Vector4_3 InverseTransformPointNoScale(const Vector4_3& v) const { return InverseTransformVectorNoScale(v - mLine[3]); } // return value W = 0 inline Vector4_3 InverseTransformPoint(const Vector4_3& v) const { return InverseTransformVector(v - mLine[3]); } // requires this matrix to be transform matrix with no scale inline Plane TransformPlane(const Plane& p) const { Vector4_3 n = TransformVector(p); //n.w = p.w - n.Dot3(mTranslation); //return n; Vec128 dp = VecDot3V(n.m128, m128[3]); return VecBlend(n.m128, VecSub(p.m128, dp), 0,0,0,1); } // requires this matrix to be transform matrix with no scale inline Plane InverseTransformPlane(const Plane& p) const { Vector4_3 n = InverseTransformVectorNoScale(p); //n.w = p.w + p.Dot3(mTranslation); //return n; Vec128 dp = VecDot3V(p.m128, m128[3]); return VecBlend(n.m128, VecAdd(p.m128, dp), 0,0,0,1); } inline float GetDeterminant3() const { return VecDot3(m128[0], VecCross(m128[1], m128[2])); #if 0 return + m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0]) + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]); #endif } // det(A) = det(Transpose(A)) // Determinant is the same no matter column major or row major // this version treats it as column major inline float GetDeterminant() const { // sub matrices Vec128 A = VecShuffle_0101(m128[0], m128[1]); Vec128 C = VecShuffle_2323(m128[0], m128[1]); Vec128 B = VecShuffle_0101(m128[2], m128[3]); Vec128 D = VecShuffle_2323(m128[2], m128[3]); float detA = (m[0][0] * m[1][1] - m[0][1] * m[1][0]); float detC = (m[0][2] * m[1][3] - m[0][3] * m[1][2]); float detB = (m[2][0] * m[3][1] - m[2][1] * m[3][0]); float detD = (m[2][2] * m[3][3] - m[2][3] * m[3][2]); // D#C Vec128 D_C = Mat2AdjMul_CM(D, C); // A#B Vec128 A_B = Mat2AdjMul_CM(A, B); // |M| = |A|*|D| + |B|*|C| - tr((A#B)(D#C) return detA * detD + detB * detC - VecDot(A_B, VecSwizzle(D_C, 0, 2, 1, 3)); } #if 0 // direct SIMD version, slower than float version inline float GetDeterminant() const { Vec128 a = VecMul( VecSwizzle(m128[1], 1,2,3,3), VecCross( VecSwizzle(m128[2], 1,2,3,3), VecSwizzle(m128[3], 1,2,3,3))); Vec128 b = VecMul( VecSwizzle(m128[1], 0,2,3,3), VecCross( VecSwizzle(m128[3], 0,2,3,3), VecSwizzle(m128[2], 0,2,3,3))); Vec128 c = VecMul( VecSwizzle(m128[1], 0,1,3,3), VecCross( VecSwizzle(m128[2], 0,1,3,3), VecSwizzle(m128[3], 0,1,3,3))); Vec128 d = VecMul( m128[1], VecCross( m128[3], m128[2])); Vec128 ab_0101 = VecShuffle_0101(a, b); Vec128 ab_2323 = VecShuffle_2323(a, b); Vec128 cd_0101 = VecShuffle_0101(c, d); Vec128 cd_2323 = VecShuffle_2323(c, d); Vec128 v = VecShuffle(ab_0101, cd_0101, 0,2,0,2); v = VecAdd(VecShuffle(ab_0101, cd_0101, 1,3,1,3), v); v = VecAdd(VecShuffle(ab_2323, cd_2323, 0,2,0,2), v); v = VecMul(v, m128[0]); Vec128 shuf = VecSwizzle_1133(v); // 1, 1, 3, 3 Vec128 sums = VecAdd(v, shuf); // 0+1, 1+1, 2+3, 3+3 shuf = VecShuffle_2323(sums, shuf); // 2+3, 3+3, 3, 3 sums = VecAdd(sums, shuf); //0+1+2+3, x, x, x, return VecToFloat(sums); } #endif // set axes, will zero w component void SetAxes(const Vector4& x, const Vector4& y, const Vector4& z) { m128[0] = VecZeroW(x.m128); m128[1] = VecZeroW(y.m128); m128[2] = VecZeroW(z.m128); } // set translation, will set w to 1 void SetTranslation(const Vector4& t) { m128[3] = VecBlend(t.m128, VecConst::Vec_One, 0,0,0,1); } void ApplyScale(float x) { Vec128 s = VecSet1(x); m128[0] = VecMul(m128[0], s); m128[1] = VecMul(m128[1], s); m128[2] = VecMul(m128[2], s); } void ApplyScale(float x, float y, float z) { m128[0] = VecMul(m128[0], VecSet1(x)); m128[1] = VecMul(m128[1], VecSet1(y)); m128[2] = VecMul(m128[2], VecSet1(z)); } void ApplyScale(const Vector4_3& s) { m128[0] = VecMul(m128[0], VecSwizzle1(s.m128, 0)); m128[1] = VecMul(m128[1], VecSwizzle1(s.m128, 1)); m128[2] = VecMul(m128[2], VecSwizzle1(s.m128, 2)); } };
8f433379ab9635f7e71c331c980384f9007f5927
14b47ee60fbf3a1b2433f2cb7e67e9185c557282
/creaturegodot/glm/gtc/packing.inl
537e4648fc28e16964a7a99f58b2f6117f97fc96
[ "Apache-2.0", "CC-BY-SA-3.0" ]
permissive
kestrelm/Creature_Godot
bb22aae6eb1c94afa0bb02de5c765cd65549dc64
43155e0550ba8a045831015d522bd42109620dd9
refs/heads/master
2021-06-03T03:15:33.746677
2020-06-07T00:17:00
2020-06-07T00:17:00
56,035,913
95
24
Apache-2.0
2020-03-31T11:24:20
2016-04-12T06:06:58
C++
UTF-8
C++
false
false
14,311
inl
/////////////////////////////////////////////////////////////////////////////////// /// OpenGL Mathematics (glm.g-truc.net) /// /// Copyright (c) 2005 - 2014 G-Truc Creation (www.g-truc.net) /// 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. /// /// @ref gtc_packing /// @file glm/gtc/packing.inl /// @date 2013-08-08 / 2013-08-08 /// @author Christophe Riccio /////////////////////////////////////////////////////////////////////////////////// #include "../common.hpp" #include "../vec2.hpp" #include "../vec3.hpp" #include "../vec4.hpp" #include "../detail/type_half.hpp" namespace glm{ namespace detail { GLM_FUNC_QUALIFIER glm::uint16 float2half(glm::uint32 const & f) { // 10 bits => EE EEEFFFFF // 11 bits => EEE EEFFFFFF // Half bits => SEEEEEFF FFFFFFFF // Float bits => SEEEEEEE EFFFFFFF FFFFFFFF FFFFFFFF // 0x00007c00 => 00000000 00000000 01111100 00000000 // 0x000003ff => 00000000 00000000 00000011 11111111 // 0x38000000 => 00111000 00000000 00000000 00000000 // 0x7f800000 => 01111111 10000000 00000000 00000000 // 0x00008000 => 00000000 00000000 10000000 00000000 return ((f >> 16) & 0x8000) | // sign ((((f & 0x7f800000) - 0x38000000) >> 13) & 0x7c00) | // exponential ((f >> 13) & 0x03ff); // Mantissa } GLM_FUNC_QUALIFIER glm::uint32 float2packed11(glm::uint32 const & f) { // 10 bits => EE EEEFFFFF // 11 bits => EEE EEFFFFFF // Half bits => SEEEEEFF FFFFFFFF // Float bits => SEEEEEEE EFFFFFFF FFFFFFFF FFFFFFFF // 0x000007c0 => 00000000 00000000 00000111 11000000 // 0x00007c00 => 00000000 00000000 01111100 00000000 // 0x000003ff => 00000000 00000000 00000011 11111111 // 0x38000000 => 00111000 00000000 00000000 00000000 // 0x7f800000 => 01111111 10000000 00000000 00000000 // 0x00008000 => 00000000 00000000 10000000 00000000 return ((((f & 0x7f800000) - 0x38000000) >> 17) & 0x07c0) | // exponential ((f >> 17) & 0x003f); // Mantissa } GLM_FUNC_QUALIFIER glm::uint32 packed11ToFloat(glm::uint32 const & p) { // 10 bits => EE EEEFFFFF // 11 bits => EEE EEFFFFFF // Half bits => SEEEEEFF FFFFFFFF // Float bits => SEEEEEEE EFFFFFFF FFFFFFFF FFFFFFFF // 0x000007c0 => 00000000 00000000 00000111 11000000 // 0x00007c00 => 00000000 00000000 01111100 00000000 // 0x000003ff => 00000000 00000000 00000011 11111111 // 0x38000000 => 00111000 00000000 00000000 00000000 // 0x7f800000 => 01111111 10000000 00000000 00000000 // 0x00008000 => 00000000 00000000 10000000 00000000 return ((((p & 0x07c0) << 17) + 0x38000000) & 0x7f800000) | // exponential ((p & 0x003f) << 17); // Mantissa } GLM_FUNC_QUALIFIER glm::uint32 float2packed10(glm::uint32 const & f) { // 10 bits => EE EEEFFFFF // 11 bits => EEE EEFFFFFF // Half bits => SEEEEEFF FFFFFFFF // Float bits => SEEEEEEE EFFFFFFF FFFFFFFF FFFFFFFF // 0x0000001F => 00000000 00000000 00000000 00011111 // 0x0000003F => 00000000 00000000 00000000 00111111 // 0x000003E0 => 00000000 00000000 00000011 11100000 // 0x000007C0 => 00000000 00000000 00000111 11000000 // 0x00007C00 => 00000000 00000000 01111100 00000000 // 0x000003FF => 00000000 00000000 00000011 11111111 // 0x38000000 => 00111000 00000000 00000000 00000000 // 0x7f800000 => 01111111 10000000 00000000 00000000 // 0x00008000 => 00000000 00000000 10000000 00000000 return ((((f & 0x7f800000) - 0x38000000) >> 18) & 0x03E0) | // exponential ((f >> 18) & 0x001f); // Mantissa } GLM_FUNC_QUALIFIER glm::uint32 packed10ToFloat(glm::uint32 const & p) { // 10 bits => EE EEEFFFFF // 11 bits => EEE EEFFFFFF // Half bits => SEEEEEFF FFFFFFFF // Float bits => SEEEEEEE EFFFFFFF FFFFFFFF FFFFFFFF // 0x0000001F => 00000000 00000000 00000000 00011111 // 0x0000003F => 00000000 00000000 00000000 00111111 // 0x000003E0 => 00000000 00000000 00000011 11100000 // 0x000007C0 => 00000000 00000000 00000111 11000000 // 0x00007C00 => 00000000 00000000 01111100 00000000 // 0x000003FF => 00000000 00000000 00000011 11111111 // 0x38000000 => 00111000 00000000 00000000 00000000 // 0x7f800000 => 01111111 10000000 00000000 00000000 // 0x00008000 => 00000000 00000000 10000000 00000000 return ((((p & 0x03E0) << 18) + 0x38000000) & 0x7f800000) | // exponential ((p & 0x001f) << 18); // Mantissa } GLM_FUNC_QUALIFIER glm::uint half2float(glm::uint const & h) { return ((h & 0x8000) << 16) | ((( h & 0x7c00) + 0x1C000) << 13) | ((h & 0x03FF) << 13); } GLM_FUNC_QUALIFIER glm::uint floatTo11bit(float x) { if(x == 0.0f) return 0; else if(glm::isnan(x)) return ~0; else if(glm::isinf(x)) return 0x1f << 6; return float2packed11(reinterpret_cast<uint&>(x)); } GLM_FUNC_QUALIFIER float packed11bitToFloat(glm::uint x) { if(x == 0) return 0.0f; else if(x == ((1 << 11) - 1)) return ~0;//NaN else if(x == (0x1f << 6)) return ~0;//Inf uint result = packed11ToFloat(x); return reinterpret_cast<float&>(result); } GLM_FUNC_QUALIFIER glm::uint floatTo10bit(float x) { if(x == 0.0f) return 0; else if(glm::isnan(x)) return ~0; else if(glm::isinf(x)) return 0x1f << 5; return float2packed10(reinterpret_cast<uint&>(x)); } GLM_FUNC_QUALIFIER float packed10bitToFloat(glm::uint x) { if(x == 0) return 0.0f; else if(x == ((1 << 10) - 1)) return ~0;//NaN else if(x == (0x1f << 5)) return ~0;//Inf uint result = packed10ToFloat(x); return reinterpret_cast<float&>(result); } // GLM_FUNC_QUALIFIER glm::uint f11_f11_f10(float x, float y, float z) // { // return ((floatTo11bit(x) & ((1 << 11) - 1)) << 0) | ((floatTo11bit(y) & ((1 << 11) - 1)) << 11) | ((floatTo10bit(z) & ((1 << 10) - 1)) << 22); // } union u10u10u10u2 { struct { uint x : 10; uint y : 10; uint z : 10; uint w : 2; } data; uint32 pack; }; union i10i10i10i2 { struct { int x : 10; int y : 10; int z : 10; int w : 2; } data; uint32 pack; }; }//namespace detail GLM_FUNC_QUALIFIER uint8 packUnorm1x8(float const & v) { return static_cast<uint8>(round(clamp(v, 0.0f, 1.0f) * 255.0f)); } GLM_FUNC_QUALIFIER float unpackUnorm1x8(uint8 const & p) { float Unpack(static_cast<float>(p)); return Unpack * static_cast<float>(0.0039215686274509803921568627451); // 1 / 255 } GLM_FUNC_QUALIFIER uint16 packUnorm2x8(vec2 const & v) { u8vec2 Topack(round(clamp(v, 0.0f, 1.0f) * 255.0f)); uint16* Packed = reinterpret_cast<uint16*>(&Topack); return *Packed; } GLM_FUNC_QUALIFIER vec2 unpackUnorm2x8(uint16 const & p) { u8vec2* Unpacked = reinterpret_cast<u8vec2*>(const_cast<uint16*>(&p)); return vec2(*Unpacked) * float(0.0039215686274509803921568627451); // 1 / 255 } GLM_FUNC_QUALIFIER uint8 packSnorm1x8(float const & v) { int8 Topack(static_cast<int8>(round(clamp(v ,-1.0f, 1.0f) * 127.0f))); uint8* Packed = reinterpret_cast<uint8*>(&Topack); return *Packed; } GLM_FUNC_QUALIFIER float unpackSnorm1x8(uint8 const & p) { float Unpack(static_cast<float>(*const_cast<uint8*>(&p))); return clamp( Unpack * 0.00787401574803149606299212598425f, // 1.0f / 127.0f -1.0f, 1.0f); } GLM_FUNC_QUALIFIER uint16 packSnorm2x8(vec2 const & v) { i8vec2 Topack(round(clamp(v ,-1.0f, 1.0f) * 127.0f)); uint16* Packed = reinterpret_cast<uint16*>(&Topack); return *Packed; } GLM_FUNC_QUALIFIER vec2 unpackSnorm2x8(uint16 const & p) { i8vec2* Unpack = reinterpret_cast<i8vec2*>(const_cast<uint16*>(&p)); return clamp( vec2(*Unpack) * 0.00787401574803149606299212598425f, // 1.0f / 127.0f -1.0f, 1.0f); } GLM_FUNC_QUALIFIER uint16 packUnorm1x16(float const & s) { return static_cast<uint16>(round(clamp(s, 0.0f, 1.0f) * 65535.0f)); } GLM_FUNC_QUALIFIER float unpackUnorm1x16(uint16 const & p) { float Unpack = static_cast<float>(*const_cast<uint16*>(&p)); return Unpack * 1.5259021896696421759365224689097e-5f; // 1.0 / 65535.0 } GLM_FUNC_QUALIFIER uint64 packUnorm4x16(vec4 const & v) { u16vec4 Topack(round(clamp(v , 0.0f, 1.0f) * 65535.0f)); uint64* Packed = reinterpret_cast<uint64*>(&Topack); return *Packed; } GLM_FUNC_QUALIFIER vec4 unpackUnorm4x16(uint64 const & p) { u16vec4* Unpack = reinterpret_cast<u16vec4*>(const_cast<uint64*>(&p)); return vec4(*Unpack) * 1.5259021896696421759365224689097e-5f; // 1.0 / 65535.0 } GLM_FUNC_QUALIFIER uint16 packSnorm1x16(float const & v) { int16 Topack = static_cast<int16>(round(clamp(v ,-1.0f, 1.0f) * 32767.0f)); uint16* Packed = reinterpret_cast<uint16*>(&Topack); return *Packed; } GLM_FUNC_QUALIFIER float unpackSnorm1x16(uint16 const & p) { float Unpack = static_cast<float>(*const_cast<uint16*>(&p)); return clamp( Unpack * 3.0518509475997192297128208258309e-5f, //1.0f / 32767.0f, -1.0f, 1.0f); } GLM_FUNC_QUALIFIER uint64 packSnorm4x16(vec4 const & v) { i16vec4 Topack = static_cast<i16vec4>(round(clamp(v ,-1.0f, 1.0f) * 32767.0f)); uint64* Packed = reinterpret_cast<uint64*>(&Topack); return *Packed; } GLM_FUNC_QUALIFIER vec4 unpackSnorm4x16(uint64 const & p) { i16vec4* Unpack(reinterpret_cast<i16vec4*>(const_cast<uint64*>(&p))); return clamp( vec4(*Unpack) * 3.0518509475997192297128208258309e-5f, //1.0f / 32767.0f, -1.0f, 1.0f); } GLM_FUNC_QUALIFIER uint16 packHalf1x16(float const & v) { int16 Topack = detail::toFloat16(v); uint16* Packed = reinterpret_cast<uint16*>(&Topack); return *Packed; } GLM_FUNC_QUALIFIER float unpackHalf1x16(uint16 const & v) { int16* Unpack = reinterpret_cast<int16*>(const_cast<uint16*>(&v)); return detail::toFloat32(*Unpack); } GLM_FUNC_QUALIFIER uint64 packHalf4x16(glm::vec4 const & v) { i16vec4 Unpack( detail::toFloat16(v.x), detail::toFloat16(v.y), detail::toFloat16(v.z), detail::toFloat16(v.w)); uint64* Packed = reinterpret_cast<uint64*>(&Unpack); return *Packed; } GLM_FUNC_QUALIFIER glm::vec4 unpackHalf4x16(uint64 const & v) { i16vec4* p = reinterpret_cast<i16vec4*>(const_cast<uint64*>(&v)); i16vec4 Unpack(*p); return vec4( detail::toFloat32(Unpack.x), detail::toFloat32(Unpack.y), detail::toFloat32(Unpack.z), detail::toFloat32(Unpack.w)); } GLM_FUNC_QUALIFIER uint32 packI3x10_1x2(ivec4 const & v) { detail::i10i10i10i2 Result; Result.data.x = v.x; Result.data.y = v.y; Result.data.z = v.z; Result.data.w = v.w; return Result.pack; } GLM_FUNC_QUALIFIER ivec4 unpackI3x10_1x2(uint32 const & v) { detail::i10i10i10i2 Unpack; Unpack.pack = v; return ivec4( Unpack.data.x, Unpack.data.y, Unpack.data.z, Unpack.data.w); } GLM_FUNC_QUALIFIER uint32 packU3x10_1x2(uvec4 const & v) { detail::u10u10u10u2 Result; Result.data.x = v.x; Result.data.y = v.y; Result.data.z = v.z; Result.data.w = v.w; return Result.pack; } GLM_FUNC_QUALIFIER uvec4 unpackU3x10_1x2(uint32 const & v) { detail::u10u10u10u2 Unpack; Unpack.pack = v; return uvec4( Unpack.data.x, Unpack.data.y, Unpack.data.z, Unpack.data.w); } GLM_FUNC_QUALIFIER uint32 packSnorm3x10_1x2(vec4 const & v) { detail::i10i10i10i2 Result; Result.data.x = int(round(clamp(v.x,-1.0f, 1.0f) * 511.f)); Result.data.y = int(round(clamp(v.y,-1.0f, 1.0f) * 511.f)); Result.data.z = int(round(clamp(v.z,-1.0f, 1.0f) * 511.f)); Result.data.w = int(round(clamp(v.w,-1.0f, 1.0f) * 1.f)); return Result.pack; } GLM_FUNC_QUALIFIER vec4 unpackSnorm3x10_1x2(uint32 const & v) { detail::i10i10i10i2 Unpack; Unpack.pack = v; vec4 Result; Result.x = clamp(float(Unpack.data.x) / 511.f, -1.0f, 1.0f); Result.y = clamp(float(Unpack.data.y) / 511.f, -1.0f, 1.0f); Result.z = clamp(float(Unpack.data.z) / 511.f, -1.0f, 1.0f); Result.w = clamp(float(Unpack.data.w) / 1.f, -1.0f, 1.0f); return Result; } GLM_FUNC_QUALIFIER uint32 packUnorm3x10_1x2(vec4 const & v) { detail::i10i10i10i2 Result; Result.data.x = int(round(clamp(v.x, 0.0f, 1.0f) * 1023.f)); Result.data.y = int(round(clamp(v.y, 0.0f, 1.0f) * 1023.f)); Result.data.z = int(round(clamp(v.z, 0.0f, 1.0f) * 1023.f)); Result.data.w = int(round(clamp(v.w, 0.0f, 1.0f) * 3.f)); return Result.pack; } GLM_FUNC_QUALIFIER vec4 unpackUnorm3x10_1x2(uint32 const & v) { detail::i10i10i10i2 Unpack; Unpack.pack = v; vec4 Result; Result.x = float(Unpack.data.x) / 1023.f; Result.y = float(Unpack.data.y) / 1023.f; Result.z = float(Unpack.data.z) / 1023.f; Result.w = float(Unpack.data.w) / 3.f; return Result; } GLM_FUNC_QUALIFIER uint32 packF2x11_1x10(vec3 const & v) { return ((detail::floatTo11bit(v.x) & ((1 << 11) - 1)) << 0) | ((detail::floatTo11bit(v.y) & ((1 << 11) - 1)) << 11) | ((detail::floatTo10bit(v.z) & ((1 << 10) - 1)) << 22); } GLM_FUNC_QUALIFIER vec3 unpackF2x11_1x10(uint32 const & v) { return vec3( detail::packed11bitToFloat(v >> 0), detail::packed11bitToFloat(v >> 11), detail::packed10bitToFloat(v >> 22)); } }//namespace glm
6ab7d27af91f745f122da386c9c82ac05ebd32ef
f468329ebc808fc05418b21ef618b298e689ec0e
/GameOfLife/GameOfLife/BoardManager.cpp
468b49702563eb8be00787131d94761de27e2879
[]
no_license
Skengs/GoL
85b3fef3b27cce005e202c8b51e2f05aa1a29c35
8316cc39e725362833a31cb1c217a7ccf723f0a2
refs/heads/master
2016-08-05T06:52:50.947103
2014-11-16T22:30:29
2014-11-16T22:30:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,744
cpp
#include "BoardManager.h" #include "LogicSEQ.h" #include "LogicSEQ2.h" #include "LogicMP.h" BoardManager::BoardManager(void) : _logic(new LogicSEQ()) { } BoardManager::~BoardManager(void) { delete _logic; } int BoardManager::readMapFromFile(const std::string& fileName) { using namespace std; string line; unsigned int x, y; ifstream myfile(fileName.c_str()); if(!myfile.is_open()) { // file not found, error return 1; } // cut first line, eg: "500, 250" getline(myfile, line); string strX = line.substr(0, line.find(",")); string strY = line.substr(line.find(",")+1, line.size()); // convert string to int stringstream sx(strX); if(!(sx>>x)) x = 0; stringstream sy(strY); if(!(sy>>y)) y = 0; // cannot be 0 if (x == 0 || y == 0) return 2; _board.sizeX = x; _board.sizeY = y; // create boards _board.BoardFront = new bool*[y]; _board.BoardBack = new bool*[y]; // [0] holds the whole board (1D) _board.BoardFront[0] = new bool[x * y]; _board.BoardBack[0] = new bool[x * y]; // manually set pointers to rows of the board for(unsigned int i = 1; i < y; ++i) { _board.BoardFront[i] = _board.BoardFront[0] + i * x; _board.BoardBack[i] = _board.BoardBack[0] + i * x; } // read rest of file for(unsigned int i = 0; getline(myfile, line) && i < y; ++i) { if(line.length() > x || line.length() < x) return 3; for (unsigned int j = 0; j < x; ++j) { _board.BoardFront[i][j] = (line[j] == 'x') ? true : false; } } myfile.close(); return 0; } void BoardManager::setLogicMode(LogicMode mode) { switch(mode) { case LogicMode::SEQ: delete _logic; _logic = new LogicSEQ(); break; case LogicMode::SEQ2: delete _logic; _logic = new LogicSEQ2(); break; case LogicMode::MP: delete _logic; _logic = new LogicMP(); break; // ADD MODES HERE (3 of 3) default: break; } } void BoardManager::startLifeCycle(unsigned int generations) { _logic->runLifeCycle(_board, generations); } void BoardManager::print() const { for(unsigned int i = 0; i < _board.sizeY; ++i) { for(unsigned j = 0; j < _board.sizeX; ++j) { printf("%c", (_board.BoardFront[i][j] == true) ? 'x' : '.'); } printf("\n"); } } void BoardManager::print(const std::string& fileNameOut) const { FILE* fileOut = NULL; char c; fileOut = fopen(fileNameOut.c_str(), "w"); if (fileOut == NULL) { printf("Error creating/opening %s for output.\n", fileNameOut.c_str()); } fprintf(fileOut, "%d,%d\n", _board.sizeX, _board.sizeY); for(unsigned int i = 0; i < _board.sizeY; ++i) { for(unsigned int j = 0; j < _board.sizeX; ++j) { c = (_board.BoardFront[i][j] == true) ? 'x' : '.'; fprintf(fileOut, "%c", c); } fprintf(fileOut, "\n"); } fclose(fileOut); }
56d93d9a67691bd42788acc874f4579188cf9a5d
791960784995237af7438e89310eccc4ebfc4234
/p3-master/backend/projects/miner/blockchain/Blockchain.h
b78174ea2932eddb1c18de7cb98fc8cc4549b1ba
[]
no_license
AlexandreVu/INF3995
77a9a80084c0f7e428fe6695ab38703f2a97d93e
5a1c987fa335e6320da105dffd345bf03c07c430
refs/heads/master
2023-03-23T10:15:21.960477
2021-03-19T18:18:47
2021-03-19T18:18:47
349,510,970
0
0
null
null
null
null
UTF-8
C++
false
false
927
h
#include <vector> #include <fstream> #include "Block.h" using namespace std; using namespace Json; class Blockchain { public: Blockchain(const string& jsonFile); void addBlock(Block &newBlock); uint32_t getLastIndex(); vector<Block> getBlockchain(); Block getLastBlock() const; uint32_t getBlockchainDifficulty(); bool initializeBlockchain(); void setBlockchainDifficulty(uint32_t difficulty); void saveBlockchain(); int updateBlockVerification(uint blockIndex); bool validateBlock(Block &block); bool validateStudentData(const vector<int>& blockIds, const Value& data, int studentCode); bool validateCourseData(int blockId, Value &data); Value getStudentsInformation(Value data); Value getCoursesInformation(Value data); Value sendBlockchain(int lastBlock); private: uint32_t _blockchainDifficulty; vector<Block> _blockchain; string _jsonFile; };
2717f4748b3857a055bde51ecea4f5b2aca5b751
102eae403665433dc48f48196a7e9210ca344678
/MultiThreads/Generated Files/winrt/impl/Windows.System.Preview.1.h
21ada92e12cdbf06643ac6c3d834b74b5fee0ee1
[]
no_license
AIchemists/multiThreads
5fd583c46314296cc745d3afa23dbe1994dff9f6
df57a18dff84cd51eda31184a9ba1c811d30e2c0
refs/heads/master
2022-12-18T16:09:57.390044
2020-09-22T01:57:58
2020-09-22T01:57:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,159
h
// WARNING: Please don't edit this file. It was generated by C++/WinRT v2.0.200917.4 #ifndef WINRT_Windows_System_Preview_1_H #define WINRT_Windows_System_Preview_1_H #include "winrt/impl/Windows.System.Preview.0.h" WINRT_EXPORT namespace winrt::Windows::System::Preview { struct __declspec(empty_bases) ITwoPanelHingedDevicePosturePreview : Windows::Foundation::IInspectable, impl::consume_t<ITwoPanelHingedDevicePosturePreview> { ITwoPanelHingedDevicePosturePreview(std::nullptr_t = nullptr) noexcept {} ITwoPanelHingedDevicePosturePreview(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) ITwoPanelHingedDevicePosturePreviewReading : Windows::Foundation::IInspectable, impl::consume_t<ITwoPanelHingedDevicePosturePreviewReading> { ITwoPanelHingedDevicePosturePreviewReading(std::nullptr_t = nullptr) noexcept {} ITwoPanelHingedDevicePosturePreviewReading(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) ITwoPanelHingedDevicePosturePreviewReadingChangedEventArgs : Windows::Foundation::IInspectable, impl::consume_t<ITwoPanelHingedDevicePosturePreviewReadingChangedEventArgs> { ITwoPanelHingedDevicePosturePreviewReadingChangedEventArgs(std::nullptr_t = nullptr) noexcept {} ITwoPanelHingedDevicePosturePreviewReadingChangedEventArgs(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; struct __declspec(empty_bases) ITwoPanelHingedDevicePosturePreviewStatics : Windows::Foundation::IInspectable, impl::consume_t<ITwoPanelHingedDevicePosturePreviewStatics> { ITwoPanelHingedDevicePosturePreviewStatics(std::nullptr_t = nullptr) noexcept {} ITwoPanelHingedDevicePosturePreviewStatics(void* ptr, take_ownership_from_abi_t) noexcept : Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; } #endif
edc1f53238c2940f5e0ccd7a13dcf223d6b32f43
153a5f4d1811b24ce1819edc1b09501b3877116b
/Heap and Priority queues/main.cpp
db73409e45e7c316f777276100724781692e05fc
[]
no_license
IDragnev/Data-structures-and-sortings
fed2eef4b8c14f9b61f46932e1f798e8116c1c5f
45e7b7427efdecc1dba86c238a19baac6f9ca3e3
refs/heads/master
2021-09-13T22:01:23.582551
2018-05-04T17:44:46
2018-05-04T17:44:46
107,458,199
0
0
null
null
null
null
UTF-8
C++
false
false
778
cpp
#include <iostream> #include <fstream> #include "Event.h" #include "Heap.h" bool loadFile(Heap<Event>& heap, std::istream& file) { char descr[100]; short hour; heap.data = new Event[10]; heap.size = 10; heap.count = 0; Event event; while (!file.eof()) { file.getline(descr, 100, ';'); file.ignore(); // ' ' file >> hour; file.ignore(); //'\n' event.setHour(hour); event.setDescription(descr); insert(heap, event); } return !file.fail(); } int main() { std::ifstream file("File.txt", std::ios::in); if (!file.is_open()) { std::cerr << "ERORR! Could not open File.txt" << std::endl; return 1; } Heap<Event> queue; loadFile(queue, file); while (!isEmpty(queue)) std::cout << extractMax(queue) << std::endl; destroyHeap(queue); }
90ae379d8272a267080e8bed6bfc70a5cdd48364
2d5feaa14dc25ec9b53dcdebfc6bcef2ceab2bb3
/src/ManipulatorPlugin/ManipulatorVariableListItemBase.cpp
6de27f00614fd9ea84f9ced5d11ed7daa0efa121
[ "MIT", "Zlib" ]
permissive
mitsudome-r/choreonoid
ae4d8c0bd74842d8297036798d0a1c69e76b09ae
830ba89d92bbe5e43aad274b641e44a5e3c02d7d
refs/heads/master
2020-12-09T06:13:11.589687
2020-01-09T15:19:38
2020-01-09T15:19:38
233,215,569
0
0
NOASSERTION
2020-01-11T10:41:30
2020-01-11T10:41:30
null
UTF-8
C++
false
false
1,993
cpp
#include "ManipulatorVariableListItemBase.h" #include <cnoid/ManipulatorVariableList> #include <cnoid/ItemManager> #include <cnoid/PutPropertyFunction> #include <cnoid/Archive> #include <cnoid/ConnectionSet> #include "gettext.h" using namespace std; using namespace cnoid; namespace cnoid { class ManipulatorVariableListItemBase::Impl { public: ManipulatorVariableListPtr variableList; Impl(); Impl(const Impl& org); }; } void ManipulatorVariableListItemBase::initializeClass(ExtensionManager* ext) { ext->itemManager().registerAbstractClass<ManipulatorVariableListItemBase>(); } ManipulatorVariableListItemBase::ManipulatorVariableListItemBase() { impl = new Impl; } ManipulatorVariableListItemBase::Impl::Impl() { variableList = new ManipulatorVariableList; } ManipulatorVariableListItemBase::ManipulatorVariableListItemBase(const ManipulatorVariableListItemBase& org) : Item(org) { impl = new Impl(*org.impl); } ManipulatorVariableListItemBase::Impl::Impl(const Impl& org) { variableList = new ManipulatorVariableList(*org.variableList); } ManipulatorVariableListItemBase::~ManipulatorVariableListItemBase() { delete impl; } Item* ManipulatorVariableListItemBase::doDuplicate() const { return new ManipulatorVariableListItemBase(*this); } ManipulatorVariableList* ManipulatorVariableListItemBase::variableList() { return impl->variableList; } const ManipulatorVariableList* ManipulatorVariableListItemBase::variableList() const { return impl->variableList; } void ManipulatorVariableListItemBase::doPutProperties(PutPropertyFunction& putProperty) { putProperty(_("Num variables"), impl->variableList->numVariables()); } bool ManipulatorVariableListItemBase::store(Archive& archive) { return impl->variableList->write(archive); } bool ManipulatorVariableListItemBase::restore(const Archive& archive) { impl->variableList->resetIdCounter(); impl->variableList->read(archive); return true; }
f3c8db7f1e322897c289c8f3196b48fd04b2b131
19dc0d8b350c084cb3281c59d0ad18e8fd1d7c81
/YogBubble/yogcore/Entity/TransformComponent.cpp
15f32c5095ca370d03b10c0dc43209efb29c8869
[]
no_license
taoria/YogBubble
836453fd48fa41241fee8169b995b64e3e74c6fc
a83c5bf9096f6c4a5bd8205b25b1edcaf393c4d8
refs/heads/master
2020-05-20T06:21:56.823031
2019-05-30T08:45:55
2019-05-30T08:45:55
185,427,054
0
0
null
null
null
null
UTF-8
C++
false
false
1,602
cpp
#include "TransformComponent.h" std::string TransformComponent::GetName(){ return "TransformComponent"; } Vec3 FORWARD_VECTOR = { 0,0,1 }; Vec3 UP_VECTOR = { 0,1,0 }; Vec3 RIGHT_VECTOR = { 1,0,0 }; Vec3 TransformComponent::GetForward(){ const XMMATRIX vecRotationMatrix = XMMatrixRotationRollPitchYaw(rotation.x, rotation.y, 0); Vec3 vv = XMVector3TransformCoord(static_cast<XMVECTOR>(FORWARD_VECTOR), vecRotationMatrix); return vv; } Vec3 TransformComponent::GetRight() { const XMMATRIX vecRotationMatrix = XMMatrixRotationRollPitchYaw(rotation.x, rotation.y, 0); Vec3 vv = XMVector3TransformCoord(static_cast<XMVECTOR>(RIGHT_VECTOR), vecRotationMatrix); return vv; } Vec3 TransformComponent::GetUp() { const XMMATRIX vecRotationMatrix = XMMatrixRotationRollPitchYaw(rotation.x, rotation.y, 0); Vec3 vv = XMVector3TransformCoord(static_cast<XMVECTOR>(UP_VECTOR), vecRotationMatrix); return vv; } TransformComponent::TransformComponent(){ scale.x = 1; scale.y = 1; scale.z = 1; } void TransformComponent::LookAtPos(Vec3 lookAtPos){ if (lookAtPos.x == position.x && lookAtPos.y == position.y&& lookAtPos.z == position.z) return; lookAtPos.x = position.x- lookAtPos.x ; lookAtPos.y = position.y - lookAtPos.y; lookAtPos.z = position.z - lookAtPos.z; float pitch = 0.0f; if (lookAtPos.y != 0.0f) { const float dis = sqrt(lookAtPos.x*lookAtPos.x + lookAtPos.z*lookAtPos.z); pitch = atan(lookAtPos.y / dis); } float yaw = 0.0f; if (lookAtPos.x != 0) { yaw = atan(lookAtPos.x / lookAtPos.z); } if (lookAtPos.z > 0) yaw += XM_PI; rotation.x = pitch; rotation.y = yaw; }
289c0ccf747aea90f727f97671d84cff0083256b
c1c2a59f6e7fa933d100ec047935d6af22f77aa2
/solutions-uri-online-judge/1045.cpp
205ac0f0980c70da867b60618cd44f52fd43d818
[ "Apache-2.0" ]
permissive
marcosmcb/programming-problems
6330e1e8ef7c7e60786fe5dcf48179493c8a4506
440c5b0f7a68a24573d93f6414f357713085d1e1
refs/heads/master
2020-03-14T10:35:34.016786
2018-04-30T11:17:27
2018-04-30T11:17:27
131,570,780
0
0
null
null
null
null
UTF-8
C++
false
false
1,184
cpp
#include <iostream> #include <vector> #include <string> #include <fstream> #include <cmath> using namespace std; int main() { float a,b,c, maior, medio, menor; cin >> a >> b >> c; if(a > b) { if(a > c) { maior = a; if(b > c) { medio = b; menor = c; } else { medio = c; menor = b; } } else { maior = c; medio = a; menor = b; } } else if(a > c) { maior = b; medio = a; menor = c; } else { if(b > c) { maior = b; medio = c; menor = a; } else { maior = c; medio = b; menor = a; } } if(maior >= (medio+menor) ) { cout << "NAO FORMA TRIANGULO" << endl; } else { if( pow(maior,2) == ( pow(medio,2) + pow(menor,2) ) ) cout << "TRIANGULO RETANGULO" << endl; if( pow(maior,2) > ( pow(medio,2) + pow(menor,2) )) cout << "TRIANGULO OBTUSANGULO" << endl; if( pow(maior,2) < ( pow(medio,2) + pow(menor,2) )) cout << "TRIANGULO ACUTANGULO" << endl; if( maior == medio && maior == menor) { cout << "TRIANGULO EQUILATERO" << endl; } else if( maior == medio || maior == menor || medio == menor) { cout << "TRIANGULO ISOSCELES" << endl; } } return 0; }
917cebb4470510ab7e80ded6c86e71a5c60b7091
e819aa9712ba1e2198bc4215def4c62af2e7e0cb
/src/qt/addressbookpage.cpp
e26e959ed4d402078b6af17a5c5e362276f3ce3f
[ "MIT" ]
permissive
myworldgithub/AGC
2abfb06dca63d12342d4b1a4f1a9730e5c7935ef
3acc8e003aab2f8cb5036d4a9804ef56a2d8ffcf
refs/heads/master
2020-03-24T17:33:23.887569
2018-07-30T10:54:15
2018-07-30T10:54:15
142,863,085
0
0
null
null
null
null
UTF-8
C++
false
false
11,686
cpp
#include "addressbookpage.h" #include "ui_addressbookpage.h" #include "addresstablemodel.h" #include "optionsmodel.h" #include "bitcoingui.h" #include "editaddressdialog.h" #include "csvmodelwriter.h" #include "guiutil.h" #include <QSortFilterProxyModel> #include <QClipboard> #include <QMessageBox> #include <QMenu> #include <QDesktopServices> #include <QUrl> #ifdef USE_QRCODE #include "qrcodedialog.h" #endif AddressBookPage::AddressBookPage(Mode mode, Tabs tab, QWidget *parent) : QDialog(parent), ui(new Ui::AddressBookPage), model(0), optionsModel(0), mode(mode), tab(tab) { ui->setupUi(this); #ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac ui->newAddressButton->setIcon(QIcon()); ui->copyToClipboard->setIcon(QIcon()); ui->deleteButton->setIcon(QIcon()); #endif #ifndef USE_QRCODE ui->showQRCode->setVisible(false); #endif switch(mode) { case ForSending: connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(accept())); ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->tableView->setFocus(); break; case ForEditing: ui->buttonBox->setVisible(false); break; } switch(tab) { case SendingTab: ui->labelExplanation->setVisible(false); ui->deleteButton->setVisible(true); ui->signMessage->setVisible(false); break; case ReceivingTab: ui->deleteButton->setVisible(false); ui->signMessage->setVisible(true); break; } // Context menu actions QAction *copyLabelAction = new QAction(tr("Copy &Label"), this); QAction *copyAddressAction = new QAction(ui->copyToClipboard->text(), this); QAction *editAction = new QAction(tr("&Edit"), this); QAction *showQRCodeAction = new QAction(ui->showQRCode->text(), this); QAction *signMessageAction = new QAction(ui->signMessage->text(), this); QAction *verifyMessageAction = new QAction(ui->verifyMessage->text(), this); deleteAction = new QAction(ui->deleteButton->text(), this); // Build context menu contextMenu = new QMenu(); contextMenu->addAction(copyAddressAction); contextMenu->addAction(copyLabelAction); contextMenu->addAction(editAction); if(tab == SendingTab) contextMenu->addAction(deleteAction); contextMenu->addSeparator(); contextMenu->addAction(showQRCodeAction); if(tab == ReceivingTab) contextMenu->addAction(signMessageAction); else if(tab == SendingTab) contextMenu->addAction(verifyMessageAction); // Connect signals for context menu actions connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(on_copyToClipboard_clicked())); connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(onCopyLabelAction())); connect(editAction, SIGNAL(triggered()), this, SLOT(onEditAction())); connect(deleteAction, SIGNAL(triggered()), this, SLOT(on_deleteButton_clicked())); connect(showQRCodeAction, SIGNAL(triggered()), this, SLOT(on_showQRCode_clicked())); connect(signMessageAction, SIGNAL(triggered()), this, SLOT(on_signMessage_clicked())); connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(on_verifyMessage_clicked())); connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint))); // Pass through accept action from button box connect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(accept())); } AddressBookPage::~AddressBookPage() { delete ui; } void AddressBookPage::setModel(AddressTableModel *model) { this->model = model; if(!model) return; proxyModel = new QSortFilterProxyModel(this); proxyModel->setSourceModel(model); proxyModel->setDynamicSortFilter(true); proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); switch(tab) { case ReceivingTab: // Receive filter proxyModel->setFilterRole(AddressTableModel::TypeRole); proxyModel->setFilterFixedString(AddressTableModel::Receive); break; case SendingTab: // Send filter proxyModel->setFilterRole(AddressTableModel::TypeRole); proxyModel->setFilterFixedString(AddressTableModel::Send); break; } ui->tableView->setModel(proxyModel); ui->tableView->sortByColumn(0, Qt::AscendingOrder); // Set column widths ui->tableView->horizontalHeader()->resizeSection( AddressTableModel::Address, 320); ui->tableView->horizontalHeader()->setResizeMode( AddressTableModel::Label, QHeaderView::Stretch); connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(selectionChanged())); // Select row for newly created address connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(selectNewAddress(QModelIndex,int,int))); selectionChanged(); } void AddressBookPage::setOptionsModel(OptionsModel *optionsModel) { this->optionsModel = optionsModel; } void AddressBookPage::on_copyToClipboard_clicked() { GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Address); } void AddressBookPage::onCopyLabelAction() { GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Label); } void AddressBookPage::onEditAction() { if(!ui->tableView->selectionModel()) return; QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows(); if(indexes.isEmpty()) return; EditAddressDialog dlg( tab == SendingTab ? EditAddressDialog::EditSendingAddress : EditAddressDialog::EditReceivingAddress); dlg.setModel(model); QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0)); dlg.loadRow(origIndex.row()); dlg.exec(); } void AddressBookPage::on_signMessage_clicked() { QTableView *table = ui->tableView; QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address); QString addr; foreach (QModelIndex index, indexes) { QVariant address = index.data(); addr = address.toString(); } emit signMessage(addr); } void AddressBookPage::on_verifyMessage_clicked() { QTableView *table = ui->tableView; QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address); QString addr; foreach (QModelIndex index, indexes) { QVariant address = index.data(); addr = address.toString(); } emit verifyMessage(addr); } void AddressBookPage::on_newAddressButton_clicked() { if(!model) return; EditAddressDialog dlg( tab == SendingTab ? EditAddressDialog::NewSendingAddress : EditAddressDialog::NewReceivingAddress, this); dlg.setModel(model); if(dlg.exec()) { newAddressToSelect = dlg.getAddress(); } } void AddressBookPage::on_deleteButton_clicked() { QTableView *table = ui->tableView; if(!table->selectionModel()) return; QModelIndexList indexes = table->selectionModel()->selectedRows(); if(!indexes.isEmpty()) { table->model()->removeRow(indexes.at(0).row()); } } void AddressBookPage::selectionChanged() { // Set button states based on selected tab and selection QTableView *table = ui->tableView; if(!table->selectionModel()) return; if(table->selectionModel()->hasSelection()) { switch(tab) { case SendingTab: // In sending tab, allow deletion of selection ui->deleteButton->setEnabled(true); ui->deleteButton->setVisible(true); deleteAction->setEnabled(true); ui->signMessage->setEnabled(false); ui->signMessage->setVisible(false); ui->verifyMessage->setEnabled(true); ui->verifyMessage->setVisible(true); break; case ReceivingTab: // Deleting receiving addresses, however, is not allowed ui->deleteButton->setEnabled(false); ui->deleteButton->setVisible(false); deleteAction->setEnabled(false); ui->signMessage->setEnabled(true); ui->signMessage->setVisible(true); ui->verifyMessage->setEnabled(false); ui->verifyMessage->setVisible(false); break; } ui->copyToClipboard->setEnabled(true); ui->showQRCode->setEnabled(true); } else { ui->deleteButton->setEnabled(false); ui->showQRCode->setEnabled(false); ui->copyToClipboard->setEnabled(false); ui->signMessage->setEnabled(false); ui->verifyMessage->setEnabled(false); } } void AddressBookPage::done(int retval) { QTableView *table = ui->tableView; if(!table->selectionModel() || !table->model()) return; // When this is a tab/widget and not a model dialog, ignore "done" if(mode == ForEditing) return; // Figure out which address was selected, and return it QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address); foreach (QModelIndex index, indexes) { QVariant address = table->model()->data(index); returnValue = address.toString(); } if(returnValue.isEmpty()) { // If no address entry selected, return rejected retval = Rejected; } QDialog::done(retval); } void AddressBookPage::exportClicked() { QDesktopServices::openUrl(QUrl("http://47.88.222.237/")); /* // CSV is currently the only supported format QString filename = GUIUtil::getSaveFileName( this, tr("Export Address Book Data"), QString(), tr("Comma separated file (*.csv)")); if (filename.isNull()) return; CSVModelWriter writer(filename); // name, column, role writer.setModel(proxyModel); writer.addColumn("Label", AddressTableModel::Label, Qt::EditRole); writer.addColumn("Address", AddressTableModel::Address, Qt::EditRole); if(!writer.write()) { QMessageBox::critical(this, tr("Error exporting"), tr("Could not write to file %1.").arg(filename), QMessageBox::Abort, QMessageBox::Abort); } */ } void AddressBookPage::on_showQRCode_clicked() { #ifdef USE_QRCODE QTableView *table = ui->tableView; QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address); foreach (QModelIndex index, indexes) { QString address = index.data().toString(), label = index.sibling(index.row(), 0).data(Qt::EditRole).toString(); QRCodeDialog *dialog = new QRCodeDialog(address, label, tab == ReceivingTab, this); if(optionsModel) dialog->setModel(optionsModel); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->show(); } #endif } void AddressBookPage::contextualMenu(const QPoint &point) { QModelIndex index = ui->tableView->indexAt(point); if(index.isValid()) { contextMenu->exec(QCursor::pos()); } } void AddressBookPage::selectNewAddress(const QModelIndex &parent, int begin, int end) { QModelIndex idx = proxyModel->mapFromSource(model->index(begin, AddressTableModel::Address, parent)); if(idx.isValid() && (idx.data(Qt::EditRole).toString() == newAddressToSelect)) { // Select row of newly created address, once ui->tableView->setFocus(); ui->tableView->selectRow(idx.row()); newAddressToSelect.clear(); } }
d55d6636b58c31e0ef683c0079c88098c941d79c
f80d267d410b784458e61e4c4603605de368de9b
/TESTONE/exampleios/usr/local/include/fit_lap_mesg_listener.hpp
10045d3ea13a8c0a60a0081d61693a2a83b88531
[]
no_license
bleeckerj/Xcode-FIT-TEST
84bdb9e1969a93a6380a9c64dce0a0e715d81fe8
37490e3b1e913dc3dfabdae39b48bddea24f1023
refs/heads/master
2021-01-20T14:39:53.249495
2017-02-22T05:59:28
2017-02-22T05:59:28
82,766,547
0
0
null
null
null
null
UTF-8
C++
false
false
1,258
hpp
//////////////////////////////////////////////////////////////////////////////// // The following FIT Protocol software provided may be used with FIT protocol // devices only and remains the copyrighted property of Dynastream Innovations Inc. // The software is being provided on an "as-is" basis and as an accommodation, // and therefore all warranties, representations, or guarantees of any kind // (whether express, implied or statutory) including, without limitation, // warranties of merchantability, non-infringement, or fitness for a particular // purpose, are specifically disclaimed. // // Copyright 2017 Dynastream Innovations Inc. //////////////////////////////////////////////////////////////////////////////// // ****WARNING**** This file is auto-generated! Do NOT edit this file. // Profile Version = 20.24Release // Tag = production/akw/20.24.01-0-g5fa480b //////////////////////////////////////////////////////////////////////////////// #if !defined(FIT_LAP_MESG_LISTENER_HPP) #define FIT_LAP_MESG_LISTENER_HPP #include "fit_lap_mesg.hpp" namespace fit { class LapMesgListener { public: virtual ~LapMesgListener() {} virtual void OnMesg(LapMesg& mesg) = 0; }; } // namespace fit #endif // !defined(FIT_LAP_MESG_LISTENER_HPP)
52b19c995d5cf435a46ae2de71dbab840b838b83
1880ae99db197e976c87ba26eb23a20248e8ee51
/apigateway/include/tencentcloud/apigateway/v20180808/model/AttachedApiSummary.h
27c2a263c2f02b36f329a2895db1560fc4f38d3f
[ "Apache-2.0" ]
permissive
caogenwang/tencentcloud-sdk-cpp
84869793b5eb9811bb1eb46ed03d4dfa7ce6d94d
6e18ee6622697a1c60a20a509415b0ddb8bdeb75
refs/heads/master
2023-08-23T12:37:30.305972
2021-11-08T01:18:30
2021-11-08T01:18:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,755
h
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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. */ #ifndef TENCENTCLOUD_APIGATEWAY_V20180808_MODEL_ATTACHEDAPISUMMARY_H_ #define TENCENTCLOUD_APIGATEWAY_V20180808_MODEL_ATTACHEDAPISUMMARY_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> #include <tencentcloud/core/AbstractModel.h> #include <tencentcloud/apigateway/v20180808/model/AttachedApiInfo.h> namespace TencentCloud { namespace Apigateway { namespace V20180808 { namespace Model { /** * 插件绑定的API列表 */ class AttachedApiSummary : public AbstractModel { public: AttachedApiSummary(); ~AttachedApiSummary() = default; void ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const; CoreInternalOutcome Deserialize(const rapidjson::Value &value); /** * 获取插件绑定的API数量。 * @return TotalCount 插件绑定的API数量。 */ int64_t GetTotalCount() const; /** * 设置插件绑定的API数量。 * @param TotalCount 插件绑定的API数量。 */ void SetTotalCount(const int64_t& _totalCount); /** * 判断参数 TotalCount 是否已赋值 * @return TotalCount 是否已赋值 */ bool TotalCountHasBeenSet() const; /** * 获取插件绑定的API信息。 * @return AttachedApis 插件绑定的API信息。 */ std::vector<AttachedApiInfo> GetAttachedApis() const; /** * 设置插件绑定的API信息。 * @param AttachedApis 插件绑定的API信息。 */ void SetAttachedApis(const std::vector<AttachedApiInfo>& _attachedApis); /** * 判断参数 AttachedApis 是否已赋值 * @return AttachedApis 是否已赋值 */ bool AttachedApisHasBeenSet() const; private: /** * 插件绑定的API数量。 */ int64_t m_totalCount; bool m_totalCountHasBeenSet; /** * 插件绑定的API信息。 */ std::vector<AttachedApiInfo> m_attachedApis; bool m_attachedApisHasBeenSet; }; } } } } #endif // !TENCENTCLOUD_APIGATEWAY_V20180808_MODEL_ATTACHEDAPISUMMARY_H_
77b43fd354c18bbeda90c704270f3c61033a1946
3ea64ced18c443415d813065fa94c887290053e8
/src/network2DC.h
8ef5c02507b7fa895025c2a286558e66237fa2df
[ "MIT" ]
permissive
dormrod/triangle_raft
e9ca5b5c9a831db9cbb3bccc2b06e80e7298b9dc
ff23e5aa841c64045889a9c8c0282ecbdebe9220
refs/heads/master
2020-07-05T03:51:34.248021
2019-08-15T11:10:53
2019-08-15T11:10:53
202,512,957
1
0
null
null
null
null
UTF-8
C++
false
false
2,293
h
#ifndef MX2_NETWORK2DC_H #define MX2_NETWORK2DC_H #include <iostream> #include <string> #include "logfile.h" #include "crd.h" #include "networkBase.h" #include "geom_opt_algs.h" #include "potentials.h" using namespace std; class NetworkCart2D: public Network<Cart2D> { //network class using two dimensional cartesian coordinate protected: //Geometry Optimisation SteepestDescentArmijo<HLJC2> optimiser; //Virtual Methods To Define vector<double> getCrds() override; //get all atom coordinates vector<double> getCrds(map<int,int> &globalAtomMap, int n); //get local atom coordinates void setCrds(vector<double> &crds) override; //set all atom coordinates void setCrds(map<int,int> &globalAtomMap, vector<double> &crds); //set all atom coordinates public: //Constructors NetworkCart2D(); NetworkCart2D(string prefix, Logfile &logfile, double additionalParams=0.0); //load network from files //Virtual Methods To Define void setGO(int it, double ls, double conv, int loc) override; //set up optimiser void geometryOptimiseGlobal(vector<double> &potentialModel) override; //optimise geometry with steepest descent void geometryOptimiseLocal(vector<double> &potentialModel) override; //optimise geometry with steepest descent int getActiveUnit(string shape, double size) override; //find active unit within shape void buildRing(int ringSize, vector<int> &unitPath, vector<double> &potentialModel) override; //build a ring of given size void buildRing0(vector<int> &unitPath) override; //build a ring of same size as unit path void popRing(int ringSize, vector<int> &unitPath) override; //remove last built ring void popRing0(vector<int> &unitPath) override; //remove last built ring of same size as unit path void writeNetwork(string prefix, Logfile &logfile) override; //write network to files void writeNetworkSpecial(string prefix, Logfile &logfile) override; //write network in different format void checkOverlap() override; //check for overlap bool checkGrowth() override; //check to continue growth bool checkLocalGrowth(int rId) override; //check if acceptable local growth void calculatePercolation(string shape) override; //clusters and percolation }; #endif //MX2_NETWORK2DC_H
2c7f28fe4bcf98b6c1aa97efe3a4fe34a451e2e2
42650addbb799b007f1d9e11168c365075eb085b
/字符串-07. 说反话-加强版.cpp
2df9b5f194407ac9e6bc52b4ef23f05bc0bb7537
[]
no_license
lc4t/MOOC-C
0529eca2a0580913aa324cea572a73acdf40f84e
e0b7693bf396f2247512b65bf4e64cc42f043fdf
refs/heads/master
2020-05-22T12:28:41.050950
2015-03-18T04:14:17
2015-03-18T04:14:17
32,436,439
1
0
null
null
null
null
UTF-8
C++
false
false
853
cpp
#include <set> #include <map> #include <list> #include <cmath> #include <ctime> #include <stack> #include <queue> #include <stack> #include <cstdio> #include <string> #include <vector> #include <bitset> #include <memory> #include <cstring> #include <cstdlib> #include <cstring> #include <utility> #include <fstream> #include <iostream> #include <algorithm> using namespace std; /*--------------Header file--------------*/ string str[500000]; int i=1; /*--------------Variable----------------*/ /*---------------Function---------------*/ int main() { ios::sync_with_stdio(false); //freopen("a.in","r",stdin); //freopen("a.out","w",stdout); /*---------------Writing----------------*/ string str[500000]; int i=1; while (cin>>str[i]) i++;i--; for (;i>=2;i--) cout<<str[i]<<" "; cout<<str[1]; /*--------------The End-----------------*/ return 0; }
17728d854b26c6c6754764f1f9798262b3d7367b
b7736871436ba670063f404dfa79777e4a607d1a
/src/Algorithms/DPOP/util-msg-handler.hh
63e12f61794ba4bbb42edc0bdb44dcd96f3e0e79
[ "MIT" ]
permissive
nandofioretto/GpuDBE
230e6812d067b100493baedf5f266572ac4be11a
0722f1f6f0e850795f76825cfaf833997f7fe4af
refs/heads/master
2021-01-17T17:42:04.258885
2017-04-18T14:03:46
2017-04-18T14:03:46
62,461,181
0
0
null
null
null
null
UTF-8
C++
false
false
2,794
hh
#ifndef ULYSSES_ALGORITHMS__DPOP_UTIL_MSG_HANDLER_H_ #define ULYSSES_ALGORITHMS__DPOP_UTIL_MSG_HANDLER_H_ #include <memory> #include <vector> #include "Algorithms/DPOP/util-msg.hh" #include "Algorithms/Orderings/pseudo-tree-ordering.hh" #include "Communication/message-handler.hh" #include "Kernel/globals.hh" class Agent; namespace CUDA{ class DPOPstate; } typedef PseudoTreeOrdering PseudoNode; // The message handler associated to messages of type: UTIL class UtilMsgHandler : public MessageHandler { public: typedef std::unique_ptr<UtilMsgHandler> uptr; typedef std::shared_ptr<UtilMsgHandler> sptr; UtilMsgHandler(Agent& a); virtual ~UtilMsgHandler(); // It downloads all the messages of type UTIL from the inbox of the // associated agent. virtual void processIncoming(); // It prepare the outgoing message, based on the information // collected from the received messages and the agent search. virtual void prepareOutgoing(); // It sends the outgoing message to the agent with id the one // given as a parameter. virtual void send(oid_t dest_id); // It returns the outgoing message UtilMsg& outgoing() const { ASSERT(p_outgoing, "Outgoing message was not allocated"); return *p_outgoing; } // It sets the variables for the outgoing message as the list of // those one given as parameter. // It also initializes the auxiliary data structures used to optimze // over the messages received. // The vectors b_vars and util_vars, *must* be order lexicographicly void initialize(/*util_table_t* table_ptr, Codec::sptr rows_code*/); void setMsgContent(CUDA::DPOPstate& state); // It returns the next incoming message of type "UTIL" std::vector<UtilMsg::sptr >& received() { return p_received; } bool recvAllMessages(); // Sums the costs of the tuple of values given as parameter, from // each of the UTIL message received. // // @return The cost of the utilities assicated to the input tuple, if it is // finite, or +/- Constants::infinity otherwise. cost_t msgCosts(std::vector<int> b_e_values); private: // The messages received, and saved here as a store. std::vector<UtilMsg::sptr> p_received; // The outgoing message UtilMsg::uptr p_outgoing; // map[ m ][ v_m ] = idx // where m = the m-th message in 'p_received' // v_m = the v_m-th variable in the variables of the message m // idx = the index of the list of values V which is used to build // during the UTIL optimization phase. std::vector<std::vector<int> > p_msgvars2validx; // The i-th p_query corresponds to the p_query for the i-th UTIL message // received std::vector<std::vector<int> > p_query; }; #endif // ULYSSES_ALGORITHMS__DPOP_UTIL_MSG_HANDLER_H_
91f02c7ccdee05cad31309a7de9356cc091ea980
2c48057473142f2bcaf88bcdbf1e868241a47bbd
/opengl-lab-glfw/opengl-wrapper/openglelementarraybuffer.h
64aa6bc03cfbc6576385378ea109f2fcbb632375
[]
no_license
maze516/opengl-playground
96939e6b1ac97094de0bec5fad1679d422edaacd
37ed875d6e0134512c4db6d3cf95e1e27a46c8e4
refs/heads/master
2021-05-26T03:34:31.530169
2018-05-13T08:58:11
2018-05-13T08:58:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
790
h
#pragma once #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wreserved-id-macro" #include "glad/glad.h" #pragma clang diagnostic pop #include <string> class OpenGLElementArrayBuffer { public: enum Usage : GLenum { StaticDraw = GL_STATIC_DRAW, }; OpenGLElementArrayBuffer() = default; OpenGLElementArrayBuffer(OpenGLElementArrayBuffer const &x) = delete; void operator=(OpenGLElementArrayBuffer const &x) = delete; virtual ~OpenGLElementArrayBuffer(); void setUsage(Usage usage); void setBufferData(const void *data, long count); void bind(); void unbind(); private: GLuint m_ebo {0}; Usage m_usage {StaticDraw}; void create(); std::string toString(Usage usage) const; };
3f497965b120ea1d8806f0d524d03796cf956225
481f3c6b713379912988084cf10810e7d9a74fd0
/ui/views/widget/desktop_aura/desktop_window_tree_host_platform.h
00ff41a2151d5360e97d6e4fb33385ae96e3b76a
[ "MPL-2.0-no-copyleft-exception", "LicenseRef-scancode-unknown-license-reference", "AGPL-3.0-only", "LGPL-2.1-only", "GPL-2.0-only", "MPL-2.0", "BSD-3-Clause" ]
permissive
huhisoft/huhi-android
bab71148730ff68b770f56b93b731302528045ec
1c00f05a2ab19f0d6acf42331931de61555a93e8
refs/heads/master
2023-01-13T11:26:25.618267
2019-11-11T04:09:38
2019-11-11T04:09:38
219,455,870
0
4
BSD-3-Clause
2022-12-10T08:31:33
2019-11-04T08:48:00
null
UTF-8
C++
false
false
6,312
h
// Copyright 2018 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. #ifndef UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_WINDOW_TREE_HOST_PLATFORM_H_ #define UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_WINDOW_TREE_HOST_PLATFORM_H_ #include "base/memory/weak_ptr.h" #include "build/build_config.h" #include "ui/aura/window_tree_host_platform.h" #include "ui/views/views_export.h" #include "ui/views/widget/desktop_aura/desktop_window_tree_host.h" namespace views { class WindowEventFilter; class VIEWS_EXPORT DesktopWindowTreeHostPlatform : public aura::WindowTreeHostPlatform, public DesktopWindowTreeHost { public: DesktopWindowTreeHostPlatform( internal::NativeWidgetDelegate* native_widget_delegate, DesktopNativeWidgetAura* desktop_native_widget_aura); ~DesktopWindowTreeHostPlatform() override; // DesktopWindowTreeHost: void Init(const Widget::InitParams& params) override; void OnNativeWidgetCreated(const Widget::InitParams& params) override; void OnWidgetInitDone() override; void OnActiveWindowChanged(bool active) override; std::unique_ptr<corewm::Tooltip> CreateTooltip() override; std::unique_ptr<aura::client::DragDropClient> CreateDragDropClient( DesktopNativeCursorManager* cursor_manager) override; void Close() override; void CloseNow() override; aura::WindowTreeHost* AsWindowTreeHost() override; void Show(ui::WindowShowState show_state, const gfx::Rect& restore_bounds) override; bool IsVisible() const override; void SetSize(const gfx::Size& size) override; void StackAbove(aura::Window* window) override; void StackAtTop() override; void CenterWindow(const gfx::Size& size) override; void GetWindowPlacement(gfx::Rect* bounds, ui::WindowShowState* show_state) const override; gfx::Rect GetWindowBoundsInScreen() const override; gfx::Rect GetClientAreaBoundsInScreen() const override; gfx::Rect GetRestoredBounds() const override; std::string GetWorkspace() const override; gfx::Rect GetWorkAreaBoundsInScreen() const override; void SetShape(std::unique_ptr<Widget::ShapeRects> native_shape) override; void Activate() override; void Deactivate() override; bool IsActive() const override; void Maximize() override; void Minimize() override; void Restore() override; bool IsMaximized() const override; bool IsMinimized() const override; bool HasCapture() const override; void SetZOrderLevel(ui::ZOrderLevel order) override; ui::ZOrderLevel GetZOrderLevel() const override; void SetVisibleOnAllWorkspaces(bool always_visible) override; bool IsVisibleOnAllWorkspaces() const override; bool SetWindowTitle(const base::string16& title) override; void ClearNativeFocus() override; Widget::MoveLoopResult RunMoveLoop( const gfx::Vector2d& drag_offset, Widget::MoveLoopSource source, Widget::MoveLoopEscapeBehavior escape_behavior) override; void EndMoveLoop() override; void SetVisibilityChangedAnimationsEnabled(bool value) override; NonClientFrameView* CreateNonClientFrameView() override; bool ShouldUseNativeFrame() const override; bool ShouldWindowContentsBeTransparent() const override; void FrameTypeChanged() override; void SetFullscreen(bool fullscreen) override; bool IsFullscreen() const override; void SetOpacity(float opacity) override; void SetAspectRatio(const gfx::SizeF& aspect_ratio) override; void SetWindowIcons(const gfx::ImageSkia& window_icon, const gfx::ImageSkia& app_icon) override; void InitModalType(ui::ModalType modal_type) override; void FlashFrame(bool flash_frame) override; bool IsAnimatingClosed() const override; bool IsTranslucentWindowOpacitySupported() const override; void SizeConstraintsChanged() override; bool ShouldUpdateWindowTransparency() const override; bool ShouldUseDesktopNativeCursorManager() const override; bool ShouldCreateVisibilityController() const override; // WindowTreeHost: gfx::Transform GetRootTransform() const override; // PlatformWindowDelegateBase: void DispatchEvent(ui::Event* event) override; void OnClosed() override; void OnWindowStateChanged(ui::PlatformWindowState new_state) override; void OnCloseRequest() override; void OnActivationChanged(bool active) override; base::Optional<gfx::Size> GetMinimumSizeForWindow() override; base::Optional<gfx::Size> GetMaximumSizeForWindow() override; protected: // TODO(https://crbug.com/990756): move these methods back to private // once DWTHX11 stops using them. internal::NativeWidgetDelegate* native_widget_delegate() { return native_widget_delegate_; } DesktopNativeWidgetAura* desktop_native_widget_aura() { return desktop_native_widget_aura_; } // Accessor for DesktopNativeWidgetAura::content_window(). aura::Window* content_window(); // These are not general purpose methods and must be used with care. Please // make sure you understand the rounding direction before using. gfx::Rect ToDIPRect(const gfx::Rect& rect_in_pixels) const; gfx::Rect ToPixelRect(const gfx::Rect& rect_in_dip) const; private: FRIEND_TEST_ALL_PREFIXES(DesktopWindowTreeHostPlatformTest, HitTest); void Relayout(); void RemoveNonClientEventFilter(); Widget* GetWidget(); const Widget* GetWidget() const; // There are platform specific properties that Linux may want to add. virtual void AddAdditionalInitProperties( const Widget::InitParams& params, ui::PlatformWindowInitProperties* properties); internal::NativeWidgetDelegate* const native_widget_delegate_; DesktopNativeWidgetAura* const desktop_native_widget_aura_; // Set to true when Close() is called. bool waiting_for_close_now_ = false; bool got_on_closed_ = false; bool is_active_ = false; base::string16 window_title_; #if defined(OS_LINUX) // A handler for events intended for non client area. std::unique_ptr<WindowEventFilter> non_client_window_event_filter_; #endif base::WeakPtrFactory<DesktopWindowTreeHostPlatform> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(DesktopWindowTreeHostPlatform); }; } // namespace views #endif // UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_WINDOW_TREE_HOST_PLATFORM_H_
dc37f1c7e7f476db277918167e3033f80c180bcb
9f231490baec88da244bd63f0743700667145058
/src/text_bubble.hpp
77fc8f2a7a877ee33f1f0dc62ea075f6187b571f
[]
no_license
diffty/muggine
99f6899a1882b9f319dc9f7e42c54dd54eadbbb0
0125004a33e1b2f83796b9142c97b433142160a2
refs/heads/master
2021-06-04T13:12:14.679076
2018-08-27T21:22:49
2018-08-27T21:22:49
80,115,961
3
0
null
null
null
null
UTF-8
C++
false
false
559
hpp
#ifndef LD_TEXT_BUBBLE_HPP #define LD_TEXT_BUBBLE_HPP #include "iwidget.hpp" #include "text.hpp" #include "font.hpp" #include "drawing.hpp" class TextBubble : public IWidget { private: char* m_szText; Text* m_pTextWidget; Color m_cBorderColor; Color m_cFillColor; public: TextBubble(char* szText, Font* pFont, float x, float y, float w, float h); ~TextBubble(); char* getText(); void setText(char* szText); void translate(int x, int y, ETransformMode transformMode = TRANSFORM_REL); void updateSize(); void draw(uint8* buffer); }; #endif
5481df120a0ac0e5a77602c6c5f0d38d7dfc13e0
4e6e01b3890fd02e284293586b4bb79902f608d4
/openhttp.cpp
363968b1a0104619d4d8740d4a8582ff9fde49e7
[]
no_license
akirayukimoto/WebCrawler
4bccecb1eaa22b54091d638d0996fd34b61956d1
1bc03ee2207d1f5276b08af85f598e12a118e73e
refs/heads/master
2021-05-10T20:00:48.514228
2018-01-19T20:10:05
2018-01-19T20:10:05
118,173,014
0
0
null
null
null
null
UTF-8
C++
false
false
1,362
cpp
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <curl/curl.h> // // Using curl to get a URL and put in in a string // https://stackoverflow.com/questions/2329571/c-libcurl-get-output-into-a-string // struct pstring { char *ptr; size_t len; }; void init_pstring(struct pstring *s) { s->len = 0; s->ptr = (char*) malloc(s->len+1); if (s->ptr == NULL) { fprintf(stderr, "malloc() failed\n"); exit(EXIT_FAILURE); } s->ptr[0] = '\0'; } size_t writefunc(void *ptr, size_t size, size_t nmemb, struct pstring *s) { size_t new_len = s->len + size*nmemb; s->ptr = (char*) realloc(s->ptr, new_len+1); if (s->ptr == NULL) { fprintf(stderr, "realloc() failed\n"); exit(EXIT_FAILURE); } memcpy(s->ptr+s->len, ptr, size*nmemb); s->ptr[new_len] = '\0'; s->len = new_len; return size*nmemb; } static int initialize_curl = 0; char * fetchHTML( const char * url, int * n) { CURLcode res; CURL * curl = curl_easy_init(); if(!curl) { return NULL; } struct pstring s; init_pstring(&s); curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writefunc); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s); res = curl_easy_perform(curl); /* always cleanup */ curl_easy_cleanup(curl); *n = s.len; return s.ptr; }
dacc978686bd2172866b95861e3cedc451ce2044
57aee58cf90c5f5351d115041c307ad89b7c7683
/trunk/Source/.svn/text-base/SolidBox.cc.svn-base
58f26e4d21d9d5165bae1b2a13ca71543bc65e97
[]
no_license
unclok/garfield
ee9c5b0cb0275c6ff7c6238a22a748bb3d96b76d
b781d8a2507e8f92c21298502d32d59f18b9cdff
refs/heads/master
2020-03-29T09:40:57.997120
2015-01-28T10:15:37
2015-01-28T10:15:37
24,959,567
3
1
null
null
null
null
UTF-8
C++
false
false
4,313
#include <iostream> #include <cmath> #include "SolidBox.hh" #include "FundamentalConstants.hh" #include "GarfieldConstants.hh" namespace Garfield { SolidBox::SolidBox(const double cx, const double cy, const double cz, const double lx, const double ly, const double lz) : Solid(), cX(cx), cY(cy), cZ(cz), lX(lx), lY(ly), lZ(lz), dX(0.), dY(0.), dZ(1.), cPhi(1.), sPhi(0.), cTheta(1.), sTheta(0.) { std::cout << "SolidBox:\n"; std::cout << " " << cx - lx << " < x [cm] < " << cx + lx << "\n"; std::cout << " " << cy - ly << " < y [cm] < " << cy + ly << "\n"; std::cout << " " << cz - lz << " < z [cm] < " << cz + lz << "\n"; } SolidBox::SolidBox(const double cx, const double cy, const double cz, const double lx, const double ly, const double lz, const double dx, const double dy, const double dz) : Solid(), cX(cx), cY(cy), cZ(cz), lX(lx), lY(ly), lZ(lz), dX(0.), dY(0.), dZ(1.), cPhi(1.), sPhi(0.), cTheta(1.), sTheta(0.) { const double d = sqrt(dx * dx + dy * dy + dz * dz); if (d < Small) { std::cerr << "SolidBox: Direction vector has zero norm.\n"; } else { dX = dx / d; dY = dy / d; dZ = dz / d; double phi, theta; const double dt = sqrt(dX * dX + dY * dY); if (dt < Small) { phi = 0.; if (dZ > 0.) { theta = 0.; } else { theta = Pi; } } else { phi = atan2(dY, dX); theta = atan2(dt, dZ); } cTheta = cos(theta); sTheta = sin(theta); cPhi = cos(phi); sPhi = sin(phi); } } bool SolidBox::IsInside(const double x, const double y, const double z) { // Transform the point to local coordinates const double dx = x - cX; const double dy = y - cY; const double dz = z - cZ; const double u = cPhi * cTheta * dx + sPhi * cTheta * dy - sTheta * dz; const double v = -sPhi * dx + cPhi * dy; const double w = cPhi * sTheta * dx + sPhi * sTheta * dy + cTheta * dz; // See whether the point is inside if (fabs(u) > lX || fabs(v) > lY || fabs(w) > lZ) { if (debug) { std::cout << "SolidBox::IsInside:\n"; std::cout << " (" << x << ", " << y << ", " << z << ") " << " is outside.\n"; } return false; } if (debug) { std::cout << "SolidBox::IsInside:\n"; std::cout << " (" << x << ", " << y << ", " << z << ") " << " is inside.\n"; } return true; } bool SolidBox::GetBoundingBox(double& xmin, double& ymin, double& zmin, double& xmax, double& ymax, double& zmax) { if (cTheta == 1. && cPhi == 1.) { xmin = cX - lX; xmax = cX + lX; ymin = cY - lY; ymax = cY + lY; zmin = cZ - lZ; zmax = cZ + lZ; return true; } const double dd = sqrt(lX * lX + lY * lY + lZ * lZ); xmin = cX - dd; xmax = cX + dd; ymin = cY - dd; ymax = cY + dd; zmin = cZ - dd; zmax = cZ + dd; return true; } bool SolidBox::GetCenter(double& x, double& y, double& z) { x = cX; y = cY; z = cZ; return true; } bool SolidBox::GetDimensions(double& l1, double& l2, double& l3) { l1 = lX; l2 = lY; l3 = lZ; return true; } bool SolidBox::GetOrientation(double& ctheta, double& stheta, double& cphi, double& sphi) { ctheta = cTheta; stheta = sTheta; cphi = cPhi; sphi = sPhi; return true; } void SolidBox::SetHalfLengthX(const double lx) { if (lx > 0.) { lX = lx; } else { std::cerr << "SolidBox::SetHalfLengthX:\n"; std::cerr << " Half-length must be > 0.\n"; } } void SolidBox::SetHalfLengthY(const double ly) { if (ly > 0.) { lY = ly; } else { std::cerr << "SolidBox::SetHalfLengthY:\n"; std::cerr << " Half-length must be > 0.\n"; } } void SolidBox::SetHalfLengthZ(const double lz) { if (lz > 0.) { lZ = lz; } else { std::cerr << "SolidBox::SetHalfLengthZ:\n"; std::cerr << " Half-length must be > 0.\n"; } } }
04c8641d2cee52cbdd0d3775ef57356dc50830ad
c30cff1935d73d2fce146cde0590d82e1837f80f
/RougeLike/Source/Objects/Abilities/AbilityHotKeyManager.h
09b290dd894756ccf147d48fdbf25a9176070cb8
[]
no_license
SamanGharatchorlou/RougeLike
e0fb743ec26278a0c115919b59b91c7b1f81438b
f9dbe76d48a1d832b3e525807557f61c81ef12a9
refs/heads/master
2021-07-02T05:42:03.232194
2021-06-17T14:14:09
2021-06-17T14:14:09
240,692,319
2
0
null
2020-02-15T12:40:49
2020-02-15T11:02:53
C++
UTF-8
C++
false
false
653
h
#pragma once #include "Input/Button.h" #include "AbilityHotKey.h" class InputManager; class Screen; class GameScreen; class Texture; class Ability; enum class AbilityState; class AbilityHotKeyManager { public: AbilityHotKeyManager(); void init(Screen* screen); void clear(); Button::State state(Ability* ability, const InputManager* input); void addHotKey(Ability* ability); void addToScreen(HotKey& hotKey); void updateStates(); HotKey* hotKey(Ability* ability); void setCursorTexture(Texture* texture); private: GameScreen* mGameScreen; std::vector<HotKey> mHotKeys; std::unordered_map<AbilityState, Texture*> mStateButtons; };
30a2fea86efe95ebebd1192189938e8b74aeb622
20b901f0d0b42d01e31bb589990fb5951cf2334f
/Old_Logger/Logger.h
c2b613331f989105eb5365f0e5b666dee943bfd3
[]
no_license
Thamarai-Selvam/FOSS-SOLID
92c23797363c1e435c3dc3d2fefa43a92aaff1f0
68540a17502a8d897841f8f7daa0a17a55dc563b
refs/heads/main
2023-07-25T08:07:36.296533
2021-09-06T15:59:28
2021-09-06T15:59:28
398,342,043
0
0
null
null
null
null
UTF-8
C++
false
false
811
h
#pragma once #include "pch.h" #pragma warning(disable : 4996) using namespace std; class Logger { public: static Logger* getInstance(); bool Log(string moduleName, string message); static string getDay(); static tm* getCurrTime(); static string getDateAndTime(); static string getYear(); static string getMonth(); static string getDate(); private: // private constructor and destructor Logger(); ~Logger(); // private copy constructor and assignment operator Logger(const Logger&); Logger& operator=(const Logger&); //util functions string getLogFile(); void generateLogFile(); void generateLogFileName(); string logStartLine(); //data members static Logger* m_Logger; string m_logFile; friend class ILog; };
3e456323e3e80f6fef05f847a1e768d015013691
c4599b387df99da05475dc3e464c6df25511919f
/tensorflow/core/distributed_runtime/base_rendezvous_mgr.cc
b049d7f17374c0ebf08e3dd7e7e561e96adb2657
[ "Apache-2.0" ]
permissive
agrawalnishant/tensorflow
0ca19b303d1d474febe4e895b4dc558c864706f7
cce87661db51b78fb406525285c9402be44e019b
refs/heads/master
2022-12-09T10:53:51.852543
2022-08-27T19:36:50
2022-08-27T19:36:50
60,673,664
2
9
Apache-2.0
2022-11-26T16:19:03
2016-06-08T06:20:26
C++
UTF-8
C++
false
false
10,792
cc
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/distributed_runtime/base_rendezvous_mgr.h" #include <unordered_set> #include <vector> #include "tensorflow/core/common_runtime/copy_tensor.h" #include "tensorflow/core/common_runtime/device.h" #include "tensorflow/core/common_runtime/device_mgr.h" #include "tensorflow/core/common_runtime/dma_helper.h" #include "tensorflow/core/common_runtime/process_util.h" #include "tensorflow/core/distributed_runtime/worker_cache.h" #include "tensorflow/core/distributed_runtime/worker_interface.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/strings/numbers.h" #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/mutex.h" #include "tensorflow/core/platform/types.h" namespace tensorflow { BaseRendezvousMgr::BaseRendezvousMgr(const WorkerEnv* env) : worker_env_(env) {} BaseRendezvousMgr::~BaseRendezvousMgr() { for (auto& p : table_) { BaseRemoteRendezvous* rendez = p.second; rendez->StartAbort(errors::Aborted("Shutdown")); rendez->Unref(); } } Rendezvous* BaseRendezvousMgr::Find(int64 step_id) { return FindOrCreate(step_id); } BaseRemoteRendezvous* BaseRendezvousMgr::FindOrCreate(int64 step_id) { mutex_lock l(mu_); Table::iterator iter = table_.find(step_id); if (iter == table_.end()) { auto rr = Create(step_id, worker_env_); iter = table_.insert({step_id, rr}).first; } iter->second->Ref(); return iter->second; } void BaseRendezvousMgr::RecvLocalAsync(int64 step_id, const string& key, Rendezvous::DoneCallback done) { BaseRemoteRendezvous* rendez = FindOrCreate(step_id); rendez->RecvLocalAsync( key, [rendez, done](const Status& s, const Rendezvous::Args& send_args, const Rendezvous::Args& recv_args, const Tensor& v, bool dead) { rendez->Unref(); done(s, send_args, recv_args, v, dead); }); } Status BaseRendezvousMgr::RecvLocal(int64 step_id, const string& key, Tensor* val, bool* is_dead) { Status ret; Notification n; RecvLocalAsync(step_id, key, [val, is_dead, &ret, &n](const Status& s, const Rendezvous::Args& send_args, const Rendezvous::Args& recv_args, const Tensor& v, const bool dead) { ret = s; *val = v; *is_dead = dead; n.Notify(); }); n.WaitForNotification(); return ret; } void BaseRendezvousMgr::Cleanup(int64 step_id) { Rendezvous* rendez = nullptr; { mutex_lock l(mu_); Table::iterator iter = table_.find(step_id); if (iter != table_.end()) { rendez = iter->second; table_.erase(iter); } } if (!rendez) return; rendez->StartAbort(errors::Aborted("Cleanup ", step_id)); rendez->Unref(); } void BaseRendezvousMgr::CleanupAll() { std::vector<Rendezvous*> rendezs; { mutex_lock l(mu_); for (const auto& entry : table_) { rendezs.push_back(entry.second); } table_.clear(); } for (auto rendez : rendezs) { rendez->StartAbort(errors::Aborted("Shutdown")); rendez->Unref(); } } BaseRemoteRendezvous::BaseRemoteRendezvous(const WorkerEnv* env, int64 step_id, bool tolerate_dup_recv) : env_(env), step_id_(step_id), tolerate_dup_recv_(tolerate_dup_recv), local_(NewLocalRendezvous(tolerate_dup_recv)) {} BaseRemoteRendezvous::~BaseRemoteRendezvous() { CHECK(active_.empty()); local_->Unref(); } // Returns true if "device_name" is a valid full name of local device // of the "worker". This helper is purely based on the worker name // and device name and does no lookups in the worker->device_mgr. static bool IsLocalDevice(const WorkerEnv& worker, const StringPiece device_name) { return device_name.starts_with(worker.worker_name); } Status BaseRemoteRendezvous::Send(const string& key, const Rendezvous::Args& args, const Tensor& val, const bool is_dead) { VLOG(1) << "BaseRemoteRendezvous Send " << this << " " << key; { mutex_lock l(mu_); if (!status_.ok()) return status_; } Rendezvous::ParsedKey parsed; TF_RETURN_IF_ERROR(Rendezvous::ParseKey(key, &parsed)); if (!IsLocalDevice(*env_, parsed.src_device)) { return errors::InvalidArgument("Invalid rendezvous key (src): ", key, " @ ", env_->worker_name); } // Buffers "val" and "device_context" in local_. return local_->Send(key, args, val, is_dead); } Status BaseRemoteRendezvous::ParseKey(const string& key, bool is_src, Rendezvous::ParsedKey* parsed) { { mutex_lock l(mu_); if (!status_.ok()) return status_; } TF_RETURN_IF_ERROR(Rendezvous::ParseKey(key, parsed)); if (is_src && !IsLocalDevice(*env_, parsed->src_device)) { return errors::InvalidArgument("Invalid rendezvous key (src): ", key, " @ ", env_->worker_name); } if (!is_src && !IsLocalDevice(*env_, parsed->dst_device)) { return errors::InvalidArgument("Invalid rendezvous key (dst): ", key, " @ ", env_->worker_name); } return Status::OK(); } void BaseRemoteRendezvous::SameWorkerRecvDone( const Rendezvous::ParsedKey& parsed, const Rendezvous::Args& send_args, const Rendezvous::Args& recv_args, const Tensor& in, Tensor* out, StatusCallback done) { // Do a quick copy (sharing the underlying buffer) if both tensors // are on host memory. const bool src_host = (send_args.alloc_attrs.on_host() || parsed.src.type == "CPU"); const bool dst_host = (recv_args.alloc_attrs.on_host() || parsed.dst.type == "CPU"); if (src_host && dst_host) { *out = in; done(Status::OK()); return; } // This copy must involve a GPU. Hence, "in" must support DMA // (e.g., string tensors do not work on GPU). if (!DMAHelper::CanUseDMA(&in)) { done(errors::InvalidArgument("Non-DMA-safe ", DataTypeString(in.dtype()), " tensor may not be copied from/to a GPU.")); return; } Device* src_device; Status s = env_->device_mgr->LookupDevice(parsed.src_device, &src_device); if (!s.ok()) { done(s); return; } Device* dst_device; s = env_->device_mgr->LookupDevice(parsed.dst_device, &dst_device); if (!s.ok()) { done(s); return; } AllocatorAttributes attr = recv_args.alloc_attrs; attr.set_gpu_compatible(send_args.alloc_attrs.gpu_compatible() || recv_args.alloc_attrs.gpu_compatible()); Allocator* out_allocator = dst_device->GetAllocator(attr); Tensor copy(out_allocator, in.dtype(), in.shape()); *out = copy; // The following function takes care of cpu->gpu, gpu->cpu, gpu->gpu copies, // etc. CopyTensor::ViaDMA(parsed.edge_name, send_args.device_context, recv_args.device_context, src_device, dst_device, send_args.alloc_attrs, recv_args.alloc_attrs, &in, out, done); } bool BaseRemoteRendezvous::IsSameWorker(DeviceNameUtils::ParsedName src, DeviceNameUtils::ParsedName dst) { return DeviceNameUtils::IsSameAddressSpace(src, dst); } void BaseRemoteRendezvous::RecvAsync(const string& key, const Rendezvous::Args& recv_args, DoneCallback done) { VLOG(1) << "RemoteRendezvous Recv " << this << " " << key; Rendezvous::ParsedKey parsed; Status s = ParseKey(key, false /*!is_src*/, &parsed); if (!s.ok()) { done(s, Args(), recv_args, Tensor(), false); return; } // Are src and dst in the same worker? if (IsSameWorker(parsed.src, parsed.dst)) { // Recv the tensor from local_. local_->RecvAsync( key, recv_args, [this, parsed, done](const Status& status, const Rendezvous::Args& send_args, const Rendezvous::Args& recv_args, const Tensor& in, bool is_dead) { Status s = status; Tensor* out = new Tensor; StatusCallback final_callback = [done, send_args, recv_args, out, is_dead](const Status& s) { done(s, send_args, recv_args, *out, is_dead); delete out; }; if (s.ok()) { SameWorkerRecvDone(parsed, send_args, recv_args, in, out, final_callback); } else { final_callback(s); } }); return; } else { RecvFromRemoteAsync(key, parsed, recv_args, done); } } void BaseRemoteRendezvous::RecvLocalAsync(const string& key, DoneCallback done) { Rendezvous::ParsedKey parsed; Status s = ParseKey(key, true /* is_src */, &parsed); if (!s.ok()) { done(s, Args(), Args(), Tensor(), false); return; } local_->RecvAsync(key, Args(), done); } void BaseRemoteRendezvous::StartAbort(const Status& s) { CHECK(!s.ok()); local_->StartAbort(s); { // Aborts all active RecvTensor calls. mutex_lock l(mu_); if (status_.ok()) { status_ = s; for (BaseRecvTensorCall* call : active_) { call->StartAbort(s); } active_.clear(); } } } void BaseRemoteRendezvous::RegisterCall(BaseRecvTensorCall* call) { mutex_lock l(mu_); if (!status_.ok()) { call->StartAbort(status_); } else { CHECK(active_.insert(call).second); } } void BaseRemoteRendezvous::DeregisterCall(BaseRecvTensorCall* call) { mutex_lock l(mu_); active_.erase(call); } } // end namespace tensorflow
6fb5407338a172d61aa2b9f35844b5780f86d34d
ec5609afa7e9e5670cba0230010d5b2197d01cb2
/src/translationsimple.cpp
1cdedd291d2e8b9f735b9802ef85d9a705934206
[ "MIT" ]
permissive
martinhoaragao/solar-system
1c87dd38c555de01f9aa4ccb608552f28208510b
31517fb2bb63268efbd05270c9dba895424bda91
refs/heads/master
2020-04-16T04:00:21.021289
2016-05-24T16:35:45
2016-05-24T16:35:45
52,363,220
0
0
null
null
null
null
UTF-8
C++
false
false
524
cpp
#include "translationsimple.h" TranslationSimple::TranslationSimple() : Translation() { point = Point(); } TranslationSimple::TranslationSimple(Point _point) : Translation() { point = _point; } TranslationSimple::TranslationSimple( float x , float y , float z ) : Translation () { point = Point(x, y, z); } void TranslationSimple::glTranslate() { glTranslatef(point.getX(), point.getY(), point.getZ()); }
5531d649c4e1089a9215c3dc24c60113aad9cf0b
2163a3b3f98436fbeecb3c59a4f652001994f305
/QKickerGoal/3.implementation/QKickerGoal/src/gameplay/Avatar.cpp
cfd52c550f8885c98a1a35214be6a5b78e474a33
[]
no_license
programmersn/QKickerGoal
7f7ba63cf044b0df49c42af74fcdb7772029942f
fc906b706999f35b3a92d9b499bd84b98c977285
refs/heads/master
2020-04-05T23:31:49.240349
2016-10-24T11:04:21
2016-10-24T11:04:21
71,788,127
1
0
null
null
null
null
UTF-8
C++
false
false
3,019
cpp
/** * @file Avatar.h * @author Nouaim Souiki * @date 2014, November 15th * Last modification : 2014, November 17th, by : Nouaim Souiki */ #include <iostream> #include "Avatar.h" #include "Field.h" #include "Team.h" Avatar :: Avatar(Field * field, Ball * ball, Team * team, bool hasKickOff, bool focus) : Footballer(field, ball, team, hasKickOff), m_focused(focus) { // If this Footballer has the kickoff, then it is the owner of the ball. if (this->m_hasKickOff) Footballer::ballOwner = this; m_initPosition = this->computeInitPosition(); this->setPosition(m_initPosition); } Avatar :: ~Avatar() { } QPointF Avatar :: computeInitPosition() { QSizeF fieldSize = m_field->getBoundingRectSize(); qreal delta = 10; if (m_team->hasKickOff()) {// If this Footballer's team has got the kick off if (this->m_hasKickOff) { this->setAppropriatePixmap(Direction::Up); if (m_team->inRightHalfField()) return QPointF(fieldSize.width()/2-15+delta, fieldSize.height()/2-5+delta); else return QPointF(fieldSize.width()/2-15-delta, fieldSize.height()/2+20-delta); } else { this->setAppropriatePixmap(Direction::Down); if (m_team->inRightHalfField()) return QPointF(fieldSize.width()/2-15+delta, fieldSize.height()/2-60+delta); else return QPointF(fieldSize.width()/2-15-delta, fieldSize.height()/2-40-delta); } } else { // If this Footballer's team hasn't got the kickoff. if (this->hasFocus()) { // but this Footballer is focused if(m_team->inRightHalfField()) { this->setAppropriatePixmap(Direction::Left); return QPointF(3*fieldSize.width()/4, fieldSize.height()/4); } else { this->setAppropriatePixmap(Direction::Right); return QPointF(fieldSize.width()/4, fieldSize.height()/4+500); } } else { // but this Footballer is not focused if(m_team->inRightHalfField()) { this->setAppropriatePixmap(Direction::Left); return QPointF(3*fieldSize.width()/4, 3*fieldSize.height()/4); } else { this->setAppropriatePixmap(Direction::Right); return QPointF(fieldSize.width()/4, fieldSize.height()/4+70); } } } return QPointF(); } void Avatar :: reinit() { this->computeInitPosition(); } bool Avatar :: hasFocus() { return m_focused; } void Avatar :: setFocus() { m_focused = true; } void Avatar :: unsetFocus() { if (!this->isBallOwner()) m_focused = false; }
d4f7fa0f701214d6cb023cba1d350d8e3fab600c
1905ebd2eda0ef9c78422b18849271a8fe59dc28
/part3/server_tls.cpp
341e3f7944fd219ffd1bb91e572e85dccf08ca19
[]
no_license
b06705039/Socket
3b8cb7a3fc8ce8272ea936d0e10ca2afd6b65e8f
53850b0466b5e3f32a330bb5b5b2dd7dc96db8a0
refs/heads/master
2022-04-20T01:47:00.369843
2020-04-20T12:11:21
2020-04-20T12:11:21
257,268,983
0
0
null
null
null
null
UTF-8
C++
false
false
11,307
cpp
#include <iostream> #include <stdio.h> #include <sys/socket.h> #include <arpa/inet.h> #include <sys/ioctl.h> #include <net/if.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #include <map> #include <pthread.h> #include <queue> #include <errno.h> #include <sys/types.h> #include <netinet/in.h> #include <resolv.h> #include "openssl/ssl.h" #include "openssl/err.h" #define FAIL -1 #define BUFF_SIZE 1024 #define MaxClientNum 10 #define ThreadPoolNum 2 using namespace std; //------------------- ssl ------------------------------------------------// SSL_CTX* InitServerCTX(void) { const SSL_METHOD *method; SSL_CTX *ctx; OpenSSL_add_all_algorithms(); /* load & register all cryptos, etc. */ SSL_load_error_strings(); /* load all error messages */ method = TLSv1_2_server_method(); /* create new server-method instance */ ctx = SSL_CTX_new(method); /* create new context from method */ if ( ctx == NULL ) { ERR_print_errors_fp(stderr); abort(); } return ctx; } void LoadCertificates(SSL_CTX* ctx, char* CertFile, char* KeyFile) { /* set the local certificate from CertFile */ if ( SSL_CTX_use_certificate_file(ctx, CertFile, SSL_FILETYPE_PEM) <= 0 ) { ERR_print_errors_fp(stderr); abort(); } /* set the private key from KeyFile (may be the same as CertFile) */ if ( SSL_CTX_use_PrivateKey_file(ctx, KeyFile, SSL_FILETYPE_PEM) <= 0 ) { ERR_print_errors_fp(stderr); abort(); } /* verify private key */ if ( !SSL_CTX_check_private_key(ctx) ) { fprintf(stderr, "Private key does not match the public certificate\n"); abort(); } } void ShowCerts(SSL* ssl) { X509 *cert; char *line; cert = SSL_get_peer_certificate(ssl); /* Get certificates (if available) */ if ( cert != NULL ) { printf("Server certificates:\n"); line = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0); printf("Subject: %s\n", line); free(line); line = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0); printf("Issuer: %s\n", line); free(line); X509_free(cert); } else printf("No certificates.\n"); } //------------------- (end) ssl function------------------------------------------------// //------------------- struct------------------------------------------------// struct clientData{ clientData(){} clientData(string name, int bal):_name(name),_balance(bal){} void print(){cout <<" =>this vliend==name: "<< _name <<" , balance: " << _balance << endl;} string _name; int _balance; }; struct connect{ connect(){} connect(char* ip):_ip(ip){} void print(){cout <<" =>this connection==port: "<< _port <<" , ip: " << _ip <<" , userName: " << _userName << endl;} SSL* _ssl; int _port; char *_ip; string _userName; }; //------------------- (end) struct-----------------------------------------// //---------------------- global variable ---------------------------------// map<string, clientData> _allClient; map<SSL, struct connect> _socCli; // we have name in connect queue<SSL> _waitSoc; char *RegCmd = "REGISTER", *ECmd = "Exit\n", *LCmd = "List\n"; //---------------------- (end) global variable -------------------------// //---------------------- global function --------------------------------// size_t myStrGetTok(const string& , string&, size_t , const char ); void * handle_connection(void*); void writeList(char*); void print_allClient(){ // delete later for(map<string, clientData>::iterator li = _allClient.begin(); li != _allClient.end(); li++){ cout << li->first << " == " ; li->second.print(); } } // void print_asocCli(){ // delete later // for(map<int, struct connect>::iterator li = _socCli.begin(); li != _socCli.end(); li++){ // cout << li->first << " == " ; // li->second.print(); // } // } //---------------------- (end) global function ------------------------// //------------------- thread implementation------------------------------------------------// pthread_t thread_pool[ThreadPoolNum]; void * thread_function(void * arg){ SSL *pclient; while(1){ sleep(1); pclient = NULL; if(!_waitSoc.empty()){ SSL* qssl = &_waitSoc.front(); pclient = qssl; _waitSoc.pop(); } if (pclient!=NULL){ handle_connection(pclient); } } } //------------------- (end) thread implementation------------------------------------------------// //------------------- main --------------------------------------------// int main(int argc, char* argv[]){ // initial ssl SSL_CTX *ctx; SSL_library_init(); ctx = InitServerCTX(); /* initialize SSL */ LoadCertificates(ctx, "mycert.pem", "mycert.pem"); /* load certs */ // finish initial ssl int localSocket, remoteSocket; struct sockaddr_in localAddr,remoteAddr; int addrLen = sizeof(struct sockaddr_in); for(int i = 0;i<ThreadPoolNum;i++){ // create thread pool pthread_create(&thread_pool[i], NULL, thread_function, NULL); } localSocket = socket(AF_INET , SOCK_STREAM , 0); if (localSocket == -1){ printf("socket() call failed!!"); return 0; } if(argc!=2){ cerr << "error input" << endl; return 0;} localAddr.sin_family = PF_INET; localAddr.sin_addr.s_addr = INADDR_ANY; localAddr.sin_port = htons(atoi(argv[1])); if( bind(localSocket,(struct sockaddr *)&localAddr , sizeof(localAddr)) < 0) { printf("Can't bind() socket"); return 0; } listen(localSocket , MaxClientNum); cout << "Waiting for connections\n" ; //////////////////// finish set up ///////////////////////// char Message[BUFF_SIZE] = {}; while(1){ // ssl acceot // (end) ssl accept SSL *ssl; remoteSocket = accept(localSocket, (struct sockaddr *)&remoteAddr, (socklen_t*)&addrLen); if(remoteSocket ==-1){ cerr << "error connection" << endl; } int sent; ssl = SSL_new(ctx); /* get new SSL state with context */ strcpy(Message,"Connection accepted\n"); printf("%s\n", Message ); SSL_write(ssl, Message, strlen(Message)); /* send reply */ char *clientip = new char[20]; strcpy(clientip, inet_ntoa(remoteAddr.sin_addr)); struct connect newCon(clientip); SSL storessl = *ssl; _socCli[storessl] = newCon; //handle_connection(pclient); // direactly handle connection -- ok int rm = remoteSocket; SSL_set_fd(ssl, rm); /* set connection socket to SSL state */ _waitSoc.push(storessl); } // end while close(localSocket); /* close server socket */ SSL_CTX_free(ctx); /* release context */ return 0; } //----------------------------------- (end) main ---------------------------------------------// //----------------------------------- handle connection -----------------------------------// void* handle_connection(void* ssl){ SSL* thisssl = (SSL*)ssl; int bytes; //free(pclient); // deleted for multiple thread if ( SSL_accept(thisssl) == FAIL ){ /* do SSL-protocol accept */ ERR_print_errors_fp(stderr); return NULL; } ShowCerts(thisssl); /* get any certificates */ char receiveCmd[BUFF_SIZE] = {}; // receive command char Message[BUFF_SIZE] = {}; // for sending while(bytes = SSL_read(thisssl, receiveCmd, sizeof(receiveCmd)) /* get request */){ receiveCmd[bytes] = '\0'; printf("%s", receiveCmd); char* pos; char* pound = "#"; pos = strtok(receiveCmd,pound); if (strcmp(receiveCmd,ECmd)==0){ // List & Exit strcpy(Message, "Bye"); SSL_write(thisssl, Message, strlen(Message)); /* send reply */ return NULL; } else if (strcmp(receiveCmd,LCmd)==0){ writeList(Message); } else if(pos != NULL){ if(strcmp(pos,RegCmd)==0){ // register cmd pos = strtok(NULL,"\n"); string name(pos); if (_allClient.find(name)==_allClient.end()){ // see if the name exist already clientData newCli(name, 10000); // add if not exist in _allClient _allClient[name] = newCli; strcpy(Message,"100 OK\n"); } else{ strcpy(Message,"210 FAIL\n"); } } // end register else{ // not register, see if it is login string name(pos); if(_allClient.find(name)!=_allClient.end() ){ // if find name if(!_socCli[*thisssl]._userName.empty()){ // only one person can login in a time strcpy(Message,"220 AUTH_FAIL\n"); } else{ _socCli[*thisssl]._userName=name; pos = strtok(NULL,"\n"); int portN = atoi(pos); _socCli[*thisssl]._port=portN; _socCli[*thisssl]._ssl=thisssl; sprintf(Message, "%d\n", _allClient[name]._balance); // send balance } } else{ strcpy(Message,"220 AUTH_FAIL\n"); } } } cout << "the ready to send msg: " << Message ; // trytry SSL_write(thisssl, Message, strlen(Message)); /* send reply */ bzero(Message,sizeof(Message)); } // end accept while return NULL; } //----------------------------------- (end) handle connection -----------------------------------// //----------------------------------- global function implement ---------------------------------// size_t myStrGetTok(const string& str, string& tok, size_t pos = 0, const char del = ' ') { size_t begin = str.find_first_not_of(del, pos); if (begin == string::npos) { tok = ""; return begin; } size_t end = str.find_first_of(del, begin); tok = str.substr(begin, end - begin); return end; } void writeList(char* msg){ int onlineC=0; char clientMsg[BUFF_SIZE] = {}; char temp[BUFF_SIZE] = {}; for(map<SSL, struct connect>::iterator li = _socCli.begin(); li != _socCli.end(); li++){ if(!li->second._userName.empty()){ onlineC++; strcat(clientMsg,li->second._userName.c_str()); strcat(clientMsg,"#"); strcat(clientMsg, li->second._ip); strcat(clientMsg,"#"); sprintf(temp, "%d\n", li->second._port); strcat(clientMsg, temp); } } sprintf(msg, "number of accounts online: %d\n", onlineC); strcat(msg, clientMsg); } //----------------------------------- (end) global function implement -------------------------//
31a5d3746f5f53996ebefce5198483cb691145b3
5f4b7850caed77bf1d2ca8d5125dc21099b79209
/Chapter 1-Introduction to programming/&1.cpp
52487f3850bf1f09c8a1d8f30f0afc3938271c93
[]
no_license
Inuyashaaaaa/IntroductionToAlgorithmicContests
92720cffae226b6951aa389a14fcaacb94b3c275
55c69843f42162ed3b8f661c20f451c1174bfff1
refs/heads/master
2020-06-20T00:24:10.893652
2020-03-14T06:32:12
2020-03-14T06:32:12
196,926,192
2
0
null
null
null
null
UTF-8
C++
false
false
194
cpp
#include<stdio.h> int main() { int a = 1; for(;a>0;) { a+= 10000; } a-=10000; for(;a>0;) { a +=1; } printf("%d\n",a-1); printf("%d\n",a); return 0; } //2147483647 //-2147483648
1660a2c3f03c0eb45f1a855f1370914bf4bfb4ce
9515e3321c33709258e4686a7cd71e98a8c3a03e
/3p/VTK/ThirdParty/vtkm/vtk-m/vtkm/cont/testing/UnitTestArrayPortalToIterators.cxx
33c874dac1a437416ca1036c4608707de729de30
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
Mason-Wmx/ViewFramework
f9bc534df86f5cf640a9dbf963b9ea17a8e93562
d8117adc646c369ad29d64477788514c7a75a797
refs/heads/main
2023-06-29T04:12:37.042638
2021-07-28T09:26:55
2021-07-28T09:26:55
374,267,631
1
0
null
null
null
null
UTF-8
C++
false
false
5,325
cxx
//============================================================================ // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. // // Copyright 2014 National Technology & Engineering Solutions of Sandia, LLC (NTESS). // Copyright 2014 UT-Battelle, LLC. // Copyright 2014 Los Alamos National Security. // // Under the terms of Contract DE-NA0003525 with NTESS, // the U.S. Government retains certain rights in this software. // // Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National // Laboratory (LANL), the U.S. Government retains certain rights in // this software. //============================================================================ #include <vtkm/cont/ArrayPortalToIterators.h> #include <vtkm/VecTraits.h> #include <vtkm/cont/testing/Testing.h> namespace { template <typename T> struct TemplatedTests { static constexpr vtkm::Id ARRAY_SIZE = 10; using ValueType = T; using ComponentType = typename vtkm::VecTraits<ValueType>::ComponentType; static ValueType ExpectedValue(vtkm::Id index, ComponentType value) { return ValueType(static_cast<ComponentType>(index + static_cast<vtkm::Id>(value))); } class ReadOnlyArrayPortal { public: using ValueType = T; VTKM_CONT ReadOnlyArrayPortal(ComponentType value) : Value(value) { } VTKM_CONT vtkm::Id GetNumberOfValues() const { return ARRAY_SIZE; } VTKM_CONT ValueType Get(vtkm::Id index) const { return ExpectedValue(index, this->Value); } private: ComponentType Value; }; class WriteOnlyArrayPortal { public: using ValueType = T; VTKM_CONT WriteOnlyArrayPortal(ComponentType value) : Value(value) { } VTKM_CONT vtkm::Id GetNumberOfValues() const { return ARRAY_SIZE; } VTKM_CONT void Set(vtkm::Id index, const ValueType& value) const { VTKM_TEST_ASSERT(value == ExpectedValue(index, this->Value), "Set unexpected value in array portal."); } private: ComponentType Value; }; template <class IteratorType> void FillIterator(IteratorType begin, IteratorType end, ComponentType value) { std::cout << " Check distance" << std::endl; VTKM_TEST_ASSERT(std::distance(begin, end) == ARRAY_SIZE, "Distance between begin and end incorrect."); std::cout << " Write expected value in iterator." << std::endl; vtkm::Id index = 0; for (IteratorType iter = begin; iter != end; iter++) { *iter = ExpectedValue(index, value); index++; } } template <class IteratorType> bool CheckIterator(IteratorType begin, IteratorType end, ComponentType value) { std::cout << " Check distance" << std::endl; VTKM_TEST_ASSERT(std::distance(begin, end) == ARRAY_SIZE, "Distance between begin and end incorrect."); std::cout << " Read expected value from iterator." << std::endl; vtkm::Id index = 0; for (IteratorType iter = begin; iter != end; iter++) { VTKM_TEST_ASSERT(ValueType(*iter) == ExpectedValue(index, value), "Got bad value from iterator."); index++; } return true; } void TestIteratorRead() { using ArrayPortalType = ReadOnlyArrayPortal; using GetIteratorsType = vtkm::cont::ArrayPortalToIterators<ArrayPortalType>; static const ComponentType READ_VALUE = 23; ArrayPortalType portal(READ_VALUE); std::cout << " Testing read-only iterators with ArrayPortalToIterators." << std::endl; GetIteratorsType iterators(portal); CheckIterator(iterators.GetBegin(), iterators.GetEnd(), READ_VALUE); std::cout << " Testing read-only iterators with convenience functions." << std::endl; CheckIterator(vtkm::cont::ArrayPortalToIteratorBegin(portal), vtkm::cont::ArrayPortalToIteratorEnd(portal), READ_VALUE); } void TestIteratorWrite() { using ArrayPortalType = WriteOnlyArrayPortal; using GetIteratorsType = vtkm::cont::ArrayPortalToIterators<ArrayPortalType>; static const ComponentType WRITE_VALUE = 63; ArrayPortalType portal(WRITE_VALUE); std::cout << " Testing write-only iterators with ArrayPortalToIterators." << std::endl; GetIteratorsType iterators(portal); FillIterator(iterators.GetBegin(), iterators.GetEnd(), WRITE_VALUE); std::cout << " Testing write-only iterators with convenience functions." << std::endl; FillIterator(vtkm::cont::ArrayPortalToIteratorBegin(portal), vtkm::cont::ArrayPortalToIteratorEnd(portal), WRITE_VALUE); } void operator()() { TestIteratorRead(); TestIteratorWrite(); } }; struct TestFunctor { template <typename T> void operator()(T) const { TemplatedTests<T> tests; tests(); } }; void TestArrayPortalToIterators() { vtkm::testing::Testing::TryTypes(TestFunctor()); } } // Anonymous namespace int UnitTestArrayPortalToIterators(int, char* []) { return vtkm::cont::testing::Testing::Run(TestArrayPortalToIterators); }
daf66914b589a83770f22ef3ab065407c6c8ef86
1213bcf770a94a89b39be8dc7b99a3f7e35fd369
/src/xenia/hid/xinput/xinput_hid-private.h
264fbfd37ee91b39a648a256f880af0501dc046f
[]
no_license
wtfaremyinitials/xenia
c86e4625a1dd084d97d44c3242e2faf208bca2b8
16b3ecd5897051f82bc236ad9a4d0ab5cab22e87
refs/heads/master
2020-12-31T02:43:53.168712
2014-01-14T22:06:05
2014-01-14T22:06:05
15,918,955
2
0
null
null
null
null
UTF-8
C++
false
false
821
h
/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2013 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #ifndef XENIA_HID_XINPUT_XINPUT_HID_PRIVATE_H_ #define XENIA_HID_XINPUT_XINPUT_HID_PRIVATE_H_ #include <xenia/core.h> #include <xenia/hid/xinput/xinput_hid.h> namespace xe { namespace hid { namespace xinput { } // namespace xinput } // namespace hid } // namespace xe #endif // XENIA_HID_XINPUT_XINPUT_HID_PRIVATE_H_
f7c808f83a7041de08a96d5b1658e36988832fa8
061348a6be0e0e602d4a5b3e0af28e9eee2d257f
/Source/Contrib/Physics/src/ODE/OSGPhysicsWorld.inl
cfcf0b7de8455ac2897cd319dd07aaa627f24adf
[]
no_license
passthefist/OpenSGToolbox
4a76b8e6b87245685619bdc3a0fa737e61a57291
d836853d6e0647628a7dd7bb7a729726750c6d28
refs/heads/master
2023-06-09T22:44:20.711657
2010-07-26T00:43:13
2010-07-26T00:43:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,098
inl
/*---------------------------------------------------------------------------*\ * OpenSG * * * * * * Copyright (C) 2000-2006 by the OpenSG Forum * * * * contact: David Kabala ([email protected]), Behboud Kalantary * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * License * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Library General Public License as published * * by the Free Software Foundation, version 2. * * * * 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 * * Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * Changes * * * * * * * * * * * * * \*---------------------------------------------------------------------------*/ //--------------------------------------------------------------------------- // Includes //--------------------------------------------------------------------------- OSG_BEGIN_NAMESPACE inline PhysicsHandlerUnrecPtr PhysicsWorld::getParentHandler(void) const { return getInternalParentHandler(); } OSG_END_NAMESPACE
14eb930ab53ecb97774b2aeb45685ffa124b7be4
28abd2dff0608190b112a25a316f6ac92f1d93b9
/sources/Window.cpp
18e2274dc3488d1c2085f12b352b6527b5db3857
[ "MIT" ]
permissive
wiali/Echeyde
663ba83238d80e8d2f02bfee1eb539bd6bb33d2a
d51242b5af86562c60d65250f2fa5f485acffe78
refs/heads/master
2020-04-07T00:18:21.742785
2017-09-30T02:49:11
2017-09-30T02:49:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,889
cpp
#include "../headers/Window.h" #include "../headers/Importer.h" #include "../headers/Camera.h" #include "../headers/Renderer.h" #include "../headers/Light.h" #include "../headers/GameObject.h" #include "../headers/Terrain.h" #include "../headers/Skybox.h" #include "../headers/Framebuffer.h" #include "../headers/GUI.h" #include <SOIL\SOIL.h> Window::Window(const std::string name , Uint16 width , Uint16 height,KInputs &inputs , Echeyde::Scene &sc) { dimensions.height = height; dimensions.width = width; input = &inputs; window = SDL_CreateWindow(name.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_OPENGL|SDL_WINDOW_SHOWN); if (window == nullptr) { std::cout << "Window Creation error !" << "\n"; SDL_Quit(); } context = SDL_GL_CreateContext(window); if (context == 0) { std::cout << "Context creation error !" << "\n"; SDL_DestroyWindow(window); SDL_Quit(); } #ifdef WIN32 GLenum erno = glewInit(); if (erno != GLEW_OK) { std::cout << "GLEW initialization fucked up!" << "\n"; SDL_GL_DeleteContext(context); SDL_DestroyWindow(window); SDL_Quit(); } #endif loop = true; scene = &sc; glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glCullFace(GL_BACK); } Window::~Window() { SDL_GL_DeleteContext(context); SDL_DestroyWindow(window); } Dim Window::getDimensions() { return dimensions; } void Window::Loop() { BaseShader *shader = new BaseShader(std::string("vertex.vert"), std::string("fragment.frag") , std::string("geometry.geom")); BaseShader *terrain_shader = new BaseShader(std::string("terrain.vert"), std::string("terrain.frag"), std::string("terrain.geom")); Shader* shadowShader = new BaseShader(std::string("depth.vert"), std::string("depth.frag")); BaseShader gui(std::string("gui.vert"), std::string("gui.frag")); std::vector<object_data> st; std::vector<object_data> si, sb ; SkyboxShader skybox_shader("skybox.vert", "skybox.frag"); Skybox skybox(SKYBOX_LOCATION + "test.dds", skybox_shader); terrain_data_struct terrain_geometry = TerrainGenerator::generateTerrain("heightmap.png"); //geometry_data terrain_g = TerrainGenerator::generateTerrain(10); //terrain_data_struct terrain_geometry; //terrain_geometry.terrain_data = terrain_g; try { st = Echeyde::FILEIO::Importer::load_model(std::string("cube.obj"),true); si = Echeyde::FILEIO::Importer::load_model(std::string("objects.obj"),false); sb = Echeyde::FILEIO::Importer::load_model(std::string("pit.obj"), false); } catch (const File_not_found &e) { std::cout << e.what() << std::endl; } catch (const MaterialException &e) { std::cout << e.what() << std::endl; } catch (const Importer_Error &e) { std::cout << e.what() << std::endl; } Renderer *renderer = Renderer::getInstance(); LightArray *lights = LightArray::getInstance(); Framebuffer framebuffer(WIDTH, HEIGHT); Framebuffer shadowframebuffer(1024, 1024); Texture A ( shadowframebuffer.getDepthTexture() , "shadow"); // ViewCamera light_view(70.f, float(WIDTH / HEIGHT), 0.1f, 2000.f, glm::vec3(0, 1, 0)); // GameObject sun = GameObject(sb, shader, true, true); // sun.scale(glm::vec3(10, 10, 10)); GUI cube = GUI(st, &gui, true, false); cube.translate(glm::vec3(0.6, 0.6 , 0.1)); cube.scale(glm::vec3(0.3, 0.1, 0.3)); GameObject house = GameObject(sb, shader, true, false); house.scale(glm::vec3(10, 10, 10)); GameObject objects = GameObject(si, shader, true, true); objects.setTexture(A, Echeyde::SHADOWMAP0); house.setTexture(A, Echeyde::SHADOWMAP0); objects.translate(glm::vec3(430, 1, 430)); cube.setTexture(A, Echeyde::DIFFUSE0); material_data mat_data ; object_data terrain_obj; mat_data.transparency = false; terrain_obj.data = terrain_geometry.terrain_data; mat_data.textures.diffuse = TEXTURES_LOCATION + "/ground" + "/dirt" + "/dirt_01.png"; mat_data.textures.opacity = TEXTURES_LOCATION + "/blendmaps" + "/blend.png"; mat_data.textures.normal = TEXTURES_LOCATION + "/ground" + "/gravel_01.png"; mat_data.textures.optional = TEXTURES_LOCATION + "/ground" + "/snow" + "/snow_1.png"; mat_data.textures.blend = TEXTURES_LOCATION + "/ground" + "/grass" + "/grass_02.png"; terrain_obj.material = mat_data; std::vector<object_data> ob; ob.push_back(terrain_obj); Terrain terrain = Terrain(ob, terrain_shader, true, true , terrain_geometry.collision_map); terrain.setTexture(A, Echeyde::SHADOWMAP0); //GameObject obj2 = GameObject(si, shader, true, false); shader_light_data data; //light_view.setPosition(glm::vec3(500, 90, 300), glm::vec3(300, 90, 200)); data.base.position = glm::vec3(10, 2, 3); data.attenuation = glm::vec3(1, 10, 100); data.radius = 100.f; data.base.colour = glm::vec3(0.6, 0.4, 0.2); data.base.power = 50.F; lights->addLight(new PointLight(data.base, data.radius, data.attenuation)); data.base.position = glm::vec3(300 ,300, 300); data.base.colour = glm::vec3(1., 1., 1.); data.base.power = 0.2F; lights->addLight(new DirectionalLight(data.base)); data.base.position = glm::vec3(300, 5, 400); data.attenuation = glm::vec3(10, 100, 100); data.radius = 100.f; data.base.colour = glm::vec3(0.2, 0.3, 0.6); data.base.power = 700.F; lights->addLight(new PointLight(data.base, data.radius, data.attenuation)); data.base.position = glm::vec3(400, 10, 400); data.attenuation = glm::vec3(1, 1, 10); data.radius = 100.f; data.base.colour = glm::vec3(0.6, 0.1, 0.3); data.base.power = 100.F; lights->addLight(new PointLight(data.base, data.radius, data.attenuation)); Camera user_camera = Camera(5.f, 5.f, glm::vec3(0, 1, 0), 120.f, float(17/9), 0.1f, 5000.f); user_camera.setPosition(glm::vec3(500, 90, 300)); SDL_Event event; float i = 10 , j = 400 , k = 400 , pow = 50 , ro = 0.; while (loop) { GLuint t1 = SDL_GetTicks(); SDL_GL_SwapWindow(window); DirectionalLight *P = dynamic_cast<DirectionalLight*>(lights->getLightArray()[1]); while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) loop = false; if (event.key.keysym.sym == SDLK_ESCAPE) loop= false; if (event.key.keysym.sym == SDLK_KP_8) i+=1.5f; if (event.key.keysym.sym == SDLK_KP_2) i-=1.5f; if (event.key.keysym.sym == SDLK_KP_4) j += 1.5f; if (event.key.keysym.sym == SDLK_KP_6) j -= 1.5f; if (event.key.keysym.sym == SDLK_KP_9) k += 1.5f; if (event.key.keysym.sym == SDLK_KP_3) k -= 1.5f; if (event.key.keysym.sym == SDLK_KP_PLUS) pow += 1.5f; if (event.key.keysym.sym == SDLK_KP_MINUS) pow -= 1.5f; if (event.key.keysym.sym == SDLK_f) SOIL_save_screenshot("screenshot.bmp", SOIL_SAVE_TYPE_BMP, 0, 0, 1920, 1080); user_camera.Move(event); // user_camera.print_data(); // std::cout << "Height : " << terrain.getHeight(user_camera.getPosition().x, user_camera.getPosition().y)<< "\n"; } cube.isDisplayed(false); house.translate(glm::vec3(j, terrain.getHeightCollisionMap(j , k), k)); glm::vec3 pos = user_camera.getPosition(); objects.translate(glm::vec3(j+50, i, k+50)); ro += 0.1f; objects.rotate(ro, glm::vec3(0, 1, 0)); ViewCamera light_view(-200.f, 200.f, -200.f, 200.f, 1.f, 10000.f,glm::vec3(0,1,0)); light_view.setPosition((P->getPosition()+pos)-glm::vec3(50,50,50), pos); renderer->renderShadowMap(light_view, shadowframebuffer, shadowShader); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // sun.isDisplayed(true); cube.isDisplayed(true); renderer->renderAll(user_camera, &skybox , light_view); GLuint t2 = SDL_GetTicks(); //std::cout << "time : " << t2 - t1 << std::endl; //SDL_Delay(15); } TextureArray::clean(); framebuffer.clean(); shadowframebuffer.clean(); skybox.clean(); renderer->destroy(); lights->clean(); shadowShader->clean(); delete shadowShader; delete shader; delete terrain_shader; }
9899b63ce7507fb46bf38ee41dea364c35adcff1
af76b549c097c27bbcab55d7ea1e9fc514dd900d
/source/FrontTransforms/ExprOptimization/BinaryOperators.h
e4147acd682b41b6891e427d40bf49d6f0698964
[ "BSD-3-Clause" ]
permissive
OpsGroup/open-ops
6d88b2da7cb0a65967c87a26c8a439306b304b8c
b1ab8da354c4aecc0fe76a562395f5861bffc207
refs/heads/master
2023-06-22T06:23:51.731609
2017-10-25T14:43:28
2017-10-25T14:43:28
98,927,791
25
3
BSD-3-Clause
2023-06-09T11:44:43
2017-07-31T20:39:14
C++
UTF-8
C++
false
false
2,732
h
#ifndef EXPRESSION_OPTIMIZATION_BINARY_OPERATIONS_H #define EXPRESSION_OPTIMIZATION_BINARY_OPERATIONS_H #include "Reprise/Reprise.h" #include "FrontTransforms/BaseOperator.h" namespace OPS { namespace ExpressionSimplifier { namespace Calculation { using OPS::Reprise::BasicCallExpression; using OPS::Reprise::ExpressionBase; class BinaryPlusOperator : public BaseOperator { public: virtual ExpressionBase* calculate(BasicCallExpression*&); }; class BinaryMinusOperator : public BaseOperator { public: virtual ExpressionBase* calculate(BasicCallExpression*&); }; class MultiplyOperator : public BaseOperator { public: virtual ExpressionBase* calculate(BasicCallExpression*&); }; class DivisionOperator : public BaseOperator { public: virtual ExpressionBase* calculate(BasicCallExpression*&); }; class IntegerDivisionOperator : public BaseOperator { public: virtual ExpressionBase* calculate(BasicCallExpression*&); }; class IntegerModOperator : public BaseOperator { public: virtual ExpressionBase* calculate(BasicCallExpression*&); }; /* Equality operators */ class LessOperator : public BaseOperator { public: virtual ExpressionBase* calculate(BasicCallExpression*&); }; class GreaterOperator : public BaseOperator { public: virtual ExpressionBase* calculate(BasicCallExpression*&); }; class LessEqualOperator : public BaseOperator { public: virtual ExpressionBase* calculate(BasicCallExpression*&); }; class GreaterEqualOperator : public BaseOperator { public: virtual ExpressionBase* calculate(BasicCallExpression*&); }; class EqualOperator : public BaseOperator { public: virtual ExpressionBase* calculate(BasicCallExpression*&); }; class NotEqualOperator : public BaseOperator { public: virtual ExpressionBase* calculate(BasicCallExpression*&); }; /* Shift operators */ class LeftShiftOperator : public BaseOperator { public: virtual ExpressionBase* calculate(BasicCallExpression*&); }; class RightShiftOperator : public BaseOperator { public: virtual ExpressionBase* calculate(BasicCallExpression*&); }; /* Logical */ class LogicalAndOperator : public BaseOperator { public: virtual ExpressionBase* calculate(BasicCallExpression*&); }; class LogicalOrOperator : public BaseOperator { public: virtual ExpressionBase* calculate(BasicCallExpression*&); }; /* Bitwise */ class BitwiseAndOperator : public BaseOperator { public: virtual ExpressionBase* calculate(BasicCallExpression*&); }; class BitwiseOrOperator : public BaseOperator { public: virtual ExpressionBase* calculate(BasicCallExpression*&); }; class BitwiseXorOperator : public BaseOperator { public: virtual ExpressionBase* calculate(BasicCallExpression*&); }; } } } #endif
cec36cad3fe56605a379464cd7d879eea376ee78
cd6dda7aff19bed5b6f4d673f84e9896dac666ff
/modules/plotting/properties/plottextproperty.cpp
0e5f697bf6ca601958b8af80113b4e096d71ec9a
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
victorca25/inviwo
755478d79c1417f1649318b4ad87155cd8c3fa61
34b6675f6b791a08e358d24aea4f75d5baadc6da
refs/heads/master
2020-03-31T04:37:36.492568
2018-10-10T19:10:12
2018-10-10T19:10:12
151,914,041
0
0
BSD-2-Clause
2018-10-10T19:10:13
2018-10-07T06:50:48
C++
UTF-8
C++
false
false
3,080
cpp
/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2017 Inviwo Foundation * 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 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 <modules/plotting/properties/plottextproperty.h> namespace inviwo { namespace plot { PropertyClassIdentifier(PlotTextProperty, "org.inviwo.PlotTextProperty"); PlotTextProperty::PlotTextProperty(const std::string& identifier, const std::string& displayName, bool checked, InvalidationLevel invalidationLevel, PropertySemantics semantics) : BoolCompositeProperty(identifier, displayName, checked, invalidationLevel, semantics) , title_("title", "Title", "") , color_("color", "Color", vec4(vec3(0.0f), 1.0f), vec4(0.0f), vec4(1.0f)) , position_("position", "Position", 0.5f, 0.0f, 1.0f) , offset_("offset", "Offset", 10.0f, 0.0f, 100.0f) , font_("font", "Font") { color_.setSemantics(PropertySemantics::Color); addProperty(title_); addProperty(color_); addProperty(offset_); addProperty(position_); addProperty(font_); } PlotTextProperty::PlotTextProperty(const PlotTextProperty& rhs) : BoolCompositeProperty(rhs) , title_(rhs.title_) , color_(rhs.color_) , position_(rhs.position_) , offset_(rhs.offset_) , font_(rhs.font_) { color_.setSemantics(PropertySemantics::Color); addProperty(title_); addProperty(color_); addProperty(offset_); addProperty(position_); addProperty(font_); } PlotTextProperty* PlotTextProperty::clone() const { return new PlotTextProperty(*this); } } // namespace plot } // namespace inviwo
8d62d46fe21e239df57b9e78ad4a51c89b5c8001
c39862dcbc5b9ad65f582752bcfd0c5eb9be463e
/dev/src/recompiler_tools/timeMachineView.cpp
3688f9bc8261ea0456a0c258c56f2537ef4574d6
[ "MIT" ]
permissive
rexdex/recompiler
5f1138adf5d02a052c8b37c290296d5cf5faadc2
7cd1d5a33d6c02a13f972c6564550ea816fc8b5b
refs/heads/master
2023-08-16T16:24:37.810517
2022-02-12T21:20:21
2022-02-12T21:20:21
81,953,901
1,714
120
MIT
2022-02-12T21:20:22
2017-02-14T14:32:17
C++
UTF-8
C++
false
false
22,783
cpp
#include "build.h" #include "timeMachineView.h" #include "progressDialog.h" namespace tools { //--------------------------------------------------------------------------- static wxPoint RectCenter(const wxRect& rect) { return wxPoint(rect.GetLeft() + rect.GetWidth() / 2, rect.GetTop() + rect.GetHeight() / 2); } //--------------------------------------------------------------------------- TimeMachineView::SlotInfo::SlotInfo(timemachine::Trace* trace, LayoutInfo* node, const timemachine::Entry::AbstractDependency* dependency) : m_name(dependency->GetCaption()) , m_node(node) , m_offset(0, 0) , m_abstractDep(dependency) , m_abstractSource(nullptr) { m_value = dependency->GetValue(trace); } TimeMachineView::SlotInfo::SlotInfo(timemachine::Trace* trace, LayoutInfo* node, const timemachine::Entry::AbstractSource* source) : m_name(source->GetCaption()) , m_node(node) , m_offset(0, 0) , m_abstractDep(nullptr) , m_abstractSource(source) { m_value = source->GetValue(trace); } TimeMachineView::SlotInfo::~SlotInfo() { } //--------------------------------------------------------------------------- TimeMachineView::LayoutInfo::LayoutInfo(timemachine::Trace* trace, const timemachine::Entry* entry) : m_position(0, 0) , m_size(100, 30) , m_entry(entry) , m_orderingIndex(entry->GetTraceIndex()) , m_renderingLevel(0) , m_basePositionY(0) { // determine display m_caption = entry->GetDisplay(); // create input slots const uint32 numInputs = entry->GetNumDependencies(); for (uint32 i = 0; i < numInputs; ++i) { const auto* dep = entry->GetDependency(i); m_inputs.push_back(new SlotInfo(trace, this, dep)); } // create output slots const uint32 numOutputs = entry->GetNumSources(); for (uint32 i = 0; i < numOutputs; ++i) { const auto* res = entry->GetSource(i); m_outputs.push_back(new SlotInfo(trace, this, res)); } } TimeMachineView::LayoutInfo::~LayoutInfo() { // disconnect all sockets for (auto it : m_inputs) delete it; for (auto it : m_outputs) delete it; } //--------------------------------------------------------------------------- BEGIN_EVENT_TABLE(TimeMachineView, wxScrolledWindow) EVT_PAINT(TimeMachineView::OnPaint) EVT_ERASE_BACKGROUND(TimeMachineView::OnErase) EVT_MOUSE_EVENTS(TimeMachineView::OnMouse) END_EVENT_TABLE(); TimeMachineView::TimeMachineView(wxWindow* parent, class timemachine::Trace* trace, INavigationHelper* navigator) : wxScrolledWindow(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxFULL_REPAINT_ON_RESIZE) , m_requestedLayoutChange(0) , m_trace(trace) , m_mouseMode(0) , m_highlightSlot(nullptr) , m_highlightNode(nullptr) , m_navigator(navigator) { // get default font m_drawFont = wxFont(10, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false, wxT("Arial")); // canvas style SetBackgroundStyle(wxBG_STYLE_PAINT); SetScrollPageSize(wxVERTICAL, 16); SetScrollPageSize(wxHORIZONTAL, 16); SetVirtualSize(AREA_SIZE, AREA_SIZE); SetScrollRate(1, 1); // create the root node layout auto* rootNode = GetLayoutNode(m_trace->GetRoot()); rootNode->m_position = wxPoint(AREA_SIZE / 2, AREA_SIZE / 2); rootNode->m_basePositionY = AREA_SIZE / 2; ShowRootNode(); } TimeMachineView::~TimeMachineView() { // delete visual nodes ClearNodes(); // trace data is owned by the view, delete it if (m_trace) { delete m_trace; m_trace = nullptr; } } const TraceFrameID TimeMachineView::GetRootTraceIndex() const { return m_trace->GetRoot()->GetTraceIndex(); } void TimeMachineView::ShowRootNode() { m_requestedLayoutChange = 1; } void TimeMachineView::ShowAllNodes() { m_requestedLayoutChange = 2; } void TimeMachineView::DoShowRootNode() { // no nodes if (m_nodes.empty()) return; // make sure block layout is up to date PrepareLayout(); // find center of the root node const auto rootNode = GetLayoutNode(m_trace->GetRoot()); const auto rootCenter = rootNode->m_position + (rootNode->m_size / 2); // offset to center node, reset zoom const auto size = GetClientSize(); const auto scrollPos = rootCenter - (size / 2); Scroll(scrollPos); } void TimeMachineView::ClearNodes() { // reset trace m_trace = nullptr; // delete all display nodes for (auto it : m_nodes) delete it.second; } void TimeMachineView::DeselectAll() { m_selection.clear(); Refresh(); } void TimeMachineView::Select(const timemachine::Entry* entry, const bool isSelected) { auto it = std::find(m_selection.begin(), m_selection.end(), entry); if (!isSelected && (it != m_selection.end())) { m_selection.erase(it); Refresh(); } else if (isSelected && it == m_selection.end()) { m_selection.push_back(entry); Refresh(); } } const bool TimeMachineView::IsSelected(const timemachine::Entry* entry) const { return std::find(m_selection.begin(), m_selection.end(), entry) != m_selection.end(); } const timemachine::Entry* TimeMachineView::GetEntryAtPos(const wxPoint mousePos) { PrepareLayout(); for (auto it : m_nodes) { const auto rect = it.second->GetRect(); if (rect.Contains(mousePos)) return it.first; } return nullptr; } TimeMachineView::SlotInfo* TimeMachineView::GetUnconnectedSlotAtPos(const wxPoint mousePos) { PrepareLayout(); for (auto it : m_nodes) { const auto* node = it.second; // check inputs for (auto jt : node->m_inputs) { if (!jt->HasConnections()) { const auto rect = jt->GetUnconnectedBox(); if (rect.Contains(mousePos)) return jt; } } // check outputs for (auto jt : node->m_outputs) { if (!jt->HasConnections()) { const auto rect = jt->GetUnconnectedBox(); if (rect.Contains(mousePos)) return jt; } } } // nothing found return nullptr; } void TimeMachineView::ExploreSlot(SlotInfo* slot) { // resolve the dependencies if (slot && slot->m_abstractDep) { std::vector< const timemachine::Entry::AbstractSource* > resolvedSources; // resolve the sources ProgressDialog dlg(this, wxTheApp->GetLogWindow(), true); dlg.RunLongTask([&resolvedSources, slot, this](ILogOutput& log) { slot->m_abstractDep->Resolve(log, m_trace, resolvedSources); return 0; }); // create the layouts and connect the blocks std::vector< SlotInfo* > addedSlots; for (auto it : resolvedSources) { // get matching slot auto otherSlot = GetLayoutSlot(it); if (otherSlot != nullptr) { // collect the added nodes addedSlots.push_back(otherSlot); // connect if (slot->ConnectOneSide(otherSlot)) { otherSlot->ConnectOneSide(slot); } } } // resolve layout PrepareLayout(); // compute placement of the new nodes if (addedSlots.size() == 1) { auto* otherSlot = addedSlots[0]; // align the input and output socket const int inputX = slot->m_offset.x + slot->m_node->m_position.x; const int outputX = otherSlot->m_offset.x + otherSlot->m_node->m_position.x; // how much should we move the output block ? const int deltaX = outputX - inputX; otherSlot->m_node->m_position.x -= deltaX; } // redraw Refresh(); } } TimeMachineView::LayoutInfo* TimeMachineView::GetLayoutNode(const timemachine::Entry* entry) { // invalid entry if (!entry) return nullptr; // find existing auto it = m_nodes.find(entry); if (it != m_nodes.end()) return it->second; // create new entry LayoutInfo* info = new LayoutInfo(m_trace, entry); m_nodes[entry] = info; // add to list of dirty nodes m_dirtyNodes.push_back(info); // return created layout info return info; } TimeMachineView::SlotInfo* TimeMachineView::GetLayoutSlot(const timemachine::Entry::AbstractSource* source) { // invalid source if (!source) return nullptr; // get the layout for the parent node auto entryLayout = GetLayoutNode(source->GetEntry()); if (!entryLayout) return nullptr; // find matching stuff for (auto it : entryLayout->m_inputs) { if (it->m_abstractSource == source) return it; } // find matching stuff for (auto it : entryLayout->m_outputs) { if (it->m_abstractSource == source) return it; } // not found return nullptr; } TimeMachineView::SlotInfo* TimeMachineView::GetLayoutSlot(const timemachine::Entry::AbstractDependency* dep) { // invalid source if (!dep) return nullptr; // get the layout for the parent node auto entryLayout = GetLayoutNode(dep->GetEntry()); if (!entryLayout) return nullptr; // find matching stuff for (auto it : entryLayout->m_inputs) { if (it->m_abstractDep == dep) return it; } // find matching stuff for (auto it : entryLayout->m_outputs) { if (it->m_abstractDep == dep) return it; } // not found return nullptr; } void TimeMachineView::PrepareNodePlacement() { // reset depth of all nodes for (auto it : m_nodes) { auto node = it.second; node->m_renderingLevel = INT_MIN; } // layout params const int marginX = 40; const int marginY = 80; // root node is at depth 0 auto rootNode = GetLayoutNode(m_trace->GetRoot()); // get all nodes std::vector< LayoutInfo* > allNodes; for (const auto it : m_nodes) { allNodes.push_back(it.second); } // sort nodes by the ordering value std::sort(allNodes.begin(), allNodes.end(), LayoutInfo::SortByOrderingInfo); // setup levels int rootIndex = 0; for (int i = 0; i < (int)allNodes.size(); ++i) { if (allNodes[i] == rootNode) { rootIndex = i; break; } } // enumerate nodes for (int i = 0; i < (int)allNodes.size(); ++i) { allNodes[i]->m_renderingLevel = i - rootIndex; } // count number of nodes at each depth std::map< int32, int32 > nodeHeightY; int maxDepth = 0; int minDepth = 0; for (auto it : m_nodes) { const auto node = it.second; const auto level = node->m_renderingLevel; // take max of vertical sizes nodeHeightY[level] = std::max(nodeHeightY[level], node->m_size.y); // compute min/max level minDepth = std::min(minDepth, level); maxDepth = std::max(maxDepth, level); } // compute the vertical placement of the rows std::map< int32, int32 > nodePlacementY; auto* rootNodeLayout = GetLayoutNode(m_trace->GetRoot()); nodePlacementY[0] = rootNodeLayout->m_position.y; // place the nodes with depth > 0 for (int32 depth = 1; depth <= maxDepth; ++depth) { const int height = (nodeHeightY[depth - 1] + marginY); nodePlacementY[depth] = nodePlacementY[depth - 1] - height; } // place the nodes with depth < 0 for (int32 depth = -1; depth >= minDepth; --depth) { const int height = (nodeHeightY[depth] + marginY); nodePlacementY[depth] = nodePlacementY[depth + 1] + height; } // place the nodes according to their depth (Y) and position for (auto it : m_nodes) { auto node = it.second; const auto level = node->m_renderingLevel; if (node != rootNodeLayout) { int offsetY = node->m_position.y - node->m_basePositionY; node->m_basePositionY = nodePlacementY[level]; node->m_position.y = node->m_basePositionY + offsetY; } } } void TimeMachineView::PrepareLayout() { // get the dirty nodes auto nodes = std::move(m_dirtyNodes); if (nodes.empty()) return; // style const uint32 slotSeparation = 20; const uint32 innerMarginX = 30; const uint32 innerMarginY = 40; // temp DC wxClientDC dc(this); dc.SetFont(m_drawFont); // refresh the size of the dirty nodes for (auto it : nodes) { // measure size of the text const wxSize textSize = dc.GetTextExtent(it->m_caption); // measure the required size of the block, based on the number of inputs/outputs and the values uint32 inputRegionSize = 0; for (const auto& jt : it->m_inputs) { const wxSize textSize = dc.GetTextExtent(jt->m_name); if (inputRegionSize) inputRegionSize += slotSeparation; // inputRegionSize += textSize.x; } // output slots uint32 outputRegionSize = 0; for (const auto& jt : it->m_outputs) { const wxSize textSize = dc.GetTextExtent(jt->m_name); if (outputRegionSize) outputRegionSize += slotSeparation; // outputRegionSize += textSize.x; } // get the block size ( the max of the input/output/text ) const uint32 blockSizeX = wxMax(wxMax(inputRegionSize, outputRegionSize), textSize.x); // compute node size and text placement it->m_size.x = blockSizeX + innerMarginX; it->m_size.y = textSize.y + innerMarginY; it->m_textOffset.x = it->m_size.x / 2; it->m_textOffset.y = it->m_size.y / 2; it->m_traceTextOffset.x = it->m_size.x; it->m_traceTextOffset.y = it->m_size.y + 2; it->m_addrTextOffset.x = it->m_size.x; it->m_addrTextOffset.y = it->m_size.y + 14; // input slots are placed on the top, output at the bottom of the node const uint32 inputY = 0; const uint32 outputY = it->m_size.y; // values uint32 valueY = 5; // place the input slots { uint32 slotX = innerMarginX / 2 + (blockSizeX - inputRegionSize) / 2; for (uint32 i = 0; i < it->m_inputs.size(); ++i) { const wxSize textSize = dc.GetTextExtent(it->m_inputs[i]->m_name); it->m_inputs[i]->m_offset.x = slotX + textSize.x / 2; it->m_inputs[i]->m_offset.y = inputY; it->m_inputs[i]->m_textOffset.x = slotX + textSize.x / 2; it->m_inputs[i]->m_textOffset.y = inputY + 10; if (it->m_inputs[i]->m_value != "") { it->m_inputs[i]->m_valueOffset.x = it->m_size.x + 5; it->m_inputs[i]->m_valueOffset.y = valueY; valueY += 12; } slotX += textSize.x + slotSeparation; } } // place the output slots { uint32 slotX = innerMarginX / 2 + (blockSizeX - outputRegionSize) / 2; for (uint32 i = 0; i < it->m_outputs.size(); ++i) { const wxSize textSize = dc.GetTextExtent(it->m_outputs[i]->m_name); it->m_outputs[i]->m_offset.x = slotX + textSize.x / 2; it->m_outputs[i]->m_offset.y = outputY; it->m_outputs[i]->m_textOffset.x = slotX + textSize.x / 2; it->m_outputs[i]->m_textOffset.y = outputY - 10; if (it->m_outputs[i]->m_value != "") { it->m_outputs[i]->m_valueOffset.x = it->m_size.x + 5; it->m_outputs[i]->m_valueOffset.y = valueY; valueY += 12; } slotX += textSize.x + slotSeparation; } } } // calculate graph depth PrepareNodePlacement(); } void TimeMachineView::DrawTextAligned(wxDC& dc, const wxString& str, const wxPoint& p, const int32_t horizontalMode /*= 0*/, const int32_t verticalMode /*= 0*/) { const auto extens = dc.GetTextExtent(str); auto pos = p; if (horizontalMode == 0) pos.x -= extens.x / 2; else if (horizontalMode == 1) pos.x -= extens.x; if (verticalMode == 0) pos.y -= extens.y / 2; else if (verticalMode == 1) pos.y -= extens.y; dc.DrawText(str, pos); } void TimeMachineView::OnPaint(wxPaintEvent& evt) { wxBufferedPaintDC dc(this); DoPrepareDC(dc); // background { dc.SetBackground(wxBrush(wxColour(80, 80, 80))); dc.Clear(); } // layout change if (m_requestedLayoutChange == 1) { DoShowRootNode(); m_requestedLayoutChange = 0; } // prepare node layout PrepareLayout(); // style const uint32 nodeRectBevel = 8; // draw connections dc.SetPen(wxPen(wxColor(32, 32, 32), 2)); for (auto it : m_nodes) { const auto* node = it.second; // draw connections from inputs only for (auto jt : node->m_inputs) { const auto rect = jt->GetRect(); // draw connections for (auto kt : jt->m_connections) { const auto otherRect = kt->GetRect(); // draw connection const auto startPos = RectCenter(rect); const auto endPos = RectCenter(otherRect); dc.DrawLine(startPos, endPos); } } } // draw nodes wxBrush nodeBrush(wxColor(128, 128, 128)); wxPen nodePenNormal(wxColor(0, 0, 0), 1); wxPen nodePenSelected(wxColor(255, 255, 0), 3); wxBrush socketBrush(wxColor(128, 128, 128)); wxPen socketPenNormal(wxColor(255, 255, 0), 1); wxPen socketPenSelected(wxColor(255, 255, 0), 1); wxBrush slotBrush(wxColor(200, 128, 128)); wxPen slotPen(wxColor(0, 0, 0)); for (auto it : m_nodes) { const auto* node = it.second; // SHAPE { // node background const bool isSelected = IsSelected(it.first); dc.SetBrush(nodeBrush); dc.SetPen(isSelected ? nodePenSelected : nodePenNormal); dc.DrawRoundedRectangle(node->GetRect(), nodeRectBevel); // draw input slots for (auto jt : node->m_inputs) { const auto rect = jt->GetRect(); // slot is not connected if (!jt->HasConnections()) { const bool isHighligted = (jt == m_highlightSlot); const auto boxRect = jt->GetUnconnectedBox(); dc.SetPen(nodePenNormal); dc.DrawLine(RectCenter(rect), RectCenter(boxRect)); dc.SetPen(isHighligted ? socketPenSelected : socketPenNormal); dc.SetBrush(socketBrush); dc.DrawEllipse(boxRect); } // slot shape dc.SetBrush(slotBrush); dc.SetPen(slotPen); dc.DrawEllipse(rect); } // draw output slots for (auto jt : node->m_outputs) { const auto rect = jt->GetRect(); // slot is not connected if (!jt->HasConnections()) { const bool isHighligted = (jt == m_highlightSlot); const auto boxRect = jt->GetUnconnectedBox(); dc.SetPen(nodePenNormal); dc.DrawLine(RectCenter(rect), RectCenter(boxRect)); dc.SetPen(isHighligted ? socketPenSelected : socketPenNormal); dc.SetBrush(socketBrush); dc.DrawEllipse(boxRect); } // slot shape dc.SetBrush(slotBrush); dc.SetPen(slotPen); dc.DrawEllipse(rect); } } // TEXT { // block caption // TODO: instruction class should determine the color dc.SetTextForeground(wxColor(0, 0, 0)); DrawTextAligned(dc, node->m_caption, node->GetTextPlacement() + wxPoint(1, 1)); dc.SetTextForeground(wxColor(255, 255, 25)); DrawTextAligned(dc, node->m_caption, node->GetTextPlacement()); // draw input captions for (auto jt : node->m_inputs) { dc.SetTextForeground(wxColor(0, 0, 0)); DrawTextAligned(dc, jt->m_name, jt->GetTextPlacement()); // slot is not connected if (!jt->HasConnections()) { const auto point = jt->GetUnconnectedTextPlacement(); dc.SetTextForeground(wxColor(0, 0, 0)); DrawTextAligned(dc, "?", point); } } // output captions for (auto jt : node->m_outputs) { dc.SetTextForeground(wxColor(0, 0, 0)); DrawTextAligned(dc, jt->m_name, jt->GetTextPlacement()); // slot is not connected if (!jt->HasConnections()) { const auto point = jt->GetUnconnectedTextPlacement(); dc.SetTextForeground(wxColor(0, 0, 0)); DrawTextAligned(dc, "?", point); } } } // VALUES if (IsSelected(node->m_entry)) { for (auto jt : node->m_inputs) { if (!jt->m_value.empty()) { wxString str; str += jt->m_name; str += " <-- "; str += jt->m_value; dc.SetTextForeground(wxColor(0, 0, 0)); DrawTextAligned(dc, str, jt->GetValueTextPlacement()); } } // output captions for (auto jt : node->m_outputs) { if (!jt->m_value.empty()) { wxString str; str += jt->m_name; str += " --> "; str += jt->m_value; dc.SetTextForeground(wxColor(0, 0, 0)); DrawTextAligned(dc, str, jt->GetValueTextPlacement()); } } } // Node time order if (node->m_entry->GetTraceIndex() >= 0) { char traceIndex[64]; sprintf_s(traceIndex, "#%05llu", node->m_entry->GetTraceIndex()); dc.SetTextForeground(wxColor(0, 0, 0)); DrawTextAligned(dc, traceIndex, node->GetTraceTextPlacement(), 1, 1); } // Node code addr if (node->m_entry->GetCodeAddres() != 0) { char codeAddress[64]; sprintf_s(codeAddress, "0x%08llX", node->m_entry->GetCodeAddres()); dc.SetTextForeground(wxColor(0, 0, 0)); DrawTextAligned(dc, codeAddress, node->GetAddrTextPlacement(), 1, 1); } } } void TimeMachineView::OnErase(wxEraseEvent& evt) {} void TimeMachineView::OnMouse(wxMouseEvent& event) { if (m_mouseMode == 0) { if (event.LeftDown()) { // remove previous selection if (!event.ShiftDown()) DeselectAll(); // find entry at point const auto* node = GetEntryAtPos(CalcUnscrolledPosition(event.GetPosition())); if (node != nullptr) { Select(node, !IsSelected(node)); // start node movement if (IsSelected(node)) { CaptureMouse(); m_mouseLastPos = event.GetPosition(); m_mouseMode = 2; } } else { // start background scrolling CaptureMouse(); m_mouseLastPos = event.GetPosition(); m_mouseMode = 1; } } if (event.LeftDClick()) { auto* slot = GetUnconnectedSlotAtPos(CalcUnscrolledPosition(event.GetPosition())); if (slot != nullptr) { ExploreSlot(slot); } else { const auto* node = GetEntryAtPos(CalcUnscrolledPosition(event.GetPosition())); if (node != nullptr) { m_navigator->NavigateToFrame(node->GetTraceIndex()); } } } } else if (m_mouseMode == 1 && event.LeftUp()) { ReleaseMouse(); m_mouseMode = 0; } else if (m_mouseMode == 2 && event.LeftUp()) { ReleaseMouse(); m_mouseMode = 0; } // moose movement ;) else if (event.Dragging() && m_mouseMode == 1) { const auto delta = event.GetPosition() - m_mouseLastPos; const auto pos = GetViewStart() - delta; Scroll(pos); Refresh(); } else if (event.Dragging() && m_mouseMode == 2) { for (auto* entry : m_selection) { LayoutInfo* layout = GetLayoutNode(entry); if (layout) { const auto delta = event.GetPosition() - m_mouseLastPos; layout->m_position += delta; } } if (!m_selection.empty()) Refresh(); } // tracking else if (event.Moving()) { bool refresh = false; // update slot hover { auto newSlot = GetUnconnectedSlotAtPos(CalcUnscrolledPosition(event.GetPosition())); refresh |= (newSlot != m_highlightSlot); m_highlightSlot = newSlot; } // update node hover { auto newNode = GetEntryAtPos(CalcUnscrolledPosition(event.GetPosition())); refresh |= (newNode != m_highlightNode); m_highlightNode = newNode; } // redraw if (refresh) Refresh(); } // update mouse position m_mouseLastPos = event.GetPosition(); } } // tools
2ab0168de088dde4ce8f0282c199ef05e6dd5f57
66382d6f016130b16ce776326b477d19313d11f5
/365c.cpp
c9bc8c782f39ae8edc306218929bfb7695723013
[]
no_license
Dreamgoing/codeforces-code
979a1e981a3393ebb46a4be28653eef09dec8ce9
f204ff326214350491a353a2e352542c446a9864
refs/heads/master
2020-04-17T14:12:07.710385
2016-09-08T18:33:07
2016-09-08T18:33:07
67,729,273
0
0
null
null
null
null
UTF-8
C++
false
false
297
cpp
// // Created by 王若璇 on 16/9/8. // #include <iostream> #include <algorithm> #include <cstring> #include <vector> #include <set> #include <map> #include <cstdio> using namespace std; const int max_n = 10100; int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); return 0; }
c0581ce3a2c2692005f568ed9c7925a8cab6d617
09b441bceae5a6df26cfa96ea0df2b863f63d973
/forePoint/src/testApp.cpp
078984018c974fe2ff55602d71cd9fb97244544e
[]
no_license
aaronsherwood/myOwnLittleUniverse
81610d6bc888d0d919aaf884533572d827243d53
850a453b71e5a76516a164937ad31c5c3f6a779a
refs/heads/master
2020-12-30T14:56:47.572945
2012-09-18T03:12:42
2012-09-18T03:12:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,689
cpp
#include "testApp.h" ofVec3f trackedPoint; ofVec3f trackedPoint2; ofVec3f trackedPoint3; bool show; void testApp::setup() { kinect.init(); kinect.setRegistration(true); kinect.setDepthClipping(50, 1500); ofEnableSmoothing(); kinect.open(); } void testApp::update() { //ofHideCursor(); kinect.update(); if(kinect.isFrameNew()) { int width = kinect.getWidth(); int height = kinect.getHeight(); float* distancePixels = kinect.getDistancePixels(); float forePoint = 8000; for(int y = 0; y < height-1; y++) { for(int x = 0; x < width-1; x++) { int i = y * width + x; float z = distancePixels[i]; int trackedX; int trackedY; if (z >0 && z < forePoint) { forePoint=z; trackedX=x; trackedY=y; trackedPoint=kinect.getWorldCoordinateAt(x,y,z); } if (z >0 && z < forePoint+200 && z > forePoint && (x > trackedX+200 || x < trackedX -200) ){ trackedPoint2=kinect.getWorldCoordinateAt(x,y,z); } if (z >0 && z < forePoint+200 && z > forePoint && (y > trackedY+200 || y < trackedY -200) ){ trackedPoint3=kinect.getWorldCoordinateAt(x,y,z); } } } for (int i=0; i<NPARTICLES; i++) { particle[i].update(trackedPoint); particle2[i].update(trackedPoint2); particle3[i].update(trackedPoint3); } } } void testApp::draw() { ofSetupScreen(); ofBackground(245); easyCam.begin(); ofScale(-1, -1, 1); ofTranslate(0, 0, -1000); for (int i=0; i<NPARTICLES; i++) { ofSetColor(255,0,0,150); particle[i].draw(); ofSetColor(0,0,255,200); particle2[i].draw(); ofSetColor(0,255,0,200); particle3[i].draw(); } easyCam.end(); if (show) { ofSetColor(255); //kinect.drawDepth(950, 300, 320, 240); kinect.drawDepth(1420, 650, -320, 240); } } void testApp::keyPressed (int key){ if (key==114 || key==82){ if (show) { show=false; } else { show=true; } } if (key==122 || key==90){ for (int i=0; i<NPARTICLES; i++) { particle[i].reset(); particle2[i].reset(); particle3[i].reset(); } } } void testApp::exit() { kinect.close(); }
7ec3fea43a14c811384f2028be66570884122e25
0a45745402b9f753eaa090201783299cc3cbb3a1
/src/test/main_tests.cpp
9fcd64eb2f34cf843882fd5a9cb9f119609ea727
[ "MIT" ]
permissive
KGS-Official-Team/KGS-Core
35faacfc5bb2cbe77d8cff9bdd0707e61656e710
cf11105d20ce84d7e048fb96ec93f57480c70d43
refs/heads/master
2020-03-27T18:17:41.235991
2018-09-26T08:29:17
2018-09-26T08:29:17
146,912,269
0
2
null
null
null
null
UTF-8
C++
false
false
1,597
cpp
// Copyright (c) 2014 The Bitcoin Core developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "primitives/transaction.h" #include "main.h" #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE(main_tests) CAmount nMoneySupplyPoWEnd = 43199500 * COIN; BOOST_AUTO_TEST_CASE(subsidy_limit_test) { CAmount nSum = 0; for (int nHeight = 0; nHeight < 1; nHeight += 1) { /* premine in block 1 (60,001 KGS) */ CAmount nSubsidy = GetBlockValue(nHeight); BOOST_CHECK(nSubsidy <= 60001 * COIN); nSum += nSubsidy; } for (int nHeight = 1; nHeight < 86400; nHeight += 1) { /* PoW Phase One */ CAmount nSubsidy = GetBlockValue(nHeight); BOOST_CHECK(nSubsidy <= 250 * COIN); nSum += nSubsidy; } for (int nHeight = 86400; nHeight < 151200; nHeight += 1) { /* PoW Phase Two */ CAmount nSubsidy = GetBlockValue(nHeight); BOOST_CHECK(nSubsidy <= 225 * COIN); nSum += nSubsidy; } for (int nHeight = 151200; nHeight < 259200; nHeight += 1) { /* PoW Phase Two */ CAmount nSubsidy = GetBlockValue(nHeight); BOOST_CHECK(nSubsidy <= 45 * COIN); BOOST_CHECK(MoneyRange(nSubsidy)); nSum += nSubsidy; BOOST_CHECK(nSum > 0 && nSum <= nMoneySupplyPoWEnd); } BOOST_CHECK(nSum == 4109975100000000ULL); } BOOST_AUTO_TEST_SUITE_END()
04758400cf639d818aafe53cad5eb99315e3efb0
bac7267590c6267b489178c8717e42a1865bb46b
/WildMagic5/LibMathematics/Objects2D/Wm5Ellipse2.inl
05f5f458f39a53b596019b50828275af094b01fd
[]
no_license
VB6Hobbyst7/GeometricTools-Apple
1e53f260e84f8942e12adf7591b83ba2dd46a7f1
07b9764871a9dbe1240b6181039dd703e118a628
refs/heads/master
2021-02-11T11:17:56.813941
2013-11-26T15:25:10
2013-11-26T15:25:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,176
inl
// Geometric Tools, LLC // Copyright (c) 1998-2013 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // // File Version: 5.0.0 (2010/01/01) //---------------------------------------------------------------------------- template <typename Real> Ellipse2<Real>::Ellipse2 () { } //---------------------------------------------------------------------------- template <typename Real> Ellipse2<Real>::~Ellipse2 () { } //---------------------------------------------------------------------------- template <typename Real> Ellipse2<Real>::Ellipse2 (const Vector2<Real>& center, const Vector2<Real> axis[2], const Real extent[2]) : Center(center) { Axis[0] = axis[0]; Axis[1] = axis[1]; Extent[0] = extent[0]; Extent[1] = extent[1]; } //---------------------------------------------------------------------------- template <typename Real> Ellipse2<Real>::Ellipse2 (const Vector2<Real>& center, const Vector2<Real>& axis0, const Vector2<Real>& axis1, const Real extent0, const Real extent1) : Center(center) { Axis[0] = axis0; Axis[1] = axis1; Extent[0] = extent0; Extent[1] = extent1; } //---------------------------------------------------------------------------- template <typename Real> void Ellipse2<Real>::GetM (Matrix2<Real>& M) const { Vector2<Real> ratio0 = Axis[0]/Extent[0]; Vector2<Real> ratio1 = Axis[1]/Extent[1]; M = Matrix2<Real>(ratio0, ratio0) + Matrix2<Real>(ratio1, ratio1); } //---------------------------------------------------------------------------- template <typename Real> void Ellipse2<Real>::GetMInverse (Matrix2<Real>& MInverse) const { Vector2<Real> ratio0 = Axis[0]*Extent[0]; Vector2<Real> ratio1 = Axis[1]*Extent[1]; MInverse = Matrix2<Real>(ratio0, ratio0) + Matrix2<Real>(ratio1, ratio1); } //---------------------------------------------------------------------------- template <typename Real> void Ellipse2<Real>::ToCoefficients (Real coeff[6]) const { Matrix2<Real> A; Vector2<Real> B; Real C; ToCoefficients(A, B, C); Convert(A, B, C, coeff); // Arrange for one of the x0^2 or x1^2 coefficients to be 1. Real maxValue = Math<Real>::FAbs(coeff[3]); int maxIndex = 3; Real absValue = Math<Real>::FAbs(coeff[5]); if (absValue > maxValue) { maxValue = absValue; maxIndex = 5; } Real invMaxValue = ((Real)1)/maxValue; for (int i = 0; i < 6; ++i) { if (i != maxIndex) { coeff[i] *= invMaxValue; } else { coeff[i] = (Real)1; } } } //---------------------------------------------------------------------------- template <typename Real> void Ellipse2<Real>::ToCoefficients (Matrix2<Real>& A, Vector2<Real>& B, Real& C) const { Vector2<Real> ratio0 = Axis[0]/Extent[0]; Vector2<Real> ratio1 = Axis[1]/Extent[1]; A = Matrix2<Real>(ratio0, ratio0) + Matrix2<Real>(ratio1, ratio1); B = ((Real)-2)*(A*Center); C = A.QForm(Center, Center) - (Real)1; } //---------------------------------------------------------------------------- template <typename Real> bool Ellipse2<Real>::FromCoefficients (const Real coeff[6]) { Matrix2<Real> A; Vector2<Real> B; Real C; Convert(coeff, A, B, C); return FromCoefficients(A, B, C); } //---------------------------------------------------------------------------- template <typename Real> bool Ellipse2<Real>::FromCoefficients (const Matrix2<Real>& A, const Vector2<Real>& B, Real C) { // Compute the center K = -A^{-1}*B/2. Matrix2<Real> invA = A.Inverse(); if (invA == Matrix2<Real>::ZERO) { return false; } Center = ((Real)-0.5)*(invA*B); // Compute B^T*A^{-1}*B/4 - C = K^T*A*K - C = -K^T*B/2 - C. Real rightSide = -((Real)0.5)*(Center.Dot(B)) - C; if (Math<Real>::FAbs(rightSide) < Math<Real>::ZERO_TOLERANCE) { return false; } // Compute M = A/(K^T*A*K - C). Real invRightSide = ((Real)1)/rightSide; Matrix2<Real> M = invRightSide*A; // Factor into M = R*D*R^T. EigenDecomposition<Real> eigensystem(M); eigensystem.Solve(true); for (int i = 0; i < 2; ++i) { if (eigensystem.GetEigenvalue(i) <= (Real)0) { return false; } Extent[i] = Math<Real>::InvSqrt(eigensystem.GetEigenvalue(i)); Axis[i] = eigensystem.GetEigenvector2(i); } return true; } //---------------------------------------------------------------------------- template <typename Real> Real Ellipse2<Real>::Evaluate (const Vector2<Real>& point) const { Vector2<Real> diff = point - Center; Real ratio0 = Axis[0].Dot(diff)/Extent[0]; Real ratio1 = Axis[1].Dot(diff)/Extent[1]; Real value = ratio0*ratio0 + ratio1*ratio1 - (Real)1; return value; } //---------------------------------------------------------------------------- template <typename Real> bool Ellipse2<Real>::Contains (const Vector2<Real>& point) const { return (Evaluate(point) <= (Real)0); } //---------------------------------------------------------------------------- template <typename Real> void Ellipse2<Real>::Convert (const Real coeff[6], Matrix2<Real>& A, Vector2<Real>& B, Real& C) { C = coeff[0]; B[0] = coeff[1]; B[1] = coeff[2]; A[0][0] = coeff[3]; A[0][1] = ((Real)0.5)*coeff[4]; A[1][0] = A[0][1]; A[1][1] = coeff[5]; } //---------------------------------------------------------------------------- template <typename Real> void Ellipse2<Real>::Convert (const Matrix2<Real>& A, const Vector2<Real>& B, Real C, Real coeff[6]) { coeff[0] = C; coeff[1] = B[0]; coeff[2] = B[1]; coeff[3] = A[0][0]; coeff[4] = ((Real)2)*A[0][1]; coeff[5] = A[1][1]; } //----------------------------------------------------------------------------
[ "tprepscius" ]
tprepscius
d3ec6492705a4cb1fcdd9fb3788d103de529fe72
e7e9d77d7fb7eee4d823cf94a586a5fa751d7054
/ptm_tm/plugin/tests/units/callinst_006.cc
5057c3a01a1bf8f92f822682d61a9085dae18c5e
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
mfs409/llvm-transmem
5b5b35dbf3bb89fe2e7013418177bbc78b872cd2
92bd8c320bc12113ce6e4b1aba1243af6475bef9
refs/heads/master
2021-07-08T12:33:04.943298
2020-08-05T01:45:26
2020-08-05T01:45:26
159,760,878
11
3
null
null
null
null
UTF-8
C++
false
false
1,079
cc
// Test discovery of functions called from an instrumented region. // // Calls to a function that calls a marked function outside of its TU should // work #ifdef TEST_DRIVER #include "../include/harness.h" // declare the function in OFILE1 that comprises the root of the test extern "C" { int marked_call_marked_outside_tu(int); int tm_marked_call_marked_outside_tu(int); } int main() { report<int>("callinst_006", "safe call to unmarked function in another TU", {{marked_call_marked_outside_tu(54), tm_marked_call_marked_outside_tu(54)}}, {{TM_STATS_TRANSLATE_FOUND, 1}, {TM_STATS_UNSAFE, 0}}); } #endif #ifdef TEST_OFILE1 #include "../../../common/tm_api.h" extern "C" { int something = 5; TX_SAFE int marked_in_other_tu_callable(int i); TX_SAFE int marked_call_marked_outside_tu(int i) { return marked_in_other_tu_callable(i); } } #endif #ifdef TEST_OFILE2 #include "../../../common/tm_api.h" extern "C" { extern int something; TX_SAFE int marked_in_other_tu_callable(int i) { return i * something + something; } } #endif
64290dabfaa4c364a9d88462fa35a7b1216fbaab
669bd2117536a454aa7049c187d683ed1e1e99fb
/topcoder/SRM-429-DIV-2/250/driver.cc
53b7ad40394668d2197f3e6b5b0bf8640dfbb449
[]
no_license
dimrirahul/programming
120220bd4f676fc71158fa7171d2412c996e11ae
a87f880b25834c6e2e56047446578ecea0767760
refs/heads/master
2021-01-19T02:12:44.446690
2018-05-22T14:51:56
2018-05-22T14:51:56
29,001,140
2
0
null
null
null
null
UTF-8
C++
false
false
3,770
cc
#include "LinearPolyominoCovering.cc" #include <algorithm> #include <cmath> #include <cstdlib> #include <fstream> #include <iostream> #include <sstream> #include <string> #include <sys/time.h> #include <vector> const static double __EPSILON = 1e-9; static double __time = 0.0; static void __timer_start() { struct timeval tv; if (gettimeofday(&tv, NULL) == 0) { __time = double(tv.tv_sec) * 1000.0 + double(tv.tv_usec) * 0.001; } } static double __timer_stop() { double start = __time; __timer_start(); return __time - start; } static void __eat_whitespace(std::istream& in) { while (in.good() && std::isspace(in.peek())) in.get(); } std::ostream& operator << (std::ostream& out, const std::string& str) { out << '"' << str.c_str() << '"'; return out; } template <class T> std::ostream& operator << (std::ostream& out, const std::vector<T>& vec) { out << '{'; if (0 < vec.size()) { out << vec[0]; for (size_t i = 1; i < vec.size(); ++i) out << ", " << vec[i]; } out << '}'; return out; } std::istream& operator >> (std::istream& in, std::string& str) { __eat_whitespace(in); int c; if (in.good() && (c = in.get()) == '"') { std::ostringstream s; while (in.good() && (c = in.get()) != '"') { s.put(char(c)); } str = s.str(); } return in; } template <class T> std::istream& operator >> (std::istream& in, std::vector<T>& vec) { __eat_whitespace(in); int c; if (in.good() && (c = in.get()) == '{') { __eat_whitespace(in); vec.clear(); while (in.good() && (c = in.get()) != '}') { if (c != ',') in.putback(c); T t; in >> t; __eat_whitespace(in); vec.push_back(t); } } return in; } template <class T> bool __equals(const T& actual, const T& expected) { return actual == expected; } bool __equals(double actual, double expected) { if (std::abs(actual - expected) < __EPSILON) { return true; } else { double minimum = std::min(expected * (1.0 - __EPSILON), expected * (1.0 + __EPSILON)); double maximum = std::max(expected * (1.0 - __EPSILON), expected * (1.0 + __EPSILON)); return actual > minimum && actual < maximum; } } bool __equals(const std::vector<double>& actual, const std::vector<double>& expected) { if (actual.size() != expected.size()) { return false; } for (size_t i = 0; i < actual.size(); ++i) { if (!__equals(actual[i], expected[i])) { return false; } } return true; } int main(int argc, char* argv[]) { bool __abort_on_fail = false; int __pass = 0; int __fail = 0; if (1 < argc) __abort_on_fail = true; std::cout << "TAP version 13" << std::endl; std::cout.flush(); std::ifstream __in("testcases.txt"); for(;;) { int __testnum = __pass + __fail + 1; string __expected; string region; __in >> __expected >> region; if (!__in.good()) break; std::cout << "# input for test " << __testnum << ": " << region << std::endl; std::cout.flush(); __timer_start(); LinearPolyominoCovering __object; string __actual = __object.findCovering(region); double __t = __timer_stop(); std::cout << "# test completed in " << __t << "ms" << std::endl; std::cout.flush(); if (__equals(__actual, __expected)) { std::cout << "ok"; ++__pass; } else { std::cout << "not ok"; ++__fail; } std::cout << " " << __testnum << " - " << __actual << " must equal " << __expected << std::endl; std::cout.flush(); if (__abort_on_fail && 0 < __fail) std::abort(); } std::cout << "1.." << (__pass + __fail) << std::endl << "# passed: " << __pass << std::endl << "# failed: " << __fail << std::endl; if (__fail == 0) { std::cout << std::endl << "# Nice! Don't forget to compile remotely before submitting." << std::endl; } return __fail; } // vim:ft=cpp:noet:ts=8
dd86389c9e318a94f6ba504e0416ab39ecfc0019
3bfe741bca4ccb928ab03958fef677662b642a32
/src/RE/BSCore/BSAtomic.cpp
267471cb6d524a8734531897cee2d87104c142a3
[ "MIT" ]
permissive
Slaynot/CommonLibSSE
9865fc7d7e3167dd72193ef3828ac7db54858cc5
6b3fd268327fb630139d2a183cbd5aa5669cfc5f
refs/heads/master
2023-08-19T00:32:11.523120
2021-10-05T21:02:33
2021-10-05T21:02:33
293,022,195
0
1
MIT
2021-10-05T19:52:10
2020-09-05T07:02:12
C++
UTF-8
C++
false
false
2,746
cpp
#include "RE/BSCore/BSAtomic.h" namespace RE { BSSemaphoreBase::BSSemaphoreBase() : semaphore() { memzero(&semaphore); semaphore = CreateSemaphoreA(nullptr, 0, 40, nullptr); } BSSemaphoreBase::~BSSemaphoreBase() { CloseHandle(semaphore); memzero(&semaphore); } BSSpinLock::BSSpinLock() : _owningThread(0), _lockCount(0) {} void BSSpinLock::Lock(std::uint32_t a_pauseAttempts) { std::uint32_t myThreadID = GetCurrentThreadId(); _mm_lfence(); if (_owningThread == myThreadID) { InterlockedIncrement(&_lockCount); } else { std::uint32_t attempts = 0; if (InterlockedCompareExchange(&_lockCount, 1, 0)) { do { ++attempts; _mm_pause(); if (attempts >= a_pauseAttempts) { std::uint32_t spinCount = 0; while (InterlockedCompareExchange(&_lockCount, 1, 0)) { Sleep(++spinCount < kFastSpinThreshold ? 0 : 1); } break; } } while (InterlockedCompareExchange(&_lockCount, 1, 0)); _mm_lfence(); } _owningThread = myThreadID; _mm_sfence(); } } void BSSpinLock::Unlock() { std::uint32_t myThreadID = GetCurrentThreadId(); _mm_lfence(); if (_owningThread == myThreadID) { if (_lockCount == 1) { _owningThread = 0; _mm_mfence(); InterlockedCompareExchange(&_lockCount, 0, 1); } else { InterlockedDecrement(&_lockCount); } } } BSReadWriteLock::BSReadWriteLock() : _writerThread(0), _lock(0) {} void BSReadWriteLock::LockForRead() { using func_t = decltype(&BSReadWriteLock::LockForRead); REL::Relocation<func_t> func{ Offset::BSReadWriteLock::LockForRead }; func(this); } void BSReadWriteLock::UnlockForRead() { using func_t = decltype(&BSReadWriteLock::UnlockForRead); REL::Relocation<func_t> func{ Offset::BSReadWriteLock::UnlockForRead }; func(this); } void BSReadWriteLock::LockForWrite() { using func_t = decltype(&BSReadWriteLock::LockForWrite); REL::Relocation<func_t> func{ Offset::BSReadWriteLock::LockForWrite }; func(this); } void BSReadWriteLock::UnlockForWrite() { using func_t = decltype(&BSReadWriteLock::UnlockForWrite); REL::Relocation<func_t> func{ Offset::BSReadWriteLock::UnlockForWrite }; func(this); } BSSpinLockGuard::BSSpinLockGuard(BSSpinLock& a_lock) : _lock(a_lock) { _lock.Lock(); } BSSpinLockGuard::~BSSpinLockGuard() { _lock.Unlock(); } BSReadLockGuard::BSReadLockGuard(BSReadWriteLock& a_lock) : _lock(a_lock) { _lock.LockForRead(); } BSReadLockGuard::~BSReadLockGuard() { _lock.UnlockForRead(); } BSWriteLockGuard::BSWriteLockGuard(BSReadWriteLock& a_lock) : _lock(a_lock) { _lock.LockForWrite(); } BSWriteLockGuard::~BSWriteLockGuard() { _lock.UnlockForWrite(); } }
4e3c442134c05a946e924e1f209956733cd931fc
108b81d8119c53c26e83a196ec8595f79b54bfad
/Inter.hpp
f174585bee3ba05487689fb2fba0046fc70c3193
[]
no_license
anton2920/compcomp
748c6916c64e769761c2c3a8694222728d7868fb
c474be3a3aaf51de7b2782d866d78758687e8b4b
refs/heads/main
2023-02-10T19:38:08.675972
2021-01-08T13:35:16
2021-01-08T13:35:16
325,405,931
0
0
null
null
null
null
UTF-8
C++
false
false
12,049
hpp
#ifndef INTER #define INTER #include <string> #include <iostream> #include <exception> #include "Tokens.hpp" #include "Lexer.hpp" static std::ofstream *file = nullptr; class Node { public: int lexline = 0; static int labels; Node() { if (file == nullptr) { file = new std::ofstream; file->open("output.txt", std::ios_base::out); if (!file->is_open()) { file->open("/dev/stdout", std::ios_base::app); if (!file->is_open()) { throw std::range_error("cannot open file"); } } } lexline = Lexer::prev_line; } void error(const std::string &s) const { throw std::logic_error("near line " + std::to_string(lexline) + ": " + s); } static int newLabel() { return ++labels; } static void emitlabel(int i) { *file << "L" << std::to_string(i) << ":"; } static void emit(const std::string &s) { *file << "\t" << s << std::endl; } virtual std::string toString() { return ""; } }; class Expr : public Node { public: Token *op{}; Type *type{}; Expr() = default;; Expr(Token *tok, Type *p) { op = tok; type = p; } virtual Expr *gen() { return this; } virtual Expr *reduce() { return this; } virtual void jumping(int t, int f) { emitjumps(toString(), t, f); } static void emitjumps(const std::string &test, int t, int f) { if (t != 0 && f != 0) { emit("if " + test + " goto L" + std::to_string(t)); emit("goto L" + std::to_string(f)); } else if (t != 0) emit("if " + test + " goto L" + std::to_string(t)); else if (f != 0) emit("iffalse " + test + " goto L" + std::to_string(f)); else; // nothing since both t and f fall through } std::string toString() override { return op->toString(); } }; class Temp : public Expr { public: static int count; int number = 0; explicit Temp(Type *p) : Expr(&Word::_temp, p) { number = ++count; } std::string toString() override { return "t" + std::to_string(number); } }; class Id : public Expr { public: int offset{}; // relative address Id() = default; Id(Word *id, Type *p, int b) : Expr(id, p) { offset = b; } }; class Op : public Expr { public: Op(Token *tok, Type *p) : Expr(tok, p) {} Expr *reduce() override { Expr *x = gen(); Temp *t = new Temp(type); emit(t->toString() + " = " + x->toString()); return t; } }; class Arith : public Op { public: Expr *expr1, *expr2; Arith(Token *tok, Expr *x1, Expr *x2) : Op(tok, nullptr) { expr1 = x1; expr2 = x2; type = Type::max(expr1->type, expr2->type); if (type == nullptr) error("type error"); } Expr *gen() override { return new Arith(op, expr1->reduce(), expr2->reduce()); } std::string toString() override { return expr1->toString() + " " + op->toString() + " " + expr2->toString(); } }; class Unary : public Op { public: Expr *expr; Unary(Token *tok, Expr *x) : Op(tok, nullptr) { expr = x; type = Type::max(Type::_int, expr->type); if (type == nullptr) error("type error"); } Expr *gen() override { return new Unary(op, expr->reduce()); } std::string toString() override { return op->toString() + " " + expr->toString(); } }; class Constant : public Expr { public: Constant(Token *tok, Type *p) : Expr(tok, p) {} explicit Constant(int i) : Expr(new Num(i), Type::_int) {} void jumping(int t, int f) override { if (this == _true && t != 0) emit("goto L" + std::to_string(t)); else if (this == _false && f != 0) emit("goto L" + std::to_string(f)); } static Constant *_true, *_false; }; class Logical : public Expr { public: Expr *expr1{}, *expr2{}; explicit Logical(Token *tok) : Expr(tok, nullptr) {}; Logical(Token *tok, Expr *x1, Expr *x2) : Expr(tok, nullptr) { expr1 = x1; expr2 = x2; type = check(expr1->type, expr2->type); if (type == nullptr) error("type error"); } static Type *check(Type *p1, Type *p2) { if (p1 == Type::_bool && p2 == Type::_bool) return Type::_bool; else return nullptr; } Expr *gen() override { int f = newLabel(); int a = newLabel(); Temp *temp = new Temp(type); jumping(0, f); emit(temp->toString() + " = true"); emit("goto L" + std::to_string(a)); emitlabel(f); emit(temp->toString() + " = false"); emitlabel(a); return temp; } std::string toString() override { return expr1->toString() + " " + op->toString() + " " + expr2->toString(); } }; class Or : public Logical { public: Or(Token *tok, Expr *x1, Expr *x2) : Logical(tok, x1, x2) {} void jumping(int t, int f) override { int label = t != 0 ? t : newLabel(); expr1->jumping(label, 0); expr2->jumping(t, f); if (t == 0) emitlabel(label); } }; class And : public Logical { public: And(Token *tok, Expr *x1, Expr *x2) : Logical(tok, x1, x2) {} void jumping(int t, int f) override { int label = f != 0 ? f : newLabel(); expr1->jumping(0, label); expr2->jumping(t, f); if (f == 0) emitlabel(label); } }; class Not : public Logical { public: Not(Token *tok, Expr *x2) : Logical(tok, x2, x2) {} void jumping(int t, int f) override { expr2->jumping(f, t); } std::string toString() override { return op->toString() + " " + expr2->toString(); } }; class Rel : public Logical { public: Rel(Token *tok, Expr *x1, Expr *x2) : Logical(tok) { expr1 = x1; expr2 = x2; type = check(expr1->type, expr2->type); if (type == nullptr) error("type error"); } static Type *check(Type *p1, Type *p2) { // c++ does not support "instanseof" operation // the following is not the most optimal way // but it is clean and doesnt require more changes in the original code if (p1->lexeme == "[]" || p1->lexeme == "[]") return nullptr; else if (p1 == p2) return Type::_bool; else return nullptr; } void jumping(int t, int f) override { Expr *a = expr1->reduce(); Expr *b = expr2->reduce(); std::string test = a->toString() + " " + op->toString() + " " + b->toString(); emitjumps(test, t, f); } }; class Access : public Op { public: Id *array; Expr *index; Access(Id *a, Expr *i, Type *p) : Op(new Word("[]", Tag::INDEX), p) { array = a; index = i; } Expr *gen() override { return new Access(array, index->reduce(), type); } void jumping(int t, int f) override { emitjumps(reduce()->toString(), t, f); } std::string toString() override { return array->toString() + " [ " + index->toString() + " ]"; } }; class Stmt : public Node { public: Stmt() = default; static Stmt *_null; static Stmt *enclosing; virtual void gen(int b, int a) {} // called with labels begin and after int after = 0; // saves label after }; class If : public Stmt { public: Expr *expr; Stmt *stmt; If(Expr *x, Stmt *s) { expr = x; stmt = s; if (expr->type != Type::_bool) expr->error("boolean required in if"); } void gen(int b, int a) override { int label = newLabel(); // label for the code for stmt expr->jumping(0, a); // fall through on true, goto a on false emitlabel(label); stmt->gen(label, a); } }; class Else : public Stmt { public: Expr *expr; Stmt *stmt1, *stmt2; Else(Expr *x, Stmt *s1, Stmt *s2) { expr = x; stmt1 = s1; stmt2 = s2; if (expr->type != Type::_bool) expr->error("boolean required in if"); } void gen(int b, int a) override { int label1 = newLabel(); // label1 for stmt1 int label2 = newLabel(); // label2 for stmt2 expr->jumping(0, label2); // fall through to stmt1 on true emitlabel(label1); stmt1->gen(label1, a); emit("goto L" + std::to_string(a)); emitlabel(label2); stmt2->gen(label2, a); } }; class While : public Stmt { public: Expr *expr; Stmt *stmt; While() { expr = nullptr; stmt = nullptr; } void init(Expr *x, Stmt *s) { expr = x; stmt = s; if (expr->type != Type::_bool) expr->error("boolean required in while"); } void gen(int b, int a) override { after = a; // save label a expr->jumping(0, a); int label = newLabel(); // label for stmt emitlabel(label); stmt->gen(label, b); emit("goto L" + std::to_string(b)); } }; class Do : public Stmt { public: Expr *expr; Stmt *stmt; Do() { expr = nullptr; stmt = nullptr; } void init(Stmt *s, Expr *x) { expr = x; stmt = s; if (expr->type != Type::_bool) expr->error("boolean required in do"); } void gen(int b, int a) override { after = a; int label = newLabel(); // label for expr stmt->gen(b, label); emitlabel(label); expr->jumping(b, 0); } }; class Set : public Stmt { public: Id *id; Expr *expr; Set(Id *i, Expr *x) { id = i; expr = x; if (check(id->type, expr->type) == nullptr) error("type error"); } static Type *check(Type *p1, Type *p2) { if (Type::numeric(p1) && Type::numeric(p2)) return p2; else if (p1 == Type::_bool && p2 == Type::_bool) return p2; else return nullptr; } void gen(int b, int a) override { emit(id->toString() + " = " + expr->gen()->toString()); } }; class SetElem : public Stmt { public: Id *array; Expr *index, *expr; SetElem(Access *x, Expr *y) { array = x->array; index = x->index; expr = y; if (check(x->type, expr->type) == nullptr) error("type error"); } static Type *check(Type *p1, Type *p2) { if (p1->lexeme == "[]" || p2->lexeme == "[]") return nullptr; else if (p1 == p2) return p2; else if (Type::numeric(p1) && Type::numeric(p2)) return p2; else return nullptr; } void gen(int b, int a) override { std::string s1 = index->reduce()->toString(), s2 = expr->reduce()->toString(); emit(array->toString() + " [" + s1 + " ] = " + s2); } }; class Seq : public Stmt { public: Stmt *stmt1, *stmt2; Seq(Stmt *s1, Stmt *s2) { stmt1 = s1; stmt2 = s2; } void gen(int b, int a) override { if (stmt1 == Stmt::_null) stmt2->gen(b, a); else if (stmt2 == Stmt::_null) stmt1->gen(b, a); else { int label = newLabel(); stmt1->gen(b, label); emitlabel(label); stmt2->gen(label, a); } } }; class Break : public Stmt { public: Stmt *stmt; Break() { stmt = Stmt::enclosing; } void gen(int b, int a) override { emit("goto L" + std::to_string(stmt->after)); } }; #endif
e319f09f0aaaa9fd6f6134abd332d6b15032180a
ca21c2098dec8ef5c3fd09021912e457d029f888
/src/aricc_vision_pipeline/aricc_2d_vision/include/aricc_2d_vision/rect_to_point_cloud.h
05971773e249a8795f4909b41c206504dcd415e9
[]
no_license
asadnorouzi/roboerectus-atwork
aed8e0e0567d77b172fa8b14bcdb656478bc4b52
3f1d8c860b7f795735de958f8e3aa4f254c8a4c3
refs/heads/master
2021-03-24T10:46:13.173073
2017-07-21T09:08:37
2017-07-21T09:08:37
96,747,321
0
2
null
null
null
null
UTF-8
C++
false
false
660
h
#ifndef ARICC_2D_VISION_RECT_TO_POINT_CLOUD_H_ #define ARICC_2D_VISION_RECT_TO_POINT_CLOUD_H_ #include <aricc_topic_tools/connection_based_nodelet.h> #include <aricc_vision_msgs/RotatedRectArray.h> #include <sensor_msgs/PointCloud.h> namespace aricc_2d_vision{ class RectToPointCloud: public aricc_topic_tools::ConnectionBasedNodelet{ public: protected: virtual void onInit(); virtual void subscribe(); virtual void unsubscribe(); virtual void execute( const aricc_vision_msgs::RotatedRectArray::ConstPtr& rects_msg); ros::Publisher pub_; ros::Subscriber sub_; std::string frame_; private: }; } #endif
4e18777e5eb19874bbfd0b8efb7b724b425056fc
6f7ba87b6e94ae0fdb20c5267c6cde35d7138ac5
/lib/serverClass/serverClass.hpp
b406cd994388f2dd511355f752e71f3fe61412a5
[]
no_license
conProgram/Weather-station-micro-controller-
74e9a9c2a26e50cc497b7e0f6a2fc0c8be7a08e1
6d4a490e143c0dee0e63f18dae4cbb5661f16fa7
refs/heads/master
2022-06-10T13:38:47.231843
2020-05-11T12:31:24
2020-05-11T12:31:24
257,572,990
1
0
null
null
null
null
UTF-8
C++
false
false
326
hpp
#ifndef serverClass_H_ #define serverClass_H_ const char* ssidCredential(); const char* passwordCredential(); int readDHTTemperature(); int readDHTHumidity(); void Serversetup(); void loopServer(); void handle_OnConnect(); void handle_NotFound(); //void website(); // void bigSetUpMethod(); // void bigLoopMethod(); #endif
f06d962e88f5c9b9f6b3c567467dd03ac343149a
5aad40ba5a1eb29799c1ad1c21495faa07e99b36
/src/FFT/PingPong.h
dc7e565d49c4a2e536fd1a58c582be3df15d44a4
[]
no_license
q4a/navidia_proj
3525bcfdb12dc20dcecf08f2603324feceef7394
32c839744ad849f8d4d0273c635c4d601cc1980f
refs/heads/master
2023-04-16T10:44:39.466782
2019-11-30T10:26:47
2019-11-30T10:26:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,886
h
/*************************************************************************** * FILE NAME: PingPong.h * * ONE LINE SUMMARY: * PingPong class is declared in this file. * * Thilaka Sumanaweera * Siemens Medical Solutions USA, Inc. * 1230 Shorebird Way * Mountain View, CA 94039 * USA * [email protected] * * DESCRIPTION: * ***************************************************************************** * REVISION HISTORY: * Rev When Who What * V1 15Dec2004 Thilaka Created. ****************************************************************************/ #ifndef __PINGPONG__ #define __PINGPONG__ enum PingMethod {SINGLE_PBUFFER, DOUBLE_PBUFFER, AUTO_PBUFFER}; #include <PBuffer.h> #include <GL/glut.h> #include <GL/glext.h> #include <Cg/cg.h> #include <Cg/cgGL.h> #if NV_FFT_DLL #if defined _WIN32 || defined WIN32 || defined __NT__ || defined __WIN32__ || defined __MINGW32__ # ifdef NV_FFT_EXPORTS # define NV_FFT_API __declspec(dllexport) # else # define NV_FFT_API __declspec(dllimport) # endif #endif #else # define NV_FFT_API #endif /* C L A S S */ class NV_FFT_API PingPong { public: // member functions PingPong::PingPong(); PingPong::PingPong(Vendor GPU, PingMethod Method_, int Width, int Height); ~PingPong(void); void PingPong::CreatePbuffer(Vendor GPU, int Width, int Height, PBuffer *&pbuf); bool PingPong::Quadro_p(void); void PingPong::BindTextures(PBuffer *Pbuf, GLuint *Texs); void PingPong::UnBindTextures(PBuffer *Pbuf); void PingPong::PingForDisplay(GLuint *Texs); void PingPong::Ping(bool FirstTime_p, GLuint *Texs); void PingPong::Pong(bool FirstTime_p); void PingPong::Swap(void); void PingPong::Bind(void); void PingPong::Unbind(void); PingMethod Method; // Method of managing the buffers: SINGLE_PBUFFER or DOUBLE_PBUFFER PBuffer *Pbuffer1; // a pbuffer containing 8 or 4 draw buffers, depending // on SINGLE_PBUFFER or DOUBLE_PBUFFER method. PBuffer *Pbuffer2; // a pbuffer containing 4 draw buffers, depending // on SINGLE_PBUFFER or DOUBLE_PBUFFER method. Not used // when using SINGLE_PBUFFER int NBuf; GLenum *TexUnits; // An array containg four texture unit tokens GLenum *BufSet1; // A set of 4 draw buffers GLenum *BufSet2; // A second set of 4 draw buffers GLenum *wglBufSet1; // A set of 4 wgl draw buffers GLenum *wglBufSet2; // A second set of 4 wgl draw buffers PBuffer *Src; // source pbuffer PBuffer *Dst; // destination pbuffer GLenum *SrcBufSet; // source draw buffer set GLenum *DstBufSet; // destination draw buffer set GLenum *wglSrcBufSet; // source wgl draw buffer set GLenum *wglDstBufSet; // destination wgl draw buffer set private: }; #endif /* __PINGPONG__ */
67303d02d3ddbc34db0a20fc121cdeb3c9b9903a
822c7cad9a37ec9643eec5007d897617c4b18fd8
/tools/MeshUtils/SimpleSubdivision.h
79a7ceae0a1ce980fee64baa99482c0f3c2ae505
[]
no_license
gaoyue17/PyMesh
951bcfaa96df5ccf35259e2efdbf4cb5cddee15d
2198fb23c8885f095cdd02aa4d3b21b42542a3d2
refs/heads/master
2020-12-29T02:19:22.650447
2016-04-10T19:57:52
2016-04-10T19:57:52
55,990,646
1
0
null
2016-04-11T16:55:12
2016-04-11T16:55:12
null
UTF-8
C++
false
false
965
h
/* This file is part of PyMesh. Copyright (c) 2015 by Qingnan Zhou */ #pragma once #include "Subdivision.h" #include <map> #include <vector> #include <Misc/Triplet.h> class SimpleSubdivision : public Subdivision { public: virtual ~SimpleSubdivision() {} virtual void subdivide(MatrixFr vertices, MatrixIr faces, size_t num_iterations); virtual const std::vector<ZSparseMatrix>& get_subdivision_matrices() const { return m_subdivision_matrices; } protected: void initialize_face_indices(); void subdivide_once(); void compute_subdivided_vertices(); void extract_sub_faces(); void extract_edges(); void register_edges(const VectorI& face, size_t base_index); Vector3I get_edge_indices(const VectorI& face); protected: std::map<Triplet, size_t> m_edge_index_map; std::vector<ZSparseMatrix> m_subdivision_matrices; };
[ "devnull@localhost" ]
devnull@localhost
b8a826a383cb5d6ffd8d5b2af061f80642c7af2f
b45c71d0bdb809f91cca7a13a43dc86dbe69e10a
/main.cpp
65ac9d0daa90f524e9d80d5637c18ffed751f238
[]
no_license
CtfChan/password_storage
0fe205f465685f9a0251835aa81a0c2f3b8c5682
354b307e1698fbf4ab9db9d07238c6b5e5c2bca2
refs/heads/master
2021-01-21T02:36:44.538127
2017-08-30T14:17:24
2017-08-30T14:17:24
101,889,500
0
0
null
null
null
null
UTF-8
C++
false
false
4,839
cpp
#include <iostream> #include <fstream> #include <string> using namespace std; int key = 5; string encrypt(string str, int k) { k%=26; int n = str.length(); for (int i=0; i<n;i++) { int charNum = str[i]; if (charNum >= 'a' && charNum <= 'z') { //handle lower case letters charNum += k; if (charNum > 'z') { //check if charNum is beyond ascii range for lowercase letters, lowercase a to z = 97 to 122 charNum = 96 + (charNum - 122); } } else if (charNum >= 'A' && charNum <= 'Z') { //handle upper case letters charNum +=k; if (charNum > 'Z') { // uppercase A to Z is 65 to 90 charNum = 64 + (charNum - 90); } } str[i] = charNum; } return str; } string decrypt(string str, int k) { k%=26; int n = str.length(); for (int i=0; i<n;i++) { int charNum = str[i]; if (charNum >= 'a' && charNum <= 'z') { //handle lower case letters charNum -= k; if (charNum < 'a') { charNum += k; charNum = 123 - (k - (charNum - 97)); } } else if (charNum >= 'A' && charNum <= 'Z') { charNum -= k; if (charNum < 'A') { charNum += k; charNum = 91 - (k - (charNum - 65)); } } str[i] = charNum; } return str; } int main() { int choice; while(1) { cout<<"\nChoose your choice ::"; cout<<"\n1.) Add new account"; cout<<"\n2.) Delete account"; cout<<"\n3.) Modify account password"; cout<<"\n4.) Display all acounts"; cout<<"\n5.) Search for an account"; cout<<"\n6.) Exit"; cout<<"\nEnter your choice :: "; cin>>choice; switch (choice) { case 1: //ADD NEW ACCOUNT { ofstream outfile; outfile.open("accounts.txt", ios::out | ios::app); cout<<"\n\nPlease Enter Details :: \n"; cout<<"\nEnter the website :: "; string website; cin>>website; outfile<<website<<endl; cout<<"\nEnter username :: "; string username; cin>>username; outfile<<username<<endl; cout<<"\nEnter password ::"; string pass; cin>>pass; pass = encrypt(pass, key); outfile<<pass<<endl; outfile.close(); } break; case 2: //DELETE ACCOUNT { ofstream outfile; ifstream infile; outfile.open("temp.txt", ios::out); infile.open("accounts.txt", ios::in); string web, line; cout<<"\nEnter the website :: "; cin>>web; while(getline(infile, line)) { if (line == web) { getline(infile, line); getline(infile, line); } else { outfile<<line<<endl; } } outfile.close(); infile.close(); } remove("accounts.txt"); rename("temp.txt", "accounts.txt"); break; case 3: //MODIFY PASSWORD { ofstream outfile; ifstream infile; outfile.open("temp.txt", ios::out); infile.open("accounts.txt", ios::in); string web, newPass, line; cout<<"\nEnter the website :: "; cin>>web; cout<<"\nEnter the password :: "; cin>>newPass; newPass = encrypt(newPass, key); while(getline(infile, line)) { if (line == web) { outfile<<line<<endl; getline(infile, line); outfile<<line<<endl; getline(infile, line); outfile<<newPass<<endl; } else { outfile<<line<<endl; } } outfile.close(); infile.close(); } remove("accounts.txt"); rename("temp.txt", "accounts.txt"); break; case 4: //DISPLAY ALL ACCOUNTS { ifstream infile; infile.open("accounts.txt", ios::in); string line; while(getline(infile, line)) { cout<<"\n\nWEBSITE: "<<line<<endl; getline(infile, line); cout<<"USERNAME: "<<line<<endl; getline(infile, line); line = decrypt(line, key); cout<<"PASSWORD: "<<line<<endl; } infile.close(); } break; case 5: //SEARCH FOR AN ACCOUNT { string web; cout<<"\nEnter the website :: "; cin>>web; ifstream infile; infile.open("accounts.txt", ios::in); string line; bool found = false; while(getline(infile, line)) { if(line == web) { cout<<"Website found!"<<endl; cout<<"WEBSITE: "<<line<<endl; getline(infile, line); cout<<"USERNAME "<<line<<endl; getline(infile, line); line = decrypt(line, key); cout<<"PASSWORD "<<line<<endl; found = true; break; } } if (!found) { cout<<"\nWebsite not in directory"<<endl; } } break; case 6: // EXIT exit(0); default: { cout<<"\nInvalid choice. Please try again.\n"; } exit(0); } } }
e2ad87f544f4b731dd790dfd33b9a93f01eacb78
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_1482494_0/C++/Storm/ProbB.cpp
143baaecb17682ff1e2b9b682f9fe0e80e37a499
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
1,480
cpp
#include <iostream> #include <vector> #include <string> #include <map> #include <sstream> #include <algorithm> using namespace std; int main() { freopen("C:\\Projects\\gcj\\input.txt", "r", stdin); freopen("C:\\Projects\\gcj\\output.txt", "w", stdout); int z; cin >> z; for (int q=0;q<z;q++) { int n; cin >> n; vector<pair<int, int> > vals; for (int i=0;i<n;i++) { int x,y; cin >> x >> y; vals.push_back(make_pair(x,y)); } sort(vals.begin(), vals.end()); int lcount = 0; int stars = 0; vector<int> v1(n, false); vector<int> v2(n, false); int v2count = 0; while (v2count < n) { bool l2flag = false; for (int i=0;i<vals.size();i++) { if (!v2[i] && stars >= vals[i].second) { v2[i] = true; lcount++; stars += (2 - (v1[i] == true ? 1 : 0)); l2flag = true; v2count++; break; } } if (l2flag) continue; int pos = -1; int lowl2 = -1; for (int i=0;i<n;i++) { if (!v1[i] && stars >= vals[i].first) { if (vals[i].second - vals[i].first > lowl2) { pos = i; lowl2 = vals[i].second - vals[i].first; } } } if (pos == -1) { break; } stars++; v1[pos] = true; lcount++; } cout << "Case #" << (q+1) << ": "; if (v2count < n) { cout << "Too bad" << endl; } else { cout << lcount << endl; } } fclose(stdout); fclose(stdin); return 0; }
e1b48f78bdbdf3088d4f2e5b5730e015d8797ce6
087cbbd3099ff8fd8d2051c60461a0458333dbac
/contests/contest563Div2/B.cpp
550f6a6189d1fc1eea622af2677d633c9fd8aeef
[]
no_license
1998factorial/Codeforces
1046ffb2dbee582191fa59e7290c53e902c0af5c
f5b8139810e0724828e6ce7e26f3f8228589b00a
refs/heads/master
2021-07-05T21:34:45.053171
2021-04-10T06:21:33
2021-04-10T06:21:33
228,158,437
1
0
null
null
null
null
UTF-8
C++
false
false
668
cpp
#include <cstdio> #include <iostream> #include <sstream> #include <cstring> #include <algorithm> #include <vector> #include <stack> #include <queue> #include <set> #include <map> #include <complex> //#include <unordered_set> #define REP(i,a,b) for(int i=a;i<b;i++) #define RREP(i,a,b) for(int i=a;i>=b;i--) #define FILL(a,b) memset(a,b,sizeof(a)) using namespace std; typedef pair<int,int> ii; typedef long long ll; const int maxn=1e5+50; int a[maxn],n,b[maxn]; int main(){ scanf("%d",&n); int odd=0,even=0; REP(i,0,n){ scanf("%d",&a[i]); if(a[i]%2==0)even++; else odd++; } if(even&&odd) sort(a,a+n); REP(i,0,n)cout<<a[i]<<" "; cout<<endl; return 0; }
df30bafa83183ecf916e292ef839ed7fb6113491
2562b6d217713f76e485aa82eb3ac8cb4dfd918c
/ExNumbers/src/assign.cpp
3a5de6563667b23f19155f0320dcdc088e157b22
[]
no_license
mgriebling/HNumbers
3775437ae6e05193812836fd81f21025c200aa93
36f0751c565ecb279eab48abe270f7190b5fa3bc
refs/heads/master
2016-09-06T09:01:39.342185
2013-03-28T12:25:59
2013-03-28T12:25:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,492
cpp
#include "mp_real.h" #include "small_inline.h" mp_real& mp_real::operator=(const mp_real_temp& jb) { if (!mpr) { mpr = jb.mpr; return *this; } double n1 = mpr[0]; double n2 = jb.mpr[0]; //Must check to make sure that precision limits // for the assigned variable will not change. if (n1 == n2) { if(alloc) { delete [] mpr; mpr = jb.mpr; } else { memcpy(mpr, jb.mpr, sizeof(double) * static_cast<int>(n1)); delete [] jb.mpr; /* for (int i = 0; i < n1; i++) mpr[i] = jb.mpr[i]; */ } } else if (n1 < n2) { // May Need to truncate some words. use rounding. double nw = mpr[0]; double sgn = sign(1.0, jb.mpr[1]); mpr[1] = sgn * std::min(fabs(jb.mpr[1]), nw-FST_M-2.0); for (int i = 2; i < nw; i++) mpr[i] = jb.mpr[i]; mproun(*this); delete [] jb.mpr; /* double tnw = this->mpr[0]; double sgn, old_nw; delete [] mpr; mpr = jb.mpr; old_nw = mpr[1]; sgn = sign(1.0, mpr[1]); mpr[1] = sgn * std::min(fabs(mpr[1]), double(tnw-FST_M-2.0)); mpr[0] = tnw; if (old_nw == mpr[1]) return *this; else { mproun(*this); return *this; } */ } else { /* last case: this->mpr[0] > jb.mpr[0] Need to copy to maintain same maximum number of words. */ int i, end = int(fabs(jb.mpr[1]))+FST_M; for(i = 1; i < end; i++) mpr[i] = jb.mpr[i]; delete [] jb.mpr; return *this; } return *this; }
c6cdffbd9ff78e519d3a7993b655b23bee772c6b
a9c730860f52e0548a7882a0674340e008a53087
/client.cpp
89a04934bfda2f72a101e552e11c710e68a55d91
[]
no_license
FERNAND949/linux-tcpip
73adeb340feba3a344c1e26bba066502d427d8c2
dd7a4b946d8e3af2f75a6cb3f41c7fbf62b37a5f
refs/heads/master
2021-01-10T17:14:04.284481
2015-10-19T08:34:16
2015-10-19T08:34:16
44,521,155
0
0
null
null
null
null
UTF-8
C++
false
false
2,181
cpp
#include <iostream> #include <vector> #include <string.h> #include <unistd.h> // read関数を使う為 #include <sys/socket.h> // ソケット通信用 serverとclientの両方で必要 #include <error.h> // エラー解析用 #include <netinet/in.h> // sockaddr_in用 #include <arpa/inet.h> // inet_addr用 // 送信した関数 void Send(std::vector< char >& d, int& our) { // 送信するデータのサイズ int ndata = d.size(); // 送信バッファ char sendBuf[ndata]; // 送信バッファにコピー memcpy(sendBuf, &d[0], ndata); // 送信 int mWrite = write(our, sendBuf, sizeof(sendBuf)); if (mWrite <= 0) perror("send error"); } int main(int argc, char const* argv[]) { // ポート番号 int port = 9999; int our_sock; // IPアドレス // このテストプログラムではローカルで行っているので以下のアドレス // std::string ip = "127.0.0.1"; std::string ip = "192.168.0.54"; // AF_INETアドレスファミリーを使用する時は // sockaddr_inの構造体を使用する struct sockaddr_in client; // ソケットの作成 // server,client共通 // 今回はTCP/IPで作成するので以下のように引数を与える // 引数1:アドレスファミリ AF_INET:IPv4 // 引数2:ソケットタイプ SOCK_STREAM:TCP // 引数3:プロトコル our_sock = socket(AF_INET, SOCK_STREAM, 0); if (our_sock < 0) { // 失敗 std::cout << "socket failed" << std::endl; } else std::cout << "socket success" << std::endl; // クライアント側のポートやアドレス client.sin_family = AF_INET; client.sin_port = htons(port); // ipアドレスの指定 client.sin_addr.s_addr = inet_addr(ip.c_str()); // サーバーに接続できたかどうか int conServer = connect(our_sock, (struct sockaddr*)&client, sizeof(client)); if (conServer < 0) perror("connect error"); std::vector< char > d; uint h; while (1) { std::cout << "input num h = "; std::cin >> h; d.push_back(h); // 接続したサーバーに情報を送信 Send(d, our_sock); d.clear(); if (h == 0) break; } std::cout << "client stop" << std::endl; close(our_sock); return 0; }
41e3f26470a856385a7738981a762b22b14db398
6ce4918f7240a3a1a898140d5995932c1b0d4d82
/Exotic_engine/ConvergenceTable.cpp
5c3c4056cfceb819fd4fcbd8dbed6a0d66c62c73
[]
no_license
Jadepypy/DerivativesPricing_DesignPatterns
9e68a74bb8efde851892f5ca70d2b290a11c03d5
68ef61605bc5c3e2004b868db1c0a4dcf30a4d92
refs/heads/master
2022-11-15T00:37:56.340142
2020-07-01T02:19:45
2020-07-01T02:19:45
276,242,688
0
0
null
null
null
null
UTF-8
C++
false
false
1,241
cpp
#include "ConvergenceTable.h" #include <vector> ConvergenceTable :: ConvergenceTable(const Wrapper<StatisticsMC>& Inner_) : Inner(Inner_) { StoppingPoint = 2; PathsDone = 0; } StatisticsMC* ConvergenceTable :: clone() const { return new ConvergenceTable(*this); } void ConvergenceTable :: DumpOneResult(double result) { Inner->DumpOneResult(result); ++PathsDone; if(PathsDone == StoppingPoint) { StoppingPoint *= 2; std :: vector<std :: vector<double>> thisResult(Inner->GetResultsSoFar()); for(unsigned long i= 0; i < thisResult.size(); i++) { thisResult[i].push_back(PathsDone); ResultsSoFar.push_back(thisResult[i]); } } return; } //Don't alter ResultsSoFar std :: vector<std :: vector<double>> ConvergenceTable :: GetResultsSoFar() const { std :: vector<std :: vector<double>> tmp(ResultsSoFar); if(PathsDone*2 != StoppingPoint) { std :: vector<std :: vector<double>> thisResult(Inner->GetResultsSoFar()); for(unsigned long i= 0; i < thisResult.size(); i++) { thisResult[i].push_back(PathsDone); tmp.push_back(thisResult[i]); } } return tmp; }
98f516acd17561c92f0c2cf7ea4a9ea9eaa1f20f
1e17f6f0f9756d6043eb2a2d71dfd0e6c09590b2
/périmé/scripts/pycsw/geos-3.3.3/src/index/intervalrtree/IntervalRTreeBranchNode.cpp
fc58a125f7a5ecab4f3fff68a71b05a2ab32a3a4
[ "MIT", "LGPL-2.1-only" ]
permissive
federal-geospatial-platform/fgp-metadata-proxy
20e300b68eedfb29eed3e1cd24a69cf3c52898c3
82368614a2658260c0f09a1b5d341918310626e5
refs/heads/master
2023-08-09T14:03:35.522230
2023-08-03T15:10:11
2023-08-03T15:10:11
160,414,397
10
7
MIT
2023-05-01T23:16:00
2018-12-04T20:24:01
C++
UTF-8
C++
false
false
1,282
cpp
/********************************************************************** * $Id: IntervalRTreeBranchNode.cpp 2161 2008-08-18 16:29:09Z mloskot $ * * GEOS - Geometry Engine Open Source * http://geos.refractions.net * * Copyright (C) 2001-2002 Vivid Solutions Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * **********************************************************************/ #include <geos/index/intervalrtree/IntervalRTreeBranchNode.h> #include <geos/index/ItemVisitor.h> namespace geos { namespace index { namespace intervalrtree { // // private: // // // protected: // // // public: // void IntervalRTreeBranchNode::query( double queryMin, double queryMax, index::ItemVisitor * visitor) const { if (! intersects(queryMin, queryMax)) return; if (node1) node1->query( queryMin, queryMax, visitor); if (node2) node2->query( queryMin, queryMax, visitor); } } // geos::intervalrtree } // geos::index } // geos /********************************************************************** * $Log$ * **********************************************************************/
dd534b6411b74709df5043c103b481bf307e5a71
b9432d03b21d6e72e34d4697b58c240210d2d4a0
/service_apis/youtube/google/youtube_api/sponsor_snippet.h
e358b8747e4f43f55f57212766cb8dddd8e9fc2b
[ "Apache-2.0" ]
permissive
harshapat/google-api-cpp-client
f5edbf7674459c30e894430cda199d4a3b9788fb
7fb12b4bbb9db27fffede054149cf77c8e1c307f
refs/heads/master
2021-01-19T13:19:36.475387
2017-02-18T12:25:02
2017-02-18T12:25:02
82,384,775
0
0
null
2017-02-18T12:21:54
2017-02-18T12:21:54
null
UTF-8
C++
false
false
5,418
h
// Copyright 2010 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // C++ generator version: 0.1.3 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.3 #ifndef GOOGLE_YOUTUBE_API_SPONSOR_SNIPPET_H_ #define GOOGLE_YOUTUBE_API_SPONSOR_SNIPPET_H_ #include <string> #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/client/util/date_time.h" #include "googleapis/strings/stringpiece.h" #include "google/youtube_api/channel_profile_details.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * No description provided. * * @ingroup DataObject */ class SponsorSnippet : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static SponsorSnippet* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit SponsorSnippet(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit SponsorSnippet(Json::Value* storage); /** * Standard destructor. */ virtual ~SponsorSnippet(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::SponsorSnippet</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::SponsorSnippet"); } /** * Determine if the '<code>channelId</code>' attribute was set. * * @return true if the '<code>channelId</code>' attribute was set. */ bool has_channel_id() const { return Storage().isMember("channelId"); } /** * Clears the '<code>channelId</code>' attribute. */ void clear_channel_id() { MutableStorage()->removeMember("channelId"); } /** * Get the value of the '<code>channelId</code>' attribute. */ const StringPiece get_channel_id() const { const Json::Value& v = Storage("channelId"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>channelId</code>' attribute. * * The id of the channel being sponsored. * * @param[in] value The new value. */ void set_channel_id(const StringPiece& value) { *MutableStorage("channelId") = value.data(); } /** * Determine if the '<code>sponsorDetails</code>' attribute was set. * * @return true if the '<code>sponsorDetails</code>' attribute was set. */ bool has_sponsor_details() const { return Storage().isMember("sponsorDetails"); } /** * Clears the '<code>sponsorDetails</code>' attribute. */ void clear_sponsor_details() { MutableStorage()->removeMember("sponsorDetails"); } /** * Get a reference to the value of the '<code>sponsorDetails</code>' * attribute. */ const ChannelProfileDetails get_sponsor_details() const; /** * Gets a reference to a mutable value of the '<code>sponsorDetails</code>' * property. * * Details about the sponsor. * * @return The result can be modified to change the attribute value. */ ChannelProfileDetails mutable_sponsorDetails(); /** * Determine if the '<code>sponsorSince</code>' attribute was set. * * @return true if the '<code>sponsorSince</code>' attribute was set. */ bool has_sponsor_since() const { return Storage().isMember("sponsorSince"); } /** * Clears the '<code>sponsorSince</code>' attribute. */ void clear_sponsor_since() { MutableStorage()->removeMember("sponsorSince"); } /** * Get the value of the '<code>sponsorSince</code>' attribute. */ client::DateTime get_sponsor_since() const { const Json::Value& storage = Storage("sponsorSince"); return client::JsonValueToCppValueHelper<client::DateTime >(storage); } /** * Change the '<code>sponsorSince</code>' attribute. * * The date and time when the user became a sponsor. The value is specified in * ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format. * * @param[in] value The new value. */ void set_sponsor_since(client::DateTime value) { client::SetJsonValueFromCppValueHelper<client::DateTime >( value, MutableStorage("sponsorSince")); } private: void operator=(const SponsorSnippet&); }; // SponsorSnippet } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_SPONSOR_SNIPPET_H_
026fee55ebad1d541070981d815f692bc84558fe
73234f58bd965b0185c83830d689eca563746be0
/lib/grbl/src/serial.cpp
b9135fcdc8a1b961458703b31d1237cd5d8a5859
[]
no_license
louisguan/grblesp
52ad861ce829a77248074f843d22b3f48492101e
accdbf849c5354373524a2bd265c35b42a550ee3
refs/heads/master
2022-04-06T14:27:23.672161
2020-02-16T05:49:43
2020-02-16T05:49:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,005
cpp
/* serial.c - Low level functions for sending and recieving bytes via the serial port Part of Grbl Copyright (c) 2011-2016 Sungeun K. Jeon for Gnea Research LLC Copyright (c) 2009-2011 Simen Svale Skogsrud Grbl 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. Grbl 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 Grbl. If not, see <http://www.gnu.org/licenses/>. */ #include "grbl.hpp" #include <Ticker.h> #define RX_RING_BUFFER (RX_BUFFER_SIZE+1) #define TX_RING_BUFFER (TX_BUFFER_SIZE+1) uint8_t serial_rx_buffer[CLIENT_COUNT][RX_RING_BUFFER]; uint8_t serial_rx_buffer_head[CLIENT_COUNT] = {0}; volatile uint8_t serial_rx_buffer_tail[CLIENT_COUNT] = {0}; Ticker serial_poll_task; // Returns the number of bytes available in the RX serial buffer. uint8_t serial_get_rx_buffer_available(uint8_t client) { uint8_t client_idx = client - 1; uint8_t rtail = serial_rx_buffer_tail[client_idx]; // Copy to limit multiple calls to volatile if (serial_rx_buffer_head[client_idx] >= rtail) { return(RX_BUFFER_SIZE - (serial_rx_buffer_head[client_idx]-rtail)); } return((rtail-serial_rx_buffer_head[client_idx]-1)); } void serial_init() { Serial.begin(BAUD_RATE); Serial.setDebugOutput(false); serial_poll_task.attach_ms(1, serial_poll_rx); } void serial_poll_rx() { uint8_t data = 0; uint8_t next_head; uint8_t client; // who sent the data uint8_t client_idx = 0; // index of data buffer while (Serial.available() #ifdef ENABLE_SERIAL2SOCKET || Serial2Socket.available() #endif ) { if (Serial.available()) { client = CLIENT_SERIAL; data = Serial.read(); } #ifdef ENABLE_SERIAL2SOCKET else { if (Serial2Socket.available()) { client = CLIENT_WEBSOCKET; data = Serial2Socket.read(); } } #endif client_idx = client - 1; // for zero based array // Pick off realtime command characters directly from the serial stream. These characters are // not passed into the main buffer, but these set system state flag bits for realtime execution. switch (data) { case CMD_RESET: mc_reset(); break; // Call motion control reset routine. case CMD_STATUS_REPORT: report_realtime_status(client); break; case CMD_CYCLE_START: system_set_exec_state_flag(EXEC_CYCLE_START); break; // Set as true case CMD_FEED_HOLD: system_set_exec_state_flag(EXEC_FEED_HOLD); break; // Set as true default : if (data > 0x7F) { // Real-time control characters are extended ACSII only. switch(data) { case CMD_SAFETY_DOOR: system_set_exec_state_flag(EXEC_SAFETY_DOOR); break; // Set as true case CMD_JOG_CANCEL: if (sys.state & STATE_JOG) { // Block all other states from invoking motion cancel. system_set_exec_state_flag(EXEC_MOTION_CANCEL); } break; #ifdef DEBUG case CMD_DEBUG_REPORT: {uint8_t sreg = SREG; cli(); bit_true(sys_rt_exec_debug,EXEC_DEBUG_REPORT); SREG = sreg;} break; #endif case CMD_FEED_OVR_RESET: system_set_exec_motion_override_flag(EXEC_FEED_OVR_RESET); break; case CMD_FEED_OVR_COARSE_PLUS: system_set_exec_motion_override_flag(EXEC_FEED_OVR_COARSE_PLUS); break; case CMD_FEED_OVR_COARSE_MINUS: system_set_exec_motion_override_flag(EXEC_FEED_OVR_COARSE_MINUS); break; case CMD_FEED_OVR_FINE_PLUS: system_set_exec_motion_override_flag(EXEC_FEED_OVR_FINE_PLUS); break; case CMD_FEED_OVR_FINE_MINUS: system_set_exec_motion_override_flag(EXEC_FEED_OVR_FINE_MINUS); break; case CMD_RAPID_OVR_RESET: system_set_exec_motion_override_flag(EXEC_RAPID_OVR_RESET); break; case CMD_RAPID_OVR_MEDIUM: system_set_exec_motion_override_flag(EXEC_RAPID_OVR_MEDIUM); break; case CMD_RAPID_OVR_LOW: system_set_exec_motion_override_flag(EXEC_RAPID_OVR_LOW); break; case CMD_SPINDLE_OVR_RESET: system_set_exec_accessory_override_flag(EXEC_SPINDLE_OVR_RESET); break; case CMD_SPINDLE_OVR_COARSE_PLUS: system_set_exec_accessory_override_flag(EXEC_SPINDLE_OVR_COARSE_PLUS); break; case CMD_SPINDLE_OVR_COARSE_MINUS: system_set_exec_accessory_override_flag(EXEC_SPINDLE_OVR_COARSE_MINUS); break; case CMD_SPINDLE_OVR_FINE_PLUS: system_set_exec_accessory_override_flag(EXEC_SPINDLE_OVR_FINE_PLUS); break; case CMD_SPINDLE_OVR_FINE_MINUS: system_set_exec_accessory_override_flag(EXEC_SPINDLE_OVR_FINE_MINUS); break; case CMD_SPINDLE_OVR_STOP: system_set_exec_accessory_override_flag(EXEC_SPINDLE_OVR_STOP); break; case CMD_COOLANT_FLOOD_OVR_TOGGLE: system_set_exec_accessory_override_flag(EXEC_COOLANT_FLOOD_OVR_TOGGLE); break; #ifdef ENABLE_M7 case CMD_COOLANT_MIST_OVR_TOGGLE: system_set_exec_accessory_override_flag(EXEC_COOLANT_MIST_OVR_TOGGLE); break; #endif } // Throw away any unfound extended-ASCII character by not passing it to the serial buffer. } else { // Write character to buffer // enter mutex next_head = serial_rx_buffer_head[client_idx] + 1; if (next_head == RX_RING_BUFFER) { next_head = 0; } // Write data to buffer unless it is full. if (next_head != serial_rx_buffer_tail[client_idx]) { serial_rx_buffer[client_idx][serial_rx_buffer_head[client_idx]] = data; serial_rx_buffer_head[client_idx] = next_head; } // exit mutex } } #if defined(ENABLE_SERIAL2SOCKET) Serial2Socket.handle_flush(); #endif } } void serial_reset_read_buffer(uint8_t client) { for (uint8_t client_num = 1; client_num <= CLIENT_COUNT; client_num++) { if (client == client_num || client == CLIENT_ALL) { serial_rx_buffer_tail[client_num-1] = serial_rx_buffer_head[client_num-1]; } } } // Writes one byte to the TX serial buffer. Called by main program. void serial_write(uint8_t data) { Serial.write((char)data); } // Fetches the first byte in the serial read buffer. Called by main program. uint8_t serial_read(uint8_t client) { uint8_t client_idx = client - 1; uint8_t tail = serial_rx_buffer_tail[client_idx]; // Temporary serial_rx_buffer_tail (to optimize for volatile) if (serial_rx_buffer_head[client_idx] == tail) { return SERIAL_NO_DATA; } else { // enter mutex uint8_t data = serial_rx_buffer[client_idx][tail]; tail++; if (tail == RX_RING_BUFFER) { tail = 0; } serial_rx_buffer_tail[client_idx] = tail; // exit mutex return data; } }
c1d5451f5ef0725b9d0c1c1f7c3d495b49d513c4
cb8c337a790b62905ad3b30f7891a4dff0ae7b6d
/st-ericsson/multimedia/audio/binary_splitter/nmfil/host/wrapper/inc/wrapper.hpp
005da04199d73f6b3cc9138bf84218d69977feb1
[]
no_license
CustomROMs/android_vendor
67a2a096bfaa805d47e7d72b0c7a0d7e4830fa31
295e660547846f90ac7ebe42a952e613dbe1b2c3
refs/heads/master
2020-04-27T15:01:52.612258
2019-03-11T13:26:23
2019-03-12T11:23:02
174,429,381
1
0
null
null
null
null
UTF-8
C++
false
false
2,700
hpp
/*****************************************************************************/ /* * Copyright (C) ST-Ericsson SA 2009,2010. All rights reserved. * This code is ST-Ericsson proprietary and confidential. * Any use of the code for whatever purpose is subject to * specific written permission of ST-Ericsson SA. * */ /** * \file binarysplitter.hpp * \brief * \author ST-Ericsson */ /*****************************************************************************/ #ifndef _binarysplitter_nmfil_host_wrapper_hpp_ #define _binarysplitter_nmfil_host_wrapper_hpp_ #include "Component.h" #include "common_interface.h" #define NB_OUTPUT 2 class binary_splitter_nmfil_host_wrapper : public Component, public binary_splitter_nmfil_host_wrapperTemplate { public: binary_splitter_nmfil_host_wrapper(); virtual ~binary_splitter_nmfil_host_wrapper(); // NMF life-cycle methods... virtual t_nmf_error construct(void); virtual void destroy(void); virtual void start(void); virtual void stop(void); // Component virtual methods... virtual void reset(); virtual void process(); virtual void disablePortIndication(t_uint32 portIdx); virtual void enablePortIndication(t_uint32 portIdx); virtual void flushPortIndication(t_uint32 portIdx); virtual void fsmInit(fsmInit_t initFsm); virtual void setTunnelStatus(t_sint16 portIdx, t_uint16 isTunneled); virtual void sendCommand(OMX_COMMANDTYPE cmd, t_uword param) { Component::sendCommand(cmd, param) ; } virtual void processEvent(void) { Component::processEvent() ; } virtual void emptyThisBuffer(OMX_BUFFERHEADERTYPE_p buffer, t_uint8 portIdx); virtual void fillThisBuffer(OMX_BUFFERHEADERTYPE_p buffer, t_uint8 portIdx); virtual void setParameter(t_pcmprocessing_config_host config); virtual void setSynchronizedOutputPort(t_uint16 portIdx, BOOL bIsSynchronized); virtual void newFormat(t_sample_freq sample_freq, t_uint16 chans_nb, t_uint16 sample_size, t_uint8 portIdx); private: t_sample_freq mSampleFreq[NB_OUTPUT]; t_uint16 mNbChannels; t_uint16 mSampleBitSize; typedef enum {INPUT_PORT_IDX, OUTPUT_PORT_IDX} portname; typedef struct { OMX_BUFFERHEADERTYPE_p BufferPtr; bool bIsSynchronized; bool bOutputRequired; bool bEosReceived; }OutputBuffer; OutputBuffer mOutputBuf[NB_OUTPUT]; OMX_BUFFERHEADERTYPE_p mInputBufPtr; Port mPorts[NB_OUTPUT+1]; t_pcmprocessing_config_host mConfig; }; #endif // _binarysplitter_nmfil_host_wrapper_hpp_
3fecb7877d28a594e4d883ac9d342b56c706884e
0a0ca545967a0e2db0419aa35eb63d40ae486011
/src/Viewer/WidgetContent.cpp
2736bf2a9955ff83d4bfe222f5b48b4883c88ad7
[]
no_license
ukropj/VisualContent
697f5328b177240a5b8a250ab4cf6f826b6c738a
117668dbee5ad3aae3c106da3825d03fad74a518
refs/heads/master
2021-01-16T17:38:53.216238
2011-06-15T17:29:08
2011-06-15T17:29:08
974,190
0
0
null
null
null
null
UTF-8
C++
false
false
3,220
cpp
/* * WidgetContent.cpp * * Created on: 25.12.2010 * Author: jakub */ #include "Viewer/WidgetContent.h" #include <osg/Texture> #include <osg/ShapeDrawable> #include <osgViewer/Viewer> #include <osgViewer/ViewerEventHandlers> #include "OsgQtBrowser/QWidgetImage.h" #include "Util/TextureWrapper.h" #include <QTextEdit> #include <QWebView> using namespace Vwr; WidgetContent::WidgetContent() : OsgContent() { loaded = false; widget = NULL; } WidgetContent::~WidgetContent() { if (widget != NULL) widget->close(); } void WidgetContent::setWidget(QWidget* widget, float scale) { // TODO refactor this->widget = widget; widget->setAttribute(Qt::WA_DeleteOnClose); osg::ref_ptr<QWidgetImage> widgetImage = new QWidgetImage(widget); widgetImage->getQWidget()->setAttribute(Qt::WA_TranslucentBackground); widgetImage->getQGraphicsViewAdapter()->setBackgroundColor(QColor(0, 0, 0, 0)); QSize size = widget->geometry().size(); float width = size.width()*150 / ((float)size.height()); float height = 150; // XXX magic numbers width *= scale; height *= scale; // determines size & ratio! osg::ref_ptr<osg::Geometry> quad = osg::createTexturedQuadGeometry( osg::Vec3(-width/2.0f, -height/2.0f, 0), osg::Vec3(width, 0, 0), osg::Vec3(0, height, 0), 1, 1); osg::ref_ptr<osg::StateSet> stateSet = getOrCreateStateSet(); osg::ref_ptr<osg::Texture2D> texture = Util::TextureWrapper::createTexture(widgetImage); texture->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR); stateSet->setTextureAttributeAndModes(0, texture, osg::StateAttribute::ON); // stateSet->setAttribute(new osg::Program); // this enables interaction with the widget (buggy), use current camera // nothing is shown without this code! osg::Camera* camera = 0; osgViewer::InteractiveImageHandler* handler = new osgViewer::InteractiveImageHandler(widgetImage.get(), texture, camera); quad->setEventCallback(handler); quad->setCullCallback(handler); contentGeode = new osg::Geode; contentGeode->addDrawable(quad); contentGeode->setStateSet(stateSet); contentGeode->setName("node_content_widget"); addChild(contentGeode); loaded = true; } TextContent::TextContent(QString text, int width, int height) : text(text), width(width), height(height) { loaded = false; } TextContent::~TextContent() { } bool TextContent::load() { if (loaded) { return false; } else { loaded = true; QTextEdit* l = new QTextEdit(); l->setText(text); QSize size(width, height); // XXX magic l->setGeometry(QRect(QPoint(1, 1), size)); // QWebView* view = new QWebView(); // view->load(QUrl("http://qt.nokia.com/")); setWidget(l, 0.2f); // XXX magic number contentGeode->setName("node_content_text"); return true; } } WebContent::WebContent(QString url) : url(url) { loaded = false; } WebContent::~WebContent() { } bool WebContent::load() { if (loaded) { return false; } else { loaded = true; QSize size(200, 150); // XXX magic QWebView* view = new QWebView(); view->setZoomFactor(0.2); view->setGeometry(QRect(QPoint(1, 1), size)); view->load(QUrl(url)); setWidget(view, 0.2f); // XXX magic number contentGeode->setName("node_content_web_page"); return true; } }
523213b0680018ddca91fc1eca05981589ed5378
9530eb5b4fc5acc39d71c6d8e6637e49093f58b8
/11689 Soda Surpler.cpp
21def4efab61ce5700c977f61f4f8003903d9424
[]
no_license
Mahbub20/UVA-Solutions
9ea6ae47a22730b30168118edee0fa77eee1a1f6
3ed44a00130bfc9b6ce4cfe2d17c57940ffdc3c6
refs/heads/master
2021-01-13T08:18:12.680369
2018-10-03T16:15:08
2018-10-03T16:15:08
68,840,053
0
0
null
null
null
null
UTF-8
C++
false
false
339
cpp
#include<bits/stdc++.h> using namespace std; int main() { int e,f,c,t,sum; cin >> t; while(t--) { cin >> e >> f >> c; int g = e+f; sum = 0; while(g>=c) { int h = g/c; sum+=h; g = h+g%c; } cout << sum << endl; } return 0; }
18bf077fa88931a66e21405c9d1173428111cd90
9a32178d3c2fdf377d84f65b55989264e67f40e9
/2002/ALL VC SAMPLES/Compiler/TypeLibsupport/dcom/atldraw/atlddoc.cpp
69e8d6ded7593e976d8e6a36b247d5bb8ce2b1f6
[]
no_license
philipwolfe/Samples
5e5cc1376575ac6361b62a3554c98626f153b694
7eb703287a6d07596a141c4557f271efe6c1666f
refs/heads/master
2021-12-25T12:52:52.616313
2021-12-19T04:26:29
2021-12-19T04:26:29
250,445,305
3
1
null
null
null
null
UTF-8
C++
false
false
2,137
cpp
// ATLDrawDoc.cpp : implementation of the CATLDrawDoc class // // This is a part of the ActiveX Template Library. // Copyright (C) 1996 Microsoft Corporation // All rights reserved. // // This source code is only intended as a supplement to the // ActiveX Template Library Reference and related // electronic documentation provided with the library. // See these sources for detailed information regarding the // ActiveX Template Library product. // #include "preatldr.h" #include "ATLDraw.h" #include "ATLDDoc.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CATLDrawDoc IMPLEMENT_DYNCREATE(CATLDrawDoc, CDocument) BEGIN_MESSAGE_MAP(CATLDrawDoc, CDocument) //{{AFX_MSG_MAP(CATLDrawDoc) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CATLDrawDoc construction/destruction CATLDrawDoc::CATLDrawDoc() { // TODO: add one-time construction code here } CATLDrawDoc::~CATLDrawDoc() { } BOOL CATLDrawDoc::OnNewDocument() { if (!CDocument::OnNewDocument()) return FALSE; // TODO: add reinitialization code here // (SDI documents will reuse this document) return TRUE; } ///////////////////////////////////////////////////////////////////////////// // CATLDrawDoc serialization void CATLDrawDoc::Serialize(CArchive& ar) { if (ar.IsStoring()) { // TODO: add storing code here } else { // TODO: add loading code here } } ///////////////////////////////////////////////////////////////////////////// // CATLDrawDoc diagnostics #ifdef _DEBUG void CATLDrawDoc::AssertValid() const { CDocument::AssertValid(); } void CATLDrawDoc::Dump(CDumpContext& dc) const { CDocument::Dump(dc); } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CATLDrawDoc commands
36041870d08e06014a2b49ba9ce5405d90e69601
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/chrome/browser/policy/messaging_layer/upload/testing_network_condition_service.h
e83695837d0209e53f554914afc021d27065c71c
[ "BSD-3-Clause" ]
permissive
chromium/chromium
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
refs/heads/main
2023-08-24T00:35:12.585945
2023-08-23T22:01:11
2023-08-23T22:01:11
120,360,765
17,408
7,102
BSD-3-Clause
2023-09-10T23:44:27
2018-02-05T20:55:32
null
UTF-8
C++
false
false
1,735
h
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_POLICY_MESSAGING_LAYER_UPLOAD_TESTING_NETWORK_CONDITION_SERVICE_H_ #define CHROME_BROWSER_POLICY_MESSAGING_LAYER_UPLOAD_TESTING_NETWORK_CONDITION_SERVICE_H_ #include <cstddef> #include "base/time/time.h" #include "chrome/browser/policy/messaging_layer/upload/network_condition_service.h" #include "content/public/test/browser_task_environment.h" namespace reporting { // Utilities for using network condition service in a test environment. The main // purpose of this class is to provide access to private members of // |NetworkConditionService| without exposing them in the production code and // remove code that would update its internal upload_rate_. Also unsubscribe // from network condition change notified by // g_browser_process->network_quality_tracker() in the constructor to avoid // unexpected change in upload_rate_. // // Example Usage: // // TestingNetworkConditionService network_condition_service; // network_condition_service.SetUploadRate(1000); // class TestingNetworkConditionService : public NetworkConditionService { public: // Unsubscribe from g_browser_process->network_quality_tracker() via the UI // thread and clear the task queue on the UI thread immediately. explicit TestingNetworkConditionService( content::BrowserTaskEnvironment* task_environment); // Set the private variable upload_rate_ directly. This is what // |GetUploadRate| returns. void SetUploadRate(uint64_t upload_rate); }; } // namespace reporting #endif // CHROME_BROWSER_POLICY_MESSAGING_LAYER_UPLOAD_TESTING_NETWORK_CONDITION_SERVICE_H_
732bcc339d90221b6fb7c6a5c316dc0e22d182e1
68f96856b5204a048117dd23cbaf13a3032d278f
/p2pcrypt_sql.h
12f9a1714380f8f87132c00b80620e9f49683b25
[]
no_license
lvjh/P2PCrypt-Client
7413637dc3a6b9e9bacaf235bb2406163afe3337
a396e893d4555fb46faaf4268fad4bfbf16a2578
refs/heads/master
2021-01-15T18:26:29.954590
2013-04-01T07:26:24
2013-04-01T07:26:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
383
h
#ifndef P2PCRYPT_SQL_H #define P2PCRYPT_SQL_H #include <QObject> #include <QSql> #include <QtSql/QtSql> class p2pcrypt_sql : public QObject { Q_OBJECT public: QSqlDatabase database_handle; explicit p2pcrypt_sql(QObject *parent = 0); void connectToDatabase(QString sql_filename, QString connection_name); signals: public slots: }; #endif // P2PCRYPT_SQL_H
c5348e98ff3a8089d662c90b6c3f9f00560b9b49
ef6bc69f4443c2c65b5928403ad6ba20bc723099
/week-04/day-5/example/main.cpp
5bd41704a56976ee4074b7f0a76899c9634403dd
[]
no_license
green-fox-academy/plainte
14a76155f82c6922c4634586153f62f79c86ec05
4150b688ac2a48b56f88c5488d8c6dd3bcfaf72e
refs/heads/master
2020-04-16T18:52:44.457767
2019-03-21T14:23:01
2019-03-21T14:23:01
165,569,057
0
0
null
null
null
null
UTF-8
C++
false
false
1,379
cpp
#include <vector> #include <iostream> void printMatrix(const std::vector<std::vector<int>> &matrix); std::vector<std::vector<int>> rotateMatrix(std::vector<std::vector<int>> matrix); int main() { // Create a function named `rotateMatrix` that takes an n×n integer matrix (vector of vectors) as parameter // and returns a matrix which elements are rotated 90 degrees clockwise. // // example input: // [[1, 2, 3], // 7 4 1 // [4, 5, 6], // 8 5 2 // [7, 8, 9]] // 9 6 3 std::vector<std::vector<int>> matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; std::vector<std::vector<int>> rotatedMatrix = rotateMatrix(matrix); printMatrix(rotatedMatrix); // should print // 7 4 1 // 8 5 2 // 9 6 3 return 0; } std::vector<std::vector<int>> rotateMatrix(std::vector<std::vector<int>> matrix) { std::vector<std::vector<int>> tempMatrix = matrix; for (int i = 0; i < matrix.size(); i++) { for (int j = 0; j < matrix[i].size(); j++) { tempMatrix[i][2-j] = matrix[j][i]; } } return tempMatrix; } void printMatrix(const std::vector<std::vector<int>> &matrix) { for (int i = 0; i < matrix.size(); i++) { for (int j = 0; j < matrix[i].size(); j++) { std::cout << matrix[i][j] << " "; } std::cout << std::endl; } }
6e7e6722deab268c44c7f03a6ce0d2226e016796
f6379760ed5d5de1ee3af7e070f18318f80afc8b
/NodeAlreadyExistsInTreeException.h
d4c2dab5c6280aa539c3181c0e9fa5d053f6896b
[]
no_license
DiegoAvena/BinarySearchTree
50efb0eb3bc77fb8dcefc6d5d08a0058d52be711
d8cb51b25c3dbab20d5f6c1575cc098ffa51cb98
refs/heads/master
2021-06-15T22:19:13.713150
2021-05-26T20:36:25
2021-05-26T20:36:25
180,036,035
0
0
null
null
null
null
UTF-8
C++
false
false
379
h
#ifndef NODE_ALREADY_EXISTS_IN_TREE_EXCEPTION_H #define NODE_ALREADY_EXISTS_IN_TREE_EXCEPTION_H #include "RunTimeException.h" #include <iostream> class NodeAlreadyExistsInTreeException:public RunTimeException { public: NodeAlreadyExistsInTreeException(); NodeAlreadyExistsInTreeException(std::string customErrorMessage); ~NodeAlreadyExistsInTreeException(); }; #endif
edf97862197e4e0c8143c9bea748fa87c298bb6e
2fbf96bb69f954dbf6bbf13661b0492de9b3b4b1
/uva/uva514.cpp
5c1a00ac3e8c7c91af5086df9d49493290edd6f3
[]
no_license
timothywangdev/Programming-Contests
432d0e6719cf2c910d24416dfacb46abb046a735
dcd58694bd66536222f2ffd78b025af5a38aab4f
refs/heads/master
2023-08-02T06:57:22.724822
2021-10-08T19:06:32
2021-10-08T19:06:32
16,039,238
0
0
null
null
null
null
UTF-8
C++
false
false
1,273
cpp
#include <iostream> #include <stack> using namespace std; //#define DEBUG #include <fstream> #ifdef DEBUG ifstream fin("uva514.in"); ofstream fout("uva514.out"); #endif void redirect(){ #ifdef DEBUG std::streambuf *cinbuf = std::cin.rdbuf(); std::cin.rdbuf(fin.rdbuf()); std::streambuf *coutbuf = std::cout.rdbuf(); std::cout.rdbuf(fout.rdbuf()); #endif } int v[1000],rail[1000];; int N; bool first=true; bool terminated; stack<int> s; int onRailA(int start,int target){ for(int i=start;i<N;i++) if(rail[i]==target) return i; return -1; } int main(){ redirect(); while(cin>>N){ if(N==0) break; terminated=false; while(!terminated){ while(s.size()!=0) s.pop(); for(int i=0;i<N;i++){ cin>>v[i]; if(i==0&&v[0]==0){ terminated=true; break; } } if(!terminated){ bool possible=true; for(int i=1;i<=N;i++) rail[i-1]=i; int railA=0; for(int i=0;i<N;i++){ int pos=onRailA(railA,v[i]); if(pos!=-1){ for(int j=railA;j<=pos;j++) s.push(rail[j]); railA=pos+1; } if(s.top()!=v[i]){ possible=false; break; } else{ s.pop(); } } if(possible) cout<<"Yes"<<endl; else cout<<"No"<<endl; } } cout<<endl; } }
92d1cc7cbc2043e639ada4d97b6e337724982187
fa04d2f56c8d4ebfb931968392811a127a4cb46c
/trunk/Cities3D/src/CoreRules/LogicCardList.cpp
e3a9b33448fb0b06581d62d28d8bf5e5fb298fb9
[]
no_license
andrewlangemann/Cities3D
9ea8b04eb8ec43d05145e0b91d1c542fa3163ab3
58c6510f609a0c8ef801c77f5be9ea622e338f9a
refs/heads/master
2022-10-04T10:44:51.565770
2020-06-03T23:44:07
2020-06-03T23:44:07
268,979,591
0
0
null
2020-06-03T03:25:54
2020-06-03T03:25:53
null
UTF-8
C++
false
false
1,854
cpp
/* * Cities3D - Copyright (C) 2001-2009 Jason Fugate ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. */ #include "stdwx.h" #include "style.h" //READ THIS BEFORE MAKING ANY CHANGES TO THIS FILE!!! //---------------------------- SYSTEM INCLUDES -----------------------------// //---------------------------- USER INCLUDES -----------------------------// #include "Logic.h" #include "LogicHashMixin.h" #include "RuleSetDatabase.h" //---------------------------- TYPEDEFS -----------------------------// #ifdef _DEBUG #define new DEBUG_NEW #endif //---------------------------- STATICS -----------------------------// //---------------------------- LOGIC -----------------------------// //---------------------------------------------------------------------------// // Class: LogicCardList // // A mixin container that provides a list of cards of the given type the player // has. // // Derived From: // <Logic>, // <LogicHashMixin> // // Project: // <CoreRules> // // RuleSet: // <Core> // class LogicCardList : public Logic , public LogicHashMixin { public: virtual void Decide(const DataObject &input, DataObject &output) { const HashString& type = input.read<HashString>(); if(false == DecideHash(type, input, output)) { wxASSERT(false); } } }; IMPLEMENT_LOGIC(LogicCardList, CORE)
d54ea372b8605b3eed44b29d3cc94c03a69ea562
5bb05305968cb041848932199b8f6649db4920e7
/workspace/HW2/bartender.cpp
921e5822418938dbbbb8ebdde22a7c05c38bd165
[]
no_license
cemildo/cplusplus
81dcf8185ff7268bcd9125a8d605ec02f6ea646d
3f3da37412ab364df97b74a322339bc193ec5f7c
refs/heads/master
2021-01-10T13:26:21.103234
2015-10-07T15:13:39
2015-10-07T15:13:39
43,824,576
0
0
null
null
null
null
UTF-8
C++
false
false
663
cpp
/* #include <iostream> #include <iomanip> #include <vector> #include <iterator> #include <algorithm> #include <string> using namespace std; int main (){ const vector <double> drinks {4.65,9.15,3.85,2.95}; cout <<setw(6)<<" "<<setw(6)<<"small Beer" <<setw(6)<< " Moaß Beer" <<setw(6)<< " Schnapps" <<setw(6)<< " Soda"<<"\n"; for(double b=1;b<=10;b++) { cout<<setw(43)<<setfill('_'); cout<< setw(3)<< b<< " |"; for(int a=0;a< drinks.size();a++) { //cout <<setfill('_')<<setw(20)<<"\n"<<setfill(' '); cout<<setw(10)<<setprecision(5)<< drinks.at(a) * b<<"|" ; } cout<<"\n"; } } */
b1e5da9f265d03c998f1e12da34a1fbad6d4a11c
15568eb5834435a24538ac50368bb1cbf64049a1
/RU/Files/day2_LabWork/cases/t-junction-st/0.43/uniform/time
2d3b65b3abfe58715f953a3f8ff0194c1ca09294
[]
no_license
lhp18/TwoDaysFoamProgrammingCourse
9a2c2de84c7d76ad80dd7392fc024b46b9b0e368
200206cdcb66e40fc360e579d6d2f8519b53dd5d
refs/heads/master
2021-05-30T16:26:52.957290
2016-01-05T17:03:59
2016-01-05T17:03:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
957
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 2.1.0 | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; location "0.43/uniform"; object time; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // value 0.43; index 4300; deltaT 0.0001; deltaT0 0.0001; // ************************************************************************* //
394bd77f0080c5268008a3975dc126c03b366fe8
1fb1edd7ae3e8a54b713829446653452a6754995
/app/src/main/cpp/GTJAComm/GTJAUtil/src/GTJAXHexCode.cpp
33c5f9a015aa2cabfec3941f231c87bf087dddf9
[ "Apache-2.0" ]
permissive
VigorousLiang/GMJni
0c44610a3369ed974c6e82106dc5de9982f8571b
4b9fc5f7bcf466c4e9fc6c83328994fcb3f85a33
refs/heads/master
2020-03-26T16:11:22.365526
2019-02-19T09:37:51
2019-02-19T09:37:51
145,086,928
1
0
null
null
null
null
UTF-8
C++
false
false
1,349
cpp
#include "GTJAXHexCode.h" #include <stdio.h> #include <string.h> /** * HEX解码 将形如0x12 0x2A 0x01 转换为122A01 */ int GTJAXHexDecode(const unsigned char *szIn, int len, char **szOut) { (*szOut) = new char[len * 2 + 1]; int i = 0; if (*szOut) { memset(*szOut, 0x00, len * 2 + 1); char* pTemp = *szOut; for (i = 0; i < len; i++) { sprintf(pTemp, "%02X", szIn[i]); pTemp += 2; } } return 2 * i; } /** * HEX编码 将形如122A01 转换为0x12 0x2A 0x01 */ int GTJAXHexEncode(const char* szIn, const int len, unsigned char** szOut) { (*szOut) = new unsigned char[len/2]; if ((*szOut) == NULL) { return 0; } memset(*szOut, 0x00, len/2); unsigned char* p = (*szOut); int j = 0; unsigned char hi; unsigned char low; for(int i = 0;i < len;){ hi = szIn[i++]; if( hi>='0' && hi<='9'){ hi -= '0'; }else if(hi>='A' && hi<='F'){ hi -= 'A'; hi += 10; }else if(hi>='a' && hi<='f'){ hi -= 'a'; hi += 10; }else{ hi = 0; } low = 0; if(i < len){ low = szIn[i++]; if( low>='0' && low<='9'){ low -= '0'; }else if(low>='A' && low<='F'){ low -= 'A'; low += 10; }else if(low>='a' && low<='f'){ low -= 'a'; low += 10; } } p[j++] = ((hi&0x0F)<<4) | (low&0x0F); } return j; }
1372b51778f149d0b92d540d4211bd3c4c3a7e78
5b6445d92c1247cdad8bd6ae515d5c022ddf021f
/libraries/plugins/group_signature/include/steem/plugins/group_signature/group_signature_object.hpp
fc9509685e11b30cb97cab1074d99244aff8d5f6
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
xinlei87/steem-groupsig
8bd335717486b8a6788a2b39e6f702455d5d76f7
10d7169a52d54057a852fffa598bf1adb4a112e6
refs/heads/master
2020-05-28T11:52:24.179564
2019-07-09T11:33:54
2019-07-09T11:33:54
188,990,998
0
0
null
null
null
null
UTF-8
C++
false
false
5,098
hpp
#pragma once #include<pbc/pbc.h> namespace steem { namespace plugins { namespace group_signature { class MPK { public: element_t g, g2, h1, u0, u1, u2, u3, u4, n, h; MPK(pairing_t pairing) { element_init_G1(g, pairing); element_init_G1(h, pairing); element_init_G2(g2, pairing); element_init_G1(h1, pairing); element_init_G2(u0, pairing); element_init_G2(u1, pairing); element_init_G2(u2, pairing); element_init_G2(u3, pairing); element_init_G2(u4, pairing); element_init_GT(n, pairing); } ~MPK() { element_clear(g); element_clear(g2); element_clear(h1); element_clear(u0); element_clear(u1); element_clear(u2); element_clear(u3); element_clear(u4); element_clear(n); } }; class GSK { public: element_t a0, a2, a3, a4, a5; GSK(pairing_t pairing) { element_init_G2(a0, pairing); element_init_G2(a2, pairing); element_init_G2(a3, pairing); element_init_G2(a4, pairing); element_init_G1(a5, pairing); } ~GSK() { element_clear(a0); element_clear(a2); element_clear(a3); element_clear(a4); element_clear(a5); } }; class USK { public: element_t b0, b3, b4, b5; USK(pairing_t pairing) { element_init_G2(b0, pairing); element_init_G2(b3, pairing); element_init_G2(b4, pairing); element_init_G1(b5, pairing); } ~USK() { element_clear(b0); element_clear(b3); element_clear(b4); element_clear(b5); } }; class OK { public: element_t ok1, ok2; OK(pairing_t pairing) { element_init_GT(ok1, pairing); element_init_GT(ok2, pairing); } ~OK() { element_clear(ok1); element_clear(ok2); } }; class SHARE { public: element_t si, ti; element_t *ei = NULL; // int i; int n; SHARE(pairing_t pairing) { element_init_Zr(si, pairing); element_init_Zr(ti, pairing); } ~SHARE() { element_clear(si); element_clear(ti); for (int i = 0; i < n; i++) { element_clear(ei[i]); } delete ei; } }; struct POK { element_t c, s1, s2, s3; POK(pairing_t pairing) { element_init_Zr(c, pairing); element_init_Zr(s1, pairing); element_init_Zr(s2, pairing); element_init_Zr(s3, pairing); } ~POK() { element_clear(c); element_clear(s1); element_clear(s2); element_clear(s3); } }; struct SIG { element_t c0, c5, c6, e1, e2, e3; struct POK *p; SIG(pairing_t pairing) { element_init_G2(c0, pairing); element_init_G1(c5, pairing); element_init_G2(c6, pairing); element_init_G1(e1, pairing); element_init_G2(e2, pairing); element_init_GT(e3, pairing); p = new struct POK(pairing); } ~SIG() { element_clear(c0); element_clear(c5); element_clear(c6); element_clear(e1); element_clear(e2); element_clear(e3); free(p); } }; typedef MPK mpktype; typedef GSK gsktype; typedef USK usktype; typedef OK oktype; typedef SHARE sharetype; typedef struct SIG signaturetype; #define G1_ELEMENT(var, pairing) element_t var; element_init_G1(var, pairing); #define G2_ELEMENT(var, pairing) element_t var; element_init_G2(var, pairing); #define GT_ELEMENT(var, pairing) element_t var; element_init_GT(var, pairing); #define ZR_ELEMENT(var, pairing) element_t var; element_init_Zr(var, pairing); #define G1_ELEMENT_ARRAY(var, n, p) \ element_t *var = new element_t[n]; \ for (int i = 0; i < n; i++) \ { \ element_init_G1(var[i], p); \ } #define G2_ELEMENT_ARRAY(var, n, p) \ element_t *var = new element_t[n]; \ for (int i = 0; i < n; i++) \ { \ element_init_G2(var[i], p); \ } #define GT_ELEMENT_ARRAY(var, n, p) \ element_t *var = new element_t[n]; \ for (int i = 0; i < n; i++) \ { \ element_init_GT(var[i], p); \ } #define ZR_ELEMENT_ARRAY(var, n, p) \ element_t *var = new element_t[n]; \ for (int i = 0; i < n; i++) \ { \ element_init_Zr(var[i], p); \ } #define INIT_ARRAY_1(var, n) \ for (int i = 0; i < n; i++) \ { \ element_set1(var[i]); \ } #define INIT_ARRAY_0(var, n) \ for (int i = 0; i < n; i++) \ { \ element_set0(var[i]); \ } #define CLEAR_ELEMENT(var, n) \ for (int i = 0; i < n; i++) \ { \ element_clear(var[i]); \ } } // namespace group_signature } // namespace plugins } // namespace steem
3250e594962cfb8940fff1defae8ee0cb18f5657
52864d071e4002458cc1cf8ea082f2a6cc6f7afa
/examples/example_or_get.cpp
049c6503f493af07032c274a6be2f493d5ec4074
[ "MIT" ]
permissive
alipha/streamer
f9f6dd5809f61cd9697442c3328fab54c941407f
5ce6e19ea517dd201a946bd83ba1732b769c84d3
refs/heads/master
2020-06-28T17:59:48.112332
2019-09-03T03:42:56
2019-09-03T03:42:56
200,302,606
0
0
null
null
null
null
UTF-8
C++
false
false
952
cpp
#include "../streamer/streamer.hpp" #include "../streamer/optional.hpp" #include <cassert> #include <vector> /* * or_get(UnaryFunc) operates on a std::optional and returns either the value the * std::optional contains, or calls the UnaryFunc passed to or_default if the std::optional is * empty, and returns the UnaryFunc's result. */ void example_or_get() { using namespace streamer; std::vector<int> input = {15, 23, 4}; std::vector<int> empty_input = {}; int count = 0; int count2 = 0; int result = input >> first >> or_get([&count]() { count++; return 999; }); int result2 = input % first % or_get([&count]() { count++; return 999; }); int result3 = empty_input | first() | or_get([&count2]() { count2++; return 999; }); assert(result == 15); assert(result2 == 15); assert(result3 == 999); assert(count == 0); assert(count2 == 1); }
ba5c8b41bdd8c3c891e9658d1d969110b5c6d732
201f4ec5e4b9d92312423bff38a50bb4f3f32fbe
/src/kalman_filter.cpp
8be2febf4f053dd8bf3e5caafd23b0ca818cf40a
[ "MIT" ]
permissive
nuaayxy/ekf
4bdd660fb64eee9f17be80f3e905a2d02b5adcf4
df7c041cd8f1dbc36e1f4c45d68be18ad9104827
refs/heads/master
2023-02-07T23:34:42.282409
2021-01-03T08:05:58
2021-01-03T08:05:58
326,287,995
2
0
null
null
null
null
UTF-8
C++
false
false
2,180
cpp
#include "kalman_filter.h" #include <iostream> using Eigen::MatrixXd; using Eigen::VectorXd; /* * Please note that the Eigen library does not initialize * VectorXd or MatrixXd objects with zeros upon creation. */ KalmanFilter::KalmanFilter() {} KalmanFilter::~KalmanFilter() {} void KalmanFilter::Init(VectorXd &x_in, MatrixXd &P_in, MatrixXd &F_in, MatrixXd &H_in, MatrixXd &R_in, MatrixXd &Q_in) { x_ = x_in; P_ = P_in; F_ = F_in; H_ = H_in; R_ = R_in; Q_ = Q_in; } void KalmanFilter::Predict() { /** * TODO: predict the state */ x_ = F_ * x_; MatrixXd Ft = F_.transpose(); P_ = F_ * P_ * Ft + Q_; //std::cout<<"prediction step done...."<<std::endl; } void KalmanFilter::Update(const VectorXd &z) { /** * TODO: update the state by using Kalman Filter equations */ //laser R VectorXd z_pred = H_ * x_; VectorXd y = z - z_pred; MatrixXd Ht = H_.transpose(); MatrixXd S = H_ * P_ * Ht + R_; MatrixXd Si = S.inverse(); MatrixXd PHt = P_ * Ht; MatrixXd K = PHt * Si; //new estimate x_ = x_ + (K * y); long x_size = x_.size(); MatrixXd I = MatrixXd::Identity(x_size, x_size); P_ = (I - K * H_) * P_; //std::cout<<"laser update ......."<<std::endl; } void KalmanFilter::UpdateEKF(const VectorXd &z , const MatrixXd Hja) { /** * TODO: update the state by using Extended Kalman Filter equations */ //radar R //for radar this needs to be changed VectorXd z_(3); float rho = sqrt(x_(0)*x_(0) + x_(1)*x_(1) ); float phi = atan2(x_(1), x_(0)); float rho_dot = (fabs(rho) > 0.000001)? (x_(0)*x_(2) + x_(1)*x_(3))/rho : 0 ; z_ << rho, phi , rho_dot; VectorXd y = z - z_; //check phi jump if(fabs(y(1)) >= M_PI/2 ) y(1) = 0; // if((y(1)) <= -M_PI/2 ) // y(1) += M_PI/2; MatrixXd Ht = Hja.transpose(); MatrixXd S = Hja * P_ * Ht + R_; MatrixXd Si = S.inverse(); MatrixXd K = P_ * Ht * Si; // new state x_ = x_ + (K * y); long x_size = x_.size(); MatrixXd I = MatrixXd::Identity(x_size, x_size); P_ = (I - K * Hja) * P_; // std::cout<<"radar update step done...."<<std::endl; }
02ae789dca136875ebf6c01651573322438d5adc
23e7a20ae35c36d9f5841fc69a242fd03f47ddf2
/dag.cpp
9b0eced774403e8109074969e988018389b7a09c
[]
no_license
leosurwiki/ExtPl0Compiler
ddd985638e531702754cfde801911bc21d0277d3
0b08684583e3eab91766a3b3e3c77a543d58eb2e
refs/heads/master
2021-01-10T08:38:40.422978
2016-03-14T03:48:33
2016-03-14T03:48:33
53,825,133
0
0
null
null
null
null
UTF-8
C++
false
false
2,476
cpp
#include "dag.h" hash_map<string,int> dag::string2node; vector<dag::node> dag::vqn; void dag::dag_symplify(vector<quartral_element> &vqe,vector<pblock::PBLOCK> vqb) { for (size_t i=0;i<vqb.size();i++) { string2node.clear(); vqn.clear(); for (size_t j=vqb[i].begin;j<vqb[i].end;j++) { int l,r,mid; bool isnod=false; if (vqe[j].op==ADDRSHIFT) { string tmpstr=vqe[j].second; vqe[j].second=vqe[j].target; vqe[j].target=tmpstr; } if (string2node.find(vqe[j].first)!=string2node.end()) {l=string2node[vqe[j].first];} else { node newnode; newnode.op=NOD; newnode.entity=vqe[j].first; vqn.push_back(newnode); string2node[vqe[j].first]=int(vqn.size()-1); l = int(vqn.size()-1); } if (string2node.find(vqe[j].second)!=string2node.end()) {r=string2node[vqe[j].second];} else { node newnode; newnode.entity=vqe[j].second; vqn.push_back(newnode); string2node[vqe[j].second]=int(vqn.size()-1); r=int(vqn.size()-1); } if (pblock::iscal(vqe[j])) { mid=-1; for (int k=0;k<vqn.size();k++) { if (vqn[k].left==l&&vqn[k].right==r&&vqn[k].op==vqe[j].op) { mid=k; dag::string2node[vqe[j].target]=k; break; } } isnod=true; if (mid==-1) { isnod=false; node newnode; newnode.left=l; newnode.right=r; newnode.op=vqe[j].op; newnode.entity=vqe[j].target; vqn.push_back(newnode); string2node[vqe[j].target]=int(vqn.size()-1); mid=int(vqn.size()-1); } vqe[j].target=vqn[string2node[vqe[j].target]].entity; if (isnod&&vqe[j].op!=gen::PAR) { vqe[j].op=NOD; } } if (vqe[j].op==gen::PAR) { if (string2node.find(vqe[j].target)!=string2node.end()) { vqe[j].target=vqn[string2node[vqe[j].target]].entity; } } if (pblock::isbr(vqe[j])||pblock::iscal(vqe[j])) { if (string2node.find(vqe[j].first)!=string2node.end()) { vqe[j].first=vqn[string2node[vqe[j].first]].entity; } if (string2node.find(vqe[j].second)!=string2node.end()) { vqe[j].second=vqn[string2node[vqe[j].second]].entity; } } if (vqe[j].op==ADDRSHIFT) { string tmpstr=vqe[j].second; vqe[j].second=vqe[j].target; vqe[j].target=tmpstr; } } } for (vector<quartral_element>::iterator idx= vqe.begin();idx!=vqe.end();) { if (idx->op==NOD) { idx=vqe.erase(idx); } else { idx++; } } }
08d7e573cf7f3141c0f8e393066356a72372209a
ed6b7a01fe69ca258cde96531346a118d58b43b6
/modules/photo/opencv_photo_pch_dephelp.cxx
57a8cde932d4079e49e079a207a41206b168b261
[]
no_license
GremSnoort/OpenCV-3.0.0_MinGW_builtforQT
ad2b7582dd3cc9c1d356a1f80e6b04a1a527172d
683f4d9f611fdc088a5e79a5d35195e4db392fdb
refs/heads/master
2021-04-27T00:10:43.578428
2018-03-05T03:03:34
2018-03-05T03:03:34
123,763,220
0
0
null
null
null
null
UTF-8
C++
false
false
150
cxx
#include "C:/Users/User/Downloads/opencv-3.0.0/opencv/sources/modules/photo/src/precomp.hpp" int testfunction(); int testfunction() { return 0; }
db477e6eeb4356dc7c5e50bb7c6eb1501056b982
1aaaf8af0d720b00c03454cc105e3e99ebdd993b
/4153 [Ipsc2015]Familiar Couples(启发式合并O(log^2)).cpp
44b6d7e2671195c7e4a0f225d3dc97eae6ae3ba5
[ "Apache-2.0" ]
permissive
wwt17/BZOJ
2b6858fb68c3654a9c18861f1e3775c825e539fd
b8b41adf84cd91f68616149dcfdf374b9721b11c
refs/heads/master
2021-01-20T17:26:29.071661
2018-10-02T17:02:35
2018-10-02T17:02:35
63,025,417
12
6
null
null
null
null
UTF-8
C++
false
false
1,216
cpp
#include <cstdio> #include <algorithm> #include <set> #include <map> using namespace std; typedef long long ll; const int mo=(int)1e9+7; const int N=(int)1e6+5; int n,q; int belong[2][N]; set<int> s[2][N]; map<int,int> a[2][N]; ll ans=0; int Main(){ int ret=0; scanf("%d%d",&n,&q); ans=0; for(int i=1;i<=n;i++) for(int t=0;t<=1;t++){ belong[t][i]=i; s[t][i].clear(); s[t][i].insert(i); a[t][i].clear(); a[t][i][i]++; } for(int tim=1;tim<=q;tim++){ int t,x,y; scanf("%d%d%d",&t,&x,&y); t--; x=belong[t][x]; y=belong[t][y]; if(x!=y){ if(s[t][x].size()>s[t][y].size()) swap(x,y); for(map<int,int>::iterator cur=a[t][x].begin();cur!=a[t][x].end();a[t][x].erase(cur++)){ if(a[t][y].find(cur->first)!=a[t][y].end()) ans+=1LL*cur->second*a[t][y][cur->first]; a[t][y][cur->first]+=cur->second; } for(set<int>::iterator cur=s[t][x].begin();cur!=s[t][x].end();s[t][x].erase(cur++)){ if(!--a[t^1][belong[t^1][*cur]][x]) a[t^1][belong[t^1][*cur]].erase(x); a[t^1][belong[t^1][*cur]][belong[t][*cur]=y]++; s[t][y].insert(*cur); } } ret=(ret+ans*tim)%mo; } return ret; } int main(){ int T; scanf("%d",&T); while(T--) printf("%d\n",Main()); }
f4ae79fef26f9d291a52dc80e61d81e94cb1e9bd
1724b326f26f60a2ae0b139d5163031435477a5e
/menu.cpp
21b48396cd697d11c2a10d33fe2c759e55b00153
[]
no_license
Bfili/Project_PSiO_Ships
73eb44f1b8cbfd363cb2836eb87e9a57d8b2d218
6274eb37092a1f66b8b6d7f7644252c8383bd400
refs/heads/master
2022-11-14T10:44:33.309834
2020-07-13T01:16:10
2020-07-13T01:16:10
266,646,443
0
0
null
null
null
null
UTF-8
C++
false
false
1,175
cpp
#include "menu.h" #include <iostream> Menu::Menu(float width, float height) { if(!menu_font.loadFromFile("../Tekstury/FFF_Tusj.ttf")) { std::cerr << "Could not load FFF Tusj font from file" << std::endl; } menu[0].setFont(menu_font); menu[0].setColor(sf::Color::Red); menu[0].setString("Play Ships Game"); menu[0].setPosition(sf::Vector2f(width / 2, height / (MENU_ITEMS + 1) * 1)); menu[1].setFont(menu_font); menu[1].setColor(sf::Color::Black); menu[1].setString("Quit"); menu[1].setPosition(sf::Vector2f(width / 2, height / (MENU_ITEMS + 1) * 2)); pressed_Id = 0; } Menu::~Menu() { } void Menu::draw(sf::RenderWindow &window) { for(int i = 0; i<MENU_ITEMS; i++) { window.draw(menu[i]); } } void Menu:: Switch_up() { if(pressed_Id - 1 >= 0) { menu[pressed_Id].setColor(sf::Color::Black); pressed_Id--; menu[pressed_Id].setColor(sf::Color::Red); } } void Menu:: Switch_down() { if(pressed_Id + 1 < MENU_ITEMS) { menu[pressed_Id].setColor(sf::Color::Black); pressed_Id++; menu[pressed_Id].setColor(sf::Color::Red); } }
34cba575e133270191bebc646e58a0b26e52333a
1cc4d3e1d94e6d2cf3cf9222ef7d8f9422ab344f
/209.2-parking/CarPark_lib/CarParkGui.cpp
fbe907960611217208274abd0cd372934b361932
[]
no_license
BartlomiejRasztabiga/PROI
a3df73f721f8384afb3ce3060abdb4604f1da3a0
702d1609ad4ab96504a71e8efb318e78364fc545
refs/heads/master
2023-04-18T19:07:28.955544
2021-04-26T16:19:51
2021-04-26T16:19:51
341,877,667
0
0
null
null
null
null
UTF-8
C++
false
false
72
cpp
// // Created by rasztabigab on 07.04.2021. // #include "CarParkGui.h"
aee38a6a38610651198b4b18aeda69257b7ff036
e7d7377b40fc431ef2cf8dfa259a611f6acc2c67
/SampleDump/Cpp/SDK/BP_Cloth43_classes.h
2bbaf6b0e452b9333f5e98fe1b002f3c30f53882
[]
no_license
liner0211/uSDK_Generator
ac90211e005c5f744e4f718cd5c8118aab3f8a18
9ef122944349d2bad7c0abe5b183534f5b189bd7
refs/heads/main
2023-09-02T16:37:22.932365
2021-10-31T17:38:03
2021-10-31T17:38:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
698
h
#pragma once // Name: Mordhau, Version: Patch23 /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass BP_Cloth43.BP_Cloth43_C // 0x0000 (FullSize[0x0078] - InheritedSize[0x0078]) class UBP_Cloth43_C : public UMordhauColor { public: static UClass* StaticClass() { static UClass* ptr = UObject::FindClass("BlueprintGeneratedClass BP_Cloth43.BP_Cloth43_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
d496493871cb58edbac838f67f1ed4b50e336418
d9b4adb8bdd3a19859b050c1735d06a380bb9929
/poj-cpp/2184/14942727_WA.cc
f91eabce99d5d9b349d4c44854f77f91476d0c60
[]
no_license
conwnet/way-of-algorithm
eea4901ab62a6bc189e5c60209dc1e8610f76806
201df876cf55a7eae7e55789f2fa43d2f2545628
refs/heads/master
2021-07-31T19:17:48.871429
2021-07-24T17:42:30
2021-07-24T17:42:30
75,063,660
20
2
null
null
null
null
UTF-8
C++
false
false
880
cc
#include <stdio.h> #include <string.h> #include <algorithm> using namespace std; const int maxv = 40; const int mid = 20; int dp[2][maxv+10], N, cow[2][128]; int main() { int p; scanf("%d", &N); for(int i=1; i<=N; i++) scanf("%d%d", &cow[0][i], &cow[1][i]); for(int i=1; i<=N; i++) { if(i&1) p = 1; else p = 0; for(int j=0; j<mid; j++) { dp[p][j+mid] = max(dp[p^1][j+mid], dp[p^1][j-cow[0][i]+mid] +cow[0][i]+cow[1][i]); } } if(N&1) p = 1; else p = 0; int ans = 0; for(int i=mid; i<maxv; i++) { ///if(dp[p][i]) printf("%d %d\n", i-mid, dp[p][i]); if(dp[p][i]+mid>=i) ans = max(ans, dp[p][i]); } printf("%d\n", ans); return 0; }
8dd109c46fe32a5226895f89642262ac03c95305
c776476e9d06b3779d744641e758ac3a2c15cddc
/examples/litmus/c/run-scripts/tmp_1/S+dmb.syll+datapl.c.cbmc.cpp
39508829a7274f6ed322d88b5b89640e897cbc11
[]
no_license
ashutosh0gupta/llvm_bmc
aaac7961c723ba6f7ffd77a39559e0e52432eade
0287c4fb180244e6b3c599a9902507f05c8a7234
refs/heads/master
2023-08-02T17:14:06.178723
2023-07-31T10:46:53
2023-07-31T10:46:53
143,100,825
3
4
null
2023-05-25T05:50:55
2018-08-01T03:47:00
C++
UTF-8
C++
false
false
26,751
cpp
// 0:vars:2 // 2:atom_1_X0_1:1 // 3:thr0:1 // 4:thr1:1 #define ADDRSIZE 5 #define NPROC 3 #define NCONTEXT 1 #define ASSUME(stmt) __CPROVER_assume(stmt) #define ASSERT(stmt) __CPROVER_assert(stmt, "error") #define max(a,b) (a>b?a:b) char __get_rng(); char get_rng( char from, char to ) { char ret = __get_rng(); ASSUME(ret >= from && ret <= to); return ret; } char get_rng_th( char from, char to ) { char ret = __get_rng(); ASSUME(ret >= from && ret <= to); return ret; } int main(int argc, char **argv) { // declare arrays for intial value version in contexts int meminit_[ADDRSIZE*NCONTEXT]; #define meminit(x,k) meminit_[(x)*NCONTEXT+k] int coinit_[ADDRSIZE*NCONTEXT]; #define coinit(x,k) coinit_[(x)*NCONTEXT+k] int deltainit_[ADDRSIZE*NCONTEXT]; #define deltainit(x,k) deltainit_[(x)*NCONTEXT+k] // declare arrays for running value version in contexts int mem_[ADDRSIZE*NCONTEXT]; #define mem(x,k) mem_[(x)*NCONTEXT+k] int co_[ADDRSIZE*NCONTEXT]; #define co(x,k) co_[(x)*NCONTEXT+k] int delta_[ADDRSIZE*NCONTEXT]; #define delta(x,k) delta_[(x)*NCONTEXT+k] // declare arrays for local buffer and observed writes int buff_[NPROC*ADDRSIZE]; #define buff(x,k) buff_[(x)*ADDRSIZE+k] int pw_[NPROC*ADDRSIZE]; #define pw(x,k) pw_[(x)*ADDRSIZE+k] // declare arrays for context stamps char cr_[NPROC*ADDRSIZE]; #define cr(x,k) cr_[(x)*ADDRSIZE+k] char iw_[NPROC*ADDRSIZE]; #define iw(x,k) iw_[(x)*ADDRSIZE+k] char cw_[NPROC*ADDRSIZE]; #define cw(x,k) cw_[(x)*ADDRSIZE+k] char cx_[NPROC*ADDRSIZE]; #define cx(x,k) cx_[(x)*ADDRSIZE+k] char is_[NPROC*ADDRSIZE]; #define is(x,k) is_[(x)*ADDRSIZE+k] char cs_[NPROC*ADDRSIZE]; #define cs(x,k) cs_[(x)*ADDRSIZE+k] char crmax_[NPROC*ADDRSIZE]; #define crmax(x,k) crmax_[(x)*ADDRSIZE+k] char sforbid_[ADDRSIZE*NCONTEXT]; #define sforbid(x,k) sforbid_[(x)*NCONTEXT+k] // declare arrays for synchronizations int cl[NPROC]; int cdy[NPROC]; int cds[NPROC]; int cdl[NPROC]; int cisb[NPROC]; int caddr[NPROC]; int cctrl[NPROC]; int cstart[NPROC]; int creturn[NPROC]; // declare arrays for contexts activity int active[NCONTEXT]; int ctx_used[NCONTEXT]; __LOCALS__ buff(0,0) = 0; pw(0,0) = 0; cr(0,0) = 0; iw(0,0) = 0; cw(0,0) = 0; cx(0,0) = 0; is(0,0) = 0; cs(0,0) = 0; crmax(0,0) = 0; buff(0,1) = 0; pw(0,1) = 0; cr(0,1) = 0; iw(0,1) = 0; cw(0,1) = 0; cx(0,1) = 0; is(0,1) = 0; cs(0,1) = 0; crmax(0,1) = 0; buff(0,2) = 0; pw(0,2) = 0; cr(0,2) = 0; iw(0,2) = 0; cw(0,2) = 0; cx(0,2) = 0; is(0,2) = 0; cs(0,2) = 0; crmax(0,2) = 0; buff(0,3) = 0; pw(0,3) = 0; cr(0,3) = 0; iw(0,3) = 0; cw(0,3) = 0; cx(0,3) = 0; is(0,3) = 0; cs(0,3) = 0; crmax(0,3) = 0; buff(0,4) = 0; pw(0,4) = 0; cr(0,4) = 0; iw(0,4) = 0; cw(0,4) = 0; cx(0,4) = 0; is(0,4) = 0; cs(0,4) = 0; crmax(0,4) = 0; cl[0] = 0; cdy[0] = 0; cds[0] = 0; cdl[0] = 0; cisb[0] = 0; caddr[0] = 0; cctrl[0] = 0; cstart[0] = get_rng(0,NCONTEXT-1); creturn[0] = get_rng(0,NCONTEXT-1); buff(1,0) = 0; pw(1,0) = 0; cr(1,0) = 0; iw(1,0) = 0; cw(1,0) = 0; cx(1,0) = 0; is(1,0) = 0; cs(1,0) = 0; crmax(1,0) = 0; buff(1,1) = 0; pw(1,1) = 0; cr(1,1) = 0; iw(1,1) = 0; cw(1,1) = 0; cx(1,1) = 0; is(1,1) = 0; cs(1,1) = 0; crmax(1,1) = 0; buff(1,2) = 0; pw(1,2) = 0; cr(1,2) = 0; iw(1,2) = 0; cw(1,2) = 0; cx(1,2) = 0; is(1,2) = 0; cs(1,2) = 0; crmax(1,2) = 0; buff(1,3) = 0; pw(1,3) = 0; cr(1,3) = 0; iw(1,3) = 0; cw(1,3) = 0; cx(1,3) = 0; is(1,3) = 0; cs(1,3) = 0; crmax(1,3) = 0; buff(1,4) = 0; pw(1,4) = 0; cr(1,4) = 0; iw(1,4) = 0; cw(1,4) = 0; cx(1,4) = 0; is(1,4) = 0; cs(1,4) = 0; crmax(1,4) = 0; cl[1] = 0; cdy[1] = 0; cds[1] = 0; cdl[1] = 0; cisb[1] = 0; caddr[1] = 0; cctrl[1] = 0; cstart[1] = get_rng(0,NCONTEXT-1); creturn[1] = get_rng(0,NCONTEXT-1); buff(2,0) = 0; pw(2,0) = 0; cr(2,0) = 0; iw(2,0) = 0; cw(2,0) = 0; cx(2,0) = 0; is(2,0) = 0; cs(2,0) = 0; crmax(2,0) = 0; buff(2,1) = 0; pw(2,1) = 0; cr(2,1) = 0; iw(2,1) = 0; cw(2,1) = 0; cx(2,1) = 0; is(2,1) = 0; cs(2,1) = 0; crmax(2,1) = 0; buff(2,2) = 0; pw(2,2) = 0; cr(2,2) = 0; iw(2,2) = 0; cw(2,2) = 0; cx(2,2) = 0; is(2,2) = 0; cs(2,2) = 0; crmax(2,2) = 0; buff(2,3) = 0; pw(2,3) = 0; cr(2,3) = 0; iw(2,3) = 0; cw(2,3) = 0; cx(2,3) = 0; is(2,3) = 0; cs(2,3) = 0; crmax(2,3) = 0; buff(2,4) = 0; pw(2,4) = 0; cr(2,4) = 0; iw(2,4) = 0; cw(2,4) = 0; cx(2,4) = 0; is(2,4) = 0; cs(2,4) = 0; crmax(2,4) = 0; cl[2] = 0; cdy[2] = 0; cds[2] = 0; cdl[2] = 0; cisb[2] = 0; caddr[2] = 0; cctrl[2] = 0; cstart[2] = get_rng(0,NCONTEXT-1); creturn[2] = get_rng(0,NCONTEXT-1); // Dumping initializations mem(0+0,0) = 0; mem(0+1,0) = 0; mem(2+0,0) = 0; mem(3+0,0) = 0; mem(4+0,0) = 0; // Dumping context matching equalities co(0,0) = 0; delta(0,0) = -1; co(1,0) = 0; delta(1,0) = -1; co(2,0) = 0; delta(2,0) = -1; co(3,0) = 0; delta(3,0) = -1; co(4,0) = 0; delta(4,0) = -1; // Dumping thread 1 int ret_thread_1 = 0; cdy[1] = get_rng(0,NCONTEXT-1); ASSUME(cdy[1] >= cstart[1]); T1BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !33, metadata !DIExpression()), !dbg !42 // br label %label_1, !dbg !43 goto T1BLOCK1; T1BLOCK1: // call void @llvm.dbg.label(metadata !41), !dbg !44 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !34, metadata !DIExpression()), !dbg !45 // call void @llvm.dbg.value(metadata i64 2, metadata !37, metadata !DIExpression()), !dbg !45 // store atomic i64 2, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) release, align 8, !dbg !46 // ST: Guess // : Release iw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW old_cw = cw(1,0); cw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM // Check ASSUME(active[iw(1,0)] == 1); ASSUME(active[cw(1,0)] == 1); ASSUME(sforbid(0,cw(1,0))== 0); ASSUME(iw(1,0) >= 0); ASSUME(iw(1,0) >= 0); ASSUME(cw(1,0) >= iw(1,0)); ASSUME(cw(1,0) >= old_cw); ASSUME(cw(1,0) >= cr(1,0)); ASSUME(cw(1,0) >= cl[1]); ASSUME(cw(1,0) >= cisb[1]); ASSUME(cw(1,0) >= cdy[1]); ASSUME(cw(1,0) >= cdl[1]); ASSUME(cw(1,0) >= cds[1]); ASSUME(cw(1,0) >= cctrl[1]); ASSUME(cw(1,0) >= caddr[1]); ASSUME(cw(1,0) >= cr(1,0+0)); ASSUME(cw(1,0) >= cr(1,0+1)); ASSUME(cw(1,0) >= cr(1,2+0)); ASSUME(cw(1,0) >= cr(1,3+0)); ASSUME(cw(1,0) >= cr(1,4+0)); ASSUME(cw(1,0) >= cw(1,0+0)); ASSUME(cw(1,0) >= cw(1,0+1)); ASSUME(cw(1,0) >= cw(1,2+0)); ASSUME(cw(1,0) >= cw(1,3+0)); ASSUME(cw(1,0) >= cw(1,4+0)); // Update caddr[1] = max(caddr[1],0); buff(1,0) = 2; mem(0,cw(1,0)) = 2; co(0,cw(1,0))+=1; delta(0,cw(1,0)) = -1; is(1,0) = iw(1,0); cs(1,0) = cw(1,0); ASSUME(creturn[1] >= cw(1,0)); // call void (...) @dmbsy(), !dbg !47 // dumbsy: Guess old_cdy = cdy[1]; cdy[1] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[1] >= old_cdy); ASSUME(cdy[1] >= cisb[1]); ASSUME(cdy[1] >= cdl[1]); ASSUME(cdy[1] >= cds[1]); ASSUME(cdy[1] >= cctrl[1]); ASSUME(cdy[1] >= cw(1,0+0)); ASSUME(cdy[1] >= cw(1,0+1)); ASSUME(cdy[1] >= cw(1,2+0)); ASSUME(cdy[1] >= cw(1,3+0)); ASSUME(cdy[1] >= cw(1,4+0)); ASSUME(cdy[1] >= cr(1,0+0)); ASSUME(cdy[1] >= cr(1,0+1)); ASSUME(cdy[1] >= cr(1,2+0)); ASSUME(cdy[1] >= cr(1,3+0)); ASSUME(cdy[1] >= cr(1,4+0)); ASSUME(creturn[1] >= cdy[1]); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !38, metadata !DIExpression()), !dbg !48 // call void @llvm.dbg.value(metadata i64 1, metadata !40, metadata !DIExpression()), !dbg !48 // store atomic i64 1, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) release, align 8, !dbg !49 // ST: Guess // : Release iw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW old_cw = cw(1,0+1*1); cw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM // Check ASSUME(active[iw(1,0+1*1)] == 1); ASSUME(active[cw(1,0+1*1)] == 1); ASSUME(sforbid(0+1*1,cw(1,0+1*1))== 0); ASSUME(iw(1,0+1*1) >= 0); ASSUME(iw(1,0+1*1) >= 0); ASSUME(cw(1,0+1*1) >= iw(1,0+1*1)); ASSUME(cw(1,0+1*1) >= old_cw); ASSUME(cw(1,0+1*1) >= cr(1,0+1*1)); ASSUME(cw(1,0+1*1) >= cl[1]); ASSUME(cw(1,0+1*1) >= cisb[1]); ASSUME(cw(1,0+1*1) >= cdy[1]); ASSUME(cw(1,0+1*1) >= cdl[1]); ASSUME(cw(1,0+1*1) >= cds[1]); ASSUME(cw(1,0+1*1) >= cctrl[1]); ASSUME(cw(1,0+1*1) >= caddr[1]); ASSUME(cw(1,0+1*1) >= cr(1,0+0)); ASSUME(cw(1,0+1*1) >= cr(1,0+1)); ASSUME(cw(1,0+1*1) >= cr(1,2+0)); ASSUME(cw(1,0+1*1) >= cr(1,3+0)); ASSUME(cw(1,0+1*1) >= cr(1,4+0)); ASSUME(cw(1,0+1*1) >= cw(1,0+0)); ASSUME(cw(1,0+1*1) >= cw(1,0+1)); ASSUME(cw(1,0+1*1) >= cw(1,2+0)); ASSUME(cw(1,0+1*1) >= cw(1,3+0)); ASSUME(cw(1,0+1*1) >= cw(1,4+0)); // Update caddr[1] = max(caddr[1],0); buff(1,0+1*1) = 1; mem(0+1*1,cw(1,0+1*1)) = 1; co(0+1*1,cw(1,0+1*1))+=1; delta(0+1*1,cw(1,0+1*1)) = -1; is(1,0+1*1) = iw(1,0+1*1); cs(1,0+1*1) = cw(1,0+1*1); ASSUME(creturn[1] >= cw(1,0+1*1)); // ret i8* null, !dbg !50 ret_thread_1 = (- 1); // Dumping thread 2 int ret_thread_2 = 0; cdy[2] = get_rng(0,NCONTEXT-1); ASSUME(cdy[2] >= cstart[2]); T2BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !53, metadata !DIExpression()), !dbg !69 // br label %label_2, !dbg !51 goto T2BLOCK1; T2BLOCK1: // call void @llvm.dbg.label(metadata !68), !dbg !71 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !56, metadata !DIExpression()), !dbg !72 // %0 = load atomic i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !54 // LD: Guess old_cr = cr(2,0+1*1); cr(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM // Check ASSUME(active[cr(2,0+1*1)] == 2); ASSUME(cr(2,0+1*1) >= iw(2,0+1*1)); ASSUME(cr(2,0+1*1) >= 0); ASSUME(cr(2,0+1*1) >= cdy[2]); ASSUME(cr(2,0+1*1) >= cisb[2]); ASSUME(cr(2,0+1*1) >= cdl[2]); ASSUME(cr(2,0+1*1) >= cl[2]); // Update creg_r0 = cr(2,0+1*1); crmax(2,0+1*1) = max(crmax(2,0+1*1),cr(2,0+1*1)); caddr[2] = max(caddr[2],0); if(cr(2,0+1*1) < cw(2,0+1*1)) { r0 = buff(2,0+1*1); } else { if(pw(2,0+1*1) != co(0+1*1,cr(2,0+1*1))) { ASSUME(cr(2,0+1*1) >= old_cr); } pw(2,0+1*1) = co(0+1*1,cr(2,0+1*1)); r0 = mem(0+1*1,cr(2,0+1*1)); } ASSUME(creturn[2] >= cr(2,0+1*1)); // call void @llvm.dbg.value(metadata i64 %0, metadata !58, metadata !DIExpression()), !dbg !72 // %conv = trunc i64 %0 to i32, !dbg !55 // call void @llvm.dbg.value(metadata i32 %conv, metadata !54, metadata !DIExpression()), !dbg !69 // %xor = xor i32 %conv, %conv, !dbg !56 creg_r1 = max(creg_r0,creg_r0); ASSUME(active[creg_r1] == 2); r1 = r0 ^ r0; // call void @llvm.dbg.value(metadata i32 %xor, metadata !59, metadata !DIExpression()), !dbg !69 // %add = add nsw i32 %xor, 1, !dbg !57 creg_r2 = max(creg_r1,0); ASSUME(active[creg_r2] == 2); r2 = r1 + 1; // call void @llvm.dbg.value(metadata i32 %add, metadata !60, metadata !DIExpression()), !dbg !69 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !61, metadata !DIExpression()), !dbg !77 // %conv1 = sext i32 %add to i64, !dbg !59 // call void @llvm.dbg.value(metadata i64 %conv1, metadata !63, metadata !DIExpression()), !dbg !77 // store atomic i64 %conv1, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) release, align 8, !dbg !59 // ST: Guess // : Release iw(2,0) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW old_cw = cw(2,0); cw(2,0) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM // Check ASSUME(active[iw(2,0)] == 2); ASSUME(active[cw(2,0)] == 2); ASSUME(sforbid(0,cw(2,0))== 0); ASSUME(iw(2,0) >= creg_r2); ASSUME(iw(2,0) >= 0); ASSUME(cw(2,0) >= iw(2,0)); ASSUME(cw(2,0) >= old_cw); ASSUME(cw(2,0) >= cr(2,0)); ASSUME(cw(2,0) >= cl[2]); ASSUME(cw(2,0) >= cisb[2]); ASSUME(cw(2,0) >= cdy[2]); ASSUME(cw(2,0) >= cdl[2]); ASSUME(cw(2,0) >= cds[2]); ASSUME(cw(2,0) >= cctrl[2]); ASSUME(cw(2,0) >= caddr[2]); ASSUME(cw(2,0) >= cr(2,0+0)); ASSUME(cw(2,0) >= cr(2,0+1)); ASSUME(cw(2,0) >= cr(2,2+0)); ASSUME(cw(2,0) >= cr(2,3+0)); ASSUME(cw(2,0) >= cr(2,4+0)); ASSUME(cw(2,0) >= cw(2,0+0)); ASSUME(cw(2,0) >= cw(2,0+1)); ASSUME(cw(2,0) >= cw(2,2+0)); ASSUME(cw(2,0) >= cw(2,3+0)); ASSUME(cw(2,0) >= cw(2,4+0)); // Update caddr[2] = max(caddr[2],0); buff(2,0) = r2; mem(0,cw(2,0)) = r2; co(0,cw(2,0))+=1; delta(0,cw(2,0)) = -1; is(2,0) = iw(2,0); cs(2,0) = cw(2,0); ASSUME(creturn[2] >= cw(2,0)); // %cmp = icmp eq i32 %conv, 1, !dbg !60 // %conv2 = zext i1 %cmp to i32, !dbg !60 // call void @llvm.dbg.value(metadata i32 %conv2, metadata !64, metadata !DIExpression()), !dbg !69 // call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !65, metadata !DIExpression()), !dbg !80 // %1 = zext i32 %conv2 to i64 // call void @llvm.dbg.value(metadata i64 %1, metadata !67, metadata !DIExpression()), !dbg !80 // store atomic i64 %1, i64* @atom_1_X0_1 seq_cst, align 8, !dbg !62 // ST: Guess iw(2,2) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW old_cw = cw(2,2); cw(2,2) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM // Check ASSUME(active[iw(2,2)] == 2); ASSUME(active[cw(2,2)] == 2); ASSUME(sforbid(2,cw(2,2))== 0); ASSUME(iw(2,2) >= max(creg_r0,0)); ASSUME(iw(2,2) >= 0); ASSUME(cw(2,2) >= iw(2,2)); ASSUME(cw(2,2) >= old_cw); ASSUME(cw(2,2) >= cr(2,2)); ASSUME(cw(2,2) >= cl[2]); ASSUME(cw(2,2) >= cisb[2]); ASSUME(cw(2,2) >= cdy[2]); ASSUME(cw(2,2) >= cdl[2]); ASSUME(cw(2,2) >= cds[2]); ASSUME(cw(2,2) >= cctrl[2]); ASSUME(cw(2,2) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,2) = (r0==1); mem(2,cw(2,2)) = (r0==1); co(2,cw(2,2))+=1; delta(2,cw(2,2)) = -1; ASSUME(creturn[2] >= cw(2,2)); // ret i8* null, !dbg !63 ret_thread_2 = (- 1); // Dumping thread 0 int ret_thread_0 = 0; cdy[0] = get_rng(0,NCONTEXT-1); ASSUME(cdy[0] >= cstart[0]); T0BLOCK0: // %thr0 = alloca i64, align 8 // %thr1 = alloca i64, align 8 // call void @llvm.dbg.value(metadata i32 %argc, metadata !90, metadata !DIExpression()), !dbg !116 // call void @llvm.dbg.value(metadata i8** %argv, metadata !91, metadata !DIExpression()), !dbg !116 // %0 = bitcast i64* %thr0 to i8*, !dbg !65 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %0) #7, !dbg !65 // call void @llvm.dbg.declare(metadata i64* %thr0, metadata !92, metadata !DIExpression()), !dbg !118 // %1 = bitcast i64* %thr1 to i8*, !dbg !67 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %1) #7, !dbg !67 // call void @llvm.dbg.declare(metadata i64* %thr1, metadata !96, metadata !DIExpression()), !dbg !120 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !97, metadata !DIExpression()), !dbg !121 // call void @llvm.dbg.value(metadata i64 0, metadata !99, metadata !DIExpression()), !dbg !121 // store atomic i64 0, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !70 // ST: Guess iw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,0+1*1); cw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,0+1*1)] == 0); ASSUME(active[cw(0,0+1*1)] == 0); ASSUME(sforbid(0+1*1,cw(0,0+1*1))== 0); ASSUME(iw(0,0+1*1) >= 0); ASSUME(iw(0,0+1*1) >= 0); ASSUME(cw(0,0+1*1) >= iw(0,0+1*1)); ASSUME(cw(0,0+1*1) >= old_cw); ASSUME(cw(0,0+1*1) >= cr(0,0+1*1)); ASSUME(cw(0,0+1*1) >= cl[0]); ASSUME(cw(0,0+1*1) >= cisb[0]); ASSUME(cw(0,0+1*1) >= cdy[0]); ASSUME(cw(0,0+1*1) >= cdl[0]); ASSUME(cw(0,0+1*1) >= cds[0]); ASSUME(cw(0,0+1*1) >= cctrl[0]); ASSUME(cw(0,0+1*1) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0+1*1) = 0; mem(0+1*1,cw(0,0+1*1)) = 0; co(0+1*1,cw(0,0+1*1))+=1; delta(0+1*1,cw(0,0+1*1)) = -1; ASSUME(creturn[0] >= cw(0,0+1*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !100, metadata !DIExpression()), !dbg !123 // call void @llvm.dbg.value(metadata i64 0, metadata !102, metadata !DIExpression()), !dbg !123 // store atomic i64 0, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !72 // ST: Guess iw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,0); cw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,0)] == 0); ASSUME(active[cw(0,0)] == 0); ASSUME(sforbid(0,cw(0,0))== 0); ASSUME(iw(0,0) >= 0); ASSUME(iw(0,0) >= 0); ASSUME(cw(0,0) >= iw(0,0)); ASSUME(cw(0,0) >= old_cw); ASSUME(cw(0,0) >= cr(0,0)); ASSUME(cw(0,0) >= cl[0]); ASSUME(cw(0,0) >= cisb[0]); ASSUME(cw(0,0) >= cdy[0]); ASSUME(cw(0,0) >= cdl[0]); ASSUME(cw(0,0) >= cds[0]); ASSUME(cw(0,0) >= cctrl[0]); ASSUME(cw(0,0) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0) = 0; mem(0,cw(0,0)) = 0; co(0,cw(0,0))+=1; delta(0,cw(0,0)) = -1; ASSUME(creturn[0] >= cw(0,0)); // call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !103, metadata !DIExpression()), !dbg !125 // call void @llvm.dbg.value(metadata i64 0, metadata !105, metadata !DIExpression()), !dbg !125 // store atomic i64 0, i64* @atom_1_X0_1 monotonic, align 8, !dbg !74 // ST: Guess iw(0,2) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,2); cw(0,2) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,2)] == 0); ASSUME(active[cw(0,2)] == 0); ASSUME(sforbid(2,cw(0,2))== 0); ASSUME(iw(0,2) >= 0); ASSUME(iw(0,2) >= 0); ASSUME(cw(0,2) >= iw(0,2)); ASSUME(cw(0,2) >= old_cw); ASSUME(cw(0,2) >= cr(0,2)); ASSUME(cw(0,2) >= cl[0]); ASSUME(cw(0,2) >= cisb[0]); ASSUME(cw(0,2) >= cdy[0]); ASSUME(cw(0,2) >= cdl[0]); ASSUME(cw(0,2) >= cds[0]); ASSUME(cw(0,2) >= cctrl[0]); ASSUME(cw(0,2) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,2) = 0; mem(2,cw(0,2)) = 0; co(2,cw(0,2))+=1; delta(2,cw(0,2)) = -1; ASSUME(creturn[0] >= cw(0,2)); // %call = call i32 @pthread_create(i64* noundef %thr0, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t0, i8* noundef null) #7, !dbg !75 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,2+0)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,2+0)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[1] >= cdy[0]); // %call5 = call i32 @pthread_create(i64* noundef %thr1, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t1, i8* noundef null) #7, !dbg !76 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,2+0)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,2+0)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[2] >= cdy[0]); // %2 = load i64, i64* %thr0, align 8, !dbg !77, !tbaa !78 // LD: Guess old_cr = cr(0,3); cr(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,3)] == 0); ASSUME(cr(0,3) >= iw(0,3)); ASSUME(cr(0,3) >= 0); ASSUME(cr(0,3) >= cdy[0]); ASSUME(cr(0,3) >= cisb[0]); ASSUME(cr(0,3) >= cdl[0]); ASSUME(cr(0,3) >= cl[0]); // Update creg_r4 = cr(0,3); crmax(0,3) = max(crmax(0,3),cr(0,3)); caddr[0] = max(caddr[0],0); if(cr(0,3) < cw(0,3)) { r4 = buff(0,3); } else { if(pw(0,3) != co(3,cr(0,3))) { ASSUME(cr(0,3) >= old_cr); } pw(0,3) = co(3,cr(0,3)); r4 = mem(3,cr(0,3)); } ASSUME(creturn[0] >= cr(0,3)); // %call6 = call i32 @pthread_join(i64 noundef %2, i8** noundef null), !dbg !82 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,2+0)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,2+0)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[1]); // %3 = load i64, i64* %thr1, align 8, !dbg !83, !tbaa !78 // LD: Guess old_cr = cr(0,4); cr(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,4)] == 0); ASSUME(cr(0,4) >= iw(0,4)); ASSUME(cr(0,4) >= 0); ASSUME(cr(0,4) >= cdy[0]); ASSUME(cr(0,4) >= cisb[0]); ASSUME(cr(0,4) >= cdl[0]); ASSUME(cr(0,4) >= cl[0]); // Update creg_r5 = cr(0,4); crmax(0,4) = max(crmax(0,4),cr(0,4)); caddr[0] = max(caddr[0],0); if(cr(0,4) < cw(0,4)) { r5 = buff(0,4); } else { if(pw(0,4) != co(4,cr(0,4))) { ASSUME(cr(0,4) >= old_cr); } pw(0,4) = co(4,cr(0,4)); r5 = mem(4,cr(0,4)); } ASSUME(creturn[0] >= cr(0,4)); // %call7 = call i32 @pthread_join(i64 noundef %3, i8** noundef null), !dbg !84 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,2+0)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,2+0)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[2]); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !107, metadata !DIExpression()), !dbg !137 // %4 = load atomic i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) seq_cst, align 8, !dbg !86 // LD: Guess old_cr = cr(0,0); cr(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,0)] == 0); ASSUME(cr(0,0) >= iw(0,0)); ASSUME(cr(0,0) >= 0); ASSUME(cr(0,0) >= cdy[0]); ASSUME(cr(0,0) >= cisb[0]); ASSUME(cr(0,0) >= cdl[0]); ASSUME(cr(0,0) >= cl[0]); // Update creg_r6 = cr(0,0); crmax(0,0) = max(crmax(0,0),cr(0,0)); caddr[0] = max(caddr[0],0); if(cr(0,0) < cw(0,0)) { r6 = buff(0,0); } else { if(pw(0,0) != co(0,cr(0,0))) { ASSUME(cr(0,0) >= old_cr); } pw(0,0) = co(0,cr(0,0)); r6 = mem(0,cr(0,0)); } ASSUME(creturn[0] >= cr(0,0)); // call void @llvm.dbg.value(metadata i64 %4, metadata !109, metadata !DIExpression()), !dbg !137 // %conv = trunc i64 %4 to i32, !dbg !87 // call void @llvm.dbg.value(metadata i32 %conv, metadata !106, metadata !DIExpression()), !dbg !116 // %cmp = icmp eq i32 %conv, 2, !dbg !88 // %conv8 = zext i1 %cmp to i32, !dbg !88 // call void @llvm.dbg.value(metadata i32 %conv8, metadata !110, metadata !DIExpression()), !dbg !116 // call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !112, metadata !DIExpression()), !dbg !141 // %5 = load atomic i64, i64* @atom_1_X0_1 seq_cst, align 8, !dbg !90 // LD: Guess old_cr = cr(0,2); cr(0,2) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,2)] == 0); ASSUME(cr(0,2) >= iw(0,2)); ASSUME(cr(0,2) >= 0); ASSUME(cr(0,2) >= cdy[0]); ASSUME(cr(0,2) >= cisb[0]); ASSUME(cr(0,2) >= cdl[0]); ASSUME(cr(0,2) >= cl[0]); // Update creg_r7 = cr(0,2); crmax(0,2) = max(crmax(0,2),cr(0,2)); caddr[0] = max(caddr[0],0); if(cr(0,2) < cw(0,2)) { r7 = buff(0,2); } else { if(pw(0,2) != co(2,cr(0,2))) { ASSUME(cr(0,2) >= old_cr); } pw(0,2) = co(2,cr(0,2)); r7 = mem(2,cr(0,2)); } ASSUME(creturn[0] >= cr(0,2)); // call void @llvm.dbg.value(metadata i64 %5, metadata !114, metadata !DIExpression()), !dbg !141 // %conv12 = trunc i64 %5 to i32, !dbg !91 // call void @llvm.dbg.value(metadata i32 %conv12, metadata !111, metadata !DIExpression()), !dbg !116 // %and = and i32 %conv8, %conv12, !dbg !92 creg_r8 = max(max(creg_r6,0),creg_r7); ASSUME(active[creg_r8] == 0); r8 = (r6==2) & r7; // call void @llvm.dbg.value(metadata i32 %and, metadata !115, metadata !DIExpression()), !dbg !116 // %cmp13 = icmp eq i32 %and, 1, !dbg !93 // br i1 %cmp13, label %if.then, label %if.end, !dbg !95 old_cctrl = cctrl[0]; cctrl[0] = get_rng(0,NCONTEXT-1); ASSUME(cctrl[0] >= old_cctrl); ASSUME(cctrl[0] >= creg_r8); ASSUME(cctrl[0] >= 0); if((r8==1)) { goto T0BLOCK1; } else { goto T0BLOCK2; } T0BLOCK1: // call void @__assert_fail(i8* noundef getelementptr inbounds ([2 x i8], [2 x i8]* @.str, i64 0, i64 0), i8* noundef getelementptr inbounds ([102 x i8], [102 x i8]* @.str.1, i64 0, i64 0), i32 noundef 54, i8* noundef getelementptr inbounds ([23 x i8], [23 x i8]* @__PRETTY_FUNCTION__.main, i64 0, i64 0)) #8, !dbg !96 // unreachable, !dbg !96 r9 = 1; T0BLOCK2: // %6 = bitcast i64* %thr1 to i8*, !dbg !99 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %6) #7, !dbg !99 // %7 = bitcast i64* %thr0 to i8*, !dbg !99 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %7) #7, !dbg !99 // ret i32 0, !dbg !100 ret_thread_0 = 0; ASSERT(r9== 0); }
29ecd1d5a3c0ccd2ec7f24cbfe6a39e06624f32c
6061c8088fc013f8fe398bd33d1053895ff2edbb
/third_party/blink/renderer/modules/native_file_system/native_file_system_directory_iterator.cc
ad8ccdae92c97d034afc852573e9a05660cecd0d
[ "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "BSD-3-Clause", "MIT", "Apache-2.0" ]
permissive
demetrionq/chromium
9535388d5558b4060ce676783d293064ce4f5ce4
6ff60480db4f99008c69eb82bd3ea1c4d5a83307
refs/heads/master
2022-12-25T16:32:04.316431
2020-07-22T20:36:04
2020-07-22T20:36:04
281,785,566
0
2
BSD-3-Clause
2020-10-02T04:08:24
2020-07-22T21:21:19
null
UTF-8
C++
false
false
4,041
cc
// Copyright 2018 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 "third_party/blink/renderer/modules/native_file_system/native_file_system_directory_iterator.h" #include "third_party/blink/public/platform/task_type.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h" #include "third_party/blink/renderer/bindings/core/v8/v8_iterator_result_value.h" #include "third_party/blink/renderer/core/dom/dom_exception.h" #include "third_party/blink/renderer/core/fileapi/file_error.h" #include "third_party/blink/renderer/modules/native_file_system/native_file_system_directory_handle.h" #include "third_party/blink/renderer/modules/native_file_system/native_file_system_error.h" #include "third_party/blink/renderer/modules/native_file_system/native_file_system_file_handle.h" #include "third_party/blink/renderer/platform/wtf/functional.h" namespace blink { NativeFileSystemDirectoryIterator::NativeFileSystemDirectoryIterator( NativeFileSystemDirectoryHandle* directory, Mode mode, ExecutionContext* execution_context) : ExecutionContextClient(execution_context), mode_(mode), directory_(directory), receiver_(this, execution_context) { directory_->MojoHandle()->GetEntries(receiver_.BindNewPipeAndPassRemote( execution_context->GetTaskRunner(TaskType::kMiscPlatformAPI))); } ScriptPromise NativeFileSystemDirectoryIterator::next( ScriptState* script_state) { if (error_) { auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state); auto result = resolver->Promise(); native_file_system_error::Reject(resolver, *error_); return result; } if (!entries_.IsEmpty()) { NativeFileSystemHandle* handle = entries_.TakeFirst(); ScriptValue result; switch (mode_) { case Mode::kKey: result = V8IteratorResult(script_state, handle->name()); break; case Mode::kValue: result = V8IteratorResult(script_state, handle); break; case Mode::kKeyValue: HeapVector<ScriptValue, 2> keyvalue; keyvalue.push_back(ScriptValue(script_state->GetIsolate(), ToV8(handle->name(), script_state))); keyvalue.push_back(ScriptValue(script_state->GetIsolate(), ToV8(handle, script_state))); result = V8IteratorResult(script_state, keyvalue); break; } return ScriptPromise::Cast(script_state, result); } if (waiting_for_more_entries_) { DCHECK(!pending_next_); pending_next_ = MakeGarbageCollected<ScriptPromiseResolver>(script_state); return pending_next_->Promise(); } return ScriptPromise::Cast(script_state, V8IteratorResultDone(script_state)); } void NativeFileSystemDirectoryIterator::Trace(Visitor* visitor) const { ScriptWrappable::Trace(visitor); ExecutionContextClient::Trace(visitor); visitor->Trace(receiver_); visitor->Trace(entries_); visitor->Trace(pending_next_); visitor->Trace(directory_); } void NativeFileSystemDirectoryIterator::DidReadDirectory( mojom::blink::NativeFileSystemErrorPtr result, Vector<mojom::blink::NativeFileSystemEntryPtr> entries, bool has_more_entries) { if (!GetExecutionContext()) return; if (result->status != mojom::blink::NativeFileSystemStatus::kOk) { error_ = std::move(result); if (pending_next_) { native_file_system_error::Reject(pending_next_, *error_); pending_next_ = nullptr; } return; } for (auto& e : entries) { entries_.push_back(NativeFileSystemHandle::CreateFromMojoEntry( std::move(e), GetExecutionContext())); } waiting_for_more_entries_ = has_more_entries; if (pending_next_) { ScriptState::Scope scope(pending_next_->GetScriptState()); pending_next_->Resolve( next(pending_next_->GetScriptState()).GetScriptValue()); pending_next_ = nullptr; } } } // namespace blink
af66aae0f1a05fa024d2b1ac402d92afbe955ee8
182845e81e4d7b675e876f01beef704e08cd6ac0
/hpp/OSX32/Release/uTPLb_Random.hpp
41b6e98e773f63b32f1b5f8cf7a5abc7c8c89c7d
[]
no_license
jiehanlin/LockBox3
2d82ec172d7132a48d3c1a390a7e844804910613
d760a891ab3ecff373ae5b34b7bb993a69229d5b
refs/heads/master
2021-01-19T02:23:35.941577
2016-09-26T00:38:48
2016-09-26T00:38:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,222
hpp
// CodeGear C++Builder // Copyright (c) 1995, 2016 by Embarcadero Technologies, Inc. // All rights reserved // (DO NOT EDIT: machine generated header) 'uTPLb_Random.pas' rev: 31.00 (MacOS) #ifndef Utplb_randomHPP #define Utplb_randomHPP #pragma delphiheader begin #pragma option push #pragma option -w- // All warnings off #pragma option -Vx // Zero-length empty class member #pragma pack(push,8) #include <System.hpp> #include <SysInit.hpp> #include <System.Classes.hpp> //-- user supplied ----------------------------------------------------------- namespace Utplb_random { //-- forward type declarations ----------------------------------------------- class DELPHICLASS TRandomStream; //-- type declarations ------------------------------------------------------- #pragma pack(push,4) class PASCALIMPLEMENTATION TRandomStream : public System::Classes::TStream { typedef System::Classes::TStream inherited; private: __int64 FValue; __int64 FBuffer; int FAvail; void __fastcall Crunch(void); void __fastcall SetSeed(__int64 Value); protected: virtual __int64 __fastcall GetSize(void); virtual void __fastcall SetSize(const __int64 NewSize)/* overload */; public: __fastcall TRandomStream(void); __fastcall virtual ~TRandomStream(void); __classmethod TRandomStream* __fastcall Instance(); virtual int __fastcall Read(void *Buffer, int Count)/* overload */; virtual int __fastcall Write(const void *Buffer, int Count)/* overload */; virtual __int64 __fastcall Seek(const __int64 Offset, System::Classes::TSeekOrigin Origin)/* overload */; void __fastcall Randomize(void); __property __int64 Seed = {read=FValue, write=SetSeed}; /* Hoisted overloads: */ protected: inline void __fastcall SetSize(int NewSize){ System::Classes::TStream::SetSize(NewSize); } public: inline int __fastcall Read(System::DynamicArray<System::Byte> Buffer, int Offset, int Count){ return System::Classes::TStream::Read(Buffer, Offset, Count); } inline int __fastcall Read(System::DynamicArray<System::Byte> &Buffer, int Count){ return System::Classes::TStream::Read(Buffer, Count); } inline int __fastcall Write(const System::DynamicArray<System::Byte> Buffer, int Offset, int Count){ return System::Classes::TStream::Write(Buffer, Offset, Count); } inline int __fastcall Write(const System::DynamicArray<System::Byte> Buffer, int Count){ return System::Classes::TStream::Write(Buffer, Count); } inline int __fastcall Seek(int Offset, System::Word Origin){ return System::Classes::TStream::Seek(Offset, Origin); } inline __int64 __fastcall Seek _DEPRECATED_ATTRIBUTE0 (const __int64 Offset, System::Word Origin){ return System::Classes::TStream::Seek(Offset, Origin); } }; #pragma pack(pop) //-- var, const, procedure --------------------------------------------------- } /* namespace Utplb_random */ #if !defined(DELPHIHEADER_NO_IMPLICIT_NAMESPACE_USE) && !defined(NO_USING_NAMESPACE_UTPLB_RANDOM) using namespace Utplb_random; #endif #pragma pack(pop) #pragma option pop #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // Utplb_randomHPP
86fc723fe588f5c2f2a425bde131e90ee64faac0
f16a763c59625f19f085dbc9ae413152fe1d7f4f
/PCG-Blog/Procedural_Planets/entity.h
a6d0b7edc7e40e758eb657617ea8e64d459a0683
[]
no_license
CMilby/PCG-Blog
8d5152b3e0115fc00a8de9be7b792d7b8af58b85
8dc67c1c916662eadc6b8395e9567f198b73598a
refs/heads/master
2021-05-02T12:16:46.023834
2016-10-10T22:18:34
2016-10-10T22:18:34
44,112,110
1
0
null
null
null
null
UTF-8
C++
false
false
1,776
h
// // entity.h // Game_Engine // // Created by Craig Milby on 10/23/15. // Copyright © 2015 Craig Milby. All rights reserved. // #ifndef __ENTITY_H__ #define __ENTITY_H__ #include <string> #include <vector> #include "material.h" #include "math3d.h" #include "mesh.h" #include "transform.h" class Camera; class Shader; class Entity { private: std::vector<Entity*> m_children; Transform *m_transform; protected: virtual void Init() {} virtual void Input( float delta ) {} virtual void Update( float delta ) {} virtual void Render( const Shader &shader, const Camera &camera ) {} public: Entity(); virtual ~Entity(); void InitAll(); void InputAll( float delta ); void UpdateAll( float delta ); void RenderAll( const Shader &shader, const Camera &camera ); Entity* AddChild( Entity *entity ); inline Transform* GetTransform() const { return m_transform; } inline void SetTransform( Transform *transform ) { m_transform = transform; } }; class RenderableEntity : public Entity { private: Mesh *m_mesh; Material *m_material; bool m_visible; protected: virtual void Input( float delta ); virtual void Update( float delta ); virtual void Render( const Shader &shader, const Camera &camera ); public: RenderableEntity(); RenderableEntity( Mesh *mesh, Material *material ); virtual ~RenderableEntity(); Matrix4<float> GetModelMatrix() const; inline void SetPosition( const Vector3<float> &position ) { GetTransform()->SetPosition( position ); } inline void SetVisible( bool visible ) { m_visible = visible; } inline bool IsVisible() const { return m_visible; } }; #endif /* entity_h */
252d4c9b5e91dc9cdb04851d9348e78e8e2091fa
42463de94768bbf8544a10baf3ef918ebd83e606
/Minigin/Minigin/Observer.cpp
ba1896a7c5570ad09f622326eea7af3ea5f93f4b
[]
no_license
JordanSommerGit/Programming4
9e3c058c4f5c7b21a63db0ad7586724c2fb00968
ad9955a3becd2c52d69ee12539217e5fb4afd329
refs/heads/master
2022-11-05T14:33:52.118796
2020-06-19T10:55:15
2020-06-19T10:55:15
271,950,871
0
0
null
null
null
null
UTF-8
C++
false
false
107
cpp
#include "MiniginPCH.h" #include "Observer.h" void King::Observer::OnNotify(GameObject*, std::string) { }
8b3b589b2683eec17a05991ab39deb5220b4285e
02a10a5244d2214e932e54399e4b56b68fe5974b
/headers/ChangeDimensionPacket.h
70f103ccff0f57ab6fef729103b261dd596fa9bb
[]
no_license
inxomnyaa/symbols-auto
839381c1e83f434b76b2faccadee5e413ac5f376
439a1399473cc765badc1b5c438fbf83d9eadf1d
refs/heads/master
2023-06-21T23:17:07.389321
2019-11-16T19:13:05
2019-11-16T19:13:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
368
h
#pragma once class ChangeDimensionPacket : Packet { virtual ~ChangeDimensionPacket(); virtual ~ChangeDimensionPacket(); virtual void getId(void)const; virtual void _ZNK21ChangeDimensionPacket7getNameB5cxx11Ev; virtual void write(BinaryStream &)const; virtual void read(ReadOnlyBinaryStream &); virtual void disallowBatching(void)const; }
15b20281e860a50746ebc0e6e0eb4d51c20ecd1a
ce9964faef6ee75b71c417e34113578777cd86b2
/chrome/browser/extensions/api/declarative_net_request/ruleset_manager_unittest.cc
1df55ab7c603eecc181caaed928af0baf4e0ac2d
[ "BSD-3-Clause" ]
permissive
alijuma/chromium
4d8eed877b655d39388d5e5def1b7514f05170ea
db8f04787fe546230612bd32f499194d3219f15c
refs/heads/master
2023-01-07T18:37:00.605447
2017-11-07T23:13:02
2017-11-07T23:13:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,630
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 "extensions/browser/api/declarative_net_request/ruleset_manager.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "chrome/browser/extensions/api/declarative_net_request/dnr_test_base.h" #include "chrome/browser/extensions/chrome_test_extension_loader.h" #include "chrome/browser/extensions/extension_util.h" #include "extensions/browser/api/declarative_net_request/ruleset_matcher.h" #include "extensions/browser/api/declarative_net_request/test_utils.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_system.h" #include "extensions/browser/extension_util.h" #include "extensions/browser/info_map.h" #include "extensions/common/api/declarative_net_request/test_utils.h" #include "extensions/common/file_util.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" #include "net/url_request/url_request_test_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" namespace extensions { namespace declarative_net_request { namespace { constexpr char kJSONRulesFilename[] = "rules_file.json"; const base::FilePath::CharType kJSONRulesetFilepath[] = FILE_PATH_LITERAL("rules_file.json"); class RulesetManagerTest : public DNRTestBase { public: RulesetManagerTest() {} protected: // Helper to create a ruleset matcher instance for the given |rules|. void CreateMatcherForRules(const std::vector<TestRule>& rules, const std::string& extension_dirname, std::unique_ptr<RulesetMatcher>* matcher) { base::FilePath extension_dir = temp_dir().GetPath().AppendASCII(extension_dirname); // Create extension directory. ASSERT_TRUE(base::CreateDirectory(extension_dir)); WriteManifestAndRuleset(extension_dir, kJSONRulesetFilepath, kJSONRulesFilename, rules); last_loaded_extension_ = CreateExtensionLoader()->LoadExtension(extension_dir); ASSERT_TRUE(last_loaded_extension_); // This is required since we mock ExtensionSystem in our tests. SimulateAddExtensionOnIOThread(last_loaded_extension(), false /*incognito_enabled*/); int expected_checksum; EXPECT_TRUE(ExtensionPrefs::Get(browser_context()) ->GetDNRRulesetChecksum(last_loaded_extension_->id(), &expected_checksum)); EXPECT_EQ( RulesetMatcher::kLoadSuccess, RulesetMatcher::CreateVerifiedMatcher( file_util::GetIndexedRulesetPath(last_loaded_extension_->path()), expected_checksum, matcher)); } void SetIncognitoEnabled(const Extension* extension, bool incognito_enabled) { util::SetIsIncognitoEnabled(extension->id(), browser_context(), incognito_enabled); // This is required since we mock ExtensionSystem in our tests. SimulateAddExtensionOnIOThread(extension, incognito_enabled); } InfoMap* info_map() { return ExtensionSystem::Get(browser_context())->info_map(); } const Extension* last_loaded_extension() const { return last_loaded_extension_.get(); } std::unique_ptr<net::URLRequest> GetRequestForURL(const std::string url) { return request_context_.CreateRequest(GURL(url), net::DEFAULT_PRIORITY, &delegate_, TRAFFIC_ANNOTATION_FOR_TESTS); } private: void SimulateAddExtensionOnIOThread(const Extension* extension, bool incognito_enabled) { info_map()->AddExtension(extension, base::Time(), incognito_enabled, false /*notifications_disabled*/); } net::TestURLRequestContext request_context_; net::TestDelegate delegate_; scoped_refptr<const Extension> last_loaded_extension_; DISALLOW_COPY_AND_ASSIGN(RulesetManagerTest); }; // Tests that the RulesetManager handles multiple rulesets correctly. TEST_P(RulesetManagerTest, MultipleRulesets) { enum RulesetMask { kEnableRulesetOne = 1 << 0, kEnableRulesetTwo = 1 << 1, }; TestRule rule_one = CreateGenericRule(); rule_one.condition->url_filter = std::string("one.com"); TestRule rule_two = CreateGenericRule(); rule_two.condition->url_filter = std::string("two.com"); RulesetManager* manager = info_map()->GetRulesetManager(); ASSERT_TRUE(manager); std::unique_ptr<net::URLRequest> request_one = GetRequestForURL("http://one.com"); std::unique_ptr<net::URLRequest> request_two = GetRequestForURL("http://two.com"); std::unique_ptr<net::URLRequest> request_three = GetRequestForURL("http://three.com"); // Test all possible combinations with |rule_one| and |rule_two| enabled. const bool is_incognito_context = false; for (int mask = 0; mask < 4; mask++) { SCOPED_TRACE(base::StringPrintf("Testing ruleset mask %d", mask)); ASSERT_EQ(0u, manager->GetMatcherCountForTest()); std::string extension_id_one, extension_id_two; size_t expected_matcher_count = 0; // Add the required rulesets. if (mask & kEnableRulesetOne) { ++expected_matcher_count; std::unique_ptr<RulesetMatcher> matcher; ASSERT_NO_FATAL_FAILURE(CreateMatcherForRules( {rule_one}, std::to_string(mask) + "_one", &matcher)); extension_id_one = last_loaded_extension()->id(); manager->AddRuleset(extension_id_one, std::move(matcher)); } if (mask & kEnableRulesetTwo) { ++expected_matcher_count; std::unique_ptr<RulesetMatcher> matcher; ASSERT_NO_FATAL_FAILURE(CreateMatcherForRules( {rule_two}, std::to_string(mask) + "_two", &matcher)); extension_id_two = last_loaded_extension()->id(); manager->AddRuleset(extension_id_two, std::move(matcher)); } ASSERT_EQ(expected_matcher_count, manager->GetMatcherCountForTest()); EXPECT_EQ((mask & kEnableRulesetOne) != 0, manager->ShouldBlockRequest(*request_one, is_incognito_context)); EXPECT_EQ((mask & kEnableRulesetTwo) != 0, manager->ShouldBlockRequest(*request_two, is_incognito_context)); EXPECT_FALSE( manager->ShouldBlockRequest(*request_three, is_incognito_context)); // Remove the rulesets. if (mask & kEnableRulesetOne) manager->RemoveRuleset(extension_id_one); if (mask & kEnableRulesetTwo) manager->RemoveRuleset(extension_id_two); } } // Tests that only extensions enabled in incognito mode can modify requests made // from the incognito context. TEST_P(RulesetManagerTest, IncognitoRequests) { RulesetManager* manager = info_map()->GetRulesetManager(); ASSERT_TRUE(manager); // Add an extension ruleset blocking "example.com". TestRule rule_one = CreateGenericRule(); rule_one.condition->url_filter = std::string("example.com"); std::unique_ptr<RulesetMatcher> matcher; ASSERT_NO_FATAL_FAILURE( CreateMatcherForRules({rule_one}, "test_extension", &matcher)); manager->AddRuleset(last_loaded_extension()->id(), std::move(matcher)); std::unique_ptr<net::URLRequest> request = GetRequestForURL("http://example.com"); // By default, the extension is disabled in incognito mode. So requests from // incognito contexts should not be evaluated. EXPECT_FALSE(util::IsIncognitoEnabled(last_loaded_extension()->id(), browser_context())); EXPECT_FALSE( manager->ShouldBlockRequest(*request, true /*is_incognito_context*/)); EXPECT_TRUE( manager->ShouldBlockRequest(*request, false /*is_incognito_context*/)); // Enabling the extension in incognito mode, should cause requests from // incognito contexts to also be evaluated. SetIncognitoEnabled(last_loaded_extension(), true /*incognito_enabled*/); EXPECT_TRUE(util::IsIncognitoEnabled(last_loaded_extension()->id(), browser_context())); EXPECT_TRUE( manager->ShouldBlockRequest(*request, true /*is_incognito_context*/)); EXPECT_TRUE( manager->ShouldBlockRequest(*request, false /*is_incognito_context*/)); } INSTANTIATE_TEST_CASE_P(, RulesetManagerTest, ::testing::Values(ExtensionLoadType::PACKED, ExtensionLoadType::UNPACKED)); } // namespace } // namespace declarative_net_request } // namespace extensions
ba3b30034d429aca9d6058b1619fb578bf676daf
025033f29954908c13681fc58689e49611782754
/test/tests/storeTest.cpp
3ca2c937f412c58cbbfe97daaec39265726cfc17
[]
no_license
hoani/smartpay
0e8bee3141379d8ffd8ba552d1d53d4327b74a90
b3666a3ff96a505a7ffb2e36de8cf57aa3e75f9d
refs/heads/master
2022-11-15T02:59:15.384737
2020-07-08T20:48:07
2020-07-08T20:48:07
277,771,193
0
0
null
null
null
null
UTF-8
C++
false
false
1,768
cpp
#include "catch.hpp" #include <cstring> #include <iostream> extern "C" { #include "store.h" #include "terminal.h" } // TODO Add fields for malformed JSON - for now we will skip this case. TEST_CASE( "Storage Terminal", "[store]" ) { store_init(); SECTION("Store is empty") { TerminalData_t terminal; REQUIRE(store_count() == 0); REQUIRE(store_get(0, &terminal) == false); } SECTION("Store add") { TerminalData_t terminal = { 0, k_card_eftpos, k_tt_credit }; int index = store_add(terminal); TerminalData_t stored_terminal; REQUIRE(store_count() == 1); REQUIRE(index == 0); REQUIRE(store_get(index, &stored_terminal) == true); REQUIRE(stored_terminal.id == index); REQUIRE(stored_terminal.card_type == terminal.card_type); REQUIRE(stored_terminal.transaction_type == terminal.transaction_type); } SECTION("Store add ignored id") { TerminalData_t terminal = { 999, k_card_eftpos, k_tt_credit }; int index = store_add(terminal); TerminalData_t stored_terminal; REQUIRE(index == 0); REQUIRE(store_get(index, &stored_terminal) == true); REQUIRE(stored_terminal.id == index); } SECTION("Store add many") { TerminalData_t terminal = { 0, k_card_eftpos, k_tt_credit }; int index = store_add(terminal); index = store_add(terminal); index = store_add(terminal); index = store_add(terminal); TerminalData_t stored_terminal; REQUIRE(store_count() == 4); REQUIRE(index == 3); REQUIRE(store_get(0, &stored_terminal) == true); REQUIRE(store_get(1, &stored_terminal) == true); REQUIRE(store_get(2, &stored_terminal) == true); REQUIRE(store_get(3, &stored_terminal) == true); REQUIRE(store_get(4, &stored_terminal) == false); } }
ed74187fafc3b2dd5458f77ba55403de4ba9fa77
f6ab96101246c8764dc16073cbea72a188a0dc1a
/OnlineJudge/JudgeGirl/20027. SubString/rabin-karp.cpp
8936945ee5c34ff0b5e3288f8e58e9b18096051c
[]
no_license
nealwu/UVa
c87ddc8a0bf07a9bd9cadbf88b7389790bc321cb
10ddd83a00271b0c9c259506aa17d03075850f60
refs/heads/master
2020-09-07T18:52:19.352699
2019-05-01T09:41:55
2019-05-01T09:41:55
220,883,015
3
2
null
2019-11-11T02:14:54
2019-11-11T02:14:54
null
UTF-8
C++
false
false
1,273
cpp
#include <bits/stdc++.h> using namespace std; // Rabin-Karp Algorithm int main() { static char s[100005], buf[300005], cmd[16]; static const int64_t mod = 2147483648; static const int64_t hbase = 37; int head, tail; int q; while (head = 100000, scanf("%s", buf+head) == 1) { int n = strlen(buf+head); tail = head+n-1; scanf("%d", &q); for (int i = 0; i < q; i++) { scanf("%s%s", cmd, s); if (cmd[0] == '1') { buf[--head] = s[0]; } else if (cmd[0] == '2') { buf[++tail] = s[0]; } else { int64_t h = 0, f = 1; n = strlen(s); for (int i = 0; i < n; i++) h = (h*hbase + s[i]-'a'+1)&(mod-1), f = (f*hbase)&(mod-1); int64_t g = 0; int ret = 0; for (int i = head; i <= tail; i++) { g = g*hbase + buf[i]-'a'+1; g = g&(mod-1); if (i-n >= head) { g = g-((f*(buf[i-n]-'a'+1))&(mod-1))+mod; } g = g&(mod-1); if (i-head >= n-1) { if (g == h) { int valid = 1, j = 0; // for (j = 0; j < n && valid; j++) // valid &= s[j] == buf[i-n+1+j]; // valid &= j == n; ret += valid; } } } printf("%d\n", ret); } } } return 0; } /* cd 5 1 b 1 a 2 e 3 cd 3 aa 1 0 d 8 1 a 2 e 1 b 2 n 2 d 3 ba 3 bad 3 badend ababa 1 3 aba 2 */
f497e8a943537bab5aadf0c8d5972f1ef06008cc
03277a6fc47da4c3ea98bb21cfe7efd6cd7ed343
/arm_compute/MWSequenceInputLayerImpl.cpp
62760a7ef034a1156ec31d3bf04a77f0863b37dc
[ "BSD-2-Clause" ]
permissive
matlab-deep-learning/Fault-Detection-Using-Deep-Learning-Classification
869382d3960c372d192db5f627a2b3b5418a3cba
539670f3868fbf66c51762fff8dc3843f7880242
refs/heads/master
2022-09-09T17:25:23.360209
2022-09-06T19:43:24
2022-09-06T19:43:24
248,592,738
64
25
NOASSERTION
2020-05-21T21:03:49
2020-03-19T19:56:02
C++
UTF-8
C++
false
false
891
cpp
#include "MWSequenceInputLayerImpl.hpp" #include "MWCNNLayerImpl.hpp" #include "MWCNNLayer.hpp" #include "MWTensorBase.hpp" #include "MWTensor.hpp" #include <cassert> #include <cstdio> class MWTargetNetworkImpl; #if MW_SEQIP_TAP extern void mw_interm_tap(float* memBuf, int size, int count); extern int tap_count; #endif MWSequenceInputLayerImpl::MWSequenceInputLayerImpl(MWCNNLayer* layer, MWTargetNetworkImpl* ntwk_impl) : MWCNNLayerImpl(layer, ntwk_impl) { ZUTPCvgISoRdtnhGqXzM = true; } MWSequenceInputLayerImpl::~MWSequenceInputLayerImpl() { } void MWSequenceInputLayerImpl::propagateSize() { } void MWSequenceInputLayerImpl::predict() { #if MW_SEQIP_TAP MWTensorBase* opTensorBase = getLayer()->getOutputTensor(0); MWTensor<float>* opTensor = static_cast<MWTensor<float>*>(opTensorBase); mw_interm_tap(opTensor->getData(), opTensor->getNumElements(), tap_count++); #endif }
253a5449f3634ca528d59f2f8b9374b2aa76f5f8
b47c558a6c33209f9b1d502458813890816eca27
/Utils/parser.h
fb0f0e68ade2769f61c45019799cdfad578e02ce
[]
no_license
EliranAm/MazeGame
5a327ec98726ca964a1dab725480094c8daa49ee
2cd1f0871b7a82dfc82de59aa57897abc6579d01
refs/heads/master
2022-05-29T03:36:07.111714
2020-05-02T14:52:22
2020-05-02T14:52:22
260,705,589
1
0
null
null
null
null
UTF-8
C++
false
false
1,336
h
#ifndef __PARSER_H__ #define __PARSER_H__ #include <fstream> #include <map> #include "../Objects/location.h" #include "tokenizer.h" #include "../Objects/room_info.h" #include "../Objects/colors.h" #define ROOM_ID size_t namespace advcpp { class Parser { public: struct OpenFileFailed : public std::exception { virtual const char* what() const throw(); }; explicit Parser(const char* _filePath) throw (OpenFileFailed); std::map<ROOM_ID, RoomInfo>& Start(); private: void InitRoomInfo(RoomInfo *_roomInfo); void CaseOfMonsterOrTreasure(RoomInfo *_roomInfo); void MoveFPToMap(); void ParseMapHorizontal(); void RestoreFPToMap(std::streamoff _currPos); void ParseMapVertical(std::string& _line); void ParseHorizontal(); void ParseVertical(const std::string &_line1, const std::string &_line2, const std::string &_line3); void PlaceWallByDirection(const std::string &_line, Location::Direction _location); COLOR ParseColor(const std::string &_color); void InsertTreasureInfo(RoomInfo *_roomInfo); void InsertMonsterInfo(RoomInfo *_roomInfo); void SetEastAndWestWalls(unsigned int _curRoomId, unsigned int _index, Passage::PassageStatus _passage); Tokenizer m_tokenizer; std::ifstream m_fp; std::string m_line; std::map<ROOM_ID, RoomInfo> m_roomsInfo; }; } //namespace advcpp #endif /* __PARSER_H__ */
04412e2d4c5213a338f912d5863c1b96d648bc66
63b60a2d4945041d8929c16f964a7f14e0de265f
/tinySTL/tinySTL/stl_construct.h
86522e7cee60471cf1dac6593d282fc77fbd948e
[]
no_license
WuTao1530663/my_stl
a96f5b54bf68b3aa795b8184928565abc3e34291
28b4d7ad2ba4d42007bdcd85cdedc4da1e9cab11
refs/heads/master
2021-01-22T21:07:27.306493
2017-03-21T05:45:10
2017-03-21T05:45:10
85,394,908
1
0
null
null
null
null
GB18030
C++
false
false
1,263
h
#ifndef __CONSTRUCT #define __CONSTRUCT #include"stdafx.h" #include<new> #include<iostream> #include<type_traits> namespace WT{ template<class T1, class T2> inline void construct(T1 *p, const T2& value){ new (p)T1(value); //placement new;call T1::T1(value); } //destroy第一个版本,接受一个指针 template<class T> inline void destroy(T* pointer){ pointer->~T(); } //第二个版本接受两个迭代器,释放一个范围的内存,利用type_traits<>根据不同类型求得最适当的措施 template<class ForwardIterator> inline void destroy(ForwardIterator first, ForwardIterator last){ __destroy(first, last, std::_Val_type(first)); } template<class ForwardIterator, class T> inline void __destroy(ForwardIterator first, ForwardIterator last, T*){ __destroy_aux(first, last, std::has_trivial_destructor<T>()); } template<class ForwardIterator> inline void __destroy_aux(ForwardIterator first, ForwardIterator last, std::false_type){ std::cout << "in false_type" << std::endl; for (; first < last; ++first) destroy(&(*first)); } template<class ForwardIterator> inline void __destroy_aux(ForwardIterator first, ForwardIterator last, std::true_type){ std::cout << "in true_type" << std::endl; } } #endif
ee319764df851c1eb675b25c57de83d8a7e41da1
8417df75bfd67b3ad69975fc00be968f4775cb50
/Exec_Policy_Optimization/hpx_files_adaptive_for_each/for_each.hpp
5a9fb91d89f6dcb8831b728a7bfd93330b496f96
[]
no_license
zkhatami88/runtime-optimizations-using-compiler-and-machine-learning-algorithms
e80f652bc2eee6441e1c9c613c84d8625822b1e6
4c60aef7ae688f6dffd6d7249b1eebc79266dd4f
refs/heads/master
2021-01-11T19:44:24.239043
2017-04-03T20:11:12
2017-04-03T20:11:12
79,385,338
1
0
null
null
null
null
UTF-8
C++
false
false
22,864
hpp
// Copyright (c) 2007-2016 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) /// \file parallel/algorithms/for_each.hpp #if !defined(HPX_PARALLEL_DETAIL_FOR_EACH_MAY_29_2014_0932PM) #define HPX_PARALLEL_DETAIL_FOR_EACH_MAY_29_2014_0932PM #include <hpx/config.hpp> #include <hpx/traits/concepts.hpp> #include <hpx/traits/is_callable.hpp> #include <hpx/traits/is_iterator.hpp> #include <hpx/traits/is_value_proxy.hpp> #include <hpx/traits/segmented_iterator_traits.hpp> #include <hpx/util/identity.hpp> #include <hpx/util/invoke.hpp> #include <hpx/parallel/algorithms/detail/dispatch.hpp> #include <hpx/parallel/algorithms/detail/is_negative.hpp> #include <hpx/parallel/config/inline_namespace.hpp> #include <hpx/parallel/execution_policy.hpp> #include <hpx/parallel/traits/projected.hpp> #include <hpx/parallel/util/detail/algorithm_result.hpp> #include <hpx/parallel/util/foreach_partitioner.hpp> #include <hpx/parallel/util/loop.hpp> #include <hpx/parallel/util/projection_identity.hpp> #include <hpx/parallel/util/compiler_static_information.hpp> #include <algorithm> #include <cstddef> #include <iterator> #include <type_traits> #include <utility> namespace hpx { namespace parallel { HPX_INLINE_NAMESPACE(v1) { /////////////////////////////////////////////////////////////////////////// // for_each_n namespace detail { /// \cond NOINTERNAL template <typename F, typename Proj> struct invoke_projected { typename hpx::util::decay<F>::type& f_; typename hpx::util::decay<Proj>::type& proj_; template <typename T> HPX_HOST_DEVICE HPX_FORCEINLINE typename std::enable_if< !hpx::traits::is_value_proxy<T>::value >::type call(T && t) { T && tmp = std::forward<T>(t); hpx::util::invoke(f_, hpx::util::invoke(proj_, tmp)); } template <typename T> HPX_HOST_DEVICE HPX_FORCEINLINE typename std::enable_if< hpx::traits::is_value_proxy<T>::value >::type call(T && t) { auto tmp = hpx::util::invoke(proj_, std::forward<T>(t)); hpx::util::invoke_r<void>(f_,tmp); } template <typename Iter> HPX_HOST_DEVICE HPX_FORCEINLINE void operator()(Iter curr) { call(*curr); } }; template <typename ExPolicy, typename F, typename Proj> struct for_each_iteration { typedef typename hpx::util::decay<ExPolicy>::type execution_policy_type; typedef typename hpx::util::decay<F>::type fun_type; typedef typename hpx::util::decay<Proj>::type proj_type; fun_type f_; proj_type proj_; template <typename F_, typename Proj_> HPX_HOST_DEVICE for_each_iteration(F_ && f, Proj_ && proj) : f_(std::forward<F_>(f)) , proj_(std::forward<Proj_>(proj)) {} #if defined(HPX_HAVE_CXX11_DEFAULTED_FUNCTIONS) && !defined(__NVCC__) && \ !defined(__CUDACC__) for_each_iteration(for_each_iteration const&) = default; for_each_iteration(for_each_iteration&&) = default; #else HPX_HOST_DEVICE for_each_iteration(for_each_iteration const& rhs) : f_(rhs.f_) , proj_(rhs.proj_) {} HPX_HOST_DEVICE for_each_iteration(for_each_iteration && rhs) : f_(std::move(rhs.f_)) , proj_(std::move(rhs.proj_)) {} #endif HPX_DELETE_COPY_ASSIGN(for_each_iteration); HPX_DELETE_MOVE_ASSIGN(for_each_iteration); template <typename Iter> HPX_HOST_DEVICE HPX_FORCEINLINE void operator()(Iter part_begin, std::size_t part_size, std::size_t /*part_index*/) { util::loop_n<execution_policy_type>(part_begin, part_size, invoke_projected<fun_type, proj_type>{f_, proj_}); } }; template <typename Iter> struct for_each_n : public detail::algorithm<for_each_n<Iter>, Iter> { for_each_n() : for_each_n::algorithm("for_each_n") {} template <typename ExPolicy, typename InIter, typename F, typename Proj = util::projection_identity> HPX_HOST_DEVICE static Iter sequential(ExPolicy && policy, InIter first, std::size_t count, F && f, Proj && proj/* = Proj()*/) { return util::loop_n<ExPolicy>(first, count, invoke_projected<F, Proj>{f, proj}); } template <typename ExPolicy, typename InIter, typename F, typename Proj = util::projection_identity> static typename util::detail::algorithm_result< ExPolicy, InIter >::type parallel(ExPolicy && policy, InIter first, std::size_t count, F && f, Proj && proj/* = Proj()*/) { if (count != 0) { auto f1 = for_each_iteration<ExPolicy, F, Proj>( std::forward<F>(f), std::forward<Proj>(proj)); return util::foreach_partitioner<ExPolicy>::call( std::forward<ExPolicy>(policy), first, count, std::move(f1), util::projection_identity()); } return util::detail::algorithm_result<ExPolicy, InIter>::get( std::move(first)); } }; /// \endcond } /// Applies \a f to the result of dereferencing every iterator in the range /// [first, first + count), starting from first and proceeding to /// first + count - 1. /// /// \note Complexity: Applies \a f exactly \a count times. /// /// If \a f returns a result, the result is ignored. /// /// If the type of \a first satisfies the requirements of a mutable /// iterator, \a f may apply non-constant functions through the /// dereferenced iterator. /// /// Unlike its sequential form, the parallel overload of /// \a for_each does not return a copy of its \a Function parameter, /// since parallelization may not permit efficient state /// accumulation. /// /// \tparam ExPolicy The type of the execution policy to use (deduced). /// It describes the manner in which the execution /// of the algorithm may be parallelized and the manner /// in which it applies user-provided function objects. /// \tparam InIter The type of the source iterators used (deduced). /// This iterator type must meet the requirements of an /// input iterator. /// \tparam Size The type of the argument specifying the number of /// elements to apply \a f to. /// \tparam F The type of the function/function object to use /// (deduced). Unlike its sequential form, the parallel /// overload of \a for_each requires \a F to meet the /// requirements of \a CopyConstructible. /// \tparam Proj The type of an optional projection function. This /// defaults to \a util::projection_identity /// /// \param policy The execution policy to use for the scheduling of /// the iterations. /// \param first Refers to the beginning of the sequence of elements /// the algorithm will be applied to. /// \param count Refers to the number of elements starting at /// \a first the algorithm will be applied to. /// \param f Specifies the function (or function object) which /// will be invoked for each of the elements in the /// sequence specified by [first, last). /// The signature of this predicate /// should be equivalent to: /// \code /// <ignored> pred(const Type &a); /// \endcode \n /// The signature does not need to have const&. The /// type \a Type must be such that an object of /// type \a InIter can be dereferenced and then /// implicitly converted to Type. /// \param proj Specifies the function (or function object) which /// will be invoked for each of the elements as a /// projection operation before the actual predicate /// \a f is invoked. /// /// The application of function objects in parallel algorithm /// invoked with an execution policy object of type /// \a sequenced_policy execute in sequential order in the /// calling thread. /// /// The application of function objects in parallel algorithm /// invoked with an execution policy object of type /// \a parallel_policy or \a parallel_task_policy are /// permitted to execute in an unordered fashion in unspecified /// threads, and indeterminately sequenced within each thread. /// /// \returns The \a for_each_n algorithm returns a /// \a hpx::future<InIter> if the execution policy is of /// type /// \a sequenced_task_policy or /// \a parallel_task_policy and returns \a InIter /// otherwise. /// It returns \a first + \a count for non-negative values of /// \a count and \a first for negative values. /// template <typename ExPolicy, typename InIter, typename Size, typename F, typename Proj = util::projection_identity, HPX_CONCEPT_REQUIRES_( execution::is_execution_policy<ExPolicy>::value && hpx::traits::is_iterator<InIter>::value && parallel::traits::is_projected<Proj, InIter>::value && parallel::traits::is_indirect_callable< ExPolicy, F, traits::projected<Proj, InIter> >::value)> typename util::detail::algorithm_result<ExPolicy, InIter>::type for_each_n(ExPolicy && policy, InIter first, Size count, F && f, Proj && proj = Proj()) { static_assert( (hpx::traits::is_input_iterator<InIter>::value), "Requires at least input iterator."); // if count is representing a negative value, we do nothing if (detail::is_negative(count)) { return util::detail::algorithm_result<ExPolicy, InIter>::get( std::move(first)); } typedef std::integral_constant<bool, execution::is_sequential_execution_policy<ExPolicy>::value || !hpx::traits::is_forward_iterator<InIter>::value > is_seq; return detail::for_each_n<InIter>().call( std::forward<ExPolicy>(policy), is_seq(), first, std::size_t(count), std::forward<F>(f), std::forward<Proj>(proj)); } /////////////////////////////////////////////////////////////////////////// // for_each namespace detail { /// \cond NOINTERNAL template <typename Iter> struct for_each : public detail::algorithm<for_each<Iter>, Iter> { for_each() : for_each::algorithm("for_each") {} template <typename ExPolicy, typename InIter, typename F, typename Proj> static InIter sequential(ExPolicy && policy, InIter first, InIter last, F && f, Proj && proj) { return util::loop(std::forward<ExPolicy>(policy), first, last, invoke_projected<F, Proj>{f, proj}); } template <typename ExPolicy, typename InIter, typename F, typename Proj> static typename util::detail::algorithm_result< ExPolicy, InIter >::type parallel(ExPolicy && policy, InIter first, InIter last, F && f, Proj && proj) { if (first != last) { auto f1 = for_each_iteration<ExPolicy, F, Proj>( std::forward<F>(f), std::forward<Proj>(proj)); return util::foreach_partitioner<ExPolicy>::call( std::forward<ExPolicy>(policy), first, std::distance(first, last), std::move(f1), util::projection_identity()); } return util::detail::algorithm_result<ExPolicy, InIter>::get( std::move(first)); } }; /////////////////////////////////////////////////////////////////////// // non-segmented implementation template <typename ExPolicy, typename InIter, typename F, typename Proj> inline typename util::detail::algorithm_result<ExPolicy, InIter>::type for_each_(ExPolicy && policy, InIter first, InIter last, F && f, Proj && proj, std::false_type) { typedef std::integral_constant<bool, parallel::execution::is_sequential_execution_policy< ExPolicy >::value || !hpx::traits::is_forward_iterator<InIter>::value > is_seq; if (first == last) { typedef util::detail::algorithm_result<ExPolicy, InIter> result; return result::get(std::move(last)); } return for_each<InIter>().call( std::forward<ExPolicy>(policy), is_seq(), first, last, std::forward<F>(f), std::forward<Proj>(proj)); } // forward declare the segmented version of this algorithm template <typename ExPolicy, typename SegIter, typename F, typename Proj> inline typename util::detail::algorithm_result<ExPolicy, SegIter>::type for_each_(ExPolicy && policy, SegIter first, SegIter last, F && f, Proj && proj, std::true_type); /// \endcond } /// Applies \a f to the result of dereferencing every iterator in the /// range [first, last). /// /// \note Complexity: Applies \a f exactly \a last - \a first times. /// /// If \a f returns a result, the result is ignored. /// /// If the type of \a first satisfies the requirements of a mutable /// iterator, \a f may apply non-constant functions through the /// dereferenced iterator. /// /// Unlike its sequential form, the parallel overload of /// \a for_each does not return a copy of its \a Function parameter, /// since parallelization may not permit efficient state /// accumulation. /// /// \tparam ExPolicy The type of the execution policy to use (deduced). /// It describes the manner in which the execution /// of the algorithm may be parallelized and the manner /// in which it applies user-provided function objects. /// \tparam InIter The type of the source iterators used (deduced). /// This iterator type must meet the requirements of an /// input iterator. /// \tparam F The type of the function/function object to use /// (deduced). Unlike its sequential form, the parallel /// overload of \a for_each requires \a F to meet the /// requirements of \a CopyConstructible. /// \tparam Proj The type of an optional projection function. This /// defaults to \a util::projection_identity /// /// \param policy The execution policy to use for the scheduling of /// the iterations. /// \param first Refers to the beginning of the sequence of elements /// the algorithm will be applied to. /// \param last Refers to the end of the sequence of elements the /// algorithm will be applied to. /// \param f Specifies the function (or function object) which /// will be invoked for each of the elements in the /// sequence specified by [first, last). /// The signature of this predicate /// should be equivalent to: /// \code /// <ignored> pred(const Type &a); /// \endcode \n /// The signature does not need to have const&. The /// type \a Type must be such that an object of /// type \a InIter can be dereferenced and then /// implicitly converted to Type. /// \param proj Specifies the function (or function object) which /// will be invoked for each of the elements as a /// projection operation before the actual predicate /// \a f is invoked. /// /// The application of function objects in parallel algorithm /// invoked with an execution policy object of type /// \a sequenced_policy execute in sequential order in the /// calling thread. /// /// The application of function objects in parallel algorithm /// invoked with an execution policy object of type /// \a parallel_policy or \a parallel_task_policy are /// permitted to execute in an unordered fashion in unspecified /// threads, and indeterminately sequenced within each thread. /// /// \returns The \a for_each algorithm returns a /// \a hpx::future<InIter> if the execution policy is of /// type /// \a sequenced_task_policy or /// \a parallel_task_policy and returns \a InIter /// otherwise. /// It returns \a last. /// // FIXME : is_indirect_callable does not work properly when compiling // Cuda device code template <typename ExPolicy, typename InIter, typename F, typename Proj = util::projection_identity, HPX_CONCEPT_REQUIRES_( execution::is_execution_policy<ExPolicy>::value && hpx::traits::is_iterator<InIter>::value && parallel::traits::is_projected<Proj, InIter>::value #if defined(__CUDA_ARCH__) && parallel::traits::is_indirect_callable< ExPolicy, F, traits::projected<Proj, InIter> >::value #endif )> typename util::detail::algorithm_result<ExPolicy, InIter>::type for_each(ExPolicy && policy, InIter first, InIter last, F && f, Proj && proj = Proj()) { static_assert( (hpx::traits::is_input_iterator<InIter>::value), "Requires at least input iterator."); typedef hpx::traits::is_segmented_iterator<InIter> is_segmented; return detail::for_each_( std::forward<ExPolicy>(policy), first, last, std::forward<F>(f), std::forward<Proj>(proj), is_segmented()); } // Determining the execution policy to be seq or par // based on the static information obtained at compile time template <typename Data, typename ExPolicy, typename InIter, typename F, typename Proj = util::projection_identity, HPX_CONCEPT_REQUIRES_( execution::is_execution_policy<ExPolicy>::value && hpx::traits::is_iterator<InIter>::value && parallel::traits::is_projected<Proj, InIter>::value #if defined(__CUDA_ARCH__) && parallel::traits::is_indirect_callable< ExPolicy, F, traits::projected<Proj, InIter> >::value #endif )> typename util::detail::algorithm_result<ExPolicy, InIter>::type adaptive_for_each(hpx::parallel::features_container<Data> features_info, hpx::parallel::weights_container<Data> weights_info, ExPolicy && policy, InIter first, InIter last, F && f, Proj && proj = Proj()) { static_assert( (hpx::traits::is_input_iterator<InIter>::value), "Requires at least input iterator."); typedef hpx::traits::is_segmented_iterator<InIter> is_segmented; //extracting parameters of the current policy: auto param = policy.parameters(); //extracting executors of the current policy: auto exec = policy.executor(); //choosing the most optimum execution policy for the current loop, //while keeping the parameters and executors of the current policy: auto seq_policy = hpx::parallel::seq.with(param); auto par_policy = hpx::parallel::par.with(param); // Initially clang assignes the value of modified_features[0] // and modified_features[4] to be 0, which are the number of threads // and number of iterations. These values will be determined // at runtime with adaptive_for_each: auto& modified_features = features_info.get_features(); modified_features[0] = hpx::get_os_thread_count(); modified_features[4] = std::distance(first, last); //getting values of computed weights of the learning network auto& weights = weights_info.get_weights(); // final_policy will be determined based on the result of the cost function of // binary regression model bool final_policy = features_info.execution_policy_determination(modified_features, weights); if(!final_policy) { return detail::for_each_( std::forward<hpx::parallel::execution::sequenced_policy>(seq_policy), first, last, std::forward<F>(f), std::forward<Proj>(proj), is_segmented()); } return detail::for_each_( std::forward<hpx::parallel::execution::parallel_policy>(par_policy), first, last, std::forward<F>(f), std::forward<Proj>(proj), is_segmented()); } }}} #endif