hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
90dec70e690f7e7ac612b7e8fa8f325a5b021084
1,118
hpp
C++
src/tuple_contains.hpp
LB--/tuples
4e1c5ecc1f3d2237050868dd1e895113484de3c6
[ "Unlicense" ]
1
2016-04-13T19:57:54.000Z
2016-04-13T19:57:54.000Z
src/tuple_contains.hpp
LB--/tuples
4e1c5ecc1f3d2237050868dd1e895113484de3c6
[ "Unlicense" ]
null
null
null
src/tuple_contains.hpp
LB--/tuples
4e1c5ecc1f3d2237050868dd1e895113484de3c6
[ "Unlicense" ]
null
null
null
#ifndef LB_tuples_tuple_contains_HeaderPlusPlus #define LB_tuples_tuple_contains_HeaderPlusPlus #include "tuple.hpp" #include "tuple_template_forward.hpp" #include "tuple_type_cat.hpp" #include <type_traits> namespace LB { namespace tuples { namespace impl { template<typename Type, typename... Args> struct tuple_contains; template<typename Type, typename First, typename... Rest> struct tuple_contains<Type, First, Rest...> final : std::integral_constant //C++17: use std::bool_constant < bool, std::is_same<Type, First>::value || tuple_contains<Type, Rest...>::value > { }; template<typename Type> struct tuple_contains<Type> final : std::false_type { }; } template<typename Tuple, typename Type> struct tuple_contains final : std::integral_constant //C++17: use std::bool_constant < bool, tuple_template_forward_t < impl::tuple_contains, tuple_type_cat_t<tuple<Type>, Tuple> >::value > { }; template<typename Tuple, typename Type> constexpr bool tuple_contains_v = tuple_contains<Tuple, Type>::value; } } #endif
21.09434
76
0.70483
LB--
90e2482efa37c6664c80bfadbaf27d497f5e2739
14,320
cc
C++
content/renderer/media/webrtc_audio_capturer.cc
pozdnyakov/chromium-crosswalk
0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/renderer/media/webrtc_audio_capturer.cc
pozdnyakov/chromium-crosswalk
0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/renderer/media/webrtc_audio_capturer.cc
pozdnyakov/chromium-crosswalk
0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2012 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 "content/renderer/media/webrtc_audio_capturer.h" #include "base/bind.h" #include "base/logging.h" #include "base/metrics/histogram.h" #include "base/strings/string_util.h" #include "content/child/child_process.h" #include "content/renderer/media/audio_device_factory.h" #include "content/renderer/media/webrtc_audio_capturer_sink_owner.h" #include "content/renderer/media/webrtc_audio_device_impl.h" #include "media/audio/audio_util.h" #include "media/audio/sample_rates.h" namespace content { // Supported hardware sample rates for input and output sides. #if defined(OS_WIN) || defined(OS_MACOSX) // media::GetAudioInputHardwareSampleRate() asks the audio layer // for its current sample rate (set by the user) on Windows and Mac OS X. // The listed rates below adds restrictions and WebRtcAudioDeviceImpl::Init() // will fail if the user selects any rate outside these ranges. static int kValidInputRates[] = {96000, 48000, 44100, 32000, 16000, 8000}; #elif defined(OS_LINUX) || defined(OS_OPENBSD) static int kValidInputRates[] = {48000, 44100}; #elif defined(OS_ANDROID) static int kValidInputRates[] = {48000, 44100}; #else static int kValidInputRates[] = {44100}; #endif static int GetBufferSizeForSampleRate(int sample_rate) { int buffer_size = 0; #if defined(OS_WIN) || defined(OS_MACOSX) // Use a buffer size of 10ms. buffer_size = (sample_rate / 100); #elif defined(OS_LINUX) || defined(OS_OPENBSD) // Based on tests using the current ALSA implementation in Chrome, we have // found that the best combination is 20ms on the input side and 10ms on the // output side. buffer_size = 2 * sample_rate / 100; #elif defined(OS_ANDROID) // TODO(leozwang): Tune and adjust buffer size on Android. buffer_size = 2 * sample_rate / 100; #endif return buffer_size; } // This is a temporary audio buffer with parameters used to send data to // callbacks. class WebRtcAudioCapturer::ConfiguredBuffer : public base::RefCounted<WebRtcAudioCapturer::ConfiguredBuffer> { public: ConfiguredBuffer() {} bool Initialize(int sample_rate, media::ChannelLayout channel_layout) { int buffer_size = GetBufferSizeForSampleRate(sample_rate); DVLOG(1) << "Using WebRTC input buffer size: " << buffer_size; media::AudioParameters::Format format = media::AudioParameters::AUDIO_PCM_LOW_LATENCY; // bits_per_sample is always 16 for now. int bits_per_sample = 16; int channels = ChannelLayoutToChannelCount(channel_layout); params_.Reset(format, channel_layout, channels, 0, sample_rate, bits_per_sample, buffer_size); buffer_.reset(new int16[params_.frames_per_buffer() * params_.channels()]); return true; } int16* buffer() const { return buffer_.get(); } const media::AudioParameters& params() const { return params_; } private: ~ConfiguredBuffer() {} friend class base::RefCounted<WebRtcAudioCapturer::ConfiguredBuffer>; scoped_ptr<int16[]> buffer_; // Cached values of utilized audio parameters. media::AudioParameters params_; }; // static scoped_refptr<WebRtcAudioCapturer> WebRtcAudioCapturer::CreateCapturer() { scoped_refptr<WebRtcAudioCapturer> capturer = new WebRtcAudioCapturer(); return capturer; } bool WebRtcAudioCapturer::Reconfigure(int sample_rate, media::ChannelLayout channel_layout) { scoped_refptr<ConfiguredBuffer> new_buffer(new ConfiguredBuffer()); if (!new_buffer->Initialize(sample_rate, channel_layout)) return false; TrackList tracks; { base::AutoLock auto_lock(lock_); buffer_ = new_buffer; tracks = tracks_; } // Tell all audio_tracks which format we use. for (TrackList::const_iterator it = tracks.begin(); it != tracks.end(); ++it) (*it)->SetCaptureFormat(new_buffer->params()); return true; } bool WebRtcAudioCapturer::Initialize(int render_view_id, media::ChannelLayout channel_layout, int sample_rate, int session_id) { DCHECK(thread_checker_.CalledOnValidThread()); DVLOG(1) << "WebRtcAudioCapturer::Initialize()"; DVLOG(1) << "Audio input hardware channel layout: " << channel_layout; UMA_HISTOGRAM_ENUMERATION("WebRTC.AudioInputChannelLayout", channel_layout, media::CHANNEL_LAYOUT_MAX); session_id_ = session_id; // Verify that the reported input channel configuration is supported. if (channel_layout != media::CHANNEL_LAYOUT_MONO && channel_layout != media::CHANNEL_LAYOUT_STEREO) { DLOG(ERROR) << channel_layout << " is not a supported input channel configuration."; return false; } DVLOG(1) << "Audio input hardware sample rate: " << sample_rate; media::AudioSampleRate asr = media::AsAudioSampleRate(sample_rate); if (asr != media::kUnexpectedAudioSampleRate) { UMA_HISTOGRAM_ENUMERATION( "WebRTC.AudioInputSampleRate", asr, media::kUnexpectedAudioSampleRate); } else { UMA_HISTOGRAM_COUNTS("WebRTC.AudioInputSampleRateUnexpected", sample_rate); } // Verify that the reported input hardware sample rate is supported // on the current platform. if (std::find(&kValidInputRates[0], &kValidInputRates[0] + arraysize(kValidInputRates), sample_rate) == &kValidInputRates[arraysize(kValidInputRates)]) { DLOG(ERROR) << sample_rate << " is not a supported input rate."; return false; } if (!Reconfigure(sample_rate, channel_layout)) return false; // Create and configure the default audio capturing source. The |source_| // will be overwritten if an external client later calls SetCapturerSource() // providing an alternative media::AudioCapturerSource. SetCapturerSource(AudioDeviceFactory::NewInputDevice(render_view_id), channel_layout, static_cast<float>(sample_rate)); return true; } WebRtcAudioCapturer::WebRtcAudioCapturer() : default_sink_(NULL), source_(NULL), running_(false), agc_is_enabled_(false), session_id_(0) { DVLOG(1) << "WebRtcAudioCapturer::WebRtcAudioCapturer()"; } WebRtcAudioCapturer::~WebRtcAudioCapturer() { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(tracks_.empty()); DCHECK(!running_); DCHECK(!default_sink_); DVLOG(1) << "WebRtcAudioCapturer::~WebRtcAudioCapturer()"; } void WebRtcAudioCapturer::SetDefaultSink(WebRtcAudioCapturerSink* sink) { DVLOG(1) << "WebRtcAudioCapturer::SetDefaultSink()"; if (sink) { DCHECK(!default_sink_); default_sink_ = sink; AddSink(sink); } else { DCHECK(default_sink_); RemoveSink(default_sink_); default_sink_ = NULL; } } void WebRtcAudioCapturer::AddSink(WebRtcAudioCapturerSink* track) { DCHECK(track); DVLOG(1) << "WebRtcAudioCapturer::AddSink()"; // Start the source if an audio track is connected to the capturer. // |default_sink_| is not an audio track. if (track != default_sink_) Start(); base::AutoLock auto_lock(lock_); // Verify that |track| is not already added to the list. DCHECK(std::find_if( tracks_.begin(), tracks_.end(), WebRtcAudioCapturerSinkOwner::WrapsSink(track)) == tracks_.end()); if (buffer_.get()) { track->SetCaptureFormat(buffer_->params()); } else { DLOG(WARNING) << "The format of the capturer has not been correctly " << "initialized"; } // Create (and add to the list) a new WebRtcAudioCapturerSinkOwner which owns // the |track| and delagates all calls to the WebRtcAudioCapturerSink // interface. tracks_.push_back(new WebRtcAudioCapturerSinkOwner(track)); // TODO(xians): should we call SetCapturerFormat() to each track? } void WebRtcAudioCapturer::RemoveSink( WebRtcAudioCapturerSink* track) { DCHECK(thread_checker_.CalledOnValidThread()); DVLOG(1) << "WebRtcAudioCapturer::RemoveSink()"; bool stop_source = false; { base::AutoLock auto_lock(lock_); // Get iterator to the first element for which WrapsSink(track) returns // true. TrackList::iterator it = std::find_if( tracks_.begin(), tracks_.end(), WebRtcAudioCapturerSinkOwner::WrapsSink(track)); if (it != tracks_.end()) { // Clear the delegate to ensure that no more capture callbacks will // be sent to this sink. Also avoids a possible crash which can happen // if this method is called while capturing is active. (*it)->Reset(); tracks_.erase(it); } // Stop the source if the last audio track is going away. // The |tracks_| might contain the |default_sink_|, we need to stop the // source if the only remaining element is |default_sink_|. if (tracks_.size() == 1 && default_sink_ && (*tracks_.begin())->IsEqual(default_sink_)) { stop_source = true; } else { // The source might have been stopped, but it is safe to call Stop() // again to make sure the source is stopped correctly. stop_source = tracks_.empty(); } } if (stop_source) Stop(); } void WebRtcAudioCapturer::SetCapturerSource( const scoped_refptr<media::AudioCapturerSource>& source, media::ChannelLayout channel_layout, float sample_rate) { DCHECK(thread_checker_.CalledOnValidThread()); DVLOG(1) << "SetCapturerSource(channel_layout=" << channel_layout << "," << "sample_rate=" << sample_rate << ")"; scoped_refptr<media::AudioCapturerSource> old_source; scoped_refptr<ConfiguredBuffer> current_buffer; bool restart_source = false; { base::AutoLock auto_lock(lock_); if (source_.get() == source.get()) return; source_.swap(old_source); source_ = source; current_buffer = buffer_; // Reset the flag to allow starting the new source. restart_source = running_; running_ = false; } const bool no_default_audio_source_exists = !current_buffer.get(); // Detach the old source from normal recording or perform first-time // initialization if Initialize() has never been called. For the second // case, the caller is not "taking over an ongoing session" but instead // "taking control over a new session". if (old_source.get() || no_default_audio_source_exists) { DVLOG(1) << "New capture source will now be utilized."; if (old_source.get()) old_source->Stop(); // Dispatch the new parameters both to the sink(s) and to the new source. // The idea is to get rid of any dependency of the microphone parameters // which would normally be used by default. if (!Reconfigure(sample_rate, channel_layout)) { return; } else { // The buffer has been reconfigured. Update |current_buffer|. base::AutoLock auto_lock(lock_); current_buffer = buffer_; } } if (source.get()) { // Make sure to grab the new parameters in case they were reconfigured. source->Initialize(current_buffer->params(), this, session_id_); } if (restart_source) Start(); } void WebRtcAudioCapturer::Start() { DVLOG(1) << "WebRtcAudioCapturer::Start()"; base::AutoLock auto_lock(lock_); if (running_) return; // Start the data source, i.e., start capturing data from the current source. // Note that, the source does not have to be a microphone. if (source_.get()) { // We need to set the AGC control before starting the stream. source_->SetAutomaticGainControl(agc_is_enabled_); source_->Start(); } running_ = true; } void WebRtcAudioCapturer::Stop() { DVLOG(1) << "WebRtcAudioCapturer::Stop()"; scoped_refptr<media::AudioCapturerSource> source; { base::AutoLock auto_lock(lock_); if (!running_) return; source = source_; running_ = false; } if (source.get()) source->Stop(); } void WebRtcAudioCapturer::SetVolume(double volume) { DVLOG(1) << "WebRtcAudioCapturer::SetVolume()"; base::AutoLock auto_lock(lock_); if (source_.get()) source_->SetVolume(volume); } void WebRtcAudioCapturer::SetAutomaticGainControl(bool enable) { base::AutoLock auto_lock(lock_); // Store the setting since SetAutomaticGainControl() can be called before // Initialize(), in this case stored setting will be applied in Start(). agc_is_enabled_ = enable; if (source_.get()) source_->SetAutomaticGainControl(enable); } void WebRtcAudioCapturer::Capture(media::AudioBus* audio_source, int audio_delay_milliseconds, double volume) { // This callback is driven by AudioInputDevice::AudioThreadCallback if // |source_| is AudioInputDevice, otherwise it is driven by client's // CaptureCallback. TrackList tracks; scoped_refptr<ConfiguredBuffer> buffer_ref_while_calling; { base::AutoLock auto_lock(lock_); if (!running_) return; // Copy the stuff we will need to local variables. In particular, we grab // a reference to the buffer so we can ensure it stays alive even if the // buffer is reconfigured while we are calling back. buffer_ref_while_calling = buffer_; tracks = tracks_; } int bytes_per_sample = buffer_ref_while_calling->params().bits_per_sample() / 8; // Interleave, scale, and clip input to int and store result in // a local byte buffer. audio_source->ToInterleaved(audio_source->frames(), bytes_per_sample, buffer_ref_while_calling->buffer()); // Feed the data to the tracks. for (TrackList::const_iterator it = tracks.begin(); it != tracks.end(); ++it) { (*it)->CaptureData(buffer_ref_while_calling->buffer(), audio_source->channels(), audio_source->frames(), audio_delay_milliseconds, volume); } } void WebRtcAudioCapturer::OnCaptureError() { NOTIMPLEMENTED(); } media::AudioParameters WebRtcAudioCapturer::audio_parameters() const { base::AutoLock auto_lock(lock_); // |buffer_| can be NULL when SetCapturerSource() or Initialize() has not // been called. return buffer_.get() ? buffer_->params() : media::AudioParameters(); } } // namespace content
33.694118
79
0.695321
pozdnyakov
90e69e6f340eeaf084901d09b18f28b3918e44a2
1,323
cpp
C++
chapter4_treesandGraphs/question2.cpp
kgajwan1/CTCI_practice
2e8e61f508777b4b7ad5d8c32dedd12ea5b27d39
[ "MIT" ]
null
null
null
chapter4_treesandGraphs/question2.cpp
kgajwan1/CTCI_practice
2e8e61f508777b4b7ad5d8c32dedd12ea5b27d39
[ "MIT" ]
null
null
null
chapter4_treesandGraphs/question2.cpp
kgajwan1/CTCI_practice
2e8e61f508777b4b7ad5d8c32dedd12ea5b27d39
[ "MIT" ]
null
null
null
//create a binary search tree from sorted array //make middle element root node, do recursion for left and right half #include<bits/stdc++.h> class node { public: int data; node *left, *right; }; //create a new node struct node *newNode(int item) { node *temp = new node; temp->data = item; temp->left = temp->right = NULL; return temp; } //utility to do preorder traversal void preOrderTraversal(node *n) { if(n == NULL) { return; } std::cout << n->data<<" "; preOrderTraversal(n->left); preOrderTraversal(n->right); } node *sortedArrtoBST(int arr[],int start,int end) { if (start>end) { // std::cout << "not possible\n"; return NULL; } //get middle elem and make it a root int mid = (start + end)/2; node *root = newNode(arr[mid]); root->left = sortedArrtoBST( arr, start,mid-1); root ->right = sortedArrtoBST( arr, mid+1,end); return root; } int main() { int arr[] = {1, 2, 3, 4, 5, 6, 7}; int n = sizeof(arr) / sizeof(arr[0]); /* Convert List to BST */ node *root = sortedArrtoBST(arr, 0, n-1); std::cout << "PreOrder Traversal of constructed BST \n"; preOrderTraversal(root); return 0; }
23.210526
70
0.557067
kgajwan1
90e82c89d9a98a73c2c5a1dbb14b53e30be80f11
1,472
cpp
C++
904-fruit-into-baskets/solution.cpp
darxsys/leetcode
1174f0dbad56c6bfd8196bc4c14798b5f8cee418
[ "MIT" ]
null
null
null
904-fruit-into-baskets/solution.cpp
darxsys/leetcode
1174f0dbad56c6bfd8196bc4c14798b5f8cee418
[ "MIT" ]
null
null
null
904-fruit-into-baskets/solution.cpp
darxsys/leetcode
1174f0dbad56c6bfd8196bc4c14798b5f8cee418
[ "MIT" ]
null
null
null
#include <cstdio> #include <cstring> #include <cstdlib> #include <cassert> #include <vector> #include <map> #include <stack> #include <queue> #include <deque> #include <map> #include <unordered_map> #include <algorithm> #include <unordered_set> using namespace std; class Solution { public: int totalFruit(vector<int>& tree) { if (tree.empty()) return 0; int sol = 1; int prev = -1; int cur = tree[0]; int seen = 1; int cur_len = 1; for (int i = 1; i < tree.size(); ++i) { int next = tree[i]; if (next == cur) { cur_len++; seen++; } else if (next == prev) { cur_len++; seen = 1; swap(cur, prev); } else { cur_len = seen + 1; seen = 1; prev = cur; cur = next; } sol = max(sol, cur_len); } return sol; } }; int main() { Solution s; vector<int> input({1, 2, 1}); assert(s.totalFruit(input) == 3); input = {0, 1, 2, 2}; assert(s.totalFruit(input) == 3); input = {1, 2, 3, 2, 2}; assert(s.totalFruit(input) == 4); input = {3,3,3,1,2,1,1,2,3,3,4}; assert(s.totalFruit(input) == 5); input = {0, 0, 0, 0, 0, 1}; assert(s.totalFruit(input) == 6); return 0; }
19.891892
45
0.443614
darxsys
90e913ad776a0343185c5d8aaae1d43df3d0020a
880
cpp
C++
PC_Clase7/max_val_k_array.cpp
Angelussz/ProgramacionCompetitiva
681c0aa21020d8e843108e77abcf2a62dd471dc5
[ "BSD-3-Clause" ]
null
null
null
PC_Clase7/max_val_k_array.cpp
Angelussz/ProgramacionCompetitiva
681c0aa21020d8e843108e77abcf2a62dd471dc5
[ "BSD-3-Clause" ]
null
null
null
PC_Clase7/max_val_k_array.cpp
Angelussz/ProgramacionCompetitiva
681c0aa21020d8e843108e77abcf2a62dd471dc5
[ "BSD-3-Clause" ]
null
null
null
/****************************************************************************** Maximum sum of any contiguous subarray of size k *******************************************************************************/ #include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); vector<int> nums{2,3,4,1,5}; int k=3; int inic = 0; int sum = 0; int maxim = INT_MIN; for(int fin=0;fin < nums.size();fin++){ if(fin<k){ sum = sum+nums[fin]; maxim = sum; } else{ sum = sum-nums[inic]; sum = sum+nums[fin]; // cout<<sum<<"\n"; maxim = max(maxim,sum); inic++; } } if (maxim == 0){ cout<<0<<"\n"; } else{ cout<<maxim<<"\n"; } return 0; }
20.465116
80
0.359091
Angelussz
90e94d58c481a250c9ec78fd20e1c1b0fecb9ddd
14,546
cpp
C++
os/net/src/socket.cpp
rvedam/es-operating-system
32d3e4791c28a5623744800f108d029c40c745fc
[ "Apache-2.0" ]
2
2020-11-30T18:38:20.000Z
2021-06-07T07:44:03.000Z
os/net/src/socket.cpp
LambdaLord/es-operating-system
32d3e4791c28a5623744800f108d029c40c745fc
[ "Apache-2.0" ]
1
2019-01-14T03:09:45.000Z
2019-01-14T03:09:45.000Z
os/net/src/socket.cpp
LambdaLord/es-operating-system
32d3e4791c28a5623744800f108d029c40c745fc
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2008, 2009 Google Inc. * Copyright 2006, 2007 Nintendo Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <new> #include <stdlib.h> #include <string.h> #include <es/net/arp.h> #include "dix.h" #include "inet4address.h" #include "loopback.h" #include "socket.h" #include "visualizer.h" es::Resolver* Socket::resolver = 0; es::InternetConfig* Socket::config = 0; es::Context* Socket::interface = 0; AddressFamily::List Socket::addressFamilyList; NetworkInterface* Socket::interfaces[Socket::INTERFACE_MAX]; Timer* Socket::timer; LoopbackAccessor LoopbackInterface::loopbackAccessor; void Socket:: initialize() { DateTime seed = DateTime::getNow(); srand48(seed.getTicks()); timer = new Timer; } int Socket:: addInterface(es::NetworkInterface* networkInterface) { int n; for (n = 1; n < Socket::INTERFACE_MAX; ++n) { if (interfaces[n] == 0) { break; } } if (Socket::INTERFACE_MAX <= n) { return -1; } switch (networkInterface->getType()) { case es::NetworkInterface::Ethernet: { DIXInterface* dixInterface = new DIXInterface(networkInterface); dixInterface->setScopeID(n); interfaces[n] = dixInterface; // Connect address families to the loopback interface. AddressFamily* af; AddressFamily::List::Iterator iter = addressFamilyList.begin(); while ((af = iter.next())) { af->addInterface(dixInterface); } #if 0 { Visualizer v; dixInterface->getAdapter()->accept(&v); } #endif dixInterface->start(); break; } case es::NetworkInterface::Loopback: { LoopbackInterface* loopbackInterface = new LoopbackInterface(networkInterface); loopbackInterface->setScopeID(n); interfaces[n] = loopbackInterface; // Connect address families to the loopback interface. AddressFamily* af; AddressFamily::List::Iterator iter = addressFamilyList.begin(); while ((af = iter.next())) { af->addInterface(loopbackInterface); } #if 0 { Visualizer v; loopbackInterface->getAdapter()->accept(&v); } #endif loopbackInterface->start(); break; } default: return -1; } return n; } void Socket:: removeInterface(es::NetworkInterface* networkInterface) { for (int n = 1; n < Socket::INTERFACE_MAX; ++n) { NetworkInterface* i = interfaces[n]; if (i && i->networkInterface == networkInterface) { interfaces[n] = 0; delete i; break; } } } Socket:: Socket(int family, int type, int protocol) : family(family), type(type), protocol(protocol), adapter(0), af(0), recvBufferSize(8192), sendBufferSize(8192), errorCode(0), selector(0), blocking(true), recvFromAddress(0), recvFromPort(0) { af = getAddressFamily(family); } Socket:: ~Socket() { // Leave from multicast groups XXX if (adapter) { SocketUninstaller uninstaller(this); adapter->accept(&uninstaller); } } bool Socket:: input(InetMessenger* m, Conduit* c) { return true; } bool Socket:: output(InetMessenger* m, Conduit* c) { return true; } bool Socket:: error(InetMessenger* m, Conduit* c) { return true; } // // ISocket // bool Socket:: isBound() { return getLocalPort(); } bool Socket:: isClosed() { return isBound() && !getAdapter(); // bound and then uninstalled? } bool Socket:: sockAtMark() { if (!adapter) { errorCode = ENOTCONN; return -errorCode; } SocketMessenger m(this, &SocketReceiver::atMark); Visitor v(&m); adapter->accept(&v); int code = m.getErrorCode(); if (code) { if (code != EAGAIN) { errorCode = code; } return -errorCode; } return m.getFlag(); } bool Socket:: isUrgent() { if (!adapter) { errorCode = ENOTCONN; return -errorCode; } SocketMessenger m(this, &SocketReceiver::isUrgent); Visitor v(&m); adapter->accept(&v); int code = m.getErrorCode(); if (code) { if (code != EAGAIN) { errorCode = code; } return -errorCode; } return m.getFlag(); } bool Socket:: isConnected() { return getRemotePort(); } int Socket:: getHops() { } void Socket:: setHops(int limit) { } int Socket:: getReceiveBufferSize() { return recvBufferSize; } void Socket:: setReceiveBufferSize(int size) { if (!isBound()) { recvBufferSize = size; } } int Socket:: getSendBufferSize() { return sendBufferSize; } void Socket:: setSendBufferSize(int size) { if (!isBound()) { sendBufferSize = size; } } long long Socket:: getTimeout() { return timeout; } void Socket:: setTimeout(long long timeSpan) { timeout = timeSpan; } bool Socket:: getReuseAddress() { } void Socket:: setReuseAddress(bool on) { } void Socket:: bind(es::InternetAddress* addr, int port) { if (isBound()) { return; } if (port == 0) { port = af->selectEphemeralPort(this); if (port == 0) { return; } // XXX Reserve anon from others } Conduit* protocol = af->getProtocol(this); if (!protocol) { return; } setLocal(dynamic_cast<Address*>(addr)); // XXX setLocalPort(port); SocketInstaller installer(this); protocol->accept(&installer); } void Socket:: connect(es::InternetAddress* addr, int port) { if (isConnected() || addr == 0 || port == 0) { return; } Conduit* protocol = af->getProtocol(this); if (!protocol) { return; } int anon = 0; if (getLocalPort() == 0) { anon = af->selectEphemeralPort(this); if (anon == 0) { return; } // XXX Reserve anon from others } es::InternetAddress* src = 0; if (!getLocal()) // XXX any { src = af->selectSourceAddress(addr); if (!src) { return; } } if (isBound()) { SocketDisconnector disconnector(this); adapter->accept(&disconnector); if (anon) { setLocalPort(anon); } if (src) { setLocal(dynamic_cast<Address*>(src)); } setRemote(dynamic_cast<Address*>(addr)); // XXX setRemotePort(port); SocketConnector connector(this, disconnector.getProtocol()); protocol->accept(&connector); } else { if (anon) { setLocalPort(anon); } if (src) { setLocal(dynamic_cast<Address*>(src)); } setRemote(dynamic_cast<Address*>(addr)); // XXX setRemotePort(port); SocketInstaller installer(this); protocol->accept(&installer); } // Request connect SocketMessenger m(this, &SocketReceiver::connect); Visitor v(&m); adapter->accept(&v); int code = m.getErrorCode(); if (code != EINPROGRESS) { errorCode = code; } } es::Socket* Socket:: accept() { SocketMessenger m(this, &SocketReceiver::accept); Visitor v(&m); adapter->accept(&v); errorCode = m.getErrorCode(); int code = m.getErrorCode(); if (code != EAGAIN) { errorCode = code; } return m.getSocket(); } void Socket:: close() { if (!adapter) { return; } SocketMessenger m(this, &SocketReceiver::close); Visitor v(&m); adapter->accept(&v); int code = m.getErrorCode(); if (code != EAGAIN) { errorCode = code; } } void Socket:: listen(int backlog) { StreamReceiver* s = dynamic_cast<StreamReceiver*>(getReceiver()); if (s) { s->setState(StreamReceiver::stateListen); s->setBackLogCount(backlog); } } int Socket:: read(void* dst, int count) { if (!adapter) { errorCode = ENOTCONN; return -errorCode; } SocketMessenger m(this, &SocketReceiver::read, dst, count); Visitor v(&m); adapter->accept(&v); int code = m.getErrorCode(); if (code) { if (code != EAGAIN) { errorCode = code; } return -errorCode; } return m.getLength(); } int Socket:: recvFrom(void* dst, int count, int flags) { if (!adapter) { errorCode = ENOTCONN; return -errorCode; } SocketMessenger m(this, &SocketReceiver::read, dst, count); Visitor v(&m); adapter->accept(&v); int code = m.getErrorCode(); if (code) { if (code != EAGAIN) { errorCode = code; } return -errorCode; } if (recvFromAddress) { recvFromAddress->release(); } recvFromAddress = m.getRemote(); recvFromPort = m.getRemotePort(); return m.getLength(); } es::InternetAddress* Socket:: getRecvFromAddress() { es::InternetAddress* addr = recvFromAddress; recvFromAddress = 0; return addr; } int Socket:: getRecvFromPort() { int port = recvFromPort; recvFromPort = 0; return port; } int Socket:: sendTo(const void* src, int count, int flags, es::InternetAddress* addr, int port) { if (!adapter) { errorCode = ENOTCONN; return -errorCode; } SocketMessenger m(this, &SocketReceiver::write, const_cast<void*>(src), count); m.setRemote(dynamic_cast<Inet4Address*>(addr)); m.setRemotePort(port); m.setFlag(flags); Visitor v(&m); adapter->accept(&v); int code = m.getErrorCode(); if (code) { if (code != EAGAIN) { errorCode = code; } return -errorCode; } return m.getLength(); } void Socket:: shutdownInput() { if (!adapter) { return; } SocketMessenger m(this, &SocketReceiver::shutdownInput); Visitor v(&m); adapter->accept(&v); errorCode = m.getErrorCode(); } void Socket:: shutdownOutput() { if (!adapter) { return; } SocketMessenger m(this, &SocketReceiver::shutdownOutput); Visitor v(&m); adapter->accept(&v); errorCode = m.getErrorCode(); } int Socket:: write(const void* src, int count) { if (!adapter) { errorCode = ENOTCONN; return -errorCode; } SocketMessenger m(this, &SocketReceiver::write, const_cast<void*>(src), count); Visitor v(&m); adapter->accept(&v); int code = m.getErrorCode(); if (code) { if (code != EAGAIN) { errorCode = code; } return -errorCode; } return m.getLength(); } bool Socket:: isAcceptable() { if (!adapter) { return false; } SocketMessenger m(this, &SocketReceiver::isAcceptable); Visitor v(&m); adapter->accept(&v); return m.getErrorCode(); } bool Socket:: isConnectable() { if (!adapter) { return false; } SocketMessenger m(this, &SocketReceiver::isConnectable); Visitor v(&m); adapter->accept(&v); return m.getErrorCode(); } bool Socket:: isReadable() { if (!adapter) { return false; } SocketMessenger m(this, &SocketReceiver::isReadable); Visitor v(&m); adapter->accept(&v); return m.getErrorCode(); } bool Socket:: isWritable() { if (!adapter) { return false; } SocketMessenger m(this, &SocketReceiver::isWritable); Visitor v(&m); adapter->accept(&v); return m.getErrorCode(); } // // IMulticastSocket // bool Socket:: getLoopbackMode() { } void Socket:: setLoopbackMode(bool disable) { } void Socket:: joinGroup(es::InternetAddress* addr) { Address* address = static_cast<Address*>(addr); if (address->isMulticast()) { addresses.addLast(address); address->addSocket(this); } } void Socket:: leaveGroup(es::InternetAddress* addr) { Address* address = static_cast<Address*>(addr); if (addresses.contains(address)) { addresses.remove(address); address->removeSocket(this); } } void Socket:: notify() { if (!adapter) { return; } SocketMessenger m(this, &SocketReceiver::notify); Visitor v(&m); adapter->accept(&v); } int Socket:: add(es::Monitor* selector) { esReport("Socket::%s(%p) : %p\n", __func__, selector, this->selector); if (!selector || this->selector) { return -1; } selector->addRef(); this->selector = selector; return 1; } int Socket:: remove(es::Monitor* selector) { esReport("Socket::%s(%p) : %p\n", __func__, selector, this->selector); if (!selector || selector != this->selector) { return -1; } selector->release(); this->selector = 0; return 1; } // // IInterface // Object* Socket:: queryInterface(const char* riid) { Object* objectPtr; if (strcmp(riid, es::Socket::iid()) == 0) { objectPtr = static_cast<es::Socket*>(this); } else if (strcmp(riid, es::Selectable::iid()) == 0) { objectPtr = static_cast<es::Selectable*>(this); } else if (strcmp(riid, Object::iid()) == 0) { objectPtr = static_cast<es::Socket*>(this); } else if (strcmp(riid, es::MulticastSocket::iid()) == 0 && type == es::Socket::Datagram) { objectPtr = static_cast<es::Socket*>(this); } else { return NULL; } objectPtr->addRef(); return objectPtr; } unsigned int Socket:: addRef() { return ref.addRef(); } unsigned int Socket:: release() { unsigned int count = ref.release(); if (count == 0) { delete this; return 0; } return count; }
18.11457
91
0.571497
rvedam
90f32b95bb13f5a5f7953dcbf0df514c560f22e5
30,383
cpp
C++
snap/snap-core/centr.cpp
dkw-aau/trident-clone
18f896db2be05870069ae7b3aa6b4837c74fff0f
[ "Apache-2.0" ]
20
2018-10-17T21:39:40.000Z
2021-11-10T11:07:23.000Z
snap/snap-core/centr.cpp
dkw-aau/trident-clone
18f896db2be05870069ae7b3aa6b4837c74fff0f
[ "Apache-2.0" ]
5
2020-07-06T22:50:04.000Z
2022-03-17T10:34:15.000Z
snap/snap-core/centr.cpp
dkw-aau/trident-clone
18f896db2be05870069ae7b3aa6b4837c74fff0f
[ "Apache-2.0" ]
9
2018-09-18T11:37:35.000Z
2022-03-29T07:46:41.000Z
namespace TSnap { ///////////////////////////////////////////////// // Node centrality measures double GetDegreeCentr(const PUNGraph& Graph, const int& NId) { if (Graph->GetNodes() > 1) { return double(Graph->GetNI(NId).GetDeg())/double(Graph->GetNodes()-1); } else { return 0.0; } } void GetEigenVectorCentr(const PUNGraph& Graph, TIntFltH& NIdEigenH, const double& Eps, const int& MaxIter) { const int NNodes = Graph->GetNodes(); NIdEigenH.Gen(NNodes); // initialize vector values for (TUNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) { NIdEigenH.AddDat(NI.GetId(), 1.0/NNodes); IAssert(NI.GetId() == NIdEigenH.GetKey(NIdEigenH.Len()-1)); } TFltV TmpV(NNodes); for (int iter = 0; iter < MaxIter; iter++) { int j = 0; // add neighbor values for (TUNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++, j++) { TmpV[j] = 0; for (int e = 0; e < NI.GetOutDeg(); e++) { TmpV[j] += NIdEigenH.GetDat(NI.GetOutNId(e)); } } // normalize double sum = 0; for (int i = 0; i < TmpV.Len(); i++) { sum += (TmpV[i]*TmpV[i]); } sum = sqrt(sum); for (int i = 0; i < TmpV.Len(); i++) { TmpV[i] /= sum; } // compute difference double diff = 0.0; j = 0; for (TUNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++, j++) { diff += fabs(NIdEigenH.GetDat(NI.GetId())-TmpV[j]); } // set new values j = 0; for (TUNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++, j++) { NIdEigenH.AddDat(NI.GetId(), TmpV[j]); } if (diff < Eps) { break; } } } // Group centrality measures double GetGroupDegreeCentr(const PUNGraph& Graph, const PUNGraph& Group) { int deg; TIntH NN; for (TUNGraph::TNodeI NI = Group->BegNI(); NI < Group->EndNI(); NI++) { deg = Graph->GetNI(NI.GetId()).GetDeg(); for (int i=0; i<deg; i++) { if (Group->IsNode(Graph->GetNI(NI.GetId()).GetNbrNId(i))==0) NN.AddDat(Graph->GetNI(NI.GetId()).GetNbrNId(i),NI.GetId()); } } return (double)NN.Len(); } double GetGroupDegreeCentr0(const PUNGraph& Graph, const TIntH& GroupNodes) { int deg; TIntH NN; for (int i = 0; i<GroupNodes.Len(); i++) { deg = Graph->GetNI(GroupNodes.GetDat(i)).GetDeg(); for (int j = 0; j < deg; j++) { if (GroupNodes.IsKey(Graph->GetNI(GroupNodes.GetDat(i)).GetNbrNId(j))==0) NN.AddDat(Graph->GetNI(GroupNodes.GetDat(i)).GetNbrNId(j),GroupNodes.GetDat(i)); } } return (double)NN.Len(); } double GetGroupDegreeCentr(const PUNGraph& Graph, const TIntH& GroupNodes) { int deg; TIntH NN; TIntH GroupNodes1; for (THashKeyDatI<TInt,TInt> NI = GroupNodes.BegI(); NI < GroupNodes.EndI(); NI++) GroupNodes1.AddDat(NI.GetDat(),NI.GetDat()); for (THashKeyDatI<TInt,TInt> NI = GroupNodes1.BegI(); NI < GroupNodes1.EndI(); NI++){ TUNGraph::TNodeI node = Graph->GetNI(NI.GetKey()); deg = node.GetDeg(); for (int j = 0; j < deg; j++){ if (GroupNodes1.IsKey(node.GetNbrNId(j))==0 && NN.IsKey(node.GetNbrNId(j))==0) NN.AddDat(node.GetNbrNId(j),NI.GetKey()); } } return (double)NN.Len(); } double GetGroupFarnessCentr(const PUNGraph& Graph, const TIntH& GroupNodes) { TIntH* NDistH = new TIntH[GroupNodes.Len()]; for (int i=0; i<GroupNodes.Len(); i++){ NDistH[i](Graph->GetNodes()); TSnap::GetShortPath<PUNGraph>(Graph, GroupNodes.GetDat(i), NDistH[i], true, TInt::Mx); } int min, dist, sum=0, len=0; for (PUNGraph::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++){ if(NDistH[0].IsKey(NI.GetId())) min = NDistH[0].GetDat(NI.GetId()); else min = -1; for (int j=1; j<GroupNodes.Len(); j++){ if (NDistH[j].IsKey(NI.GetId())) dist = NDistH[j].GetDat(NI.GetId()); else dist = -1; if ((dist < min && dist != -1) || (dist > min && min == -1)) min = dist; } if (min>0){ sum += min; len++; } } if (len > 0) { return sum/double(len); } else { return 0.0; } } PUNGraph *AllGraphsWithNNodes(int n){ PUNGraph* g = new PUNGraph[(((n*n)-n)/2)+1]; PUNGraph g0; for(int i=0; i<n; i++) g0->AddNode(i); g[0] = g0; int br=1; for(int i=0; i<n; i++) for(int j=i; j<n; j++){ g0->AddEdge(i,j); g[br] = g0; br++; } return g; } TIntH *AllCombinationsMN(int m, int n){ float N = 1; for(int i=n; i>0; i--){ N *= (float)m/(float)n; m--; n--; } TIntH* C = new TIntH[(int)N]; return C; } double GetGroupClosenessCentr(const PUNGraph& Graph, const TIntH& GroupNodes) { const double Farness = GetGroupFarnessCentr(Graph, GroupNodes); if (Farness != 0.0) { return 1.0/Farness; } else { return 0.0; } } TIntH MaxCPGreedyBetter(const PUNGraph& Graph, const int k) { TIntH GroupNodes; // buildup cpntainer of group nodes TIntH NNodes; // container of neighbouring nodes TIntH Nodes; // nodes sorted by vd double gc = 0, gc0 = 0; int addId = 0, addIdPrev = 0; for (TUNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) { Nodes.AddDat(NI.GetId(),NI.GetDeg()); } Nodes.SortByDat(false); int br = 0; while (br < k) { for (THashKeyDatI<TInt,TInt> NI = Nodes.BegI(); NI < Nodes.EndI(); NI++) { if ((NI.GetDat() <= (int)gc0)) break; gc = NI.GetDat()-Intersect(Graph->GetNI(NI.GetKey()),NNodes); if (gc>gc0) { gc0 = gc; addId = NI.GetKey(); } } if (addId != addIdPrev){ GroupNodes.AddDat(br,addId); br++; gc0=0; NNodes.AddDat(addId,0); for (int i=0; i<Graph->GetNI(addId).GetDeg(); i++) { NNodes.AddDat(Graph->GetNI(addId).GetNbrNId(i),0); } addIdPrev = addId; Nodes.DelKey(addId); } else { br = k; } printf("%i,",br); } // gcFinal = GetGroupDegreeCentr(Graph, GroupNodes); return GroupNodes; } // this is the variation of the first version that doesent stop after finding the optimal K TIntH MaxCPGreedyBetter1(const PUNGraph& Graph, const int k) { TIntH GroupNodes; TIntH NNodes; TIntH Nodes; double gc = 0, gc0 = 0; int addId = 0, addIdPrev = 0; // put nodes in the container and sort them by vertex degree for (TUNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++){ Nodes.AddDat(NI.GetId(),NI.GetDeg()); } Nodes.SortByDat(false); int br = 0; while (br < k) { for (THashKeyDatI<TInt,TInt> NI = Nodes.BegI(); NI < Nodes.EndI(); NI++){ if((NI.GetDat() < (int)gc0)) break; gc = NI.GetDat()-Intersect(Graph->GetNI(NI.GetKey()),NNodes); if (gc>gc0) { gc0 = gc; addId = NI.GetKey(); } } if (addId != addIdPrev){ GroupNodes.AddDat(br,addId); br++; gc0=-10000000; NNodes.AddDat(addId,0); for (int i=0; i<Graph->GetNI(addId).GetDeg(); i++) { NNodes.AddDat(Graph->GetNI(addId).GetNbrNId(i),0); } addIdPrev = addId; Nodes.DelKey(addId); } } // gcFinal = GetGroupDegreeCentr(Graph, GroupNodes); return GroupNodes; } // version with string type of container of group nodes - Fail (it is slower) TIntH MaxCPGreedyBetter2(const PUNGraph& Graph, const int k) { TIntH GroupNodes; // buildup cpntainer of group nodes TStr NNodes; // container of neighbouring nodes TIntH Nodes; // nodes sorted by vd double gc = 0, gc0 = 0; int addId = 0, addIdPrev=0; for (TUNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++){ Nodes.AddDat(NI.GetId(),NI.GetDeg()); } Nodes.SortByDat(false); int br=0; while (br < k) { for (THashKeyDatI<TInt,TInt> NI = Nodes.BegI(); NI < Nodes.EndI(); NI++){ if((NI.GetDat() <= (int)gc0)) break; gc = NI.GetDat()-Intersect(Graph->GetNI(NI.GetKey()),NNodes); if (gc>gc0) { gc0 = gc; addId = NI.GetKey(); } } if (addId != addIdPrev) { GroupNodes.AddDat(br,addId); br++; gc0=0; TInt digi = addId; TStr buf = digi.GetStr(); NNodes += " "+buf; for (int i=0; i<Graph->GetNI(addId).GetDeg(); i++) { TInt digi = Graph->GetNI(addId).GetNbrNId(i); TStr buf = digi.GetStr(); NNodes += " "+buf; } addIdPrev = addId; Nodes.DelKey(addId); } else { br = k; } printf("%i,",br); } // gcFinal = GetGroupDegreeCentr(Graph, GroupNodes); return GroupNodes; } // version with int array - the fastest TIntH MaxCPGreedyBetter3(const PUNGraph& Graph, const int k) { TIntH GroupNodes; // buildup cpntainer of group nodes const int n = Graph->GetNodes(); int *NNodes = new int[n]; // container of neighbouring nodes int NNodes_br = 0; TIntH Nodes; // nodes sorted by vd double gc = 0, gc0 = 0; int addId = 0, addIdPrev = 0; for (TUNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++){ Nodes.AddDat(NI.GetId(),NI.GetDeg()); } Nodes.SortByDat(false); int br = 0; while (br < k) { for (THashKeyDatI<TInt,TInt> NI = Nodes.BegI(); NI < Nodes.EndI(); NI++){ if((NI.GetDat() <= (int)gc0)) break; gc = NI.GetDat()-Intersect(Graph->GetNI(NI.GetKey()),NNodes,NNodes_br); if (gc>gc0){ gc0 = gc; addId = NI.GetKey(); } } if (addId != addIdPrev) { GroupNodes.AddDat(br,addId); br++; gc0=0; int nn = addId; bool nnnew = true; for (int j=0; j<NNodes_br; j++) if (NNodes[j] == nn){ nnnew = false; j = NNodes_br; } if (nnnew){ NNodes[NNodes_br] = nn; NNodes_br++; } for (int i=0; i<Graph->GetNI(addId).GetDeg(); i++) { int nn = Graph->GetNI(addId).GetNbrNId(i); bool nnnew = true; for (int j=0; j<NNodes_br; j++) { if (NNodes[j] == nn){ nnnew = false; j = NNodes_br; } } if (nnnew){ NNodes[NNodes_br] = nn; NNodes_br++; } } addIdPrev = addId; Nodes.DelKey(addId); } else { br = k; } printf("%i,",br); } delete[] NNodes; // gcFinal = GetGroupDegreeCentr(Graph, GroupNodes); return GroupNodes; } //Weighted PageRank int GetWeightedPageRank(const PNEANet Graph, TIntFltH& PRankH, const TStr& Attr, const double& C, const double& Eps, const int& MaxIter) { if (!Graph->IsFltAttrE(Attr)) return -1; TFltV Weights = Graph->GetFltAttrVecE(Attr); int mxid = Graph->GetMxNId(); TFltV OutWeights(mxid); Graph->GetWeightOutEdgesV(OutWeights, Weights); const int NNodes = Graph->GetNodes(); //const double OneOver = 1.0/double(NNodes); PRankH.Gen(NNodes); for (TNEANet::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) { PRankH.AddDat(NI.GetId(), 1.0/NNodes); //IAssert(NI.GetId() == PRankH.GetKey(PRankH.Len()-1)); } TFltV TmpV(NNodes); for (int iter = 0; iter < MaxIter; iter++) { int j = 0; for (TNEANet::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++, j++) { TmpV[j] = 0; for (int e = 0; e < NI.GetInDeg(); e++) { const int InNId = NI.GetInNId(e); const TFlt OutWeight = OutWeights[InNId]; int EId = Graph->GetEId(InNId, NI.GetId()); const TFlt Weight = Weights[Graph->GetFltKeyIdE(EId)]; if (OutWeight > 0) { TmpV[j] += PRankH.GetDat(InNId) * Weight / OutWeight; } } TmpV[j] = C*TmpV[j]; // Berkhin (the correct way of doing it) //TmpV[j] = C*TmpV[j] + (1.0-C)*OneOver; // iGraph } double diff=0, sum=0, NewVal; for (int i = 0; i < TmpV.Len(); i++) { sum += TmpV[i]; } const double Leaked = (1.0-sum) / double(NNodes); for (int i = 0; i < PRankH.Len(); i++) { // re-instert leaked PageRank NewVal = TmpV[i] + Leaked; // Berkhin //NewVal = TmpV[i] / sum; // iGraph diff += fabs(NewVal-PRankH[i]); PRankH[i] = NewVal; } if (diff < Eps) { break; } } return 0; } #ifdef USE_OPENMP int GetWeightedPageRankMP(const PNEANet Graph, TIntFltH& PRankH, const TStr& Attr, const double& C, const double& Eps, const int& MaxIter) { if (!Graph->IsFltAttrE(Attr)) return -1; const int NNodes = Graph->GetNodes(); TVec<TNEANet::TNodeI> NV; //const double OneOver = 1.0/double(NNodes); PRankH.Gen(NNodes); int MxId = 0; for (TNEANet::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) { NV.Add(NI); PRankH.AddDat(NI.GetId(), 1.0/NNodes); int Id = NI.GetId(); if (Id > MxId) { MxId = Id; } } TFltV PRankV(MxId+1); TFltV OutWeights(MxId+1); TFltV Weights = Graph->GetFltAttrVecE(Attr); #pragma omp parallel for schedule(dynamic,10000) for (int j = 0; j < NNodes; j++) { TNEANet::TNodeI NI = NV[j]; int Id = NI.GetId(); OutWeights[Id] = Graph->GetWeightOutEdges(NI, Attr); PRankV[Id] = 1/NNodes; } TFltV TmpV(NNodes); for (int iter = 0; iter < MaxIter; iter++) { #pragma omp parallel for schedule(dynamic,10000) for (int j = 0; j < NNodes; j++) { TNEANet::TNodeI NI = NV[j]; TFlt Tmp = 0; for (int e = 0; e < NI.GetInDeg(); e++) { const int InNId = NI.GetInNId(e); const TFlt OutWeight = OutWeights[InNId]; int EId = Graph->GetEId(InNId, NI.GetId()); const TFlt Weight = Weights[Graph->GetFltKeyIdE(EId)]; if (OutWeight > 0) { Tmp += PRankH.GetDat(InNId) * Weight / OutWeight; } } TmpV[j] = C*Tmp; // Berkhin (the correct way of doing it) //TmpV[j] = C*TmpV[j] + (1.0-C)*OneOver; // iGraph } double sum = 0; #pragma omp parallel for reduction(+:sum) schedule(dynamic,10000) for (int i = 0; i < TmpV.Len(); i++) { sum += TmpV[i]; } const double Leaked = (1.0-sum) / double(NNodes); double diff = 0; #pragma omp parallel for reduction(+:diff) schedule(dynamic,10000) for (int i = 0; i < NNodes; i++) { TNEANet::TNodeI NI = NV[i]; double NewVal = TmpV[i] + Leaked; // Berkhin //NewVal = TmpV[i] / sum; // iGraph int Id = NI.GetId(); diff += fabs(NewVal-PRankV[Id]); PRankV[Id] = NewVal; } if (diff < Eps) { break; } } #pragma omp parallel for schedule(dynamic,10000) for (int i = 0; i < NNodes; i++) { TNEANet::TNodeI NI = NV[i]; PRankH[i] = PRankV[NI.GetId()]; } return 0; } #endif // USE_OPENMP //Event importance TIntFltH EventImportance(const PNGraph& Graph, const int k) { TIntFltH NodeList; // values for nodese for (TNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++){ NodeList.AddDat(NI.GetId(),NI.GetOutDeg()); } for (THashKeyDatI<TInt,TFlt> NI = NodeList.BegI(); NI < NodeList.EndI(); NI++){ int outdeg = Graph->GetNI(NI.GetKey()).GetOutDeg(); int indeg = Graph->GetNI(NI.GetKey()).GetInDeg(); if (outdeg>1 && indeg>0){ double val = (1-(1/(double)outdeg))/(double)indeg; for(int i=0; i<(outdeg+indeg);i++){ int NId = Graph->GetNI(NI.GetKey()).GetNbrNId(i); if (Graph->GetNI(NI.GetKey()).IsInNId(NId) == true){ NodeList.AddDat(NId,NodeList.GetDat(NId)+val); } } } } return NodeList; } //Event importance 1 TIntFltH EventImportance1 (const PNGraph& Graph, const int k) { TIntFltH NodeList; // values for nodese for (TNGraph::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++){ NodeList.AddDat(NI.GetId(),NI.GetOutDeg()); } for (THashKeyDatI<TInt,TFlt> NI = NodeList.BegI(); NI < NodeList.EndI(); NI++){ int outdeg = Graph->GetNI(NI.GetKey()).GetOutDeg(); int indeg = Graph->GetNI(NI.GetKey()).GetInDeg(); if (outdeg>1 && indeg>0){ double val = (1-(1/(double)outdeg))/(double)indeg; for(int i=0; i<(outdeg+indeg);i++){ int NId = Graph->GetNI(NI.GetKey()).GetNbrNId(i); if (Graph->GetNI(NI.GetKey()).IsInNId(NId) == true){ NodeList.AddDat(NId,NodeList.GetDat(NId)+val); } } } } return NodeList; } int Intersect(TUNGraph::TNodeI Node, TIntH NNodes){ int br=0; for (int i=0; i<Node.GetDeg(); i++) { if (NNodes.IsKey(Node.GetNbrNId(i))) br++; } if (NNodes.IsKey(Node.GetId())) br++; return br; } int Intersect(TUNGraph::TNodeI Node, TStr NNodes){ int br=0; TInt digi = -1; TStr buf = ""; for (int i=0; i<Node.GetDeg(); i++) { digi = Node.GetNbrNId(i); TStr buf = digi.GetStr(); if (NNodes.IsStrIn(buf.CStr())) br++; } digi = Node.GetId(); buf = digi.GetStr(); if (NNodes.IsStrIn(buf.CStr())) br++; return br; } int Intersect(TUNGraph::TNodeI Node, int *NNodes, int NNodes_br){ int br = 0; int neig; for (int i=0; i<Node.GetDeg(); i++) { neig = Node.GetNbrNId(i); for (int j=0; j<NNodes_br; j++) { if (neig == NNodes[j]) { br++; j = NNodes_br; } } } neig = Node.GetId(); for (int j=0; j<NNodes_br; j++) { if (neig == NNodes[j]) { br++; j = NNodes_br; } } return br; } int Intersect1(TUNGraph::TNodeI Node, TStr NNodes){ int br=0; for (int i=0; i<Node.GetDeg(); i++) { TInt digi = Node.GetNbrNId(i); TStr buf = ""; buf = digi.GetStr(); if (NNodes.SearchStr(buf.CStr())!=-1) br++; } TInt digi = Node.GetId(); TStr buf = digi.GetStr(); if (NNodes.SearchStr(buf.CStr())!=-1) br++; return br; } TIntH LoadNodeList(TStr InFNmNodes){ TSsParser Ss(InFNmNodes, ssfWhiteSep, true, true, true); TIntIntH Nodes; int br = 0, NId; while (Ss.Next()) { if (Ss.GetInt(0, NId)) { Nodes.AddDat(br,NId); br++; } } return Nodes; } int findMinimum(TIntV& Frontier, TIntFltH& NIdDistH) { TFlt minimum = TInt::Mx; int min_index = 0; for (int i = 0; i < Frontier.Len(); i++) { int NId = Frontier.GetVal(i); if (NIdDistH[NId] < minimum) { minimum = NIdDistH[NId]; min_index = i; } } const int NId = Frontier.GetVal(min_index); Frontier.Del(min_index); return NId; } int GetWeightedShortestPath( const PNEANet Graph, const int& SrcNId, TIntFltH& NIdDistH, const TFltV& Attr) { TIntV frontier; NIdDistH.Clr(false); NIdDistH.AddDat(SrcNId, 0); frontier.Add(SrcNId); while (! frontier.Empty()) { const int NId = findMinimum(frontier, NIdDistH); const PNEANet::TObj::TNodeI NodeI = Graph->GetNI(NId); for (int v = 0; v < NodeI.GetOutDeg(); v++) { int DstNId = NodeI.GetOutNId(v); int EId = NodeI.GetOutEId(v); if (! NIdDistH.IsKey(DstNId)) { NIdDistH.AddDat(DstNId, NIdDistH.GetDat(NId) + Attr[EId]); frontier.Add(DstNId); } else { if (NIdDistH[DstNId] > NIdDistH.GetDat(NId) + Attr[EId]) { NIdDistH[DstNId] = NIdDistH.GetDat(NId) + Attr[EId]; } } } } return 0; } double GetWeightedFarnessCentr(const PNEANet Graph, const int& NId, const bool& IsDir, const TFltV& Attr, const bool& Normalized) { TIntFltH NDistH(Graph->GetNodes()); GetWeightedShortestPath(Graph, NId, NDistH, Attr); double sum = 0; for (TIntFltH::TIter I = NDistH.BegI(); I < NDistH.EndI(); I++) { sum += I->Dat(); } if (NDistH.Len() > 1) { double centr = sum/double(NDistH.Len()-1); if (Normalized) { centr *= (Graph->GetNodes() - 1)/double(NDistH.Len()-1); } return centr; } else { return 0.0; } } double GetWeightedClosenessCentr(const PNEANet Graph, const int& NId, const bool& IsDir, const TFltV& Attr, const bool& Normalized) { const double Farness = GetWeightedFarnessCentr(Graph, NId, IsDir, Attr, Normalized); if (Farness != 0.0) { return 1.0/Farness; } else { return 0.0; } return 0.0; } void GetWeightedBetweennessCentr(const PNEANet Graph, const TIntV& BtwNIdV, TIntFltH& NodeBtwH, const bool& IsDir, const bool& DoNodeCent, TIntPrFltH& EdgeBtwH, const bool& DoEdgeCent, const TFltV& Attr) { if (DoNodeCent) { NodeBtwH.Clr(); } if (DoEdgeCent) { EdgeBtwH.Clr(); } const int nodes = Graph->GetNodes(); TIntS S(nodes); TIntQ Q(nodes); TIntIntVH P(nodes); // one vector for every node TIntFltH delta(nodes); TIntFltH sigma(nodes), d(nodes); // init for (PNEANet::TObj::TNodeI NI = Graph->BegNI(); NI < Graph->EndNI(); NI++) { if (DoNodeCent) { NodeBtwH.AddDat(NI.GetId(), 0); } if (DoEdgeCent) { for (int e = 0; e < NI.GetOutDeg(); e++) { if (NI.GetId() < NI.GetOutNId(e)) { EdgeBtwH.AddDat(TIntPr(NI.GetId(), NI.GetOutNId(e)), 0); } } } sigma.AddDat(NI.GetId(), 0); d.AddDat(NI.GetId(), -1); P.AddDat(NI.GetId(), TIntV()); delta.AddDat(NI.GetId(), 0); } // calc betweeness for (int k=0; k < BtwNIdV.Len(); k++) { const PNEANet::TObj::TNodeI NI = Graph->GetNI(BtwNIdV[k]); // reset for (int i = 0; i < sigma.Len(); i++) { sigma[i]=0; d[i]=-1; delta[i]=0; P[i].Clr(false); } S.Clr(false); Q.Clr(false); sigma.AddDat(NI.GetId(), 1); d.AddDat(NI.GetId(), 0); Q.Push(NI.GetId()); while (! Q.Empty()) { const int v = Q.Top(); Q.Pop(); const PNEANet::TObj::TNodeI NI2 = Graph->GetNI(v); S.Push(v); const double VDat = d.GetDat(v); for (int e = 0; e < NI2.GetOutDeg(); e++) { const int w = NI2.GetOutNId(e); const int eid = NI2.GetOutEId(e); if (d.GetDat(w) < 0) { // find w for the first time Q.Push(w); d.AddDat(w, VDat+Attr[eid]); } //shortest path to w via v ? if (d.GetDat(w) == VDat+Attr[eid]) { sigma.AddDat(w) += sigma.GetDat(v); P.GetDat(w).Add(v); } } } while (! S.Empty()) { const int w = S.Top(); const double SigmaW = sigma.GetDat(w); const double DeltaW = delta.GetDat(w); const TIntV NIdV = P.GetDat(w); S.Pop(); for (int i = 0; i < NIdV.Len(); i++) { const int NId = NIdV[i]; const double c = (sigma.GetDat(NId)*1.0/SigmaW) * (1+DeltaW); delta.AddDat(NId) += c; if (DoEdgeCent) { EdgeBtwH.AddDat(TIntPr(TMath::Mn(NId, w), TMath::Mx(NId, w))) += c; } } double factor = (IsDir) ? 1.0 : 2.0; if (DoNodeCent && w != NI.GetId()) { NodeBtwH.AddDat(w) += delta.GetDat(w)/factor; } } } } void GetWeightedBetweennessCentr(const PNEANet Graph, TIntFltH& NodeBtwH, TIntPrFltH& EdgeBtwH, const TFltV& Attr, const bool& IsDir, const double& NodeFrac) { TIntV NIdV; Graph->GetNIdV(NIdV); if (NodeFrac < 1.0) { // calculate beetweenness centrality for a subset of nodes NIdV.Shuffle(TInt::Rnd); for (int i = int((1.0-NodeFrac)*NIdV.Len()); i > 0; i--) { NIdV.DelLast(); } } GetWeightedBetweennessCentr(Graph, NIdV, NodeBtwH, IsDir, true, EdgeBtwH, true, Attr ); } void GetWeightedBetweennessCentr(const PNEANet Graph, TIntFltH& NodeBtwH, const TFltV& Attr, const bool& IsDir, const double& NodeFrac) { TIntPrFltH EdgeBtwH; TIntV NIdV; Graph->GetNIdV(NIdV); if (NodeFrac < 1.0) { // calculate beetweenness centrality for a subset of nodes NIdV.Shuffle(TInt::Rnd); for (int i = int((1.0-NodeFrac)*NIdV.Len()); i > 0; i--) { NIdV.DelLast(); } } GetWeightedBetweennessCentr(Graph, NIdV, NodeBtwH, IsDir, true, EdgeBtwH, false, Attr); } void GetWeightedBetweennessCentr(const PNEANet Graph, TIntPrFltH& EdgeBtwH, const TFltV& Attr, const bool& IsDir, const double& NodeFrac) { TIntFltH NodeBtwH; TIntV NIdV; Graph->GetNIdV(NIdV); if (NodeFrac < 1.0) { // calculate beetweenness centrality for a subset of nodes NIdV.Shuffle(TInt::Rnd); for (int i = int((1.0-NodeFrac)*NIdV.Len()); i > 0; i--) { NIdV.DelLast(); } } GetWeightedBetweennessCentr(Graph, NIdV, NodeBtwH, IsDir, false, EdgeBtwH, true, Attr); } }; // namespace TSnap
35.165509
210
0.453313
dkw-aau
90f393f374347ea6a5f0ca26af15137e11c1348f
3,135
cpp
C++
modules/task_3/oganyan_r_global_search/main.cpp
orcyyy/pp_2020_autumn_engineer-1
14cb1248b8b765a02eaa4c73f06807c250545491
[ "BSD-3-Clause" ]
null
null
null
modules/task_3/oganyan_r_global_search/main.cpp
orcyyy/pp_2020_autumn_engineer-1
14cb1248b8b765a02eaa4c73f06807c250545491
[ "BSD-3-Clause" ]
1
2020-12-27T20:31:37.000Z
2020-12-27T20:31:37.000Z
modules/task_3/oganyan_r_global_search/main.cpp
schelyanskovan/pp_2020_autumn_engineer
2bacf7ccaf3c638044c41068565a693ac4fae828
[ "BSD-3-Clause" ]
1
2021-03-29T10:15:47.000Z
2021-03-29T10:15:47.000Z
// Copyright by Oganyan Robert 2020 #include <gtest/gtest.h> #include <gtest-mpi-listener.hpp> #include <iostream> #include "../../../modules/task_3/oganyan_r_global_search/functions.h" #include "../../../modules/task_3/oganyan_r_global_search/global_search.h" using std::cout; using std::endl; void CreateTest(int num_fun, double x_left, double x_right, double y_left, double y_right, double ans_minimum, dpair ans_pos, int repeat = 200) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); double time_start{MPI_Wtime()}; double res_par{ParallelGlobalSearch(num_fun, x_left, x_right, y_left, y_right)}; double time_par_end{MPI_Wtime()}; auto par_time{time_par_end - time_start}; cout << std::fixed << std::setprecision(10); if (rank == 0) { cout << " Test number: " << num_fun << endl; cout << "-#-#-#-#-#-# Parallel Time: " << par_time << " -#-#-#-#-#-#" << endl; cout << "-#-#-#-#-#-# Parallel Result: " << res_par << " -#-#-#-#-#-#" << endl; time_start = MPI_Wtime(); double res_seq{SequentialGlobalSearch(num_fun, x_left, x_right, y_left, y_right, repeat)}; const double time_end_s{MPI_Wtime()}; cout << "-#-#-#-#-#-# Sequential Time :" << time_end_s - time_start << " -#-#-#-#-#-#" << endl; cout << "-#-#-#-#-#-# Sequential Result :" << res_seq << " -#-#-#-#-#-#" << endl; ASSERT_EQ(1, abs(ans_minimum - res_par) <= 0.15); } } TEST(Parallel_Operations_MPI, Test_first_fun) { const std::function<double(dpair)> func{fun_first}; const std::function<dpair(dpair)> grad{grad_first}; CreateTest(1, -200.0, 200.0, -200.0, 200.0, 0.0, {0.0, 0.0}, 300); } TEST(Parallel_Operations_MPI, Test_second_fun) { const std::function<double(dpair)> func {fun_second}; const std::function<dpair(dpair)> grad { grad_second }; CreateTest(2, -300.0, 300.0, -200.0, 600.0, -2.0, {0.0, 1.0}, 100); } TEST(Parallel_Operations_MPI, Test_third_fun) { const std::function<double(dpair)> func {fun_third}; const std::function<dpair(dpair)> grad { grad_third }; double anss = -8.0 / (2.71828 * 2.71828); CreateTest(3, -10.0, 10.0, -10.0, 10.0, anss, {-4.0, 2.0}); } TEST(Parallel_Operations_MPI, Test_forth_fun) { const std::function<double(dpair)> func {fun_forth}; const std::function<dpair(dpair)> grad { grad_forth }; CreateTest(4, -200.0, 300.0, -200.0, 300.0, -0.125, {1.0, 0.5}, 100); } TEST(Parallel_Operations_MPI, Test_fifth_fun) { const std::function<double(dpair)> func {fun_fifth}; const std::function<dpair(dpair)> grad { grad_fifth }; CreateTest(5, -100.0, 100.0, -200.0, 300.0, 0.0, {3.0, 2.0}); } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); MPI_Init(&argc, &argv); ::testing::AddGlobalTestEnvironment(new GTestMPIListener::MPIEnvironment); ::testing::TestEventListeners& listeners = ::testing::UnitTest::GetInstance()->listeners(); listeners.Release(listeners.default_result_printer()); listeners.Release(listeners.default_xml_generator()); listeners.Append(new GTestMPIListener::MPIMinimalistPrinter); return RUN_ALL_TESTS(); }
37.321429
99
0.652632
orcyyy
90f39cbff051c475bc215a36bb286219abebed96
540
cpp
C++
DeathMask/DeathMask.cpp
demensdeum/Death-Mask
6251bd5b3540adc494f2d8ea387e35479aa7b238
[ "MIT" ]
null
null
null
DeathMask/DeathMask.cpp
demensdeum/Death-Mask
6251bd5b3540adc494f2d8ea387e35479aa7b238
[ "MIT" ]
11
2017-08-12T17:04:34.000Z
2017-10-15T08:27:58.000Z
DeathMask/DeathMask.cpp
demensdeum/Death-Mask
6251bd5b3540adc494f2d8ea387e35479aa7b238
[ "MIT" ]
null
null
null
#include <iostream> #include <memory> #include <DeathMask/src/Controllers/GameController/DMGameController.h> #include <DeathMask/src/Const/DMConstStates.h> using namespace std; int main() { cout << "Death Mask - Cyber Fantasy Adventure in Endless Techno-Maze\nPrepare to die!\n" << endl; #ifdef __EMSCRIPTEN__ try { #endif auto controller = make_shared<DMGameController>(); controller->startGameFromState(DMStateCompanyLogo); #ifdef __EMSCRIPTEN__ } catch (const std::exception &exc) { cout << exc.what(); } #endif }
19.285714
98
0.733333
demensdeum
90f42b30ce2c6d92894acac56640cb4fdc126166
907
cpp
C++
0410-Split Array Largest Sum/0410-Split Array Largest Sum.cpp
zhuangli1987/LeetCode-1
e81788abf9e95e575140f32a58fe983abc97fa4a
[ "MIT" ]
49
2018-05-05T02:53:10.000Z
2022-03-30T12:08:09.000Z
0401-0500/0410-Split Array Largest Sum/0410-Split Array Largest Sum.cpp
jolly-fellow/LeetCode
ab20b3ec137ed05fad1edda1c30db04ab355486f
[ "MIT" ]
11
2017-12-15T22:31:44.000Z
2020-10-02T12:42:49.000Z
0401-0500/0410-Split Array Largest Sum/0410-Split Array Largest Sum.cpp
jolly-fellow/LeetCode
ab20b3ec137ed05fad1edda1c30db04ab355486f
[ "MIT" ]
28
2017-12-05T10:56:51.000Z
2022-01-26T18:18:27.000Z
class Solution { public: int splitArray(vector<int>& nums, int m) { int start = nums[0], end = 0; for (int num : nums) { start = max(start, num); end += num; } while (start < end) { int mid = start + (end - start) / 2; if (doable(nums, mid, m)) { end = mid; } else { start = mid + 1; } } return start; } private: bool doable(vector<int>& nums, int target, int m) { int sum = 0; int count = 1; for (int num : nums) { if (sum + num > target) { sum = num; if (++count > m) { return false; } } else { sum += num; } } return true; } };
21.595238
55
0.342889
zhuangli1987
90f48bfbae987cbc20421d1ad70fed346527945d
37,683
cpp
C++
src/prod/src/Hosting2/FabricUpgradeImpl.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
1
2020-06-15T04:33:36.000Z
2020-06-15T04:33:36.000Z
src/prod/src/Hosting2/FabricUpgradeImpl.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
null
null
null
src/prod/src/Hosting2/FabricUpgradeImpl.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
null
null
null
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" #include "Common/FabricGlobals.h" using namespace std; using namespace Common; using namespace ServiceModel; using namespace Hosting2; using namespace Management; using namespace ImageModel; StringLiteral const TraceType("FabricUpgradeImpl"); class FabricUpgradeImpl::ValidateFabricUpgradeAsyncOperation : public AsyncOperation, protected TextTraceComponent<TraceTaskCodes::Hosting> { DENY_COPY(ValidateFabricUpgradeAsyncOperation) public: ValidateFabricUpgradeAsyncOperation( FabricUpgradeImpl & owner, FabricVersionInstance const & currentFabricVersionInstance, FabricUpgradeSpecification const & fabricUpgradeSpec, AsyncCallback const & callback, AsyncOperationSPtr const & parent) : AsyncOperation(callback, parent), owner_(owner), currentFabricVersionInstance_(currentFabricVersionInstance), fabricUpgradeSpec_(fabricUpgradeSpec), shouldRestartReplica_(false), fabricDeployerProcessWait_(), fabricDeployerProcessHandle_() { } virtual ~ValidateFabricUpgradeAsyncOperation() { } static ErrorCode End( __out bool & shouldRestartReplica, AsyncOperationSPtr const & operation) { auto thisPtr = AsyncOperation::End<ValidateFabricUpgradeAsyncOperation>(operation); shouldRestartReplica = thisPtr->shouldRestartReplica_; return thisPtr->Error; } protected: virtual void OnStart(AsyncOperationSPtr const & thisSPtr) { WriteNoise( TraceType, owner_.Root.TraceId, "ValidateAndAnalyzeFabricUpgradeImpl: CurrentVersion: {0}, TargetVersion: {1}", currentFabricVersionInstance_, FabricVersionInstance(fabricUpgradeSpec_.Version, fabricUpgradeSpec_.InstanceId)); if(currentFabricVersionInstance_.Version.CodeVersion != fabricUpgradeSpec_.Version.CodeVersion) { shouldRestartReplica_ = true; TryComplete(thisSPtr, ErrorCodeValue::Success); return; } if(currentFabricVersionInstance_.Version.ConfigVersion != fabricUpgradeSpec_.Version.ConfigVersion) { HandleUPtr fabricDeployerThreadHandle; wstring tempOutputFile = File::GetTempFileNameW(owner_.hosting_.NodeWorkFolder); wstring tempErrorFile = File::GetTempFileNameW(owner_.hosting_.NodeWorkFolder); wstring commandLineArguments = wformatString( Constants::FabricDeployer::ValidateAndAnalyzeArguments, owner_.fabricUpgradeRunLayout_.GetClusterManifestFile(fabricUpgradeSpec_.Version.ConfigVersion.ToString()), owner_.hosting_.NodeName, owner_.hosting_.NodeType, tempOutputFile, tempErrorFile); WriteInfo( TraceType, owner_.Root.TraceId, "ValidateAndAnalyzeFabricUpgradeImpl: FabricDeployerProcess called with {0}", commandLineArguments); wstring deployerPath = Path::Combine(Environment::GetExecutablePath(), Constants::FabricDeployer::ExeName); vector<wchar_t> envBlock(0); #if defined(PLATFORM_UNIX) // Environment map is only needed in linux since the environment is not // passed in by default in linux EnvironmentMap environmentMap; auto getEnvResult = Environment::GetEnvironmentMap(environmentMap); auto createEnvError = ProcessUtility::CreateDefaultEnvironmentBlock(envBlock); if (!createEnvError.IsSuccess()) { WriteWarning( TraceType, owner_.Root.TraceId, "Failed to create EnvironmentBlock for ValidateFabricUpgradeAsyncOperation due to {0}", createEnvError); TryComplete(thisSPtr, createEnvError); return; } #endif pid_t pid = 0; auto error = ProcessUtility::CreateProcessW( ProcessUtility::GetCommandLine(deployerPath, commandLineArguments), L"", envBlock, DETACHED_PROCESS /* Do not inherit console */, fabricDeployerProcessHandle_, fabricDeployerThreadHandle, pid); if (!error.IsSuccess()) { WriteWarning( TraceType, owner_.Root.TraceId, "ValidateAndAnalyzeFabricUpgradeImpl: Create FabricDeployerProcess failed with {0}", error); TryComplete(thisSPtr, error); return; } fabricDeployerProcessWait_ = ProcessWait::CreateAndStart( Handle(fabricDeployerProcessHandle_->Value, Handle::DUPLICATE()), pid, [this, thisSPtr, tempOutputFile, tempErrorFile](pid_t, ErrorCode const & waitResult, DWORD exitCode) { OnFabricDeployerProcessTerminated(thisSPtr, waitResult, exitCode, tempOutputFile, tempErrorFile); }); } else { TryComplete(thisSPtr, ErrorCodeValue::Success); return; } } void OnFabricDeployerProcessTerminated( AsyncOperationSPtr const & thisSPtr, Common::ErrorCode const & waitResult, DWORD fabricDeployerExitCode, wstring const & tempOutputFile, wstring const & tempErrorFile) { if(!waitResult.IsSuccess()) { TryComplete(thisSPtr, waitResult); return; } // Exit Code 1(256) and 2(512) is used by deployer currently to indicate whether restart is required or not // Exit Code 2 is restart not required and treated as success. On windows the exit code can go below 0 but // on linux it does not so basically anything other than 0, 1(256) or 2(512) is an error and we try to read the error file ErrorCode error; if (fabricDeployerExitCode != 0 && fabricDeployerExitCode != Constants::FabricDeployer::ExitCode_RestartRequired && fabricDeployerExitCode != Constants::FabricDeployer::ExitCode_RestartNotRequired) { wstring fileContent; error = owner_.ReadFabricDeployerTempFile(tempErrorFile, fileContent); if(error.IsSuccess()) { error = ErrorCode(ErrorCodeValue::FabricNotUpgrading, move(fileContent)); } else { WriteWarning( TraceType, owner_.Root.TraceId, "CheckIfRestartRequired: Could not read error file: {0}", tempErrorFile); } } WriteTrace( error.ToLogLevel(), TraceType, owner_.Root.TraceId, "ValidateAndAnalyzeFabricUpgradeImpl: FabricDeployer process terminated. CurrentVersion: {0}, TargetVersion: {1}. ExitCode:{2}. Error: {3}.", currentFabricVersionInstance_, FabricVersionInstance(fabricUpgradeSpec_.Version, fabricUpgradeSpec_.InstanceId), fabricDeployerExitCode, error); if(!error.IsSuccess()) { TryComplete(thisSPtr, error); return; } ASSERT_IF( Constants::FabricDeployer::ExitCode_RestartRequired == fabricDeployerExitCode && !File::Exists(tempOutputFile), "The output file should be generated by deployer when exit code is ExitCode_RestartRequired. File:{0}", tempOutputFile); bool staticParameterModified = false; if(Constants::FabricDeployer::ExitCode_RestartRequired == fabricDeployerExitCode) { error = CheckIfRestartRequired(tempOutputFile, staticParameterModified); WriteTrace( error.ToLogLevel(), TraceType, owner_.Root.TraceId, "CheckIfRestartRequired returned {0}. CurrentVersion: {1}, TargetVersion: {2}.", error, currentFabricVersionInstance_, FabricVersionInstance(fabricUpgradeSpec_.Version, fabricUpgradeSpec_.InstanceId)); if(!error.IsSuccess()) { TryComplete(thisSPtr, error); return; } } if(staticParameterModified || fabricUpgradeSpec_.UpgradeType == UpgradeType::Rolling_ForceRestart) { this->shouldRestartReplica_ = true; } TryComplete(thisSPtr, ErrorCodeValue::Success); } ErrorCode CheckIfRestartRequired(wstring const & validateOutputFileName, __out bool & staticParameterModified) { staticParameterModified = false; wstring fileContent; auto error = owner_.ReadFabricDeployerTempFile(validateOutputFileName, fileContent); if(!error.IsSuccess()) { WriteWarning( TraceType, owner_.Root.TraceId, "CheckIfRestartRequired: Could not read output file: {0}", validateOutputFileName); return error; } vector<wstring> tokens; #ifdef PLATFORM_UNIX StringUtility::SplitOnString<wstring>(StringUtility::ToWString(fileContent), tokens, L"\n", false); #else StringUtility::SplitOnString<wstring>(StringUtility::ToWString(fileContent), tokens, L"\r\n", false); #endif ASSERT_IF(tokens.size() == 0 || tokens.size() % 4 != 0, "The fileContent is invalid : {0}", fileContent); int index = 0; do { wstring section = tokens[index++]; wstring key = tokens[index++]; wstring value = tokens[index++]; bool isEncrypted = StringUtility::AreEqualCaseInsensitive(tokens[index++], L"true"); auto configStore = FabricGlobals::Get().GetConfigStore().Store; bool canUpgradeWithoutRestart = configStore->CheckUpdate( section, key, value, isEncrypted); WriteInfo( TraceType, owner_.Root.TraceId, "CheckIfRestartRequired: Section:{0}, Key:{1}, CanUpgradeWithoutRestart:{2}.", section, key, canUpgradeWithoutRestart); if(!canUpgradeWithoutRestart) { staticParameterModified = true; break; } } while(index < tokens.size()); return error; } virtual void OnCancel() { fabricDeployerProcessWait_->Cancel(); ErrorCode error; if(!::TerminateProcess(fabricDeployerProcessHandle_->Value, ProcessActivator::ProcessAbortExitCode)) { error = ErrorCode::FromWin32Error(); } WriteTrace( error.IsSuccess() ? LogLevel::Info : LogLevel::Warning, TraceType, owner_.Root.TraceId, "ValidateFabircUpgradeAsyncOperation OnCancel TerminateProcess: ErrorCode={0}", error); } private: FabricUpgradeImpl & owner_; FabricVersionInstance const currentFabricVersionInstance_; FabricUpgradeSpecification const fabricUpgradeSpec_; bool shouldRestartReplica_; ProcessWaitSPtr fabricDeployerProcessWait_; HandleUPtr fabricDeployerProcessHandle_; }; class FabricUpgradeImpl::FabricUpgradeAsyncOperation : public AsyncOperation, protected TextTraceComponent<TraceTaskCodes::Hosting> { DENY_COPY(FabricUpgradeAsyncOperation) public: FabricUpgradeAsyncOperation( FabricUpgradeImpl & owner, FabricVersionInstance const & currentFabricVersionInstance, FabricUpgradeSpecification const & fabricUpgradeSpec, AsyncCallback const & callback, AsyncOperationSPtr const & parent) : AsyncOperation(callback, parent), owner_(owner), currentFabricVersionInstance_(currentFabricVersionInstance), fabricUpgradeSpec_(fabricUpgradeSpec), timeoutHelper_(HostingConfig::GetConfig().FabricUpgradeTimeout) { } virtual ~FabricUpgradeAsyncOperation() { } static ErrorCode End(AsyncOperationSPtr const & operation) { auto thisPtr = AsyncOperation::End<FabricUpgradeAsyncOperation>(operation); return thisPtr->Error; } protected: virtual void OnStart(AsyncOperationSPtr const & thisSPtr) { bool hasCodeChanged = (currentFabricVersionInstance_.Version.CodeVersion != fabricUpgradeSpec_.Version.CodeVersion); bool hasConfigChanged = (currentFabricVersionInstance_.Version.ConfigVersion != fabricUpgradeSpec_.Version.ConfigVersion); bool hasInstanceIdChanged = (currentFabricVersionInstance_.InstanceId != fabricUpgradeSpec_.InstanceId); WriteInfo( TraceType, owner_.Root.TraceId, "FabricUpgradeImpl: CurrentVersion: {0}, TargetVersion: {1}", currentFabricVersionInstance_, FabricVersionInstance(fabricUpgradeSpec_.Version, fabricUpgradeSpec_.InstanceId)); if(hasCodeChanged) { this->CodeUpgrade(thisSPtr); } else if(hasConfigChanged) { this->ConfigUpgrade(thisSPtr, false /*instanceIdOnlyUpgrade*/); } else if(hasInstanceIdChanged) { this->ConfigUpgrade(thisSPtr, true /*instanceIdOnlyUpgrade*/); } else { TryComplete(thisSPtr, ErrorCodeValue::FabricAlreadyInTargetVersion); return; } } virtual void OnCancel() { AsyncOperation::Cancel(); } void CodeUpgrade(AsyncOperationSPtr const & thisSPtr) { wstring dataRoot, logRoot; auto error = FabricEnvironment::GetFabricDataRoot(dataRoot); if(!error.IsSuccess()) { WriteInfo( TraceType, owner_.Root.TraceId, "Error getting FabricDataRoot. Error:{0}", error); TryComplete(thisSPtr, error); return; } error = FabricEnvironment::GetFabricLogRoot(logRoot); if(!error.IsSuccess()) { WriteInfo( TraceType, owner_.Root.TraceId, "Error getting FabricLogRoot. Error:{0}", error); TryComplete(thisSPtr, error); return; } FabricDeploymentSpecification fabricDeploymentSpec(dataRoot, logRoot); // Write the installer script only if the target code package is a MSI or Cab File bool useFabricInstallerService = false; bool isCabFilePresent = false; wstring installerFilePath = owner_.fabricUpgradeRunLayout_.GetPatchFile(fabricUpgradeSpec_.Version.CodeVersion.ToString()); bool isInstallerFilePresent = File::Exists(installerFilePath); wstring downloadedFabricPackage(L""); if (isInstallerFilePresent) { #if defined(PLATFORM_UNIX) downloadedFabricPackage = move(installerFilePath); #else DWORD useFabricInstallerSvc; RegistryKey regKey(FabricConstants::FabricRegistryKeyPath, true, true); if (regKey.IsValid && regKey.GetValue(FabricConstants::UseFabricInstallerSvcKeyName, useFabricInstallerSvc) && useFabricInstallerSvc == 1UL) { downloadedFabricPackage = move(installerFilePath); useFabricInstallerService = true; WriteInfo( TraceType, owner_.Root.TraceId, "Hosting CodeUpgrade MSI path using FabricInstallerSvc. MSI: {0}", downloadedFabricPackage); } #endif } else { downloadedFabricPackage = move(owner_.fabricUpgradeRunLayout_.GetCabPatchFile(fabricUpgradeSpec_.Version.CodeVersion.ToString())); isCabFilePresent = File::Exists(downloadedFabricPackage); if (isCabFilePresent) { bool containsWUfile = false; int errorCode = CabOperations::ContainsFile(downloadedFabricPackage, *Constants::FabricUpgrade::FabricWindowsUpdateContainedFile, containsWUfile); if (errorCode != S_OK) { error = ErrorCode::FromWin32Error(errorCode); WriteTrace( error.ToLogLevel(), TraceType, owner_.Root.TraceId, "CabOperations::ContainsFile : Error:{0}", error); TryComplete(thisSPtr, error); return; } useFabricInstallerService = !containsWUfile; // WU file identifies package as incompatible with FabricInstallerSvc } else { // Directory package no longer supported WriteError(TraceType, "CodeUpgrade did not find CAB/MSI package for the given version."); TryComplete(thisSPtr, ErrorCode(ErrorCodeValue::InvalidArgument)); return; } } wstring installationScriptFilePath(L""); if (useFabricInstallerService) { // If Fabric installer service is running, wait till it stops //LINUXTODO #if !defined(PLATFORM_UNIX) ServiceController sc(Constants::FabricUpgrade::FabricInstallerServiceName); error = sc.WaitForServiceStop(timeoutHelper_.GetRemainingTime()); if (!error.IsSuccess() && !error.IsWin32Error(ERROR_SERVICE_DOES_NOT_EXIST)) { WriteWarning( TraceType, owner_.Root.TraceId, "Error {0} while waiting for Fabric installer service to stop", error); TryComplete(thisSPtr, error); return; } #endif } else { installationScriptFilePath = fabricDeploymentSpec.GetInstallerScriptFile(owner_.hosting_.NodeName); wstring installationLogFilePath = fabricDeploymentSpec.GetInstallerLogFile(owner_.hosting_.NodeName, fabricUpgradeSpec_.Version.CodeVersion.ToString()); error = WriteInstallationScriptFile(installationScriptFilePath, installationLogFilePath, isCabFilePresent); WriteTrace( error.ToLogLevel(), TraceType, owner_.Root.TraceId, "WriteInstallationScriptFile : Error:{0}", error); if (!error.IsSuccess()) { TryComplete(thisSPtr, error); return; } } wstring targetInformationFilePath = fabricDeploymentSpec.GetTargetInformationFile(); error = WriteTargetInformationFile(targetInformationFilePath, downloadedFabricPackage, useFabricInstallerService); WriteTrace( error.ToLogLevel(), TraceType, owner_.Root.TraceId, "WriteTargetInformationFile : Error:{0}", error); if (!error.IsSuccess()) { TryComplete(thisSPtr, error); return; } #if defined(PLATFORM_UNIX) wstring upgradeArgs = targetInformationFilePath;/* arguments */ #else wstring upgradeArgs = L"" /* arguments */; #endif if (!useFabricInstallerService) { WriteNoise( TraceType, owner_.Root.TraceId, "Begin(FabricActivatorClient FabricUpgrade): InstallationScript:{0}", installationScriptFilePath); } auto operation = owner_.hosting_.FabricActivatorClientObj->BeginFabricUpgrade( useFabricInstallerService, installationScriptFilePath, upgradeArgs /* arguments */, downloadedFabricPackage, [this, useFabricInstallerService](AsyncOperationSPtr const & operation) { this->FinishCodeUpgrade(operation, useFabricInstallerService, false); }, thisSPtr); FinishCodeUpgrade(operation, useFabricInstallerService, true); } void FinishCodeUpgrade(AsyncOperationSPtr const & operation, bool useFabricInstallerService, bool expectedCompletedSynhronously) { if (operation->CompletedSynchronously != expectedCompletedSynhronously) { return; } auto error = owner_.hosting_.FabricActivatorClientObj->EndFabricUpgrade(operation); // The assert is only valid if the upgrade was done using a MSI. if (!useFabricInstallerService) { ASSERT_IF(error.IsSuccess(), "The FabricUpgrade call for code should return only with failure. In case of success, the host will be killed."); } WriteTrace( error.ToLogLevel(), TraceType, owner_.Root.TraceId, "End(FabricActivatorClient FabricUpgrade): {0}", error); TryComplete(operation->Parent, error); } ErrorCode WriteTargetInformationFile(wstring const & targetInformationFilePath, wstring const & targetPackagePath, bool) { wstring currentInstallationElement(L""); wstring currentClusterManifestFile = move(owner_.fabricUpgradeRunLayout_.GetClusterManifestFile(currentFabricVersionInstance_.Version.ConfigVersion.ToString())); bool isCurrentMsi = false; bool isCurrentCab = false; bool isWindowsUpdate = false; // If the current version files are not provisioned Rollback will not be supported // Current Installation element is set only if both the cluster manifest and MSI/CodePackage are present if (File::Exists(currentClusterManifestFile)) { wstring currentCodeVersion = move(currentFabricVersionInstance_.Version.CodeVersion.ToString()); wstring currentMsiPackagePath = move(owner_.fabricUpgradeRunLayout_.GetPatchFile(currentCodeVersion)); wstring currentCabPackagePath = move(owner_.fabricUpgradeRunLayout_.GetCabPatchFile(currentCodeVersion)); wstring currentPackagePath(L""); if (File::Exists(currentMsiPackagePath)) { currentPackagePath = currentMsiPackagePath; isCurrentMsi = true; } else if (File::Exists(currentCabPackagePath)) { currentPackagePath = currentCabPackagePath; isCurrentCab = true; } // If !isCurrentCab && !isCurrentMsi then we skip writing CurrentInstallation for TargetInformationFile if (isCurrentCab) { int errorCode = CabOperations::ContainsFile(currentPackagePath, *Constants::FabricUpgrade::FabricWindowsUpdateContainedFile, isWindowsUpdate); if (errorCode != S_OK) { auto error = ErrorCode::FromWin32Error(errorCode); WriteTrace( error.ToLogLevel(), TraceType, owner_.Root.TraceId, "WriteTargetInformationFile CabOperations::ContainsFile : Error:{0}", error); return error; } if (!isWindowsUpdate) { // Current code package exists and is a XCOPY package currentInstallationElement = wformatString( Constants::FabricUpgrade::CurrentInstallationElementForXCopy, currentFabricVersionInstance_.InstanceId, currentFabricVersionInstance_.Version.CodeVersion.ToString(), currentClusterManifestFile, currentPackagePath, owner_.hosting_.NodeName, Constants::FabricSetup::ExeName, Constants::FabricSetup::UpgradeArguments, Constants::FabricSetup::ExeName, Constants::FabricSetup::UndoUpgradeArguments); } } if (isCurrentMsi || isWindowsUpdate) { currentInstallationElement = wformatString( Constants::FabricUpgrade::CurrentInstallationElement, currentFabricVersionInstance_.InstanceId, currentFabricVersionInstance_.Version.CodeVersion.ToString(), currentClusterManifestFile, currentPackagePath, owner_.hosting_.NodeName); } if (currentInstallationElement == L"") { WriteWarning(TraceType, "WriteTargetInformationFile did not find CAB/MSI package for the given version. Skip writing CurrentInstallation element."); } } wstring targetInstallationElement(L""); wstring targetCodeVersion = fabricUpgradeSpec_.Version.CodeVersion.ToString(); if (!isWindowsUpdate && Path::GetExtension(targetPackagePath) == L".cab") { // Target code package is a XCOPY package targetInstallationElement = wformatString( Constants::FabricUpgrade::TargetInstallationElementForXCopy, fabricUpgradeSpec_.InstanceId, fabricUpgradeSpec_.Version.CodeVersion.ToString(), owner_.fabricUpgradeRunLayout_.GetClusterManifestFile(fabricUpgradeSpec_.Version.ConfigVersion.ToString()), targetPackagePath, owner_.hosting_.NodeName, Constants::FabricSetup::ExeName, Constants::FabricSetup::UpgradeArguments, Constants::FabricSetup::ExeName, Constants::FabricSetup::UndoUpgradeArguments); } else { targetInstallationElement = wformatString( Constants::FabricUpgrade::TargetInstallationElement, fabricUpgradeSpec_.InstanceId, fabricUpgradeSpec_.Version.CodeVersion.ToString(), owner_.fabricUpgradeRunLayout_.GetClusterManifestFile(fabricUpgradeSpec_.Version.ConfigVersion.ToString()), targetPackagePath, owner_.hosting_.NodeName); } #if defined(PLATFORM_UNIX) wstring targetInformationContentUtf16 = wformatString( Constants::FabricUpgrade::TargetInformationXmlContent, currentInstallationElement, targetInstallationElement); string targetInformationContent = StringUtility::Utf16ToUtf8(targetInformationContentUtf16); #else wstring targetInformationContent = wformatString( Constants::FabricUpgrade::TargetInformationXmlContent, currentInstallationElement, targetInstallationElement); #endif FileWriter fileWriter; auto error = fileWriter.TryOpen(targetInformationFilePath); if(!error.IsSuccess()) { return error; } #if defined(PLATFORM_UNIX) fileWriter.WriteAsciiBuffer(targetInformationContent.c_str(), targetInformationContent.size()); #else fileWriter.WriteUnicodeBuffer(targetInformationContent.c_str(), targetInformationContent.size()); #endif fileWriter.Close(); return ErrorCodeValue::Success; } ErrorCode WriteInstallationScriptFile(wstring const & installationScriptFilePath, wstring const & installationLogFilePath, bool const & useCabFile) { if (File::Exists(installationScriptFilePath)) { File::Delete2(installationScriptFilePath).ReadValue(); } #if defined(PLATFORM_UNIX) wstring installerFile = Path::Combine(Environment::GetExecutablePath(), Constants::FabricUpgrade::LinuxPackageInstallerScriptFileName); return File::Copy(installerFile, installationScriptFilePath); #else FileWriter fileWriter; auto error = fileWriter.TryOpen(installationScriptFilePath); if(!error.IsSuccess()) { return error; } wstring installCommand = L""; wstring execCommand = L""; if (useCabFile) { wstring currentFabricCodeVersion = currentFabricVersionInstance_.Version.CodeVersion.ToString(); wstring upgradeCodeVersion = fabricUpgradeSpec_.Version.CodeVersion.ToString(); string stopFabricHostSvcAnsi; StringUtility::UnicodeToAnsi(*Constants::FabricUpgrade::StopFabricHostServiceCommand, stopFabricHostSvcAnsi); fileWriter.WriteLine(stopFabricHostSvcAnsi); if (currentFabricCodeVersion > upgradeCodeVersion) { installCommand = wformatString( Constants::FabricUpgrade::DISMExecUnInstallCommand, owner_.fabricUpgradeRunLayout_.GetCabPatchFile(currentFabricCodeVersion), installationLogFilePath); } else { installCommand = wformatString( Constants::FabricUpgrade::DISMExecCommand, owner_.fabricUpgradeRunLayout_.GetCabPatchFile(upgradeCodeVersion), installationLogFilePath); } } else { installCommand = wformatString( Constants::FabricUpgrade::MSIExecCommand, owner_.fabricUpgradeRunLayout_.GetPatchFile(fabricUpgradeSpec_.Version.CodeVersion.ToString()), installationLogFilePath); } string installCommandAnsi; StringUtility::UnicodeToAnsi(installCommand, installCommandAnsi); string startFabricHostSvcAnsi; StringUtility::UnicodeToAnsi(*Constants::FabricUpgrade::StartFabricHostServiceCommand, startFabricHostSvcAnsi); fileWriter.WriteLine(installCommandAnsi); fileWriter.WriteLine(startFabricHostSvcAnsi); fileWriter.Close(); return ErrorCodeValue::Success; #endif } void ConfigUpgrade(AsyncOperationSPtr const & thisSPtr, bool instanceIdOnlyUpgrade) { wstring tempErrorFile = File::GetTempFileNameW(owner_.hosting_.NodeWorkFolder); wstring pathToClusterManifest = owner_.fabricUpgradeRunLayout_.GetClusterManifestFile(fabricUpgradeSpec_.Version.ConfigVersion.ToString()); wstring upgradeArgument; if(instanceIdOnlyUpgrade) { upgradeArgument = wformatString( Constants::FabricDeployer::InstanceIdOnlyUpgradeArguments, fabricUpgradeSpec_.Version.CodeVersion.ToString(), fabricUpgradeSpec_.InstanceId, owner_.hosting_.NodeName, tempErrorFile); } else { upgradeArgument = wformatString( Constants::FabricDeployer::ConfigUpgradeArguments, pathToClusterManifest, fabricUpgradeSpec_.Version.CodeVersion.ToString(), fabricUpgradeSpec_.InstanceId, owner_.hosting_.NodeName, tempErrorFile); } wstring deployerPath = Path::Combine(Environment::GetExecutablePath(), Constants::FabricDeployer::ExeName); WriteInfo( TraceType, owner_.Root.TraceId, "Begin(FabricActivatorClient FabricUpgrade): Program:{0}, Arguments:{1}", deployerPath, upgradeArgument); auto operation = owner_.hosting_.FabricActivatorClientObj->BeginFabricUpgrade( false, deployerPath, upgradeArgument, L"", [this, tempErrorFile](AsyncOperationSPtr const & operation) { this->FinishConfigUpgrade(operation, false, tempErrorFile); }, thisSPtr); FinishConfigUpgrade(operation, true, tempErrorFile); } void FinishConfigUpgrade(AsyncOperationSPtr const & operation, bool expectedCompletedSynhronously, wstring const & tempErrorFile) { if (operation->CompletedSynchronously != expectedCompletedSynhronously) { return; } auto error = owner_.hosting_.FabricActivatorClientObj->EndFabricUpgrade(operation); if(!error.IsSuccess()) { wstring fileContent; auto fileReadError = owner_.ReadFabricDeployerTempFile(tempErrorFile, fileContent); if(fileReadError.IsSuccess()) { error = ErrorCode(error.ReadValue(), move(fileContent)); } else { WriteInfo(TraceType, owner_.Root.TraceId, "End(FabricActivatorClient FabricUpgrade): Could not read FabricDeployer error file."); } } WriteTrace( error.ToLogLevel(), TraceType, owner_.Root.TraceId, "End(FabricActivatorClient FabricUpgrade): {0}", error); TryComplete(operation->Parent, error); } private: FabricUpgradeImpl & owner_; FabricVersionInstance const currentFabricVersionInstance_; FabricUpgradeSpecification const fabricUpgradeSpec_; TimeoutHelper timeoutHelper_; }; FabricUpgradeImpl::FabricUpgradeImpl( ComponentRoot const & root, __in HostingSubsystem & hosting) : RootedObject(root), hosting_(hosting), fabricUpgradeRunLayout_(hosting.FabricUpgradeDeploymentFolder) { } FabricUpgradeImpl::~FabricUpgradeImpl() { } AsyncOperationSPtr FabricUpgradeImpl::BeginDownload( FabricVersion const & fabricVersion, AsyncCallback const & callback, AsyncOperationSPtr const & parent) { return this->hosting_.DownloadManagerObj->BeginDownloadFabricUpgradePackage( fabricVersion, callback, parent); } ErrorCode FabricUpgradeImpl::EndDownload( AsyncOperationSPtr const & operation) { return this->hosting_.DownloadManagerObj->EndDownloadFabricUpgradePackage(operation); } AsyncOperationSPtr FabricUpgradeImpl::BeginValidateAndAnalyze( FabricVersionInstance const & currentFabricVersionInstance, FabricUpgradeSpecification const & fabricUpgradeSpec, AsyncCallback const & callback, Common::AsyncOperationSPtr const & parent) { return AsyncOperation::CreateAndStart<ValidateFabricUpgradeAsyncOperation>( *this, currentFabricVersionInstance, fabricUpgradeSpec, callback, parent); } ErrorCode FabricUpgradeImpl::EndValidateAndAnalyze( __out bool & shouldCloseReplica, AsyncOperationSPtr const & operation) { return ValidateFabricUpgradeAsyncOperation::End(shouldCloseReplica, operation); } AsyncOperationSPtr FabricUpgradeImpl::BeginUpgrade( FabricVersionInstance const & currentFabricVersionInstance, FabricUpgradeSpecification const & fabricUpgradeSpec, AsyncCallback const & callback, AsyncOperationSPtr const & parent) { return AsyncOperation::CreateAndStart<FabricUpgradeAsyncOperation>( *this, currentFabricVersionInstance, fabricUpgradeSpec, callback, parent); } ErrorCode FabricUpgradeImpl::EndUpgrade( AsyncOperationSPtr const & operation) { return FabricUpgradeAsyncOperation::End(operation); } ErrorCode FabricUpgradeImpl::ReadFabricDeployerTempFile(std::wstring const & filePath, std::wstring & fileContent) { File file; auto error = file.TryOpen( filePath, FileMode::Open, FileAccess::Read, FileShare::Read); if (!error.IsSuccess()) { TraceWarning( TraceTaskCodes::Hosting, TraceType, Root.TraceId, "Failed to open file '{0}'. Error: {1}", filePath, error); return ErrorCode(error.ReadValue(), StringResource::Get(IDS_HOSTING_FabricDeployed_Output_Read_Failed)); } int bytesRead = 0; int fileSize = static_cast<int>(file.size()); vector<byte> buffer(fileSize); if((bytesRead = file.TryRead(reinterpret_cast<void*>(buffer.data()), fileSize)) > 0) { buffer.push_back(0); buffer.push_back(0); // skip byte-order mark fileContent = wstring(reinterpret_cast<wchar_t *>(&buffer[2])); error = ErrorCodeValue::Success; } else { TraceWarning( TraceTaskCodes::Hosting, TraceType, Root.TraceId, "Failed to read file '{0}'.", filePath); error = ErrorCode(ErrorCodeValue::OperationFailed, StringResource::Get(IDS_HOSTING_FabricDeployed_Output_Read_Failed)); } file.Close2(); File::Delete2(filePath, true /*deleteReadOnlyFiles*/); return error; }
38.256853
220
0.619616
vishnuk007
90f4baba0b86bb00ab5acbc2c492e5f808627a28
12,211
cpp
C++
test/dualtime/dualtimeExpDecayTest.cpp
MaxZZG/ExprLib
c35e361ef6af365e7cd6afca6548595693bd149a
[ "MIT" ]
null
null
null
test/dualtime/dualtimeExpDecayTest.cpp
MaxZZG/ExprLib
c35e361ef6af365e7cd6afca6548595693bd149a
[ "MIT" ]
null
null
null
test/dualtime/dualtimeExpDecayTest.cpp
MaxZZG/ExprLib
c35e361ef6af365e7cd6afca6548595693bd149a
[ "MIT" ]
null
null
null
#include <expression/dualtime/FixedPointBDFDualTimeIntegrator.h> #include <expression/dualtime/VariableImplicitBDFDualTimeIntegrator.h> #include <expression/dualtime/BlockImplicitBDFDualTimeIntegrator.h> #include <spatialops/structured/Grid.h> #include <spatialops/structured/FVStaggered.h> #include <spatialops/structured/FieldComparisons.h> #include <test/TestHelper.h> #include "ExpDecay.h" #include <expression/Functions.h> #include <expression/ExpressionTree.h> #include <expression/ExprPatch.h> #include <expression/matrix-assembly/SparseMatrix.h> #include <expression/matrix-assembly/ScaledIdentityMatrix.h> #include <boost/program_options.hpp> #include <iostream> #include <fstream> using std::cout; using std::endl; namespace po = boost::program_options; namespace so = SpatialOps; typedef so::SVolField FieldT; enum IntegratorType{ FIXED_POINT, VARIABLE_IMPLICIT, BLOCK_IMPLICIT }; #define ASSEMBLER(MatrixT, FieldT, name) \ boost::shared_ptr<MatrixT<FieldT> > name = boost::make_shared<MatrixT<FieldT> >(); bool test( const IntegratorType integratorType ) { /* --------------------------------------------------------------- * domain, operators, field managers, etc setup * --------------------------------------------------------------- */ Expr::ExprPatch patch(1); SpatialOps::OperatorDatabase sodb; Expr::FieldManagerList& fml = patch.field_manager_list(); /* --------------------------------------------------------------- * variable and rhs names, jacobian, preconditioner * --------------------------------------------------------------- */ std::string phiName = "phi"; const Expr::Tag phiTag ( phiName, Expr::STATE_NONE ); const Expr::Tag phiNTag ( phiName, Expr::STATE_N ); const Expr::Tag phiRHSTag( phiName + "_rhs", Expr::STATE_NONE ); /* --------------------------------------------------------------- * build integrator, set constant physical and dual time step * --------------------------------------------------------------- */ const unsigned bdfOrder = 1; boost::shared_ptr<Expr::DualTime::BDFDualTimeIntegrator> integrator; const Expr::Tag dtTag( "timestep" , Expr::STATE_NONE ); const Expr::Tag dsTag( "dual_timestep", Expr::STATE_NONE ); double ds; // dual time step size switch( integratorType ){ case FIXED_POINT:{ ds = 0.01; integrator = boost::make_shared<Expr::DualTime::FixedPointBDFDualTimeIntegrator<FieldT> >( 0, "Fixed Point BDF", dtTag, dsTag, bdfOrder ); break; } case VARIABLE_IMPLICIT:{ ds = 1e16; integrator = boost::make_shared<Expr::DualTime::VariableImplicitBDFDualTimeIntegrator<FieldT> >( 0, "Variable Implicit BDF", dtTag, dsTag, bdfOrder ); break; } case BLOCK_IMPLICIT:{ ds = 1e16; integrator = boost::make_shared<Expr::DualTime::BlockImplicitBDFDualTimeIntegrator<FieldT> >( 0, "Block Implicit BDF", dtTag, dsTag, bdfOrder ); break; } } const double dt = 0.01; typedef Expr::ConstantExpr<so::SingleValueField>::Builder ConstantSingleValueT; integrator->set_physical_time_step_expression( new ConstantSingleValueT( dtTag, dt ) ); integrator->set_dual_time_step_expression ( new ConstantSingleValueT( dsTag, ds ) ); /* --------------------------------------------------------------- * register variables and RHS at STATE_NONE to the integrator * --------------------------------------------------------------- */ Expr::ExpressionFactory& factory = integrator->factory(); const double rateConst = 1.3; factory.register_expression( new ExpDecayRHS<FieldT>::Builder( rateConst, phiRHSTag, phiTag ) ); integrator->add_variable<FieldT>( phiTag.name(), phiRHSTag ); if( integratorType == BLOCK_IMPLICIT ){ // because we have a generic integrator type, we need to cast to block implicit type to continue typedef Expr::DualTime::BlockImplicitBDFDualTimeIntegrator<FieldT> BIType; auto biPtr = boost::dynamic_pointer_cast<BIType>( integrator ); // need to call this before indices can be obtained biPtr->done_adding_variables(); // these are maps from tags to indices std::map<Expr::Tag,int> varIndices = biPtr->variable_tag_index_map(); std::map<Expr::Tag,int> rhsIndices = biPtr->rhs_tag_index_map(); const int phiVarIdx = varIndices[phiTag]; const int phiRhsIdx = rhsIndices[phiRHSTag]; // build an assembler to compute the Jacobian matrix of the rhs to the governed variable ASSEMBLER( Expr::matrix::DenseSubMatrix, FieldT, jacobian ) jacobian->element<FieldT>(phiRhsIdx,phiVarIdx) = Expr::matrix::sensitivity( phiRHSTag, phiTag ); jacobian->finalize(); // need to finalize before using // build an identity matrix preconditioner ASSEMBLER( Expr::matrix::ScaledIdentityMatrix, FieldT, preconditioner ) preconditioner->finalize(); // need to finalize before using // set the Jacobian and preconditioner assemblers biPtr->set_jacobian_and_preconditioner( jacobian, preconditioner ); } /* --------------------------------------------------------------- * final integrator prep, must happen before setting initial conditions, and tree output * --------------------------------------------------------------- */ integrator->prepare_for_integration( fml, sodb, patch.field_info() ); integrator->lock_field<FieldT>( phiNTag ); integrator->lock_all_execution_fields(); integrator->copy_from_initial_condition_to_execution<FieldT>( phiNTag.name() ); { std::ofstream f("dualtimeExpDecayTest-integrator-tree.dot"); integrator->get_tree().write_tree( f ); } /* --------------------------------------------------------------- * set initial conditions with STATE_N * --------------------------------------------------------------- */ Expr::ExpressionFactory icFactory; const double phi0 = 1.0; const Expr::ExpressionID id = icFactory.register_expression( new Expr::ConstantExpr<FieldT>::Builder( phiNTag, phi0 ) ); Expr::ExpressionTree icTree( id, icFactory, patch.id() ); icTree.register_fields( fml ); icTree.bind_fields( fml ); icTree.execute_tree(); /* --------------------------------------------------------------- * set iteration counts, prep solution history file * --------------------------------------------------------------- */ const unsigned maxIterPerStep = 100; unsigned totalIter = 0; unsigned stepCount = 0; unsigned dualIter = 0; bool converged = false; std::ofstream fout("dualtimeExpDecayTest-solution-history.txt"); fout << " t \t c-exact \t c\n"; /* --------------------------------------------------------------- * perform the integration * --------------------------------------------------------------- */ const double tend = 2.0; double t = 0; while( t<tend ){ dualIter = 0; integrator->begin_time_step(); do{ integrator->advance_dualtime( converged ); dualIter++; totalIter++; } while( !converged && dualIter <= maxIterPerStep ); integrator->end_time_step(); stepCount++; t += dt; FieldT& phiN = fml.field_ref<FieldT>(phiNTag); phiN.add_device(CPU_INDEX); fout << std::scientific << std::setprecision(10) << t << "\t" << phi0*exp(-rateConst*t) << "\t" << phiN[0] << std::endl; } fout.close(); /* --------------------------------------------------------------- * process the test * --------------------------------------------------------------- */ TestHelper status(false); if( integratorType != FIXED_POINT ){ status( integrator->get_tree().computes_field( sens_tag( phiRHSTag, phiTag ) ), "Computes d phi_rhs / d phi" ); status( integrator->get_tree().computes_field( sens_tag(phiTag,phiTag) ), "Computes d phi / d phi" ); } const FieldT& phiPredicted = fml.field_ref<FieldT>( phiNTag ); const double phiFromMatlabCode = 0.075528511873306; SpatialOps::SpatFldPtr<FieldT> tmp = SpatialOps::SpatialFieldStore::get<FieldT>( phiPredicted ); *tmp <<= phiFromMatlabCode; status( SpatialOps::field_equal_abs( phiPredicted, *tmp, 1e-6 ), "phi value-check" ); const double meanStepPerIter = ( (double) totalIter ) / ( (double) stepCount ); switch( integratorType ){ case FIXED_POINT:{ const double meanStepPerIterFromMatlabCode = 27; status( std::abs( meanStepPerIter - meanStepPerIterFromMatlabCode ) < 1e-8, "fixed-point convergence rate check" ); break; } case VARIABLE_IMPLICIT:{ const double meanStepPerIterFromMatlabCode = 2; status( std::abs( meanStepPerIter - meanStepPerIterFromMatlabCode ) < 1e-8, "variable-implicit convergence rate check" ); break; } case BLOCK_IMPLICIT:{ const double meanStepPerIterFromMatlabCode = 2; status( std::abs( meanStepPerIter - meanStepPerIterFromMatlabCode ) < 1e-8, "block-implicit convergence rate check" ); break; } } return status.ok(); } int main( int iarg, char* carg[] ) { /* --------------------------------------------------------------- * initialization from command line options * --------------------------------------------------------------- */ bool fixedPoint = false; bool variableImplicit = false; bool blockImplicit = false; { po::options_description desc("Supported Options"); desc.add_options() ( "help", "print help message" ) ( "fixed-point", "Use the fixed point dualtime integration scheme") ( "variable-implicit", "Use the variable implicit dualtime integration scheme") ( "block-implicit", "Use the block implicit dualtime integration scheme");; po::variables_map args; try{ po::store( po::parse_command_line(iarg,carg,desc), args ); po::notify(args); } catch( std::exception& err ){ cout << "\nError parsing command line options.\n\n" << err.what() << "\n\n" << desc << "\n"; return -1; } if( args.count("help") ){ cout << desc << "\n"; return 1; } fixedPoint = args.count("fixed-point"); variableImplicit = args.count("variable-implicit"); blockImplicit = args.count("block-implicit"); if( !fixedPoint && !variableImplicit && !blockImplicit ){ std::cout << "Error: no dualtime integration method selected.\n" << desc << std::endl; return -1; } } try{ TestHelper status( true ); if( fixedPoint ) status( test( FIXED_POINT ), "Fixed Point" ); if( variableImplicit ) status( test( VARIABLE_IMPLICIT ), "Variable Implicit" ); if( blockImplicit ) status( test( BLOCK_IMPLICIT ), "Block Implicit" ); if( status.ok() ){ std::cout << "PASS\n"; return 0; } } catch( std::exception& err ){ std::cout << err.what() << std::endl; } std::cout << "FAIL\n"; return -1; }
37.804954
127
0.534518
MaxZZG
90f55aecb8cea0f565a768b770147bdb8ebb289e
2,583
cpp
C++
dev/test/so_5/environment/reg_coop_after_stop/main.cpp
ZaMaZaN4iK/sobjectizer
afe9fc4d9fac6157860ec4459ac7a129223be87c
[ "BSD-3-Clause" ]
272
2019-05-16T11:45:54.000Z
2022-03-28T09:32:14.000Z
dev/test/so_5/environment/reg_coop_after_stop/main.cpp
ZaMaZaN4iK/sobjectizer
afe9fc4d9fac6157860ec4459ac7a129223be87c
[ "BSD-3-Clause" ]
40
2019-10-29T18:19:18.000Z
2022-03-30T09:02:49.000Z
dev/test/so_5/environment/reg_coop_after_stop/main.cpp
ZaMaZaN4iK/sobjectizer
afe9fc4d9fac6157860ec4459ac7a129223be87c
[ "BSD-3-Clause" ]
29
2019-05-16T12:05:32.000Z
2022-03-19T12:28:33.000Z
/* * A test for checking autoshutdown during execution of init function. */ #include <iostream> #include <map> #include <exception> #include <stdexcept> #include <cstdlib> #include <thread> #include <chrono> #include <sstream> #include <mutex> #include <so_5/all.hpp> #include <test/3rd_party/various_helpers/time_limited_execution.hpp> class log_t { public : void append( const std::string & what ) { std::lock_guard< std::mutex > l( m_lock ); m_value += what; } std::string get() { std::lock_guard< std::mutex > l( m_lock ); return m_value; } private : std::mutex m_lock; std::string m_value; }; class a_second_t : public so_5::agent_t { struct msg_timer : public so_5::signal_t {}; public : a_second_t( so_5::environment_t & env, log_t & log ) : so_5::agent_t( env ) , m_log( log ) {} virtual void so_evt_start() override { m_log.append( "s.start;" ); std::this_thread::sleep_for( std::chrono::milliseconds( 200 ) ); } virtual void so_evt_finish() override { m_log.append( "s.finish;" ); } private : log_t & m_log; }; class a_first_t : public so_5::agent_t { public : a_first_t( so_5::environment_t & env, log_t & log ) : so_5::agent_t( env ) , m_log( log ) {} virtual void so_evt_start() override { m_log.append( "f.start;" ); std::this_thread::sleep_for( std::chrono::milliseconds( 200 ) ); so_environment().stop(); m_log.append( "env.stop;" ); try { so_environment().register_agent_as_coop( so_environment().make_agent< a_second_t >( m_log ), so_5::disp::active_obj::make_dispatcher( so_environment() ).binder() ); } catch( const so_5::exception_t & x ) { std::ostringstream s; s << "exception(" << x.error_code() << ");"; m_log.append( s.str() ); } } virtual void so_evt_finish() override { m_log.append( "f.finish;" ); } private : log_t & m_log; }; int main() { try { log_t log; run_with_time_limit( [&log]() { so_5::launch( [&log]( so_5::environment_t & env ) { env.register_agent_as_coop( env.make_agent< a_first_t >( log ) ); } ); }, 20, "SO Environment reg_coop_after_stop test" ); const std::string expected = "f.start;env.stop;exception(28);f.finish;"; const std::string actual = log.get(); if( expected != actual ) throw std::runtime_error( expected + " != " + actual ); } catch( const std::exception & ex ) { std::cerr << "Error: " << ex.what() << std::endl; return 1; } return 0; }
17.22
74
0.612079
ZaMaZaN4iK
90f7b9d5a31589c2ee3fc23a3c03685f4f45815c
4,649
cc
C++
mindspore/lite/src/ops/concat.cc
huxian123/mindspore
ec5ba10c82bbd6eccafe32d3a1149add90105bc8
[ "Apache-2.0" ]
2
2021-04-22T07:00:59.000Z
2021-11-08T02:49:09.000Z
mindspore/lite/src/ops/concat.cc
huxian123/mindspore
ec5ba10c82bbd6eccafe32d3a1149add90105bc8
[ "Apache-2.0" ]
1
2020-12-29T06:46:38.000Z
2020-12-29T06:46:38.000Z
mindspore/lite/src/ops/concat.cc
huxian123/mindspore
ec5ba10c82bbd6eccafe32d3a1149add90105bc8
[ "Apache-2.0" ]
1
2021-05-10T03:30:36.000Z
2021-05-10T03:30:36.000Z
/** * Copyright 2019-2020 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "src/ops/concat.h" #include <memory> #include "include/errorcode.h" #include "utils/log_adapter.h" #include "src/tensor.h" namespace mindspore { namespace lite { #ifdef PRIMITIVE_WRITEABLE int Concat::GetAxis() const { return this->primitive_->value.AsConcat()->axis; } int Concat::GetN() const { return this->primitive_->value.AsConcat()->n; } void Concat::SetAxis(int axis) { this->primitive_->value.AsConcat()->axis = axis; } void Concat::SetN(int n) { this->primitive_->value.AsConcat()->n = n; } int Concat::UnPackAttr(const Primitive &prim, const std::vector<AnfNodePtr> &inputs) { if (this->primitive_ == nullptr) { this->primitive_ = new (std::nothrow) schema::PrimitiveT; if (this->primitive_ == nullptr) { MS_LOG(ERROR) << "new primitiveT failed"; return RET_ERROR; } this->primitive_->value.type = schema::PrimitiveType_Concat; } if (this->primitive_->value.type != schema::PrimitiveType_Concat) { MS_LOG(ERROR) << "Primitive type is error :" << this->primitive_->value.type; return RET_ERROR; } if (this->primitive_->value.value == nullptr) { auto attr = new (std::nothrow) schema::ConcatT(); if (attr == nullptr) { MS_LOG(ERROR) << "new primitiveT value failed"; return RET_ERROR; } auto prim_axis = GetValue<int>(prim.GetAttr("axis")); attr->axis = prim_axis; this->primitive_->value.value = attr; if (this->primitive_->value.value == nullptr) { MS_LOG(ERROR) << "primitive value is nullptr"; return RET_ERROR; } } return RET_OK; } #else int Concat::UnPackToFlatBuilder(const schema::Primitive *primitive, flatbuffers::FlatBufferBuilder *fbb) { MS_ASSERT(nullptr != primitive); MS_ASSERT(nullptr != fbb); auto attr = primitive->value_as_Concat(); if (attr == nullptr) { MS_LOG(ERROR) << "value_as_Concat return nullptr"; return RET_ERROR; } auto val_offset = schema::CreateConcat(*fbb, attr->axis(), attr->n()); auto prim_offset = schema::CreatePrimitive(*fbb, schema::PrimitiveType_Concat, val_offset.o); fbb->Finish(prim_offset); return RET_OK; } int Concat::GetAxis() const { return this->primitive_->value_as_Concat()->axis(); } int Concat::GetN() const { return this->primitive_->value_as_Concat()->n(); } #endif namespace { constexpr int kConcatOutputNum = 1; } int Concat::InferShape(std::vector<Tensor *> inputs_, std::vector<Tensor *> outputs_) { if (this->primitive_ == nullptr) { MS_LOG(ERROR) << "primitive is nullptr!"; return RET_PARAM_INVALID; } auto input0 = inputs_.front(); auto output = outputs_.front(); if (outputs_.size() != kConcatOutputNum) { MS_LOG(ERROR) << "output size is error"; return RET_PARAM_INVALID; } output->set_data_type(input0->data_type()); output->SetFormat(input0->GetFormat()); if (!GetInferFlag()) { return RET_OK; } MS_ASSERT(concat_prim != nullptr); auto input0_shape = inputs_.at(0)->shape(); auto axis = GetAxis() < 0 ? GetAxis() + input0_shape.size() : GetAxis(); if (axis < 0 || axis >= input0_shape.size()) { MS_LOG(ERROR) << "Invalid axis: " << axis; return RET_PARAM_INVALID; } auto input0_shape_without_axis = input0_shape; input0_shape_without_axis.erase(input0_shape_without_axis.begin() + axis); int output_axis_dim = input0_shape.at(axis); for (size_t i = 1; i < inputs_.size(); ++i) { auto shape_tmp = inputs_.at(i)->shape(); if (shape_tmp.size() != input0_shape.size()) { MS_LOG(ERROR) << "All inputs should have the same dim num!"; return RET_PARAM_INVALID; } auto axis_tmp = shape_tmp[axis]; shape_tmp.erase(shape_tmp.begin() + axis); if (input0_shape_without_axis != shape_tmp) { MS_LOG(ERROR) << "Inputs should have the same dim except axis!"; return RET_PARAM_INVALID; } output_axis_dim += axis_tmp; } auto output_shape = input0_shape; output_shape[axis] = output_axis_dim; outputs_[0]->set_shape(output_shape); return RET_OK; } } // namespace lite } // namespace mindspore
35.219697
106
0.687029
huxian123
90fc34239f2ecedc10add0d63ee205a7f0900360
211
hpp
C++
SwapChain/Driver/OpenGL-DX/include/GL-DX/Win32/Surface.hpp
Gpinchon/OCRA
341bb07facc616f1f8a27350054d1e86f022d7c6
[ "Apache-2.0" ]
null
null
null
SwapChain/Driver/OpenGL-DX/include/GL-DX/Win32/Surface.hpp
Gpinchon/OCRA
341bb07facc616f1f8a27350054d1e86f022d7c6
[ "Apache-2.0" ]
null
null
null
SwapChain/Driver/OpenGL-DX/include/GL-DX/Win32/Surface.hpp
Gpinchon/OCRA
341bb07facc616f1f8a27350054d1e86f022d7c6
[ "Apache-2.0" ]
null
null
null
#pragma once #include <GL-DX/Surface.hpp> namespace OCRA::Surface::Win32 { struct Impl : Surface::Impl { Impl(const Instance::Handle& a_Instance, const Info& a_Info); ~Impl(); const void* hdc; }; }
16.230769
65
0.668246
Gpinchon
290028fc14d0d66e7b0b96d1caf2a91a9bcefa8e
52,764
cxx
C++
Rendering/RayTracing/vtkOSPRayPolyDataMapperNode.cxx
gabrielventosa/vtk
723711d79b0a23de6f07421a27e89539f9d500da
[ "BSD-3-Clause" ]
null
null
null
Rendering/RayTracing/vtkOSPRayPolyDataMapperNode.cxx
gabrielventosa/vtk
723711d79b0a23de6f07421a27e89539f9d500da
[ "BSD-3-Clause" ]
null
null
null
Rendering/RayTracing/vtkOSPRayPolyDataMapperNode.cxx
gabrielventosa/vtk
723711d79b0a23de6f07421a27e89539f9d500da
[ "BSD-3-Clause" ]
null
null
null
/*========================================================================= Program: Visualization Toolkit Module: vtkOSPRayPolyDataMapperNode.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkOSPRayPolyDataMapperNode.h" #include "vtkActor.h" #include "vtkDataArray.h" #include "vtkFloatArray.h" #include "vtkImageData.h" #include "vtkImageExtractComponents.h" #include "vtkInformation.h" #include "vtkInformationDoubleKey.h" #include "vtkInformationObjectBaseKey.h" #include "vtkMapper.h" #include "vtkMatrix3x3.h" #include "vtkMatrix4x4.h" #include "vtkOSPRayActorNode.h" #include "vtkOSPRayMaterialHelpers.h" #include "vtkOSPRayRendererNode.h" #include "vtkObjectFactory.h" #include "vtkPiecewiseFunction.h" #include "vtkPointData.h" #include "vtkPolyData.h" #include "vtkPolyDataMapper.h" #include "vtkProperty.h" #include "vtkRenderer.h" #include "vtkScalarsToColors.h" #include "vtkSmartPointer.h" #include "vtkTexture.h" #include "vtkUnsignedCharArray.h" #include "RTWrapper/RTWrapper.h" #include <map> //============================================================================ namespace vtkosp { void VToOPointNormals( vtkDataArray* vNormals, std::vector<osp::vec3f>& normals, vtkMatrix3x3* matrix) { int numNormals = vNormals->GetNumberOfTuples(); normals.resize(numNormals); for (int i = 0; i < numNormals; i++) { double vNormal[3]; double* vtmp = vNormals->GetTuple(i); matrix->MultiplyPoint(vtmp, vNormal); vtkMath::Normalize(vNormal); normals[i] = osp::vec3f{ static_cast<float>(vNormal[0]), static_cast<float>(vNormal[1]), static_cast<float>(vNormal[2]) }; } } //------------------------------------------------------------------------------ void MakeCellMaterials(vtkOSPRayRendererNode* orn, OSPRenderer oRenderer, vtkPolyData* poly, vtkMapper* mapper, vtkScalarsToColors* s2c, std::map<std::string, OSPMaterial> mats, std::vector<OSPMaterial>& ospMaterials, vtkUnsignedCharArray* vColors, float* specColor, float specPower, float opacity) { RTW::Backend* backend = orn->GetBackend(); if (backend == nullptr) return; vtkAbstractArray* scalars = nullptr; bool try_mats = s2c->GetIndexedLookup() && s2c->GetNumberOfAnnotatedValues() && !mats.empty(); if (try_mats) { int cflag2 = -1; scalars = mapper->GetAbstractScalars(poly, mapper->GetScalarMode(), mapper->GetArrayAccessMode(), mapper->GetArrayId(), mapper->GetArrayName(), cflag2); } int numColors = vColors->GetNumberOfTuples(); int width = vColors->GetNumberOfComponents(); for (int i = 0; i < numColors; i++) { bool found = false; if (scalars) { vtkVariant v = scalars->GetVariantValue(i); vtkIdType idx = s2c->GetAnnotatedValueIndex(v); if (idx > -1) { std::string name(s2c->GetAnnotation(idx)); if (mats.find(name) != mats.end()) { OSPMaterial oMaterial = mats[name]; ospCommit(oMaterial); ospMaterials.push_back(oMaterial); found = true; } } } if (!found) { double* color = vColors->GetTuple(i); OSPMaterial oMaterial; oMaterial = vtkOSPRayMaterialHelpers::NewMaterial(orn, oRenderer, "obj"); float diffusef[] = { static_cast<float>(color[0]) / (255.0f), static_cast<float>(color[1]) / (255.0f), static_cast<float>(color[2]) / (255.0f) }; float localOpacity = 1.f; if (width >= 4) { localOpacity = static_cast<float>(color[3]) / (255.0f); } ospSetVec3f(oMaterial, "kd", diffusef[0], diffusef[1], diffusef[2]); float specAdjust = 2.0f / (2.0f + specPower); float specularf[] = { specColor[0] * specAdjust, specColor[1] * specAdjust, specColor[2] * specAdjust }; ospSetVec3f(oMaterial, "ks", specularf[0], specularf[1], specularf[2]); ospSetFloat(oMaterial, "ns", specPower); ospSetFloat(oMaterial, "d", opacity * localOpacity); ospCommit(oMaterial); ospMaterials.push_back(oMaterial); } } } //------------------------------------------------------------------------------ float MapThroughPWF(double in, vtkPiecewiseFunction* scaleFunction) { double out = in; if (!scaleFunction) { out = in; } else { out = scaleFunction->GetValue(in); } return static_cast<float>(out); } //---------------------------------------------------------------------------- OSPGeometricModel RenderAsSpheres(osp::vec3f* vertices, std::vector<unsigned int>& indexArray, std::vector<unsigned int>& rIndexArray, double pointSize, vtkDataArray* scaleArray, vtkPiecewiseFunction* scaleFunction, bool useCustomMaterial, OSPMaterial actorMaterial, vtkImageData* vColorTextureMap, bool sRGB, int numTextureCoordinates, float* textureCoordinates, int numCellMaterials, std::vector<OSPMaterial>& CellMaterials, int numPointColors, osp::vec4f* PointColors, int numPointValueTextureCoords, float* pointValueTextureCoords, RTW::Backend* backend) { if (backend == nullptr) return OSPGeometry(); OSPGeometry ospMesh = ospNewGeometry("sphere"); OSPGeometricModel ospGeoModel = ospNewGeometricModel(ospMesh); ospRelease(ospMesh); size_t numSpheres = indexArray.size(); std::vector<osp::vec3f> vdata; std::vector<float> radii; vdata.reserve(indexArray.size()); if (scaleArray != nullptr) { radii.reserve(indexArray.size()); } for (size_t i = 0; i < indexArray.size(); i++) { vdata.emplace_back(vertices[indexArray[i]]); if (scaleArray != nullptr) { radii.emplace_back(MapThroughPWF(*scaleArray->GetTuple(indexArray[i]), scaleFunction)); } } OSPData positionData = ospNewCopyData1D(vdata.data(), OSP_VEC3F, vdata.size()); ospCommit(positionData); ospSetObject(ospMesh, "sphere.position", positionData); if (scaleArray != nullptr) { OSPData radiiData = ospNewCopyData1D(radii.data(), OSP_FLOAT, radii.size()); ospCommit(radiiData); ospSetObject(ospMesh, "sphere.radius", radiiData); } else { ospSetFloat(ospMesh, "radius", pointSize); } // send the texture map and texture coordinates over bool _hastm = false; if (numTextureCoordinates || numPointValueTextureCoords) { _hastm = true; if (numPointValueTextureCoords) { // using 1D texture for point value LUT std::vector<osp::vec2f> tc(indexArray.size()); for (size_t i = 0; i < indexArray.size(); i++) { float t1; int index1 = indexArray[i]; t1 = pointValueTextureCoords[index1 + 0]; tc[i] = osp::vec2f{ t1, 0 }; } OSPData tcs = ospNewCopyData1D(tc.data(), OSP_VEC2F, indexArray.size()); ospCommit(tcs); ospSetObject(ospMesh, "sphere.texcoord", tcs); } else if (numTextureCoordinates) { // 2d texture mapping float* itc = textureCoordinates; std::vector<osp::vec2f> tc(indexArray.size()); for (size_t i = 0; i < indexArray.size(); i++) { float t1, t2; int index1 = indexArray[i]; t1 = itc[index1 * 2 + 0]; t2 = itc[index1 * 2 + 1]; tc[i] = osp::vec2f{ t1, t2 }; } OSPData tcs = ospNewCopyData1D(tc.data(), OSP_VEC2F, indexArray.size()); ospCommit(tcs); ospSetObject(ospMesh, "sphere.texcoord", tcs); } } OSPData _cmats = nullptr; OSPData _PointColors = nullptr; bool perCellColor = false; bool perPointColor = false; if (!useCustomMaterial) { if (vColorTextureMap && _hastm) { OSPTexture t2d = vtkOSPRayMaterialHelpers::VTKToOSPTexture(backend, vColorTextureMap, sRGB); ospSetObject(actorMaterial, "map_kd", ((OSPTexture)(t2d))); ospRelease(t2d); ospCommit(actorMaterial); } else if (numCellMaterials) { // per cell color perCellColor = true; std::vector<OSPMaterial> perCellMats; for (size_t i = 0; i < numSpheres; i++) { perCellMats.push_back(CellMaterials[rIndexArray[i]]); } _cmats = ospNewCopyData1D(&perCellMats[0], OSP_MATERIAL, numSpheres); ospCommit(_cmats); ospSetObject(ospGeoModel, "material", _cmats); ospRelease(_cmats); } else if (numPointColors) { // per point color perPointColor = true; std::vector<osp::vec4f> perPointColors; for (size_t i = 0; i < numSpheres; i++) { perPointColors.push_back(PointColors[indexArray[i]]); } _PointColors = ospNewCopyData1D(&perPointColors[0], OSP_VEC4F, numSpheres); ospCommit(_PointColors); ospSetObject(ospGeoModel, "color", _PointColors); ospRelease(_PointColors); } } if (actorMaterial && !perCellColor && !perPointColor) { ospCommit(actorMaterial); ospSetObjectAsData(ospGeoModel, "material", OSP_MATERIAL, actorMaterial); } ospCommit(ospMesh); ospCommit(ospGeoModel); return ospGeoModel; } //---------------------------------------------------------------------------- OSPGeometricModel RenderAsCylinders(std::vector<osp::vec3f>& vertices, std::vector<unsigned int>& indexArray, std::vector<unsigned int>& rIndexArray, double lineWidth, vtkDataArray* scaleArray, vtkPiecewiseFunction* scaleFunction, bool useCustomMaterial, OSPMaterial actorMaterial, vtkImageData* vColorTextureMap, bool sRGB, int numTextureCoordinates, float* textureCoordinates, int numCellMaterials, std::vector<OSPMaterial>& CellMaterials, int numPointColors, osp::vec4f* PointColors, int numPointValueTextureCoords, float* pointValueTextureCoords, RTW::Backend* backend) { if (backend == nullptr) return OSPGeometry(); OSPGeometry ospMesh = ospNewGeometry("curve"); OSPGeometricModel ospGeoModel = ospNewGeometricModel(ospMesh); ospRelease(ospMesh); size_t numCylinders = indexArray.size() / 2; if (scaleArray != nullptr) { std::vector<osp::vec4f> mdata; mdata.reserve(indexArray.size() * 2); for (size_t i = 0; i < indexArray.size(); i++) { const double avg = (*scaleArray->GetTuple(indexArray[i]) + *scaleArray->GetTuple(indexArray[i])) * 0.5; const float r = static_cast<float>(MapThroughPWF(avg, scaleFunction)); const osp::vec3f& v = vertices[indexArray[i]]; // linear not supported for variable radii, must use curve type with // 4 instead of 2 control points mdata.emplace_back(osp::vec4f({ v.x, v.y, v.z, r })); mdata.emplace_back(osp::vec4f({ v.x, v.y, v.z, r })); } OSPData _mdata = ospNewCopyData1D(mdata.data(), OSP_VEC4F, mdata.size()); ospCommit(_mdata); ospSetObject(ospMesh, "vertex.position_radius", _mdata); ospRelease(_mdata); ospSetInt(ospMesh, "type", OSP_ROUND); ospSetInt(ospMesh, "basis", OSP_BEZIER); } else { std::vector<osp::vec3f> mdata; mdata.reserve(indexArray.size()); for (size_t i = 0; i < indexArray.size(); i++) { mdata.emplace_back(vertices[indexArray[i]]); } OSPData _mdata = ospNewCopyData1D(mdata.data(), OSP_VEC3F, mdata.size()); ospCommit(_mdata); ospSetObject(ospMesh, "vertex.position", _mdata); ospRelease(_mdata); ospSetFloat(ospMesh, "radius", lineWidth); ospSetInt(ospMesh, "type", OSP_ROUND); ospSetInt(ospMesh, "basis", OSP_LINEAR); } std::vector<unsigned int> indices; indices.reserve(indexArray.size() / 2); for (unsigned int i = 0; i < indexArray.size(); i += 2) { indices.push_back((scaleArray != nullptr ? i * 2 : i)); } OSPData _idata = ospNewCopyData1D(indices.data(), OSP_UINT, indices.size()); ospCommit(_idata); ospSetObject(ospMesh, "index", _idata); ospRelease(_idata); // send the texture map and texture coordinates over bool _hastm = false; if (numTextureCoordinates || numPointValueTextureCoords) { _hastm = true; if (numPointValueTextureCoords) { // using 1D texture for point value LUT std::vector<osp::vec2f> tc(indexArray.size()); for (size_t i = 0; i < indexArray.size(); i += 2) { float t1, t2; int index1 = indexArray[i + 0]; t1 = pointValueTextureCoords[index1 + 0]; tc[i] = osp::vec2f{ t1, 0 }; int index2 = indexArray[i + 1]; t2 = pointValueTextureCoords[index2 + 0]; tc[i + 1] = osp::vec2f{ t2, 0 }; } OSPData tcs = ospNewCopyData1D(tc.data(), OSP_VEC2F, indexArray.size()); ospCommit(tcs); ospSetObject(ospMesh, "vertex.texcoord", tcs); } else if (numTextureCoordinates) { // 2d texture mapping float* itc = textureCoordinates; std::vector<osp::vec2f> tc(indexArray.size()); for (size_t i = 0; i < indexArray.size(); i += 2) { float t1, t2; int index1 = indexArray[i + 0]; t1 = itc[index1 * 2 + 0]; t2 = itc[index1 * 2 + 1]; tc[i] = osp::vec2f{ t1, t2 }; int index2 = indexArray[i + 1]; t1 = itc[index2 * 2 + 0]; t2 = itc[index2 * 2 + 1]; tc[i + 1] = osp::vec2f{ t1, t2 }; } OSPData tcs = ospNewCopyData1D(tc.data(), OSP_VEC2F, indexArray.size()); ospCommit(tcs); ospSetObject(ospMesh, "vertex.texcoord", tcs); } } OSPData _cmats = nullptr; OSPData _PointColors = nullptr; bool perCellColor = false; if (!useCustomMaterial) { if (vColorTextureMap && _hastm) { OSPTexture t2d = vtkOSPRayMaterialHelpers::VTKToOSPTexture(backend, vColorTextureMap, sRGB); ospSetObject(actorMaterial, "map_kd", ((OSPTexture)(t2d))); ospRelease(t2d); ospCommit(actorMaterial); } else if (numCellMaterials) { // per cell color perCellColor = true; std::vector<OSPMaterial> perCellMats; for (size_t i = 0; i < numCylinders; i++) { perCellMats.push_back(CellMaterials[rIndexArray[i * 2 + 0]]); } _cmats = ospNewCopyData1D(&perCellMats[0], OSP_MATERIAL, numCylinders); ospCommit(_cmats); ospSetObject(ospGeoModel, "material", _cmats); ospRelease(_cmats); } else if (numPointColors) { // per point color std::vector<osp::vec4f> perPointColor; for (size_t i = 0; i < numCylinders; i++) { perPointColor.push_back(PointColors[indexArray[i * 2 + 0]]); } _PointColors = ospNewCopyData1D(&perPointColor[0], OSP_VEC4F, numCylinders); ospCommit(_PointColors); ospSetObject(ospGeoModel, "color", _PointColors); ospRelease(_PointColors); #if 0 //this should work, but it doesn't render whole mesh, I think ospray bug // per point color _PointColors = ospNewCopyData1D(&PointColors[0], OSP_VEC4F, numPointColors); ospCommit(_PointColors); ospSetObject(ospMesh, "vertex.color", _PointColors); ospRelease(_PointColors); #endif } } if (actorMaterial && !perCellColor) { ospCommit(actorMaterial); ospSetObjectAsData(ospGeoModel, "material", OSP_MATERIAL, actorMaterial); } ospCommit(ospMesh); ospCommit(ospGeoModel); return ospGeoModel; } //---------------------------------------------------------------------------- OSPGeometricModel RenderAsTriangles(OSPData vertices, std::vector<unsigned int>& indexArray, std::vector<unsigned int>& rIndexArray, bool useCustomMaterial, OSPMaterial actorMaterial, int numNormals, const std::vector<osp::vec3f>& normals, int interpolationType, vtkImageData* vColorTextureMap, bool sRGB, vtkImageData* vNormalTextureMap, vtkImageData* vMaterialTextureMap, vtkImageData* vAnisotropyTextureMap, vtkImageData* vCoatNormalTextureMap, int numTextureCoordinates, float* textureCoordinates, const osp::vec4f& textureTransform, int numCellMaterials, std::vector<OSPMaterial>& CellMaterials, int numPointColors, osp::vec4f* PointColors, int numPointValueTextureCoords, float* pointValueTextureCoords, RTW::Backend* backend) { if (backend == nullptr) return OSPGeometry(); OSPGeometry ospMesh = ospNewGeometry("mesh"); OSPGeometricModel ospGeoModel = ospNewGeometricModel(ospMesh); ospRelease(ospMesh); ospCommit(vertices); ospSetObject(ospMesh, "vertex.position", vertices); size_t numTriangles = indexArray.size() / 3; std::vector<osp::vec3ui> triangles(numTriangles); for (size_t i = 0, mi = 0; i < numTriangles; i++, mi += 3) { triangles[i] = osp::vec3ui{ static_cast<unsigned int>(indexArray[mi + 0]), static_cast<unsigned int>(indexArray[mi + 1]), static_cast<unsigned int>(indexArray[mi + 2]) }; } OSPData index = ospNewCopyData1D(triangles.data(), OSP_VEC3UI, numTriangles); ospCommit(index); ospSetObject(ospMesh, "index", index); ospRelease(index); OSPData _normals = nullptr; if (numNormals) { _normals = ospNewCopyData1D(normals.data(), OSP_VEC3F, numNormals); ospCommit(_normals); ospSetObject(ospMesh, "vertex.normal", _normals); ospRelease(_normals); } // send the texture map and texture coordinates over bool _hastm = false; OSPData tcs = nullptr; std::vector<osp::vec2f> tc; if (numTextureCoordinates || numPointValueTextureCoords) { _hastm = true; if (numPointValueTextureCoords) { // using 1D texture for point value LUT tc.resize(numPointValueTextureCoords); for (size_t i = 0; i < static_cast<size_t>(numPointValueTextureCoords); i++) { tc[i] = osp::vec2f{ pointValueTextureCoords[i], 0 }; } tcs = ospNewCopyData1D(tc.data(), OSP_VEC2F, numPointValueTextureCoords); ospCommit(tcs); ospSetObject(ospMesh, "vertex.texcoord", tcs); ospRelease(tcs); } else if (numTextureCoordinates) { // 2d texture mapping tc.resize(numTextureCoordinates / 2); float* itc = textureCoordinates; for (size_t i = 0; i < static_cast<size_t>(numTextureCoordinates); i += 2) { float t1, t2; t1 = *itc; itc++; t2 = *itc; itc++; tc[i / 2] = osp::vec2f{ t1, t2 }; } tcs = ospNewCopyData1D(tc.data(), OSP_VEC2F, numTextureCoordinates / 2); ospCommit(tcs); ospSetObject(ospMesh, "vertex.texcoord", tcs); ospRelease(tcs); } } // send over cell colors, point colors or whole actor color OSPData _cmats = nullptr; OSPData _PointColors = nullptr; bool perCellColor = false; if (!useCustomMaterial) { if (vNormalTextureMap && _hastm) { OSPTexture t2d = vtkOSPRayMaterialHelpers::VTKToOSPTexture(backend, vNormalTextureMap); if (interpolationType == VTK_PBR) { ospSetObject(actorMaterial, "map_normal", t2d); ospSetVec4f(actorMaterial, "map_normal.transform", textureTransform.x, textureTransform.y, textureTransform.z, textureTransform.w); } else { ospSetObject(actorMaterial, "map_Bump", t2d); ospSetVec4f(actorMaterial, "map_Bump.transform", textureTransform.x, textureTransform.y, textureTransform.z, textureTransform.w); } ospRelease(t2d); ospCommit(actorMaterial); } if (interpolationType == VTK_PBR && _hastm) { if (vMaterialTextureMap) { vtkNew<vtkImageExtractComponents> extractRoughness; extractRoughness->SetInputData(vMaterialTextureMap); extractRoughness->SetComponents(1); extractRoughness->Update(); vtkNew<vtkImageExtractComponents> extractMetallic; extractMetallic->SetInputData(vMaterialTextureMap); extractMetallic->SetComponents(2); extractMetallic->Update(); vtkImageData* vRoughnessTextureMap = extractRoughness->GetOutput(); vtkImageData* vMetallicTextureMap = extractMetallic->GetOutput(); OSPTexture t2dR = vtkOSPRayMaterialHelpers::VTKToOSPTexture(backend, vRoughnessTextureMap); ospSetObject(actorMaterial, "map_roughness", t2dR); ospSetVec4f(actorMaterial, "map_roughness.transform", textureTransform.x, textureTransform.y, textureTransform.z, textureTransform.w); ospRelease(t2dR); OSPTexture t2dM = vtkOSPRayMaterialHelpers::VTKToOSPTexture(backend, vMetallicTextureMap); ospSetObject(actorMaterial, "map_metallic", t2dM); ospSetVec4f(actorMaterial, "map_metallic.transform", textureTransform.x, textureTransform.y, textureTransform.z, textureTransform.w); ospRelease(t2dM); ospCommit(actorMaterial); } if (vAnisotropyTextureMap) { vtkNew<vtkImageExtractComponents> extractAnisotropyValue; extractAnisotropyValue->SetInputData(vAnisotropyTextureMap); extractAnisotropyValue->SetComponents(0); extractAnisotropyValue->Update(); vtkNew<vtkImageExtractComponents> extractAnisotropyRotation; extractAnisotropyRotation->SetInputData(vAnisotropyTextureMap); extractAnisotropyRotation->SetComponents(1); extractAnisotropyRotation->Update(); vtkImageData* vAnisotropyValueTextureMap = extractAnisotropyValue->GetOutput(); vtkImageData* vAnisotropyRotationTextureMap = extractAnisotropyRotation->GetOutput(); OSPTexture t2dA = vtkOSPRayMaterialHelpers::VTKToOSPTexture(backend, vAnisotropyValueTextureMap); ospSetObject(actorMaterial, "map_anisotropy", t2dA); ospSetVec4f(actorMaterial, "map_anisotropy.transform", textureTransform.x, textureTransform.y, textureTransform.z, textureTransform.w); ospRelease(t2dA); OSPTexture t2dR = vtkOSPRayMaterialHelpers::VTKToOSPTexture(backend, vAnisotropyRotationTextureMap); ospSetObject(actorMaterial, "map_rotation", t2dR); ospSetVec4f(actorMaterial, "map_rotation.transform", textureTransform.x, textureTransform.y, textureTransform.z, textureTransform.w); ospRelease(t2dR); ospCommit(actorMaterial); } if (vCoatNormalTextureMap) { OSPTexture t2d = vtkOSPRayMaterialHelpers::VTKToOSPTexture(backend, vCoatNormalTextureMap); ospSetObject(actorMaterial, "map_coatNormal", t2d); ospSetVec4f(actorMaterial, "map_coatNormal.transform", textureTransform.x, textureTransform.y, textureTransform.z, textureTransform.w); ospRelease(t2d); ospCommit(actorMaterial); } } if (vColorTextureMap && _hastm) { // Note: this will only have an affect on OBJMaterials OSPTexture t2d = vtkOSPRayMaterialHelpers::VTKToOSPTexture(backend, vColorTextureMap, sRGB); if (interpolationType == VTK_PBR) { ospSetObject(actorMaterial, "map_baseColor", ((OSPTexture)(t2d))); ospSetVec4f(actorMaterial, "map_baseColor.transform", textureTransform.x, textureTransform.y, textureTransform.z, textureTransform.w); } else { ospSetObject(actorMaterial, "map_kd", ((OSPTexture)(t2d))); ospSetVec4f(actorMaterial, "map_kd.transform", textureTransform.x, textureTransform.y, textureTransform.z, textureTransform.w); } ospRelease(t2d); ospCommit(actorMaterial); } else if (numCellMaterials) { perCellColor = true; std::vector<OSPMaterial> perCellMats; for (size_t i = 0; i < numTriangles; i++) { perCellMats.push_back(CellMaterials[rIndexArray[i * 3 + 0]]); } _cmats = ospNewCopyData1D(&perCellMats[0], OSP_MATERIAL, numTriangles); ospCommit(_cmats); ospSetObject(ospGeoModel, "material", _cmats); ospRelease(_cmats); } else if (numPointColors) { _PointColors = ospNewCopyData1D(&PointColors[0], OSP_VEC4F, numPointColors); ospCommit(_PointColors); ospSetObject(ospMesh, "vertex.color", _PointColors); ospRelease(_PointColors); } } if (actorMaterial && !perCellColor) { ospCommit(actorMaterial); ospSetObjectAsData(ospGeoModel, "material", OSP_MATERIAL, actorMaterial); } ospCommit(ospMesh); ospCommit(ospGeoModel); return ospGeoModel; } //------------------------------------------------------------------------------ OSPMaterial MakeActorMaterial(vtkOSPRayRendererNode* orn, OSPRenderer oRenderer, vtkProperty* property, double* ambientColor, double* diffuseColor, float* specularf, double opacity, bool pt_avail, bool& useCustomMaterial, std::map<std::string, OSPMaterial>& mats, const std::string& materialName) { RTW::Backend* backend = orn->GetBackend(); useCustomMaterial = false; if (backend == nullptr) { return OSPMaterial(); } float lum = static_cast<float>(vtkOSPRayActorNode::GetLuminosity(property)); float diffusef[] = { static_cast<float>(diffuseColor[0] * property->GetDiffuse()), static_cast<float>(diffuseColor[1] * property->GetDiffuse()), static_cast<float>(diffuseColor[2] * property->GetDiffuse()) }; if (lum > 0.0) { OSPMaterial oMaterial = vtkOSPRayMaterialHelpers::NewMaterial(orn, oRenderer, "luminous"); ospSetVec3f(oMaterial, "color", diffusef[0], diffusef[1], diffusef[2]); ospSetFloat(oMaterial, "intensity", lum); return oMaterial; } if (pt_avail && property->GetMaterialName()) { if (std::string("Value Indexed") == property->GetMaterialName()) { vtkOSPRayMaterialHelpers::MakeMaterials( orn, oRenderer, mats); // todo: do an mtime check to avoid doing this when unchanged std::string requested_mat_name = materialName; if (!requested_mat_name.empty() && requested_mat_name != "Value Indexed") { useCustomMaterial = true; return vtkOSPRayMaterialHelpers::MakeMaterial(orn, oRenderer, requested_mat_name.c_str()); } } else { useCustomMaterial = true; return vtkOSPRayMaterialHelpers::MakeMaterial(orn, oRenderer, property->GetMaterialName()); } } OSPMaterial oMaterial; if (pt_avail && property->GetInterpolation() == VTK_PBR) { oMaterial = vtkOSPRayMaterialHelpers::NewMaterial(orn, oRenderer, "principled"); ospSetVec3f(oMaterial, "baseColor", diffusef[0], diffusef[1], diffusef[2]); ospSetFloat(oMaterial, "metallic", static_cast<float>(property->GetMetallic())); ospSetFloat(oMaterial, "roughness", static_cast<float>(property->GetRoughness())); ospSetFloat(oMaterial, "opacity", static_cast<float>(opacity)); // As OSPRay seems to not recalculate the refractive index of the base layer // we need to recalculate, from the effective reflectance of the base layer (with the // coat), the ior of the base that will produce the same reflectance but with the air // with an ior of 1.0 double baseF0 = property->ComputeReflectanceOfBaseLayer(); const double exteriorIor = 1.0; double baseIor = vtkProperty::ComputeIORFromReflectance(baseF0, exteriorIor); ospSetFloat(oMaterial, "ior", static_cast<float>(baseIor)); float edgeColor[3] = { static_cast<float>(property->GetEdgeTint()[0]), static_cast<float>(property->GetEdgeTint()[1]), static_cast<float>(property->GetEdgeTint()[2]) }; ospSetVec3f(oMaterial, "edgeColor", edgeColor[0], edgeColor[1], edgeColor[2]); ospSetFloat(oMaterial, "anisotropy", static_cast<float>(property->GetAnisotropy())); ospSetFloat(oMaterial, "rotation", static_cast<float>(property->GetAnisotropyRotation())); ospSetFloat(oMaterial, "baseNormalScale", static_cast<float>(property->GetNormalScale())); ospSetFloat(oMaterial, "coat", static_cast<float>(property->GetCoatStrength())); ospSetFloat(oMaterial, "coatIor", static_cast<float>(property->GetCoatIOR())); ospSetFloat(oMaterial, "coatRoughness", static_cast<float>(property->GetCoatRoughness())); float coatColor[] = { static_cast<float>(property->GetCoatColor()[0]), static_cast<float>(property->GetCoatColor()[1]), static_cast<float>(property->GetCoatColor()[2]) }; ospSetVec3f(oMaterial, "coatColor", coatColor[0], coatColor[1], coatColor[2]); ospSetFloat(oMaterial, "coatNormal", static_cast<float>(property->GetCoatNormalScale())); } else { oMaterial = vtkOSPRayMaterialHelpers::NewMaterial(orn, oRenderer, "obj"); float ambientf[] = { static_cast<float>(ambientColor[0] * property->GetAmbient()), static_cast<float>(ambientColor[1] * property->GetAmbient()), static_cast<float>(ambientColor[2] * property->GetAmbient()) }; float specPower = static_cast<float>(property->GetSpecularPower()); float specAdjust = 2.0f / (2.0f + specPower); specularf[0] = static_cast<float>(property->GetSpecularColor()[0] * property->GetSpecular() * specAdjust); specularf[1] = static_cast<float>(property->GetSpecularColor()[1] * property->GetSpecular() * specAdjust); specularf[2] = static_cast<float>(property->GetSpecularColor()[2] * property->GetSpecular() * specAdjust); ospSetVec3f(oMaterial, "ka", ambientf[0], ambientf[1], ambientf[2]); if (property->GetDiffuse() == 0.0) { // a workaround for ParaView, remove when ospray supports Ka ospSetVec3f(oMaterial, "kd", ambientf[0], ambientf[1], ambientf[2]); } else { ospSetVec3f(oMaterial, "kd", diffusef[0], diffusef[1], diffusef[2]); } ospSetVec3f(oMaterial, "Ks", specularf[0], specularf[1], specularf[2]); ospSetFloat(oMaterial, "Ns", specPower); ospSetFloat(oMaterial, "d", static_cast<float>(opacity)); } return oMaterial; } //------------------------------------------------------------------------------ OSPMaterial MakeActorMaterial(vtkOSPRayRendererNode* orn, OSPRenderer oRenderer, vtkProperty* property, double* ambientColor, double* diffuseColor, float* specularf, double opacity) { bool dontcare1; std::map<std::string, OSPMaterial> dontcare2; return MakeActorMaterial(orn, oRenderer, property, ambientColor, diffuseColor, specularf, opacity, false, dontcare1, dontcare2, ""); }; } //============================================================================ vtkStandardNewMacro(vtkOSPRayPolyDataMapperNode); //------------------------------------------------------------------------------ vtkOSPRayPolyDataMapperNode::vtkOSPRayPolyDataMapperNode() {} //------------------------------------------------------------------------------ vtkOSPRayPolyDataMapperNode::~vtkOSPRayPolyDataMapperNode() {} //------------------------------------------------------------------------------ void vtkOSPRayPolyDataMapperNode::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } //------------------------------------------------------------------------------ void vtkOSPRayPolyDataMapperNode::ORenderPoly(void* renderer, vtkOSPRayActorNode* aNode, vtkPolyData* poly, double* ambientColor, double* diffuseColor, double opacity, std::string materialName) { vtkOSPRayRendererNode* orn = static_cast<vtkOSPRayRendererNode*>(this->GetFirstAncestorOfType("vtkOSPRayRendererNode")); RTW::Backend* backend = orn->GetBackend(); if (backend == nullptr) return; OSPRenderer oRenderer = static_cast<OSPRenderer>(renderer); vtkActor* act = vtkActor::SafeDownCast(aNode->GetRenderable()); vtkProperty* property = act->GetProperty(); // get texture transform osp::vec4f texTransform{ 1.f, 0.f, 0.f, 1.f }; vtkInformation* info = act->GetPropertyKeys(); if (info && info->Has(vtkProp::GeneralTextureTransform())) { double* mat = info->Get(vtkProp::GeneralTextureTransform()); texTransform.x = mat[0]; texTransform.y = mat[1]; texTransform.z = mat[4]; texTransform.w = mat[5]; } // make geometry std::vector<double> _vertices; vtkPolyDataMapperNode::TransformPoints(act, poly, _vertices); size_t numPositions = _vertices.size() / 3; if (numPositions == 0) { return; } std::vector<osp::vec3f> vertices(numPositions); for (size_t i = 0; i < numPositions; i++) { vertices[i] = osp::vec3f{ static_cast<float>(_vertices[i * 3 + 0]), static_cast<float>(_vertices[i * 3 + 1]), static_cast<float>(_vertices[i * 3 + 2]) }; } OSPData position = ospNewCopyData1D(&vertices[0], OSP_VEC3F, numPositions); ospCommit(position); _vertices.clear(); // make connectivity vtkPolyDataMapperNode::vtkPDConnectivity conn; vtkPolyDataMapperNode::MakeConnectivity(poly, property->GetRepresentation(), conn); // choosing sphere and cylinder radii (for points and lines) that // approximate pointsize and linewidth vtkMapper* mapper = act->GetMapper(); double length = 1.0; if (mapper) { length = mapper->GetLength(); } int scalingMode = vtkOSPRayActorNode::GetEnableScaling(act); double pointSize = length / 1000.0 * property->GetPointSize(); double lineWidth = length / 1000.0 * property->GetLineWidth(); if (scalingMode == vtkOSPRayActorNode::ALL_EXACT) { pointSize = property->GetPointSize(); lineWidth = property->GetLineWidth(); } // finer control over sphere and cylinders sizes vtkDataArray* scaleArray = nullptr; vtkPiecewiseFunction* scaleFunction = nullptr; if (mapper && scalingMode > vtkOSPRayActorNode::ALL_APPROXIMATE) { vtkInformation* mapInfo = mapper->GetInformation(); char* scaleArrayName = (char*)mapInfo->Get(vtkOSPRayActorNode::SCALE_ARRAY_NAME()); scaleArray = poly->GetPointData()->GetArray(scaleArrayName); if (scalingMode != vtkOSPRayActorNode::EACH_EXACT) { scaleFunction = vtkPiecewiseFunction::SafeDownCast(mapInfo->Get(vtkOSPRayActorNode::SCALE_FUNCTION())); } } // now ask mapper to do most of the work and provide us with // colors per cell and colors or texture coordinates per point vtkUnsignedCharArray* vColors = nullptr; vtkFloatArray* vColorCoordinates = nullptr; vtkImageData* pColorTextureMap = nullptr; int cellFlag = -1; // mapper tells us which if (mapper) { mapper->MapScalars(poly, 1.0, cellFlag); vColors = mapper->GetColorMapColors(); vColorCoordinates = mapper->GetColorCoordinates(); pColorTextureMap = mapper->GetColorTextureMap(); } if (vColors || (vColorCoordinates && pColorTextureMap)) { // OSPRay scales the color mapping with the solid color but OpenGL backend does not do it. // set back to white to workaround this difference. std::fill(diffuseColor, diffuseColor + 3, 1.0); } // per actor material float specularf[3]; bool useCustomMaterial = false; std::map<std::string, OSPMaterial> mats; std::set<OSPMaterial> uniqueMats; const std::string rendererType = orn->GetRendererType(vtkRenderer::SafeDownCast(orn->GetRenderable())); bool pt_avail = rendererType == std::string("pathtracer") || rendererType == std::string("optix pathtracer"); OSPMaterial oMaterial = vtkosp::MakeActorMaterial(orn, oRenderer, property, ambientColor, diffuseColor, specularf, opacity, pt_avail, useCustomMaterial, mats, materialName); ospCommit(oMaterial); uniqueMats.insert(oMaterial); // texture int numTextureCoordinates = 0; std::vector<osp::vec2f> textureCoordinates; if (vtkDataArray* da = poly->GetPointData()->GetTCoords()) { numTextureCoordinates = da->GetNumberOfTuples(); textureCoordinates.resize(numTextureCoordinates); for (int i = 0; i < numTextureCoordinates; i++) { textureCoordinates[i] = osp::vec2f( { static_cast<float>(da->GetTuple(i)[0]), static_cast<float>(da->GetTuple(i)[1]) }); } numTextureCoordinates = numTextureCoordinates * 2; } vtkTexture* texture = nullptr; if (property->GetInterpolation() == VTK_PBR) { texture = property->GetTexture("albedoTex"); } else { texture = act->GetTexture(); } vtkImageData* vColorTextureMap = nullptr; vtkImageData* vNormalTextureMap = nullptr; vtkImageData* vMaterialTextureMap = nullptr; vtkImageData* vAnisotropyTextureMap = nullptr; vtkImageData* vCoatNormalTextureMap = nullptr; bool sRGB = false; if (texture) { sRGB = texture->GetUseSRGBColorSpace(); vColorTextureMap = texture->GetInput(); ospSetVec3f(oMaterial, "kd", 1.0f, 1.0f, 1.0f); ospCommit(oMaterial); } // colors from point and cell arrays int numCellMaterials = 0; std::vector<OSPMaterial> cellMaterials; int numPointColors = 0; std::vector<osp::vec4f> pointColors; int numPointValueTextureCoords = 0; std::vector<float> pointValueTextureCoords; if (vColors) { if (cellFlag == 2 && mapper->GetFieldDataTupleId() > -1) { // color comes from field data entry bool use_material = false; // check if the field data content says to use a material lookup vtkScalarsToColors* s2c = mapper->GetLookupTable(); bool try_mats = s2c->GetIndexedLookup() && s2c->GetNumberOfAnnotatedValues() && !mats.empty(); if (try_mats) { int cflag2 = -1; vtkAbstractArray* scalars = mapper->GetAbstractScalars(poly, mapper->GetScalarMode(), mapper->GetArrayAccessMode(), mapper->GetArrayId(), mapper->GetArrayName(), cflag2); vtkVariant v = scalars->GetVariantValue(mapper->GetFieldDataTupleId()); vtkIdType idx = s2c->GetAnnotatedValueIndex(v); if (idx > -1) { std::string name(s2c->GetAnnotation(idx)); if (mats.find(name) != mats.end()) { // yes it does! oMaterial = mats[name]; ospCommit(oMaterial); use_material = true; } } } if (!use_material) { // just use the color for the field data value int numComp = vColors->GetNumberOfComponents(); unsigned char* colorPtr = vColors->GetPointer(0); colorPtr = colorPtr + mapper->GetFieldDataTupleId() * numComp; // this setting (and all the other scalar colors) // really depends on mapper->ScalarMaterialMode // but I'm not sure Ka is working currently so leaving it on Kd float fdiffusef[] = { static_cast<float>(colorPtr[0] * property->GetDiffuse() / 255.0f), static_cast<float>(colorPtr[1] * property->GetDiffuse() / 255.0f), static_cast<float>(colorPtr[2] * property->GetDiffuse() / 255.0f) }; ospSetVec3f(oMaterial, "kd", fdiffusef[0], fdiffusef[1], fdiffusef[2]); ospCommit(oMaterial); } } else if (cellFlag == 1) { // color or material on cell vtkScalarsToColors* s2c = mapper->GetLookupTable(); vtkosp::MakeCellMaterials(orn, oRenderer, poly, mapper, s2c, mats, cellMaterials, vColors, specularf, float(property->GetSpecularPower()), opacity); numCellMaterials = static_cast<int>(cellMaterials.size()); for (OSPMaterial mat : cellMaterials) { uniqueMats.insert(mat); } } else if (cellFlag == 0) { // color on point interpolated RGB numPointColors = vColors->GetNumberOfTuples(); pointColors.resize(numPointColors); for (int i = 0; i < numPointColors; i++) { unsigned char* color = vColors->GetPointer(4 * i); pointColors[i] = osp::vec4f{ color[0] / 255.0f, color[1] / 255.0f, color[2] / 255.0f, (color[3] / 255.0f) * static_cast<float>(opacity) }; } ospSetVec3f(oMaterial, "kd", 1.0f, 1.0f, 1.0f); ospCommit(oMaterial); } } else { if (vColorCoordinates && pColorTextureMap) { // color on point interpolated values (subsequently colormapped via 1D LUT) numPointValueTextureCoords = vColorCoordinates->GetNumberOfTuples(); pointValueTextureCoords.resize(numPointValueTextureCoords); float* tc = vColorCoordinates->GetPointer(0); for (int i = 0; i < numPointValueTextureCoords; i++) { float v = *tc; v = ((v >= 1.0f) ? 0.99999f : ((v < 0.0f) ? 0.0f : v)); // clamp [0..1) pointValueTextureCoords[i] = v; tc += 2; } vColorTextureMap = pColorTextureMap; ospSetVec3f(oMaterial, "kd", 1.0f, 1.0f, 1.0f); ospCommit(oMaterial); } } // create an ospray mesh for the vertex cells if (!conn.vertex_index.empty()) { this->GeometricModels.emplace_back(vtkosp::RenderAsSpheres(vertices.data(), conn.vertex_index, conn.vertex_reverse, pointSize, scaleArray, scaleFunction, useCustomMaterial, oMaterial, vColorTextureMap, sRGB, numTextureCoordinates, (float*)textureCoordinates.data(), numCellMaterials, cellMaterials, numPointColors, pointColors.data(), numPointValueTextureCoords, (float*)pointValueTextureCoords.data(), backend)); } // create an ospray mesh for the line cells if (!conn.line_index.empty()) { // format depends on representation style if (property->GetRepresentation() == VTK_POINTS) { this->GeometricModels.emplace_back(vtkosp::RenderAsSpheres(vertices.data(), conn.line_index, conn.line_reverse, pointSize, scaleArray, scaleFunction, useCustomMaterial, oMaterial, vColorTextureMap, sRGB, numTextureCoordinates, (float*)textureCoordinates.data(), numCellMaterials, cellMaterials, numPointColors, pointColors.data(), numPointValueTextureCoords, (float*)pointValueTextureCoords.data(), backend)); } else { this->GeometricModels.emplace_back(vtkosp::RenderAsCylinders(vertices, conn.line_index, conn.line_reverse, lineWidth, scaleArray, scaleFunction, useCustomMaterial, oMaterial, vColorTextureMap, sRGB, numTextureCoordinates, (float*)textureCoordinates.data(), numCellMaterials, cellMaterials, numPointColors, pointColors.data(), numPointValueTextureCoords, (float*)pointValueTextureCoords.data(), backend)); } } // create an ospray mesh for the polygon cells if (!conn.triangle_index.empty()) { // format depends on representation style switch (property->GetRepresentation()) { case VTK_POINTS: { this->GeometricModels.emplace_back( vtkosp::RenderAsSpheres(vertices.data(), conn.triangle_index, conn.triangle_reverse, pointSize, scaleArray, scaleFunction, useCustomMaterial, oMaterial, vColorTextureMap, sRGB, numTextureCoordinates, (float*)textureCoordinates.data(), numCellMaterials, cellMaterials, numPointColors, pointColors.data(), numPointValueTextureCoords, (float*)pointValueTextureCoords.data(), backend)); break; } case VTK_WIREFRAME: { this->GeometricModels.emplace_back(vtkosp::RenderAsCylinders(vertices, conn.triangle_index, conn.triangle_reverse, lineWidth, scaleArray, scaleFunction, useCustomMaterial, oMaterial, vColorTextureMap, sRGB, numTextureCoordinates, (float*)textureCoordinates.data(), numCellMaterials, cellMaterials, numPointColors, pointColors.data(), numPointValueTextureCoords, (float*)pointValueTextureCoords.data(), backend)); break; } default: { if (property->GetEdgeVisibility()) { // edge mesh vtkPolyDataMapperNode::vtkPDConnectivity conn2; vtkPolyDataMapperNode::MakeConnectivity(poly, VTK_WIREFRAME, conn2); // edge material double* eColor = property->GetEdgeColor(); OSPMaterial oMaterial2 = vtkosp::MakeActorMaterial(orn, oRenderer, property, eColor, eColor, specularf, opacity); ospCommit(oMaterial2); this->GeometricModels.emplace_back( vtkosp::RenderAsCylinders(vertices, conn2.triangle_index, conn2.triangle_reverse, lineWidth, scaleArray, scaleFunction, false, oMaterial2, vColorTextureMap, sRGB, 0, (float*)textureCoordinates.data(), numCellMaterials, cellMaterials, numPointColors, pointColors.data(), 0, (float*)pointValueTextureCoords.data(), backend)); uniqueMats.insert(oMaterial2); } std::vector<osp::vec3f> normals; int numNormals = 0; if (property->GetInterpolation() != VTK_FLAT) { vtkDataArray* vNormals = poly->GetPointData()->GetNormals(); if (vNormals) { vtkSmartPointer<vtkMatrix4x4> m = vtkSmartPointer<vtkMatrix4x4>::New(); act->GetMatrix(m); vtkSmartPointer<vtkMatrix3x3> mat3 = vtkSmartPointer<vtkMatrix3x3>::New(); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { mat3->SetElement(i, j, m->GetElement(i, j)); } } mat3->Invert(); mat3->Transpose(); vtkosp::VToOPointNormals(vNormals, normals, mat3); numNormals = vNormals->GetNumberOfTuples(); } } texture = property->GetTexture("normalTex"); if (texture) { vNormalTextureMap = texture->GetInput(); } if (property->GetInterpolation() == VTK_PBR) { texture = property->GetTexture("materialTex"); if (texture) { vMaterialTextureMap = texture->GetInput(); } texture = property->GetTexture("anisotropyTex"); if (texture) { vAnisotropyTextureMap = texture->GetInput(); } texture = property->GetTexture("coatNormalTex"); if (texture) { vCoatNormalTextureMap = texture->GetInput(); } } this->GeometricModels.emplace_back( vtkosp::RenderAsTriangles(position, conn.triangle_index, conn.triangle_reverse, useCustomMaterial, oMaterial, numNormals, normals, property->GetInterpolation(), vColorTextureMap, sRGB, vNormalTextureMap, vMaterialTextureMap, vAnisotropyTextureMap, vCoatNormalTextureMap, numTextureCoordinates, (float*)textureCoordinates.data(), texTransform, numCellMaterials, cellMaterials, numPointColors, pointColors.data(), numPointValueTextureCoords, (float*)pointValueTextureCoords.data(), backend)); } } } if (!conn.strip_index.empty()) { switch (property->GetRepresentation()) { case VTK_POINTS: { this->GeometricModels.emplace_back( vtkosp::RenderAsSpheres(vertices.data(), conn.strip_index, conn.strip_reverse, pointSize, scaleArray, scaleFunction, useCustomMaterial, oMaterial, vColorTextureMap, sRGB, numTextureCoordinates, (float*)textureCoordinates.data(), numCellMaterials, cellMaterials, numPointColors, pointColors.data(), numPointValueTextureCoords, (float*)pointValueTextureCoords.data(), backend)); break; } case VTK_WIREFRAME: { this->GeometricModels.emplace_back(vtkosp::RenderAsCylinders(vertices, conn.strip_index, conn.strip_reverse, lineWidth, scaleArray, scaleFunction, useCustomMaterial, oMaterial, vColorTextureMap, sRGB, numTextureCoordinates, (float*)textureCoordinates.data(), numCellMaterials, cellMaterials, numPointColors, pointColors.data(), numPointValueTextureCoords, (float*)pointValueTextureCoords.data(), backend)); break; } default: { if (property->GetEdgeVisibility()) { // edge mesh vtkPolyDataMapperNode::vtkPDConnectivity conn2; vtkPolyDataMapperNode::MakeConnectivity(poly, VTK_WIREFRAME, conn2); // edge material double* eColor = property->GetEdgeColor(); OSPMaterial oMaterial2 = vtkosp::MakeActorMaterial(orn, oRenderer, property, eColor, eColor, specularf, opacity); ospCommit(oMaterial2); this->GeometricModels.emplace_back( vtkosp::RenderAsCylinders(vertices, conn2.strip_index, conn2.strip_reverse, lineWidth, scaleArray, scaleFunction, false, oMaterial2, vColorTextureMap, sRGB, 0, (float*)textureCoordinates.data(), numCellMaterials, cellMaterials, numPointColors, pointColors.data(), 0, (float*)pointValueTextureCoords.data(), backend)); uniqueMats.insert(oMaterial2); } std::vector<osp::vec3f> normals; int numNormals = 0; if (property->GetInterpolation() != VTK_FLAT) { vtkDataArray* vNormals = poly->GetPointData()->GetNormals(); if (vNormals) { vtkSmartPointer<vtkMatrix4x4> m = vtkSmartPointer<vtkMatrix4x4>::New(); act->GetMatrix(m); vtkSmartPointer<vtkMatrix3x3> mat3 = vtkSmartPointer<vtkMatrix3x3>::New(); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { mat3->SetElement(i, j, m->GetElement(i, j)); } } mat3->Invert(); mat3->Transpose(); vtkosp::VToOPointNormals(vNormals, normals, mat3); numNormals = vNormals->GetNumberOfTuples(); } } this->GeometricModels.emplace_back( vtkosp::RenderAsTriangles(position, conn.strip_index, conn.strip_reverse, useCustomMaterial, oMaterial, numNormals, normals, property->GetInterpolation(), vColorTextureMap, sRGB, vNormalTextureMap, vMaterialTextureMap, vAnisotropyTextureMap, vCoatNormalTextureMap, numTextureCoordinates, (float*)textureCoordinates.data(), texTransform, numCellMaterials, cellMaterials, numPointColors, pointColors.data(), numPointValueTextureCoords, (float*)pointValueTextureCoords.data(), backend)); } } } ospRelease(position); for (auto it : mats) { uniqueMats.insert(it.second); } for (OSPMaterial mat : uniqueMats) { ospRelease(mat); } for (auto g : this->GeometricModels) { OSPGroup group = ospNewGroup(); OSPInstance instance = ospNewInstance(group); // valgrind reports instance is lost ospCommit(instance); ospRelease(group); OSPData data = ospNewCopyData1D(&g, OSP_GEOMETRIC_MODEL, 1); ospRelease(&(*g)); ospCommit(data); ospSetObject(group, "geometry", data); ospCommit(group); ospRelease(data); this->Instances.emplace_back(instance); } this->GeometricModels.clear(); } //------------------------------------------------------------------------------ void vtkOSPRayPolyDataMapperNode::Invalidate(bool prepass) { if (prepass) { this->RenderTime = 0; } } //------------------------------------------------------------------------------ void vtkOSPRayPolyDataMapperNode::Render(bool prepass) { if (prepass) { // we use a lot of params from our parent vtkOSPRayActorNode* aNode = vtkOSPRayActorNode::SafeDownCast(this->Parent); vtkActor* act = vtkActor::SafeDownCast(aNode->GetRenderable()); if (act->GetVisibility() == false) { return; } vtkOSPRayRendererNode* orn = static_cast<vtkOSPRayRendererNode*>(this->GetFirstAncestorOfType("vtkOSPRayRendererNode")); // if there are no changes, just reuse last result vtkMTimeType inTime = aNode->GetMTime(); if (this->RenderTime >= inTime) { this->RenderGeometricModels(); return; } this->RenderTime = inTime; this->ClearGeometricModels(); vtkPolyData* poly = nullptr; vtkPolyDataMapper* mapper = vtkPolyDataMapper::SafeDownCast(act->GetMapper()); if (mapper && mapper->GetNumberOfInputPorts() > 0) { poly = mapper->GetInput(); } if (poly) { vtkProperty* property = act->GetProperty(); double ambient[3]; double diffuse[3]; property->GetAmbientColor(ambient); property->GetDiffuseColor(diffuse); this->ORenderPoly( orn->GetORenderer(), aNode, poly, ambient, diffuse, property->GetOpacity(), ""); } this->RenderGeometricModels(); } } //---------------------------------------------------------------------------- void vtkOSPRayPolyDataMapperNode::RenderGeometricModels() { vtkOSPRayRendererNode* orn = static_cast<vtkOSPRayRendererNode*>(this->GetFirstAncestorOfType("vtkOSPRayRendererNode")); for (auto instance : this->Instances) { orn->Instances.emplace_back(instance); } } //---------------------------------------------------------------------------- void vtkOSPRayPolyDataMapperNode::ClearGeometricModels() { vtkOSPRayRendererNode* orn = static_cast<vtkOSPRayRendererNode*>(this->GetFirstAncestorOfType("vtkOSPRayRendererNode")); RTW::Backend* backend = orn->GetBackend(); for (auto instance : this->Instances) ospRelease(&(*instance)); this->Instances.clear(); }
37.315417
100
0.652813
gabrielventosa
2901d924cf1d1014a689b00559a8cd3d4932b738
10,041
cpp
C++
modules/basegl/processors/background.cpp
liu3xing3long/inviwo
69cca9b6ecd58037bda0ed9e6f53d02f189f19a7
[ "BSD-2-Clause" ]
1
2018-04-07T14:30:29.000Z
2018-04-07T14:30:29.000Z
modules/basegl/processors/background.cpp
liu3xing3long/inviwo
69cca9b6ecd58037bda0ed9e6f53d02f189f19a7
[ "BSD-2-Clause" ]
null
null
null
modules/basegl/processors/background.cpp
liu3xing3long/inviwo
69cca9b6ecd58037bda0ed9e6f53d02f189f19a7
[ "BSD-2-Clause" ]
null
null
null
/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2013-2018 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/basegl/processors/background.h> #include <modules/opengl/texture/textureunit.h> #include <modules/opengl/texture/textureutils.h> #include <modules/opengl/image/imagegl.h> #include <modules/opengl/shader/shaderutils.h> #include <modules/opengl/inviwoopengl.h> namespace inviwo { const ProcessorInfo Background::processorInfo_{ "org.inviwo.Background", // Class identifier "Background", // Display name "Image Operation", // Category CodeState::Stable, // Code state Tags::GL, // Tags }; const ProcessorInfo Background::getProcessorInfo() const { return processorInfo_; } Background::Background() : Processor() , inport_("inport") , outport_("outport") , backgroundStyle_("backgroundStyle", "Style", {{"linearGradientVertical", "Linear gradient (Vertical)", BackgroundStyle::LinearVertical}, {"linearGradientHorizontal", "Linear gradient (Horizontal)", BackgroundStyle::LinearHorizontal}, { "linearGradientSpherical", "Linear gradient (Spherical)", BackgroundStyle::LinearSpherical }, {"uniformColor", "Uniform color", BackgroundStyle::Uniform}, {"checkerBoard", "Checker board", BackgroundStyle::CheckerBoard}}, 0, InvalidationLevel::InvalidResources) , bgColor1_("bgColor1", "Color 1", vec4(0.0f, 0.0f, 0.0f, 1.0f)) , bgColor2_("bgColor2", "Color 2", vec4(1.0f)) , checkerBoardSize_("checkerBoardSize", "Checker Board Size", ivec2(10, 10), ivec2(1, 1), ivec2(256, 256)) , switchColors_("switchColors", "Switch Colors", InvalidationLevel::Valid) , blendMode_("blendMode", "Blend mode", {{"backtofront", "Back To Front (Pre-multiplied)", BlendMode::BackToFront}, {"alphamixing", "Alpha Mixing", BlendMode::AlphaMixing}}, 0, InvalidationLevel::InvalidResources) , shader_("background.frag", false) { addPort(inport_); addPort(outport_); inport_.setOptional(true); addProperty(backgroundStyle_); bgColor1_.setSemantics(PropertySemantics::Color); addProperty(bgColor1_); bgColor2_.setSemantics(PropertySemantics::Color); addProperty(bgColor2_); addProperty(checkerBoardSize_); addProperty(switchColors_); addProperty(blendMode_); switchColors_.onChange([&]() { vec4 tmp = bgColor1_.get(); bgColor1_.set(bgColor2_.get()); bgColor2_.set(tmp); }); shader_.onReload([this]() { invalidate(InvalidationLevel::InvalidResources); }); } Background::~Background() = default; void Background::initializeResources() { std::string bgStyleValue; switch (backgroundStyle_.get()) { default: case BackgroundStyle::LinearVertical: // linear gradient bgStyleValue = "linearGradientVertical(texCoord)"; checkerBoardSize_.setVisible(false); break; case BackgroundStyle::LinearHorizontal: // linear gradient bgStyleValue = "linearGradientHorizontal(texCoord)"; checkerBoardSize_.setVisible(false); break; case BackgroundStyle::LinearSpherical: // linear spherical gradient bgStyleValue = "linearGradientSpherical(texCoord)"; checkerBoardSize_.setVisible(false); break; case BackgroundStyle::Uniform: // uniform color bgStyleValue = "bgColor1"; checkerBoardSize_.setVisible(false); break; case BackgroundStyle::CheckerBoard: // checker board bgStyleValue = "checkerBoard(texCoord)"; checkerBoardSize_.setVisible(true); break; } shader_.getFragmentShaderObject()->addShaderDefine("BACKGROUND_STYLE_FUNCTION", bgStyleValue); if (inport_.hasData()) { shader_.getFragmentShaderObject()->addShaderDefine("SRC_COLOR", "texture(inportColor, texCoord)"); // set shader inputs to match number of available color layers updateShaderInputs(); shader_.getFragmentShaderObject()->addShaderDefine("PICKING_LAYER"); shader_.getFragmentShaderObject()->addShaderDefine("DEPTH_LAYER"); hadData_ = true; } else { shader_.getFragmentShaderObject()->addShaderDefine("SRC_COLOR", "vec4(0)"); shader_.getFragmentShaderObject()->removeShaderDefine("PICKING_LAYER"); shader_.getFragmentShaderObject()->removeShaderDefine("DEPTH_LAYER"); hadData_ = false; } std::string blendfunc = ""; switch (blendMode_.get()) { case BlendMode::BackToFront: blendfunc = "blendBackToFront"; break; default: case BlendMode::AlphaMixing: blendfunc = "blendAlphaCompositing"; break; } shader_.getFragmentShaderObject()->addShaderDefine("BLENDFUNC", blendfunc); shader_.build(); } void Background::process() { if (inport_.hasData() != hadData_) initializeResources(); if (inport_.hasData()) { // Check data format, make sure we always have 4 channels auto inDataFromat = inport_.getData()->getDataFormat(); auto format = DataFormatBase::get(inDataFromat->getNumericType(), 4, inDataFromat->getSize() * 8 / inDataFromat->getComponents()); if (outport_.getData()->getDataFormat() != format) { outport_.setData(std::make_shared<Image>(outport_.getDimensions(), format)); } } utilgl::activateTarget(outport_, ImageType::AllLayers); shader_.activate(); if (inport_.hasData()) { TextureUnitContainer textureUnits; auto image = inport_.getData(); utilgl::bindAndSetUniforms(shader_, textureUnits, inport_, ImageType::AllLayers); { // bind all additional color layers const auto numColorLayers = image->getNumberOfColorLayers(); auto imageGL = image->getRepresentation<ImageGL>(); for (size_t i = 1; i < numColorLayers; ++i) { TextureUnit texUnit; imageGL->getColorLayerGL(i)->bindTexture(texUnit.getEnum()); shader_.setUniform("color" + toString<size_t>(i), texUnit.getUnitNumber()); textureUnits.push_back(std::move(texUnit)); } } } utilgl::setUniforms(shader_, outport_, bgColor1_, bgColor2_, checkerBoardSize_); utilgl::singleDrawImagePlaneRect(); shader_.deactivate(); utilgl::deactivateCurrentTarget(); } void Background::updateShaderInputs() { const auto numColorLayers = inport_.getData()->getNumberOfColorLayers(); if (numColorLayers > 1) { // location 0 is reserved for FragData0, location 1 for PickingData size_t outputLocation = 2; std::stringstream ssUniform; ssUniform << "\n"; for (size_t i = 1; i < numColorLayers; ++i) { ssUniform << "layout(location = " << outputLocation++ << ") out vec4 FragData" << i << ";\n"; } for (size_t i = 1; i < numColorLayers; ++i) { ssUniform << "uniform sampler2D color" << i << ";\n"; } shader_.getFragmentShaderObject()->addShaderDefine("ADDITIONAL_COLOR_LAYER_OUT_UNIFORMS", ssUniform.str()); std::stringstream ssWrite; for (size_t i = 1; i < numColorLayers; ++i) { ssWrite << "FragData" << i << " = texture(color" << i << ", texCoord.xy);"; if(i<numColorLayers-1){ ssWrite << " \\"; } ssWrite << "\n"; } shader_.getFragmentShaderObject()->addShaderDefine("ADDITIONAL_COLOR_LAYER_WRITE", ssWrite.str()); shader_.getFragmentShaderObject()->addShaderDefine("ADDITIONAL_COLOR_LAYERS"); } else { shader_.getFragmentShaderObject()->removeShaderDefine("ADDITIONAL_COLOR_LAYERS"); shader_.getFragmentShaderObject()->removeShaderDefine( "ADDITIONAL_COLOR_LAYER_OUT_UNIFORMS"); shader_.getFragmentShaderObject()->removeShaderDefine("ADDITIONAL_COLOR_LAYER_WRITE"); } } } // namespace
41.8375
98
0.627926
liu3xing3long
290236235d9c903a150cf047abbc35c1493025fa
11,083
cpp
C++
editor/DrawState.cpp
tay10r/libpx
0cdcaf959aed59907f68d08428e3808e69cfc8de
[ "MIT" ]
19
2020-06-16T01:43:26.000Z
2022-01-08T09:12:20.000Z
editor/DrawState.cpp
tay10r/libpx
0cdcaf959aed59907f68d08428e3808e69cfc8de
[ "MIT" ]
3
2020-06-16T10:27:14.000Z
2021-02-10T16:26:54.000Z
editor/DrawState.cpp
tay10r/libpx
0cdcaf959aed59907f68d08428e3808e69cfc8de
[ "MIT" ]
3
2020-10-24T09:26:28.000Z
2021-06-17T04:59:38.000Z
#include "DrawState.hpp" #include "App.hpp" #include "ColorEdit.hpp" #include "DrawPanel.hpp" #include "Input.hpp" #include "LayerPanel.hpp" #include "MenuBar.hpp" #include "Platform.hpp" #include "Renderer.hpp" #include "BucketTool.hpp" #include "ColorPickerTool.hpp" #include "EllipseTool.hpp" #include "EraserTool.hpp" #include "PenTool.hpp" #include "RectTool.hpp" #include "StrokeTool.hpp" #include <libpx.hpp> #include <imgui.h> #include <imgui_stdlib.h> #include <glm/glm.hpp> #include <glm/vec3.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtx/transform.hpp> #include <memory> #include <cstdio> namespace px { namespace { /// The panel that goes on the left side of the image. /// Shows drawing tools and document properties. class LeftPanel final { /// Whether or not the document size can be changed. bool sizeLock = true; /// Used for editing the background color. ColorEdit4 backgroundEdit; public: /// Renders the left panel. void operator() (App* app, DrawPanel::Observer* drawPanelObserver, DrawPanel& drawPanel) { ImGui::Begin("##left_panel", nullptr, windowFlags()); drawPanel.frame(drawPanelObserver); if (ImGui::CollapsingHeader("Document Properties")) { documentProperties(app); } ImGui::End(); } protected: /// Renders the document properties. void documentProperties(App* app) { documentName(app); documentBackground(app); documentSize(app); } /// Renders the document background setting. void documentBackground(App* app) { float bg[4] { 0, 0, 0, 0 }; getBackground(app->getDocument(), bg); if (backgroundEdit("Background Color", bg)) { setBackground(app->getDocument(), bg); } if (backgroundEdit.isJustStarted()) { app->snapshotDocument(); } if (backgroundEdit.isCommitted()) { app->stashDocument(); } } /// Renders the document name. void documentName(App* app) { auto docName = app->getDocumentName(); if (ImGui::InputText("Name", &docName)) { app->renameDocument(docName.c_str()); } } /// Renders the document size. void documentSize(App* app) { const auto* doc = app->getDocument(); auto w = int(getDocWidth(doc)); auto h = int(getDocHeight(doc)); auto wChanged = ImGui::InputInt("Width", &w); auto hChanged = ImGui::InputInt("Height", &h); if ((wChanged || hChanged) && !sizeLock) { app->snapshotDocument(); app->resizeDocument(w, h); app->stashDocument(); } ImGui::Checkbox("Size Lock", &sizeLock); } /// Gets the window flags used to create /// the left panel window. static constexpr ImGuiWindowFlags windowFlags() { return ImGuiWindowFlags_AlwaysAutoResize; } }; /// The panel that goes on the right side of the image. /// Contains the layers and eventually will also contain /// the navigation panel and the palette table. class RightPanel final { public: /// Renders the right panel. void operator () (App* app, LayerPanel& layerPanel) { ImGui::Begin("##right_panel", nullptr, windowFlags()); layerPanel.frame(app); ImGui::End(); } protected: /// Gets the window flags used to create /// the left panel window. static constexpr ImGuiWindowFlags windowFlags() { return ImGuiWindowFlags_AlwaysAutoResize; } }; /// Represents the application when it is being used /// for drawing the artwork. class DrawStateImpl final : public DrawState, public DrawPanel::Observer { /// Contains state information on /// the drawing tools. DrawPanel drawPanel; /// Shows all the layers from the document. LayerPanel layerPanel; /// The current draw tool. std::unique_ptr<DrawTool> currentTool; /// Contains draw tools, document properties, etc. LeftPanel leftPanel; /// Contains the layers in the document. RightPanel rightPanel; public: DrawStateImpl(App* app) : DrawState(app) { currentTool.reset(new PenTool(this)); } /// Renders the draw state windows. void frame() override { renderDocument(); leftPanel(getApp(), this, drawPanel); rightPanel(getApp(), layerPanel); } /// Handles a mouse button event. void mouseButton(const MouseButtonEvent& mouseButton) override { if (!currentTool) { return; } auto usable = (currentTool->isLeftClickTool() && mouseButton.isLeft()) || (currentTool->isRightClickTool() && mouseButton.isRight()); if (!usable) { return; } auto cursor = ImGui::GetIO().MousePos; auto docPos = windowToDoc(glm::vec2(cursor.x, cursor.y)); if (!currentTool->isActive() && mouseButton.isPressed()) { currentTool->begin(mouseButton, docPos.x, docPos.y); } else if (currentTool->isActive() && mouseButton.isReleased()) { currentTool->end(docPos.x, docPos.y); } } /// Handles mouse motion event. void mouseMotion(const MouseMotionEvent& motion) override { auto pos = windowToDoc(glm::vec2(motion.x, motion.y)); if (currentTool && currentTool->isActive()) { currentTool->drag(motion, pos.x, pos.y); } getPlatform()->getRenderer()->setCursor(pos.x, pos.y); } /// Gets a pointer to the draw panel. const DrawPanel* getDrawPanel() const noexcept override { return &drawPanel; } /// Gets a non-const pointer to the draw panel. DrawPanel* getDrawPanel() noexcept override { return &drawPanel; } /// Gets a pointer to the layer panel. /// /// @return A pointer to the layer panel. const LayerPanel* getLayerPanel() const noexcept override { return &layerPanel; } /// Requires that a layer be available for editing. /// This function will create a layer if it doesn't /// already exist. std::size_t requireCurrentLayer() override { std::size_t layerIndex = 0; if (layerPanel.getSelectedLayer(&layerIndex)) { return layerIndex; } auto* doc = getDocument(); if (!getLayerCount(doc)) { px::addLayer(doc); } return 0; } protected: /// Gets the current window size. glm::vec2 getWinSize() noexcept { std::size_t w = 0; std::size_t h = 0; getPlatform()->getWindowSize(&w, &h); return glm::vec2(float(w), float(h)); } /// Gets the size of the current document snapshot. glm::vec2 getDocSize() const noexcept { const auto* doc = getDocument(); return glm::vec2(float(getDocWidth(doc)), float(getDocHeight(doc))); } /// Calculates the transformation to be applied /// based on the editing position, zoom factor, /// and aspect ratios. glm::mat4 calculateTransform() noexcept { float zoom = getApp()->getZoom(); std::size_t fbW = 0; std::size_t fbH = 0; getPlatform()->getWindowSize(&fbW, &fbH); const auto* doc = getDocument(); std::size_t docW = getDocWidth(doc); std::size_t docH = getDocHeight(doc); float aspectA = float(fbW) / fbH; float aspectB = float(docW) / docH; float scaleX = zoom * (aspectB / aspectA); float scaleY = zoom; return glm::scale(glm::vec3(scaleX, scaleY, 1.0f)); } /// Gets a pointer to the platform interface. Platform* getPlatform() noexcept { return getApp()->getPlatform(); } /// Gets a pointer to the current document snapshot. Document* getDocument() noexcept { return getApp()->getDocument(); } /// Gets a pointer to the current document snapshot. const Document* getDocument() const noexcept { return getApp()->getDocument(); } /// Renders the document onto the window. void renderDocument() { auto* renderer = getPlatform()->getRenderer(); auto transform = calculateTransform(); renderer->setTransform(glm::value_ptr(transform)); auto* doc = getDocument(); auto* image = getApp()->getImage(); render(doc, image); auto* color = getColorBuffer(image); auto w = getImageWidth(image); auto h = getImageHeight(image); renderer->blit(color, w, h); } /// Observes an event from the draw panel. void observe(DrawPanel::Event event) override { switch (event) { case DrawPanel::Event::ChangedBlendMode: break; case DrawPanel::Event::ChangedPixelSize: break; case DrawPanel::Event::ChangedPrimaryColor: break; case DrawPanel::Event::ChangedTool: updateTool(); break; } } /// Changes the currently selected tool, /// based on what's indicating in the draw panel. void updateTool() { currentTool.reset(); switch (drawPanel.getCurrentTool()) { case DrawPanel::Tool::Bucket: currentTool.reset(new BucketTool(this)); break; case DrawPanel::Tool::ColorPicker: currentTool.reset(new ColorPickerTool(this)); break; case DrawPanel::Tool::Ellipse: currentTool.reset(new EllipseTool(this)); break; case DrawPanel::Tool::Eraser: currentTool.reset(new EraserTool(this)); break; case DrawPanel::Tool::Pen: currentTool.reset(new PenTool(this)); break; case DrawPanel::Tool::Rectangle: currentTool.reset(new RectTool(this)); break; case DrawPanel::Tool::Stroke: currentTool.reset(new StrokeTool(this)); break; } } /// Converts a position in window space to a position /// in document space. /// /// @param in The position in window space to convert. /// /// @return The resultant position in document space. glm::vec2 windowToDoc(const glm::vec2& in) noexcept { auto winSize = getWinSize(); auto transform = calculateTransform(); glm::vec4 scaledSize = transform * glm::vec4(winSize.x, winSize.y, 0, 1); auto offset = (winSize - glm::vec2(scaledSize.x, scaledSize.y)) * 0.5f; auto docSize = getDocSize(); auto pos = in - offset; pos = glm::vec2(pos.x * docSize.x / scaledSize.x, pos.y * docSize.y / scaledSize.y); return pos; } /// Converts NDC coordinates to document coordinates. /// /// @param in The NDC coordinates to convert. /// /// @return The NDC coordinates converted to document coordinates. glm::vec2 ndcToDocument(const glm::vec2& in) noexcept { auto w = getDocWidth(getDocument()); auto h = getDocHeight(getDocument()); return glm::vec2 { ((in[0] + 1) * 0.5) * w, ((1 - in[1]) * 0.5) * h }; } #if 0 glm::vec2 docToNDC(const glm::vec2& in) noexcept { } #endif /// Converts window coordinates to NDC coordinates. /// /// @param in The window coordinates to convert. /// /// @return The window coordinates as normalized coordinates. glm::vec2 windowToNDC(const glm::vec2& in) noexcept { std::size_t w = 0; std::size_t h = 0; getPlatform()->getWindowSize(&w, &h); glm::vec2 uv { in[0] / float(w), in[1] / float(h) }; return glm::vec2 { (2 * uv[0]) - 1, 1 - (2 * uv[1]) }; } }; } // namesapce DrawState* DrawState::init(App* app) { return new DrawStateImpl(app); } } // namespace px
24.961712
90
0.643689
tay10r
2906827781d0fba19b4c5e6adab1a47edcbcd851
6,739
cpp
C++
software/build-gui-Qt_5_12_8_qt5_temporary-Profile/app/controls_graphs_FlowGraph_qml.cpp
wajo10/Ventilator
ff6678d8c2b7037113f0947fb2d91b6b07fff7b9
[ "Apache-2.0" ]
null
null
null
software/build-gui-Qt_5_12_8_qt5_temporary-Profile/app/controls_graphs_FlowGraph_qml.cpp
wajo10/Ventilator
ff6678d8c2b7037113f0947fb2d91b6b07fff7b9
[ "Apache-2.0" ]
null
null
null
software/build-gui-Qt_5_12_8_qt5_temporary-Profile/app/controls_graphs_FlowGraph_qml.cpp
wajo10/Ventilator
ff6678d8c2b7037113f0947fb2d91b6b07fff7b9
[ "Apache-2.0" ]
null
null
null
// /controls/graphs/FlowGraph.qml namespace QmlCacheGeneratedCode { namespace _controls_graphs_FlowGraph_qml { extern const unsigned char qmlData alignas(16) [] = { 0x71,0x76,0x34,0x63,0x64,0x61,0x74,0x61, 0x20,0x0,0x0,0x0,0x8,0xc,0x5,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0xdc,0x5,0x0,0x0,0x31,0x30,0x31,0x37, 0x39,0x39,0x66,0x38,0x61,0x63,0x64,0x62, 0x66,0x63,0x34,0x65,0x62,0x64,0x30,0x35, 0x66,0x33,0x37,0x61,0x37,0x63,0x30,0x39, 0x35,0x34,0x34,0x64,0x32,0x34,0x62,0x34, 0x31,0x61,0x66,0x31,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x23,0x0,0x0,0x0, 0x11,0x0,0x0,0x0,0x60,0x1,0x0,0x0, 0x1,0x0,0x0,0x0,0xf8,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0xfc,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0xfc,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0xfc,0x0,0x0,0x0, 0x2,0x0,0x0,0x0,0xfc,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x4,0x1,0x0,0x0, 0x2,0x0,0x0,0x0,0x10,0x1,0x0,0x0, 0x0,0x0,0x0,0x0,0x20,0x1,0x0,0x0, 0x0,0x0,0x0,0x0,0x20,0x1,0x0,0x0, 0x0,0x0,0x0,0x0,0x20,0x1,0x0,0x0, 0x0,0x0,0x0,0x0,0x20,0x1,0x0,0x0, 0x0,0x0,0x0,0x0,0x20,0x1,0x0,0x0, 0x0,0x0,0x0,0x0,0x20,0x1,0x0,0x0, 0x0,0x0,0x0,0x0,0x20,0x1,0x0,0x0, 0xff,0xff,0xff,0xff,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0xa8,0x4,0x0,0x0, 0x20,0x1,0x0,0x0,0xf3,0x0,0x0,0x0, 0x0,0x1,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0xb2,0x3f, 0x0,0x0,0x0,0x0,0x0,0x0,0xb2,0xbf, 0x38,0x0,0x0,0x0,0x7,0x0,0x0,0x0, 0xe,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x30,0x0,0x0,0x0,0x30,0x0,0x0,0x0, 0x0,0x0,0x1,0x0,0xff,0xff,0xff,0xff, 0x0,0x0,0x7,0x0,0x0,0x0,0x7,0x0, 0xd,0x0,0x50,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0xd,0x0,0x0,0x0, 0x2e,0x0,0x3a,0x1,0x18,0x6,0x2,0x0, 0xa8,0x1,0x0,0x0,0xc8,0x1,0x0,0x0, 0xf0,0x1,0x0,0x0,0x30,0x2,0x0,0x0, 0x58,0x2,0x0,0x0,0x78,0x2,0x0,0x0, 0xa8,0x2,0x0,0x0,0xd8,0x2,0x0,0x0, 0x0,0x3,0x0,0x0,0x28,0x3,0x0,0x0, 0x50,0x3,0x0,0x0,0x78,0x3,0x0,0x0, 0xa0,0x3,0x0,0x0,0xc8,0x3,0x0,0x0, 0xf0,0x3,0x0,0x0,0x38,0x4,0x0,0x0, 0x78,0x4,0x0,0x0,0x0,0x0,0x0,0x0, 0xff,0xff,0xff,0xff,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x18,0x0,0x0,0x0, 0x18,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0xff,0xff,0xff,0xff,0x7,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x18,0x0,0x0,0x0, 0x18,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x51,0x0,0x74,0x0,0x51,0x0,0x75,0x0, 0x69,0x0,0x63,0x0,0x6b,0x0,0x0,0x0, 0xff,0xff,0xff,0xff,0x10,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x18,0x0,0x0,0x0, 0x18,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x51,0x0,0x74,0x0,0x51,0x0,0x75,0x0, 0x69,0x0,0x63,0x0,0x6b,0x0,0x2e,0x0, 0x43,0x0,0x6f,0x0,0x6e,0x0,0x74,0x0, 0x72,0x0,0x6f,0x0,0x6c,0x0,0x73,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0xff,0xff,0xff,0xff,0x7,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x18,0x0,0x0,0x0, 0x18,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x52,0x0,0x65,0x0,0x73,0x0,0x70,0x0, 0x69,0x0,0x72,0x0,0x61,0x0,0x0,0x0, 0xff,0xff,0xff,0xff,0x2,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x18,0x0,0x0,0x0, 0x18,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x2e,0x0,0x2e,0x0,0x0,0x0,0x0,0x0, 0xff,0xff,0xff,0xff,0x9,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x18,0x0,0x0,0x0, 0x18,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x53,0x0,0x63,0x0,0x6f,0x0,0x70,0x0, 0x65,0x0,0x56,0x0,0x69,0x0,0x65,0x0, 0x77,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0xff,0xff,0xff,0xff,0x8,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x18,0x0,0x0,0x0, 0x18,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x66,0x0,0x6c,0x0,0x6f,0x0,0x77,0x0, 0x56,0x0,0x69,0x0,0x65,0x0,0x77,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0xff,0xff,0xff,0xff,0x4,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x18,0x0,0x0,0x0, 0x18,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x6e,0x0,0x61,0x0,0x6d,0x0,0x65,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0xff,0xff,0xff,0xff,0x4,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x18,0x0,0x0,0x0, 0x18,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x46,0x0,0x6c,0x0,0x6f,0x0,0x77,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0xff,0xff,0xff,0xff,0x4,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x18,0x0,0x0,0x0, 0x18,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x75,0x0,0x6e,0x0,0x69,0x0,0x74,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0xff,0xff,0xff,0xff,0x5,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x18,0x0,0x0,0x0, 0x18,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x4c,0x0,0x2f,0x0,0x6d,0x0,0x69,0x0, 0x6e,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0xff,0xff,0xff,0xff,0x4,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x18,0x0,0x0,0x0, 0x18,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x79,0x0,0x4d,0x0,0x69,0x0,0x6e,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0xff,0xff,0xff,0xff,0x4,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x18,0x0,0x0,0x0, 0x18,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x79,0x0,0x4d,0x0,0x61,0x0,0x78,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0xff,0xff,0xff,0xff,0x7,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x18,0x0,0x0,0x0, 0x18,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x64,0x0,0x61,0x0,0x74,0x0,0x61,0x0, 0x73,0x0,0x65,0x0,0x74,0x0,0x0,0x0, 0xff,0xff,0xff,0xff,0x16,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x18,0x0,0x0,0x0, 0x18,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x65,0x0,0x78,0x0,0x70,0x0,0x72,0x0, 0x65,0x0,0x73,0x0,0x73,0x0,0x69,0x0, 0x6f,0x0,0x6e,0x0,0x20,0x0,0x66,0x0, 0x6f,0x0,0x72,0x0,0x20,0x0,0x64,0x0, 0x61,0x0,0x74,0x0,0x61,0x0,0x73,0x0, 0x65,0x0,0x74,0x0,0x0,0x0,0x0,0x0, 0xff,0xff,0xff,0xff,0x11,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x18,0x0,0x0,0x0, 0x18,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x47,0x0,0x75,0x0,0x69,0x0,0x53,0x0, 0x74,0x0,0x61,0x0,0x74,0x0,0x65,0x0, 0x43,0x0,0x6f,0x0,0x6e,0x0,0x74,0x0, 0x61,0x0,0x69,0x0,0x6e,0x0,0x65,0x0, 0x72,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0xff,0xff,0xff,0xff,0xa,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x18,0x0,0x0,0x0, 0x18,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x66,0x0,0x6c,0x0,0x6f,0x0,0x77,0x0, 0x53,0x0,0x65,0x0,0x72,0x0,0x69,0x0, 0x65,0x0,0x73,0x0,0x0,0x0,0x0,0x0, 0x4,0x0,0x0,0x0,0x10,0x0,0x0,0x0, 0x1,0x0,0x0,0x0,0x70,0x0,0x0,0x0, 0x1,0x0,0x0,0x0,0x1,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x2,0x0,0x0,0x0, 0xb,0x0,0x0,0x0,0x1,0x0,0x10,0x0, 0x1,0x0,0x0,0x0,0x2,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x2,0x0,0x0,0x0, 0x4,0x0,0x0,0x0,0x2,0x0,0x10,0x0, 0x1,0x0,0x0,0x0,0x3,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x3,0x0,0x10,0x0, 0x2,0x0,0x0,0x0,0x4,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0x4,0x0,0x10,0x0, 0x74,0x0,0x0,0x0,0x5,0x0,0x0,0x0, 0x6,0x0,0x0,0x0,0x0,0x0,0xff,0xff, 0xff,0xff,0xff,0xff,0x0,0x0,0x0,0x0, 0x44,0x0,0x0,0x0,0x44,0x0,0x0,0x0, 0x44,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x44,0x0,0x0,0x0,0x44,0x0,0x0,0x0, 0x0,0x0,0x5,0x0,0x44,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0xbc,0x0,0x0,0x0, 0x6,0x0,0x10,0x0,0x7,0x0,0x50,0x0, 0xd,0x0,0x0,0x0,0x0,0x0,0x6,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0xd,0x0,0x50,0x0,0xd,0x0,0xe0,0x0, 0xc,0x0,0x0,0x0,0x0,0x0,0x2,0x0, 0x1,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0xc,0x0,0x50,0x0,0xc,0x0,0xb0,0x0, 0xb,0x0,0x0,0x0,0x0,0x0,0x2,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0xb,0x0,0x50,0x0,0xb,0x0,0xb0,0x0, 0x9,0x0,0x0,0x0,0x0,0x0,0x3,0x0, 0x0,0x0,0x0,0x0,0xa,0x0,0x0,0x0, 0x9,0x0,0x50,0x0,0x9,0x0,0xb0,0x0, 0x7,0x0,0x0,0x0,0x0,0x0,0x3,0x0, 0x0,0x0,0x0,0x0,0x8,0x0,0x0,0x0, 0x8,0x0,0x50,0x0,0x8,0x0,0xb0,0x0, 0x0,0x0,0x0,0x0 }; } }
34.208122
53
0.743879
wajo10
290701c5781bd90b45d89b9372e917a8b4dd3533
14,078
cpp
C++
DNPakCrypto/DNPakCrypto/ACT_DNT.cpp
alin1337/DNSkyProject
f2126e7ac547837156c5a192ba4b02755ae2c73b
[ "WTFPL", "Unlicense" ]
4
2017-02-14T16:22:37.000Z
2018-06-10T02:29:44.000Z
DNPakCrypto/DNPakCrypto/ACT_DNT.cpp
alin1337/DNSkyProject
f2126e7ac547837156c5a192ba4b02755ae2c73b
[ "WTFPL", "Unlicense" ]
2
2017-04-14T20:11:24.000Z
2018-07-01T10:57:36.000Z
DNPakCrypto/DNPakCrypto/ACT_DNT.cpp
alin1337/DNSkyProject
f2126e7ac547837156c5a192ba4b02755ae2c73b
[ "WTFPL", "Unlicense" ]
5
2018-02-24T03:03:20.000Z
2022-02-02T02:48:14.000Z
#include <Windows.h> #include <iostream> #include <fstream> #include <algorithm> #include <string> #include <dirent.h> #include <conio.h> #include <time.h> #include "..\\..\\DNSkyProject\\vlizer.h" #include "lzo.h" #include "Header.h" #include <random> #include <stdio.h> #include <VMProtectSDK.h> using namespace std; #include <vector> using namespace std; vector<unsigned char> intToBytes(DWORD paramInt) { vector<unsigned char> arrayOfByte(4); for (int i = 0; i < 4; i++) arrayOfByte[3 - i] = (paramInt >> (i * 8)); return arrayOfByte; } void encrypt_act(const string& s) { string outputF = "encrypted_act\\" + s; std::ifstream infile(s, std::ifstream::binary); if (infile.is_open()) { infile.seekg(0, ios::end); int size = infile.tellg(); BYTE *buffer = new BYTE[size]; infile.seekg(0, ios::beg); infile.read((char*)buffer, size); if (buffer[0x15] == 0xDA || buffer[0x15] == 0xDB) { printf("%s - > Already encrypted, skipping!\n", s.c_str()); return; } if (buffer[0x00] != 'E' && buffer[0x01] != 't') { printf("%s - > Invalid ACT file, skipping!\n", s.c_str()); return; } // ///start! DWORD TotalEncryptedBytes = 0x00; DWORD i = 0x20; int key_size = 0; BYTE key[9] = { 0 }; //generare potentiale chei. DWORD test[256] = { 0 }; for (int i = 0x20; i < size; i++) { if (buffer[i] != 0x00) { test[buffer[i]] += 1; } } VMProtectBeginVirtualization("ACT Encrypt"); //lista cheilor potentiale std::vector<BYTE> chei;// = new std::vector<BYTE>(); // printf("FILE : %s \n",s.c_str()); for (int i = 1; i <= 255;i++) { if (test[i] == 0x00) { // printf("%X = %X\n",i,test[i]); chei.push_back(i); key_size++; } } int MarimeChei = chei.size(); //stabilim dimensiunea fixa 9! if (key_size > 9) key_size = 9; if (key_size != 0 && chei.size() != 0) { //alegerea cheilor din lista //printf("Chei alese : "); for (int i = 0; i < key_size; i++) { /* std::random_device rd; std::mt19937 mt(rd()); std::uniform_int_distribution<int> dist(0, chei.size()); */ key[i] = chei[(i*8)%chei.size()] & 0xFF; //hack for (int j = 0; j < chei.size(); j++) { if (chei[j] == key[i]) chei.erase(chei.begin()+j); } // printf("%X ",key[i]); } //printf("\n"); //criptare i = 0x20; //incepem de la 0x20 for (; i < size; i++) { if (buffer[i] != 0x00) { buffer[i] ^= key[i % key_size]; TotalEncryptedBytes++; if (buffer[i] == 0x00) { printf("ATTENTION, NULL HOLE!!! %X , cheie %X\n", i, key[i % key_size]); } } } //printf("%s - > Encrypted %d Bytes, Potential Keys: %d , Total Keys: %d!\n", s.c_str(), TotalEncryptedBytes, MarimeChei, key_size); //scriem header. buffer[0x15] = 0xDA; //este criptatt buffer[0x16] = key_size; //dimensiunea la chei for (int i = 0; i < key_size; i++) { buffer[i + 0x17] = key[i]; //cheile } // //encrypt key length buffer[0x16] ^= buffer[0x24]; }else{ // DWORD CryptoSize = buffer[0x24] * 10; //encrypt header for (DWORD j = 0x28; j < CryptoSize; j++) { buffer[j] ^= cheimagice[j % 512]; TotalEncryptedBytes++; } //encrypt data //encrypt data 8byte block! for (DWORD i = CryptoSize; i < size; i += CryptoSize) { for (DWORD j = 0; j < 8; j++) { buffer[i + j] ^= cheimagice[(j + 2) % 512]; } TotalEncryptedBytes += 8; } //criptare STATICA PHA! buffer[0x15] = 0xDB; //Criptate v2 //printf("%s - > Encrypted %d Bytes! Version 2\n", s.c_str(), TotalEncryptedBytes); } VMProtectEnd(); chei.clear(); ofstream outfile; outfile.open(outputF, ios::out | ios::binary); outfile.write((char*)buffer, size); outfile.close(); infile.close(); free(buffer); } return; } void decrypt_act(const string& s) { string outputF = "decrypted_act\\" + s; std::ifstream infile(s, std::ifstream::binary); if (infile.is_open()) { infile.seekg(0, ios::end); int size = infile.tellg(); BYTE *buffer = new BYTE[size]; infile.seekg(0, ios::beg); infile.read((char*)buffer, size); VMProtectBeginVirtualization("ACT DEcrypt"); if (buffer[0x15] == 0xDA) goto NEXT; if(buffer[0x15] == 0xDB) goto NEXT; printf("%s - > Not encrypted, skipping!\n", s.c_str()); return; NEXT: if (buffer[0x00] != 'E' && buffer[0x01] != 't') { printf("%s - > Invalid ACT file, skipping!\n", s.c_str()); return; } //globala DWORD TotalEncryptedBytes = 0x00; if (buffer[0x15] == 0xDA) { //decrypt key length buffer[0x16] ^= buffer[0x24]; //get keys BYTE key_size = buffer[0x16]; BYTE key[9] = { 0 }; for (BYTE i = 0; i < key_size; i++) { key[i] = buffer[i + 0x17]; } // ///start! DWORD i = 0x20; DWORD j = 0; for (; i < size; i++) { if (buffer[i] != 0x00) { buffer[i] ^= key[i % key_size]; TotalEncryptedBytes++; } } printf("%s - > DEcrypted %d Bytes!\n", s.c_str(), TotalEncryptedBytes); //HERE HEADER char *RaluKat_Stamp = "dRLKT13"; *RaluKat_Stamp = '\0'; i = 0; j = 0x15; for (; i < strlen(RaluKat_Stamp); i++) { buffer[j] = RaluKat_Stamp[i]; j++; } } else if(buffer[0x15] == 0xDB) { DWORD CryptoSize = buffer[0x24] * 10; //encrypt header for (DWORD j = 0x28; j < CryptoSize; j++) { buffer[j] ^= cheimagice[j % 512]; TotalEncryptedBytes++; } //encrypt data for (DWORD i = CryptoSize; i < size; i += CryptoSize) { buffer[i - 2] ^= cheimagice[(i + 2) % 512]; buffer[i - 1] ^= cheimagice[(i + 1) % 512]; buffer[i] ^= cheimagice[i % 512]; TotalEncryptedBytes += 3; } //criptare STATICA PHA! buffer[0x15] = 0x00; //Criptate v2 printf("%s - > DEcrypted %d Bytes!\n", s.c_str(), TotalEncryptedBytes); } VMProtectEnd(); ofstream outfile; outfile.open(outputF, ios::out | ios::binary); outfile.write((char*)buffer, size); outfile.close(); infile.close(); free(buffer); } return; } void encrypt_dnt(const string& s) { string outputF = "encrypted_dnt\\" + s; std::ifstream infile(s, std::ifstream::binary); if (infile.is_open()) { infile.seekg(0, ios::end); int size = infile.tellg(); BYTE *buffer = new BYTE[size]; infile.seekg(0, ios::beg); infile.read((char*)buffer, size); VMProtectBeginVirtualization("DNT Encrypt"); if (buffer[0x00] == 0xDA) { printf("%s - > Already encrypted, skipping!\n", s.c_str()); return; } // buffer[0x00] = 0xDA; DWORD CryptoSize = buffer[4]*10; //encrypt header for (DWORD j = 5; j < CryptoSize; j++) { buffer[j] ^= cheimagice[j % 512]; } //encrypt data 32byte block! for (DWORD i = CryptoSize; i < size; i += CryptoSize) { for (DWORD j = 0; j < 32; j++) { buffer[i + j] ^= cheimagice[(j + 2) % 512]; } } VMProtectEnd(); ofstream outfile; outfile.open(outputF, ios::out | ios::binary); outfile.write((char*)buffer, size); outfile.close(); infile.close(); free(buffer); } return; } void decrypt_dnt(const string& s) { string outputF = "decrypted_dnt\\" + s; std::ifstream infile(s, std::ifstream::binary); if (infile.is_open()) { infile.seekg(0, ios::end); int size = infile.tellg(); BYTE *buffer = new BYTE[size]; infile.seekg(0, ios::beg); infile.read((char*)buffer, size); if (buffer[0x00] != 0xDA) { printf("%s - > Not encrypted, skipping!\n", s.c_str()); return; } buffer[0] = 0x00; DWORD CryptoSize = buffer[4] * 10; VMProtectBeginVirtualization("DNT Decrypt"); //encrypt header for (DWORD j = 5; j < CryptoSize; j++) { buffer[j] ^= cheimagice[j % 512]; } //encrypt data for (DWORD i = CryptoSize; i < size; i += CryptoSize) { buffer[i - 2] ^= cheimagice[(i + 2) % 512]; buffer[i - 1] ^= cheimagice[(i + 1) % 512]; buffer[i] ^= cheimagice[i % 512]; } VMProtectEnd(); ofstream outfile; outfile.open(outputF, ios::out | ios::binary); outfile.write((char*)buffer, size); outfile.close(); infile.close(); free(buffer); } return; } void encryptTEST(const string& s) { string outputF = "encryptedACT-DNT-XML\\" + s; std::ifstream infile(s, std::ifstream::binary); bool isAct = false; if (infile.is_open()) { infile.seekg(0, ios::end); int size = infile.tellg(); BYTE *buffer = new BYTE[size]; BYTE *outBuffer = new BYTE[size*2]; infile.seekg(0, ios::beg); infile.read((char*)buffer, size); DWORD forSize = size+5; for (DWORD i = 0; i < forSize; i++) { outBuffer[i] = 0x00; } if (has_suffix(outputF, ".act")) { isAct = true; } DWORD NewSize = compress(buffer, size, outBuffer); BYTE bFileSize[4] = { 0 }; std::vector<BYTE> bytes = intToBytes(NewSize); for (int i = 0; i < bytes.size(); i++) bFileSize[i] = bytes[i]; if (isAct){ if (outBuffer[size - 1] == 0x00 && outBuffer[size - 2] == 0x00 && outBuffer[size - 3] == 0x00 && outBuffer[size - 4] == 0x00 && outBuffer[size - 5] == 0x00 && outBuffer[size - 6] == 0x00 && outBuffer[size - 7] == 0x00) { outBuffer[size - 1] = bFileSize[0]; outBuffer[size - 2] = bFileSize[1]; outBuffer[size - 3] = bFileSize[2]; outBuffer[size - 4] = bFileSize[3]; outBuffer[size - 5] = 0xDE; outBuffer[size - 7] ^= cheimagice[0]; outBuffer[size - 6] ^= cheimagice[1]; outBuffer[size - 4] ^= cheimagice[2]; outBuffer[size - 3] ^= cheimagice[3]; outBuffer[size - 2] ^= cheimagice[4]; outBuffer[size - 1] ^= cheimagice[5]; } else{ NewSize = 0; //.. } } // ofstream outfile; outfile.open(outputF, ios::out | ios::binary); if (NewSize == 0) { printf("%s NOT CRYPTED!!!!\n", s.c_str()); } else{ printf("%s OK!\n", s.c_str()); } if (NewSize == 0) { outfile.write((char*)buffer, size); //bagam un intreg pt original file size } else if(NewSize>0){ //scrie header! /*if (has_suffix(outputF, ".dnt")) { //outBuffer[3] = 0xDD; } else if (has_suffix(outputF, ".act")) { //outBuffer[0] = 0xDD; } else if (has_suffix(outputF, ".xml")) { //outBuffer[size-7] = 0xDD; }*/ if (!isAct) { outBuffer[size +4] = bFileSize[0]; outBuffer[size +3] = bFileSize[1]; outBuffer[size +2] = bFileSize[2]; outBuffer[size +1] = bFileSize[3]; outBuffer[size] = 0xDD; printf(" %.2X %.2X %.2X %.2X %.2X \n", outBuffer[size], outBuffer[size + 1], outBuffer[size + 2], outBuffer[size + 3], outBuffer[size + 4]); //Criptam footer. outBuffer[size -2] ^= cheimagice[0]; outBuffer[size -1] ^= cheimagice[1]; outBuffer[size +1] ^= cheimagice[2]; outBuffer[size +2] ^= cheimagice[3]; outBuffer[size +3] ^= cheimagice[4]; outBuffer[size +4] ^= cheimagice[5]; } //criptam header #if defined(RO) || defined(CHN) //decrypt header outBuffer[0] ^= cheimagice[10]; outBuffer[1] ^= cheimagice[11]; outBuffer[2] ^= cheimagice[12]; outBuffer[3] ^= cheimagice[13]; #endif if (isAct) { outfile.write((char*)outBuffer, size); //bagam un intreg pt original file size } else { outfile.write((char*)outBuffer, size + 5); //bagam un intreg pt original file size } //outfile.write((char*)bFileSize, sizeof(bFileSize)); //original file size } outfile.close(); infile.close(); free(outBuffer); free(buffer); } } void decryptTEST(const string &s) { string outputF = "decryptedACT-DNT-XML\\" + s; std::ifstream infile(s, std::ifstream::binary); bool isValid = TRUE; bool isAct = false; if (infile.is_open()) { infile.seekg(0, ios::end); int size = infile.tellg(); BYTE *buffer = new BYTE[size]; infile.seekg(0, ios::beg); infile.read((char*)buffer, size); //decriptam footer. if (has_suffix(outputF, ".act")) { if (buffer[size - 5] != 0xDE) { isValid = FALSE; } else if (buffer[size - 5] == 0xDE) { buffer[size - 5] = 0x00; } } if (has_suffix(outputF, ".dnt") || has_suffix(outputF, ".xml")) { if (buffer[size-5] != 0xDD) { isValid = FALSE; } else if (buffer[size - 5] == 0xDD) { buffer[size - 5] = 0x00; } } if (isValid) { #if defined(RO) || defined(CHN) //decrypt header buffer[0] ^= cheimagice[10]; buffer[1] ^= cheimagice[11]; buffer[2] ^= cheimagice[12]; buffer[3] ^= cheimagice[13]; #endif //decrypt footer buffer[size - 7] ^= cheimagice[0]; buffer[size - 6] ^= cheimagice[1]; buffer[size - 4] ^= cheimagice[2]; buffer[size - 3] ^= cheimagice[3]; buffer[size - 2] ^= cheimagice[4]; buffer[size - 1] ^= cheimagice[5]; //printf(" %.2X %.2X %.2X %.2X %.2X %.2X \n", buffer[size], buffer[size - 1], buffer[size - 2], buffer[size - 3], buffer[size - 4], buffer[size - 5]); /*buffer[size - 6] ^= cheimagice[0]; buffer[size - 5] ^= cheimagice[1]; buffer[size - 4] ^= cheimagice[2]; buffer[size - 3] ^= cheimagice[3]; buffer[size - 2] ^= cheimagice[4]; buffer[size - 1] ^= cheimagice[5];*/ } //printf("%x %x %x %x\n", buffer[size - 4], buffer[size - 3], buffer[size - 2], buffer[size-1]); DWORD OrigFileSize = (buffer[size - 1] << 24) | (buffer[size - 2] << 16) | (buffer[size - 3] << 8) | (buffer[size - 4]); //printf("Orig Size: %d\n",OrigFileSize); BYTE *outBuffer = new BYTE[size]; /* BYTE OrigSize[4] = { 0 }; std::vector<BYTE> bytes = intToBytes(size); for (int i = 0; i < bytes.size(); i++) OrigSize[i] = bytes[i]; */ DWORD NewSize = 0; if (isValid) NewSize = decompress(buffer, OrigFileSize, outBuffer); //scoatem int din size if (isValid == FALSE) { printf("%s NOT CRYPTED!!!!\n", s.c_str()); } else{ printf("%s OK!\n", s.c_str()); } ofstream outfile; outfile.open(outputF, ios::out | ios::binary); if (isValid) { outfile.write((char*)outBuffer, NewSize); }else{ outfile.write((char*)buffer, size); } outfile.close(); infile.close(); free(outBuffer); free(buffer); } }
19.912306
221
0.575437
alin1337
290df6ca8947eadb25f8ac80c44dc683dd5457d4
1,953
cpp
C++
core/graphics/layout.cpp
NebulousDev/WyvernEngine
06e506a1b1c3dba8c4b9c57a6bbc33a003519854
[ "Apache-2.0" ]
4
2018-05-23T16:40:27.000Z
2018-06-19T22:28:59.000Z
core/graphics/layout.cpp
NebulousDev/WyvernEngine
06e506a1b1c3dba8c4b9c57a6bbc33a003519854
[ "Apache-2.0" ]
null
null
null
core/graphics/layout.cpp
NebulousDev/WyvernEngine
06e506a1b1c3dba8c4b9c57a6bbc33a003519854
[ "Apache-2.0" ]
null
null
null
#include "layout.h" #include "graphics.h" static InputLayout sLayouts[MAX_INPUT_LAYOUTS] = {}; static uint32 sNextLayout = 0; static bool8 sInitialized = false; bool8 ValidateLayoutHandle(InputLayoutHandle hHandle) { return hHandle > -1 && hHandle < (MAX_INPUT_LAYOUTS + 1) && sLayouts[hHandle].valid; } const InputLayoutHandle CreateInputLayout(const InputLayoutInfo info) { if (!sInitialized) { for (uint32 i = 0; i < MAX_INPUT_LAYOUTS; i++) { sLayouts[i].hID = i; sLayouts[i].hNext = i + 1; } sInitialized = true; } InputLayoutHandle hLayout = sNextLayout; if (sNextLayout > MAX_INPUT_LAYOUTS) { //TODO: throw error? return INVALID_HANDLE; } InputLayout* pLayout = &sLayouts[hLayout]; pLayout->pElements = info.pElements; pLayout->elementCount = info.elementCount; pLayout->valid = true; if (!GetCurrentContext()->fpCreateInputLayout(&pLayout, GetCurrentContext(), info)) { //TODO: throw error? return INVALID_HANDLE; } sNextLayout = sLayouts[hLayout].hNext; return hLayout; } RESULT ReleaseInputLayout(InputLayoutHandle* phInputLayout) { if (phInputLayout != NULLPTR && ValidateLayoutHandle(*phInputLayout)) { InputLayout* pInputLayout = &sLayouts[*phInputLayout]; if (GetCurrentContext()->fpReleaseInputLayout(&pInputLayout, GetCurrentContext())) { sLayouts[*phInputLayout].hNext = sNextLayout; sNextLayout = sLayouts[*phInputLayout].hID; pInputLayout->valid = false; *phInputLayout = INVALID_HANDLE; return SUCCESS; } } return FAILURE; } RESULT BindInputLayout(InputLayoutHandle hInputLayout) { if (ValidateLayoutHandle(hInputLayout)) return GetCurrentContext()->fpBindInputLayout(&sLayouts[hInputLayout], GetCurrentContext()); return FAILURE; } RESULT UnbindInputLayout(InputLayoutHandle hInputLayout) { if (ValidateLayoutHandle(hInputLayout)) return GetCurrentContext()->fpUnbindInputLayout(&sLayouts[hInputLayout], GetCurrentContext()); return FAILURE; }
24.4125
96
0.747568
NebulousDev
290e287b9485e49bf9303d3de19ceaf168fad9ef
2,312
hpp
C++
include/bounded/detail/underlying_type.hpp
davidstone/bounded-integer
d4f9a88a12174ca8382af60b00c5affd19aa8632
[ "BSL-1.0" ]
44
2020-10-03T21:37:52.000Z
2022-03-26T10:08:46.000Z
include/bounded/detail/underlying_type.hpp
davidstone/bounded-integer
d4f9a88a12174ca8382af60b00c5affd19aa8632
[ "BSL-1.0" ]
1
2021-01-01T23:22:39.000Z
2021-01-01T23:22:39.000Z
include/bounded/detail/underlying_type.hpp
davidstone/bounded-integer
d4f9a88a12174ca8382af60b00c5affd19aa8632
[ "BSL-1.0" ]
null
null
null
// Copyright David Stone 2017. // 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) #pragma once #include <bounded/detail/comparison.hpp> #include <bounded/detail/int128.hpp> #include <bounded/detail/overlapping_range.hpp> #include <bounded/detail/type.hpp> namespace bounded { namespace detail { template<typename T> constexpr auto range_fits_in_type(auto const minimum, auto const maximum) { return value_fits_in_type<T>(minimum) and value_fits_in_type<T>(maximum); } template<auto...> inline constexpr auto false_ = false; template<auto minimum, auto maximum> constexpr auto determine_type() { if constexpr (range_fits_in_type<unsigned char>(minimum, maximum)) { return types<unsigned char>{}; } else if constexpr (range_fits_in_type<signed char>(minimum, maximum)) { return types<signed char>{}; } else if constexpr (range_fits_in_type<unsigned short>(minimum, maximum)) { return types<unsigned short>{}; } else if constexpr (range_fits_in_type<signed short>(minimum, maximum)) { return types<signed short>{}; } else if constexpr (range_fits_in_type<unsigned int>(minimum, maximum)) { return types<unsigned int>{}; } else if constexpr (range_fits_in_type<signed int>(minimum, maximum)) { return types<signed int>{}; } else if constexpr (range_fits_in_type<unsigned long>(minimum, maximum)) { return types<unsigned long>{}; } else if constexpr (range_fits_in_type<signed long>(minimum, maximum)) { return types<signed long>{}; } else if constexpr (range_fits_in_type<unsigned long long>(minimum, maximum)) { return types<unsigned long long>{}; } else if constexpr (range_fits_in_type<signed long long>(minimum, maximum)) { return types<signed long long>{}; #if defined BOUNDED_DETAIL_HAS_128_BIT } else if constexpr (range_fits_in_type<uint128_t>(minimum, maximum)) { return types<uint128_t>{}; } else if constexpr (range_fits_in_type<int128_t>(minimum, maximum)) { return types<int128_t>{}; #endif } else { static_assert(false_<minimum, maximum>, "Bounds cannot fit in any type."); } } template<auto minimum, auto maximum> using underlying_type_t = typename decltype(determine_type<minimum, maximum>())::type; } // namespace detail } // namespace bounded
36.698413
86
0.754758
davidstone
290f0e43b3e843c5b55ae10774695af5f843ca99
591
cpp
C++
LCP.cpp
laxmena/CodeKata
6ae0b911f1a436f691dfac13a760a53beedf7405
[ "MIT" ]
null
null
null
LCP.cpp
laxmena/CodeKata
6ae0b911f1a436f691dfac13a760a53beedf7405
[ "MIT" ]
null
null
null
LCP.cpp
laxmena/CodeKata
6ae0b911f1a436f691dfac13a760a53beedf7405
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main(){ vector<string> bucket; int n,minStr = INT_MAX; string temp; cout<<"enter number of strings: "; cin>>n; for(int i=0;i<n;i++){ cin>>temp; if(temp.size() < minStr) minStr = temp.size(); bucket.push_back(temp); } int prefixLen = 0; for(int i=0;i<minStr;i++){ for(int j=0;j<bucket.size()-1;j++){ if(bucket[j][i] != bucket[j+1][i]){ if(prefixLen == 0) cout<<"No Common Prefix found"; cout<<bucket[0].substr(0,prefixLen)<<endl; return 0; } } prefixLen++; } cout<<bucket[0]<<endl; return 0; }
18.46875
54
0.597293
laxmena
290f2cd9b71db8f4be70b7a7a61889028ec99130
3,868
cc
C++
gax/backoff_policy_test.cc
software-dov/gapic-generator-cpp
c5898a519bd2765ff02e3e0303dbb09ac17b41a0
[ "Apache-2.0" ]
9
2019-03-14T16:00:58.000Z
2021-10-07T21:32:08.000Z
gax/backoff_policy_test.cc
software-dov/gapic-generator-cpp
c5898a519bd2765ff02e3e0303dbb09ac17b41a0
[ "Apache-2.0" ]
43
2019-03-05T01:17:40.000Z
2020-07-18T03:43:21.000Z
gax/backoff_policy_test.cc
software-dov/gapic-generator-cpp
c5898a519bd2765ff02e3e0303dbb09ac17b41a0
[ "Apache-2.0" ]
9
2019-03-01T16:19:32.000Z
2020-11-03T11:05:45.000Z
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "gax/backoff_policy.h" #include <gtest/gtest.h> #include <chrono> #include <memory> #include <random> namespace google { namespace gax { TEST(ExponentialBackoffPolicy, Basic) { ExponentialBackoffPolicy tested(std::chrono::milliseconds(1), std::chrono::milliseconds(32)); for (int i = 0; i < 5; ++i) { auto base_delay = tested.current_delay_range_; EXPECT_EQ(base_delay, std::chrono::milliseconds(1 << i)); auto delay = tested.OnCompletion(); EXPECT_GE(delay, base_delay / 2.0); EXPECT_LE(delay, base_delay); } EXPECT_EQ(tested.current_delay_range_, tested.maximum_delay_); // current_delay_range_ saturates to max delay. tested.OnCompletion(); EXPECT_EQ(tested.current_delay_range_, tested.maximum_delay_); } TEST(ExponentialBackoffPolicy, CopyConstruct) { ExponentialBackoffPolicy tested(std::chrono::milliseconds(10), std::chrono::milliseconds(320)); tested.OnCompletion(); ExponentialBackoffPolicy copy( tested); // Copy starts with fresh backoff delays EXPECT_EQ(copy.current_delay_range_, std::chrono::milliseconds(10)); EXPECT_EQ(copy.maximum_delay_, std::chrono::milliseconds(320)); } TEST(ExponentialBackoffPolicy, MoveConstruct) { ExponentialBackoffPolicy tested(std::chrono::milliseconds(10), std::chrono::milliseconds(320)); tested.OnCompletion(); ExponentialBackoffPolicy moved( std::move(tested)); // Starts with fresh backoff delays EXPECT_EQ(moved.current_delay_range_, std::chrono::milliseconds(10)); EXPECT_EQ(moved.maximum_delay_, std::chrono::milliseconds(320)); } TEST(ExponentialBackoffPolicy, Clone) { ExponentialBackoffPolicy tested(std::chrono::milliseconds(10), std::chrono::milliseconds(320)); tested.OnCompletion(); std::unique_ptr<BackoffPolicy> clone = tested.clone(); // We need to check that the clone method has the right signature, but we also // need to check that the clone attributes have the right initial values. auto cast_clone = std::unique_ptr<ExponentialBackoffPolicy>( static_cast<ExponentialBackoffPolicy*>(clone.release())); EXPECT_EQ(cast_clone->current_delay_range_, std::chrono::milliseconds(10)); EXPECT_EQ(cast_clone->maximum_delay_, std::chrono::milliseconds(320)); } TEST(ExponentialBackoffPolicy, LazyGenerator) { ExponentialBackoffPolicy tested(std::chrono::milliseconds(10), std::chrono::milliseconds(320)); EXPECT_EQ(tested.generator_, nullptr); tested.OnCompletion(); EXPECT_NE(tested.generator_, nullptr); // Copies and clones use their own lazily constructed generators ExponentialBackoffPolicy copy(tested); EXPECT_EQ(copy.generator_, nullptr); copy.OnCompletion(); EXPECT_NE(copy.generator_, nullptr); auto clone = std::unique_ptr<ExponentialBackoffPolicy>( static_cast<ExponentialBackoffPolicy*>(copy.clone().release())); EXPECT_EQ(clone->generator_, nullptr); clone->OnCompletion(); EXPECT_NE(clone->generator_, nullptr); // Moves reuse the existing generator ExponentialBackoffPolicy move(std::move(tested)); EXPECT_NE(move.generator_, nullptr); } } // namespace gax } // namespace google
36.838095
80
0.721044
software-dov
291655fe5de39ea765a8d9575aa61f7c3a8e220e
10,493
hpp
C++
samples/slam_or_pt_tutorial_1/cpp/pt/pt_module.hpp
bram4370/realsense_samples
69a1ca2c00765c76d524da56c6026e7abb95c1e3
[ "Apache-2.0" ]
36
2016-09-27T14:42:59.000Z
2021-09-22T09:45:41.000Z
samples/slam_or_pt_tutorial_1/cpp/pt/pt_module.hpp
bram4370/realsense_samples
69a1ca2c00765c76d524da56c6026e7abb95c1e3
[ "Apache-2.0" ]
12
2016-12-14T18:32:19.000Z
2017-12-19T13:46:04.000Z
samples/slam_or_pt_tutorial_1/cpp/pt/pt_module.hpp
bram4370/realsense_samples
69a1ca2c00765c76d524da56c6026e7abb95c1e3
[ "Apache-2.0" ]
22
2017-01-31T22:23:36.000Z
2022-02-18T11:59:28.000Z
// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2017 Intel Corporation. All Rights Reserved. #pragma once #include <sys/stat.h> #include <string> #include <iostream> #include <unistd.h> #include <thread> #include <mutex> #include <algorithm> #include <set> #include <iomanip> #include <librealsense/rs.hpp> #include <signal.h> #include "rs_sdk.h" #include "person_tracking_video_module_factory.h" namespace RS = Intel::RealSense; using namespace RS::PersonTracking; using namespace std; using namespace rs::core; class PT_module { public: PT_module(module_result_listener_interface* module_listener) : lastPersonCount(0), totalPersonIncrements(0), prevPeopleInFrame(-1), prevPeopleTotal(-1), id_set(nullptr), pt_initialized(false), pt_is_running(false), m_stopped(false), m_module_listener(module_listener) { dataDir = get_data_files_path(); // Create person tracker video module ptModule.reset(rs::person_tracking::person_tracking_video_module_factory:: create_person_tracking_video_module(dataDir.c_str())); m_sample_set = new rs::core::correlated_sample_set(); } int init_pt(rs::core::video_module_interface::supported_module_config& cfg, rs::device* device) { // Configure camera and get parameters for person tracking video module auto actualModuleConfig = ConfigureCamera(device, cfg); // Configure projection rs::core::intrinsics color_intrin = rs::utils::convert_intrinsics(device->get_stream_intrinsics(rs::stream::color)); rs::core::intrinsics depth_intrin = rs::utils::convert_intrinsics(device->get_stream_intrinsics(rs::stream::depth)); rs::core::extrinsics extrinsics = rs::utils::convert_extrinsics(device->get_extrinsics(rs::stream::depth, rs::stream::color)); actualModuleConfig.projection = rs::core::projection_interface::create_instance(&color_intrin, &depth_intrin, &extrinsics); // Enabling Person head pose and orientation ptModule->QueryConfiguration()->QueryTracking()->Enable(); ptModule->QueryConfiguration()->QueryTracking()->SetTrackingMode((Intel::RealSense::PersonTracking::PersonTrackingConfiguration::TrackingConfiguration::TrackingMode)0); // Set the enabled module configuration if(ptModule->set_module_config(actualModuleConfig) != rs::core::status_no_error) { cerr<<"error : failed to set the enabled module configuration" << endl; return -1; } pt_initialized = true; cout << "init_pt complete" << endl; return 0; } bool negotiate_supported_cfg( rs::core::video_module_interface::supported_module_config& slam_config) { slam_config.image_streams_configs[(int)rs::stream::color].size.width = 640; slam_config.image_streams_configs[(int)rs::stream::color].size.height = 480; slam_config[stream_type::color].is_enabled = true; slam_config[stream_type::color].frame_rate = 30.f; return true; } int query_supported_config(rs::device* device, video_module_interface::supported_module_config& supported_config) { supported_config.image_streams_configs[(int)rs::stream::color].size.width = 640; supported_config.image_streams_configs[(int)rs::stream::color].size.height = 480; supported_config[stream_type::color].is_enabled = true; supported_config[stream_type::color].frame_rate = 30.f; supported_config.image_streams_configs[(int)rs::stream::depth].size.width = 320; supported_config.image_streams_configs[(int)rs::stream::depth].size.height = 240; supported_config[stream_type::depth].is_enabled = true; supported_config[stream_type::depth].frame_rate = 30.f; return 0; } int process_pt(rs::core::correlated_sample_set& pt_sample_set) { std::unique_lock<std::mutex> mtx_lock(mtx); if(!pt_initialized || pt_is_running || m_stopped) { // Drop the frame mtx_lock.unlock(); return false; } pt_is_running = true; m_sample_set = &pt_sample_set; std::thread pt_work_thread(&PT_module::pt_worker, this); pt_work_thread.detach(); mtx_lock.unlock(); return 0; } void pt_worker() { // Process frame if (ptModule->process_sample_set(*m_sample_set) != rs::core::status_no_error) { cerr << "error : failed to process sample" << endl; return; } set<int>* new_ids = get_persion_ids(ptModule->QueryOutput()); int numPeopleInFrame = ptModule->QueryOutput()->QueryNumberOfPeople(); if (numPeopleInFrame > lastPersonCount) totalPersonIncrements += (numPeopleInFrame - lastPersonCount); else if(numPeopleInFrame == lastPersonCount && id_set != nullptr) { set<int> diff; set_difference(id_set->begin(), id_set->end(), new_ids->begin(), new_ids->end(), inserter(diff, diff.begin())); totalPersonIncrements += diff.size(); } if (id_set != nullptr) delete id_set; id_set = new_ids; bool people_changed =false; lastPersonCount = numPeopleInFrame; if (numPeopleInFrame != prevPeopleInFrame || totalPersonIncrements != prevPeopleTotal) { prevPeopleInFrame = numPeopleInFrame; prevPeopleTotal = totalPersonIncrements; people_changed = true; } m_module_listener->on_person_tracking_finished(*m_sample_set, numPeopleInFrame, totalPersonIncrements, people_changed); pt_is_running = false; } set<int>* get_persion_ids(PersonTrackingData* trackingData) { set<int>* id_set = new set<int>; for (int index = 0; index < trackingData->QueryNumberOfPeople(); ++index) { PersonTrackingData::Person* personData = trackingData->QueryPersonData( Intel::RealSense::PersonTracking::PersonTrackingData::ACCESS_ORDER_BY_INDEX, index); if (personData) { PersonTrackingData::PersonTracking* personTrackingData = personData->QueryTracking(); int id = personTrackingData->QueryId(); id_set->insert(id); } } return id_set; } wstring get_data_files_path() { struct stat stat_struct; if(stat(PERSON_TRACKING_DATA_FILES, &stat_struct) != 0) { cerr << "Failed to find person tracking data files at " << PERSON_TRACKING_DATA_FILES << endl; cerr << "Please check that you run sample from correct directory" << endl; exit(EXIT_FAILURE); } string person_tracking_data_files = PERSON_TRACKING_DATA_FILES; int size = person_tracking_data_files.length(); wchar_t wc_person_tracking_data_files[size + 1]; mbstowcs(wc_person_tracking_data_files, person_tracking_data_files.c_str(), size + 1); return wstring(wc_person_tracking_data_files); } rs::core::video_module_interface::actual_module_config ConfigureCamera ( rs::device* device, rs::core::video_module_interface::supported_module_config& cfg) { rs::core::video_module_interface::actual_module_config actualModuleConfig = {}; // Person tracking uses only color & depth vector<rs::core::stream_type> possible_streams = {rs::core::stream_type::depth, rs::core::stream_type::color }; for (auto &stream : possible_streams) { rs::stream librealsenseStream = rs::utils::convert_stream_type(stream); auto &supported_stream_config = cfg[stream]; int width = supported_stream_config.size.width; int height = supported_stream_config.size.height; int frame_rate = supported_stream_config.frame_rate; rs::core::video_module_interface::actual_image_stream_config &actualStreamConfig = actualModuleConfig[stream]; actualStreamConfig.size.width = width; actualStreamConfig.size.height = height; actualStreamConfig.frame_rate = frame_rate; actualStreamConfig.intrinsics = rs::utils::convert_intrinsics( device->get_stream_intrinsics(librealsenseStream)); actualStreamConfig.extrinsics = rs::utils::convert_extrinsics( device->get_extrinsics(rs::stream::depth, librealsenseStream)); actualStreamConfig.is_enabled = true; } return actualModuleConfig; } int8_t get_pixel_size(rs::format format) { switch(format) { case rs::format::any: return 0; case rs::format::z16: return 2; case rs::format::disparity16: return 2; case rs::format::xyz32f: return 4; case rs::format::yuyv: return 2; case rs::format::rgb8: return 3; case rs::format::bgr8: return 3; case rs::format::rgba8: return 4; case rs::format::bgra8: return 4; case rs::format::y8: return 1; case rs::format::y16: return 2; case rs::format::raw8: return 1; case rs::format::raw10: return 0;//not supported case rs::format::raw16: return 2; } } bool get_pt_running() { return pt_is_running; } bool get_pt_is_ready() { return pt_initialized && !pt_is_running && !m_stopped; } void stop() { m_stopped = true; } private: wstring dataDir; unique_ptr<rs::person_tracking::person_tracking_video_module_interface> ptModule; int lastPersonCount; int totalPersonIncrements; int prevPeopleInFrame; int prevPeopleTotal; set<int> *id_set; bool pt_initialized; bool pt_is_running; bool m_stopped; std::mutex mtx; rs::core::correlated_sample_set* m_sample_set; module_result_listener_interface* m_module_listener; };
34.976667
176
0.631755
bram4370
29180c6f6adc24d05286dceb2845501570ccbef1
5,028
cpp
C++
example/Mcached/McachedRequestHandler.cpp
fasShare/moxie-simple
9b21320f868ca1fe05ca5d39e70eb053d31155ee
[ "MIT" ]
1
2018-09-27T09:10:11.000Z
2018-09-27T09:10:11.000Z
example/Mcached/McachedRequestHandler.cpp
fasShare/moxie-simple
9b21320f868ca1fe05ca5d39e70eb053d31155ee
[ "MIT" ]
1
2018-09-16T07:17:29.000Z
2018-09-16T07:17:29.000Z
example/Mcached/McachedRequestHandler.cpp
fasShare/moxie-simple
9b21320f868ca1fe05ca5d39e70eb053d31155ee
[ "MIT" ]
null
null
null
#include <McachedRequestHandler.h> #include <mraft/floyd/include/floyd.h> extern floyd::Floyd *floyd_raft; moxie::McachedClientHandler::McachedClientHandler(const std::shared_ptr<PollerEvent>& client, const std::shared_ptr<moxie::NetAddress>& cad) : event_(client), peer_(cad), argc_(0), argv_() { } void moxie::McachedClientHandler::AfetrRead(const std::shared_ptr<PollerEvent>& event, EventLoop *loop) { if (ParseRedisRequest()) { DoMcachedCammand(); } if (writeBuf_.writableBytes()) { event_->EnableWrite(); loop->Modity(event); } } void moxie::McachedClientHandler::AfetrWrite(const std::shared_ptr<PollerEvent>& event, EventLoop *loop) { if (writeBuf_.readableBytes() > 0) { return; } event->DisableWrite(); loop->Modity(event); } bool moxie::McachedClientHandler::DoMcachedCammand() { ResetArgcArgv reset(argc_, argv_); assert(argc_ == argv_.size()); assert(argc_ > 0); assert(floyd_raft); //DebugArgcArgv(); slash::Status s; std::string res; s = floyd_raft->ExecMcached(argv_, res); if (s.ok()) { if (argv_[0] == "SET" || argv_[0] == "set") { res = "+OK\r\n"; ReplyString(res); } else if (argv_[0] == "get" || argv_[0] == "GET") { ReplyBulkString(res); } } else { if (argv_[0] == "SET" || argv_[0] == "set") { res = "-ERR write " + s.ToString() + " \r\n"; } else if (argv_[0] == "get" || argv_[0] == "GET") { res = "-ERR read " + s.ToString() + " \r\n"; } else { res = "-ERR request " + s.ToString() + " \r\n"; } ReplyString(res); } return true; } bool moxie::McachedClientHandler::ParseRedisRequest() { if (readBuf_.readableBytes() <= 0) { return false; } if (argc_ <= 0) { // parse buffer to get argc argv_.clear(); curArgvlen_ = -1; const char* crlf = readBuf_.findChars(Buffer::kCRLF, 2); if (crlf == nullptr) { return false; } std::string argc_str = readBuf_.retrieveAsString(crlf - readBuf_.peek()); if (argc_str[0] != '*') { ReplyString("-ERR Protocol error: invalid multibulk length\r\n"); return false; } argc_ = std::atoi(argc_str.c_str() + sizeof('*')); if (argc_ == 0) { ReplyString("-ERR Protocol error: invalid multibulk length\r\n"); return false; } // \r\n readBuf_.retrieve(2); //std::cout << "argc:" << argc_ << std::endl; } while (argv_.size() < argc_) { const char* crlf = readBuf_.findChars(Buffer::kCRLF, 2); if (crlf == nullptr) { return false; } if (curArgvlen_ < 0) { std::string argv_len = readBuf_.retrieveAsString(crlf - readBuf_.peek()); if (argv_len[0] != '$') { curArgvlen_ = -1; argc_ = 0; //std::cout << argv_len << " " << argv_len[0] << std::endl; ReplyString("-ERR Protocol error: invalid bulk length (argv_len)\r\n"); return false; } // remove $ curArgvlen_ = std::atoi(argv_len.c_str() + sizeof('$')); //std::cout << "curArgvlen_:" << curArgvlen_ << std::endl; // \r\n readBuf_.retrieve(2); } else { std::string argv_str = readBuf_.retrieveAsString(crlf - readBuf_.peek()); if (static_cast<ssize_t>(argv_str.size()) != curArgvlen_) { curArgvlen_ = -1; argc_ = 0; std::cout << argv_str << std::endl; ReplyString("-ERR Protocol error: invalid bulk length (argv_str)\r\n"); return false; } argv_.push_back(argv_str); //std::cout << "argv_str:" << argv_str << std::endl; // \r\n readBuf_.retrieve(2); curArgvlen_ = -1; // must do, to read next argv item } } // request can be solved if ((argc_ > 0) && (argv_.size() == argc_)) { return true; } return false; } void moxie::McachedClientHandler::DebugArgcArgv() const { std::cout << peer_->getIp() << ":" << peer_->getPort() << "->"; for (size_t index = 0; index < argc_; index++) { std::cout << argv_[index]; if (index != argc_ - 1) { std::cout << " "; } } std::cout << std::endl; } void moxie::McachedClientHandler::ReplyString(const std::string& error) { writeBuf_.append(error.c_str(), error.size()); } void moxie::McachedClientHandler::ReplyBulkString(const std::string& item) { writeBuf_.append("$", 1); std::string len = std::to_string(item.size()); writeBuf_.append(len.c_str(), len.size()); writeBuf_.append(Buffer::kCRLF, 2); writeBuf_.append(item.c_str(), item.size()); writeBuf_.append(Buffer::kCRLF, 2); }
31.425
143
0.532617
fasShare
291c2493a5971195986acc6175589d3ad95574e8
346
cpp
C++
examples/cpp/common/Utils.cpp
jzitelli/OculusRiftInAction
7b4136ef4af3d5c392f464cf712e618e6f6a60f9
[ "Apache-2.0" ]
135
2015-01-08T03:27:23.000Z
2022-03-06T08:30:21.000Z
examples/cpp/common/Utils.cpp
jzitelli/OculusRiftInAction
7b4136ef4af3d5c392f464cf712e618e6f6a60f9
[ "Apache-2.0" ]
34
2015-01-03T10:40:12.000Z
2021-04-15T18:24:02.000Z
examples/cpp/common/Utils.cpp
jzitelli/OculusRiftInAction
7b4136ef4af3d5c392f464cf712e618e6f6a60f9
[ "Apache-2.0" ]
80
2015-01-10T08:41:28.000Z
2022-03-06T08:30:24.000Z
#include "Common.h" namespace oria { std::string readFile(const std::string & filename) { using namespace std; ifstream ins(filename.c_str(), ios::binary); if (!ins) { throw runtime_error("Failed to load file " + filename); } assert(ins); stringstream sstr; sstr << ins.rdbuf(); return sstr.str(); } }
20.352941
61
0.615607
jzitelli
291fcbfab4f16beff40ee534f447e348a833ece6
65,591
cc
C++
tests/ut/common/graph/testcase/ge_graph/ge_model_serialize_unittest.cc
TommyLike/graphengine
da2c616522cc078c2573eca8422ff70fda229efb
[ "Apache-2.0" ]
1
2020-07-18T17:49:20.000Z
2020-07-18T17:49:20.000Z
tests/ut/common/graph/testcase/ge_graph/ge_model_serialize_unittest.cc
zengchen1024/graphengine
0c33e9d12562953ca4bd6c03cb77da2c2da74acd
[ "Apache-2.0" ]
null
null
null
tests/ut/common/graph/testcase/ge_graph/ge_model_serialize_unittest.cc
zengchen1024/graphengine
0c33e9d12562953ca4bd6c03cb77da2c2da74acd
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2019-2020 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <gtest/gtest.h> #include <functional> #include <iostream> #include <map> #include <memory> #include <queue> #include <sstream> #include <string> #include <utility> #include <vector> #define private public #define protected public #include "graph/model_serialize.h" #include "graph/detail/model_serialize_imp.h" #include "graph/ge_attr_value.h" #include "graph/utils/graph_utils.h" #include "graph/utils/tensor_utils.h" #undef private #undef protected #include "proto/ge_ir.pb.h" using namespace ge; using std::string; using std::vector; bool LinkEdge(NodePtr src_node, int32_t src_index, NodePtr dst_node, int32_t dst_index) { if (src_index >= 0) { auto src_anchor = src_node->GetOutDataAnchor(src_index); auto dst_anchor = dst_node->GetInDataAnchor(dst_index); src_anchor->LinkTo(dst_anchor); } else { auto src_anchor = src_node->GetOutControlAnchor(); auto dst_anchor = dst_node->GetInControlAnchor(); src_anchor->LinkTo(dst_anchor); } } NodePtr CreateNode(OpDescPtr op, ComputeGraphPtr owner_graph) { return owner_graph->AddNode(op); } void CompareShape(const vector<int64_t> &shape1, const vector<int64_t> &shape2) { EXPECT_EQ(shape1.size(), shape2.size()); if (shape1.size() == shape2.size()) { for (int i = 0; i < shape1.size(); i++) { EXPECT_EQ(shape1[i], shape2[i]); } } } template <typename T> void CompareList(const vector<T> &val1, const vector<T> &val2) { EXPECT_EQ(val1.size(), val2.size()); if (val1.size() == val2.size()) { for (int i = 0; i < val1.size(); i++) { EXPECT_EQ(val1[i], val2[i]); } } } static bool NamedAttrsSimpleCmp(const GeAttrValue &left, const GeAttrValue &right) { GeAttrValue::NamedAttrs val1, val2; left.GetValue<GeAttrValue::NamedAttrs>(val1); right.GetValue<GeAttrValue::NamedAttrs>(val2); if (val1.GetName() != val2.GetName()) { return false; } auto attrs1 = val1.GetAllAttrs(); auto attrs2 = val2.GetAllAttrs(); if (attrs1.size() != attrs1.size()) { return false; } for (auto it : attrs1) { auto it2 = attrs2.find(it.first); if (it2 == attrs2.end()) { // simple check return false; } if (it.second.GetValueType() != it2->second.GetValueType()) { return false; } switch (it.second.GetValueType()) { case GeAttrValue::VT_INT: { int64_t i1 = 0, i2 = 0; it.second.GetValue<GeAttrValue::INT>(i1); it2->second.GetValue<GeAttrValue::INT>(i2); if (i1 != i2) { return false; } } case GeAttrValue::VT_FLOAT: { GeAttrValue::FLOAT i1 = 0, i2 = 0; it.second.GetValue<GeAttrValue::FLOAT>(i1); it2->second.GetValue<GeAttrValue::FLOAT>(i2); if (i1 != i2) { return false; } } case GeAttrValue::VT_STRING: { string i1, i2; it.second.GetValue<GeAttrValue::STR>(i1); it2->second.GetValue<GeAttrValue::STR>(i2); if (i1 != i2) { return false; } } case GeAttrValue::VT_BOOL: { bool i1 = false, i2 = false; it.second.GetValue<GeAttrValue::BOOL>(i1); it2->second.GetValue<GeAttrValue::BOOL>(i2); if (i1 != i2) { return false; } } } } return true; } static GeAttrValue::NamedAttrs CreateNamedAttrs(const string &name, std::map<string, GeAttrValue> map) { GeAttrValue::NamedAttrs named_attrs; named_attrs.SetName(name); for (auto it : map) { named_attrs.SetAttr(it.first, it.second); } return named_attrs; } TEST(UtestGeModelSerialize, simple) { Model model("model_name", "custom version3.0"); model.SetAttr("model_key1", GeAttrValue::CreateFrom<GeAttrValue::INT>(123)); model.SetAttr("model_key2", GeAttrValue::CreateFrom<GeAttrValue::FLOAT>(456.78f)); model.SetAttr("model_key3", GeAttrValue::CreateFrom<GeAttrValue::STR>("abcd")); model.SetAttr("model_key4", GeAttrValue::CreateFrom<GeAttrValue::LIST_INT>({123, 456})); model.SetAttr("model_key5", GeAttrValue::CreateFrom<GeAttrValue::LIST_FLOAT>({456.78f, 998.90f})); model.SetAttr("model_key6", GeAttrValue::CreateFrom<GeAttrValue::LIST_STR>({"abcd", "happy"})); model.SetAttr("model_key7", GeAttrValue::CreateFrom<GeAttrValue::BOOL>(false)); model.SetAttr("model_key8", GeAttrValue::CreateFrom<GeAttrValue::LIST_BOOL>({true, false})); auto compute_graph = std::make_shared<ComputeGraph>("graph_name"); // input auto input_op = std::make_shared<OpDesc>("input", "Input"); input_op->AddOutputDesc(GeTensorDesc(GeShape({12, 32, 64, 64}), FORMAT_NCHW, DT_FLOAT)); auto input = CreateNode(input_op, compute_graph); // w1 auto w1_op = std::make_shared<OpDesc>("w1", "ConstOp"); w1_op->AddOutputDesc(GeTensorDesc(GeShape({12, 2, 64, 64, 16}), FORMAT_NC1HWC0, DT_FLOAT16)); auto w1 = CreateNode(w1_op, compute_graph); // node1 auto node1_op = std::make_shared<OpDesc>("node1", "Conv2D"); node1_op->AddInputDesc(GeTensorDesc(GeShape({12, 32, 64, 64}), FORMAT_NCHW, DT_FLOAT)); node1_op->AddInputDesc(GeTensorDesc(GeShape({12, 2, 64, 64, 16}), FORMAT_NC1HWC0, DT_FLOAT16)); node1_op->AddOutputDesc(GeTensorDesc(GeShape({12, 32, 64, 64}), FORMAT_NCHW, DT_FLOAT)); auto node1 = CreateNode(node1_op, compute_graph); // Attr set node1_op->SetAttr("node_key1", GeAttrValue::CreateFrom<GeAttrValue::BYTES>(Buffer(10))); node1_op->SetAttr("node_key2", GeAttrValue::CreateFrom<GeAttrValue::LIST_BYTES>({Buffer(20), Buffer(30)})); auto named_attrs1 = GeAttrValue::CreateFrom<GeAttrValue::NAMED_ATTRS>( CreateNamedAttrs("my_name", {{"int_val", GeAttrValue::CreateFrom<int64_t>(123)}, {"str_val", GeAttrValue::CreateFrom<string>("abc")}, {"float_val", GeAttrValue::CreateFrom<GeAttrValue::FLOAT>(345.345)}})); node1_op->SetAttr("node_key3", std::move(named_attrs1)); auto list_named_attrs = GeAttrValue::CreateFrom<GeAttrValue::LIST_NAMED_ATTRS>( {CreateNamedAttrs("my_name", {{"int_val", GeAttrValue::CreateFrom<int64_t>(123)}, {"float_val", GeAttrValue::CreateFrom<GeAttrValue::FLOAT>(345.345)}}), CreateNamedAttrs("my_name2", {{"str_val", GeAttrValue::CreateFrom<string>("abc")}, {"float_val", GeAttrValue::CreateFrom<GeAttrValue::FLOAT>(345.345)}})}); node1_op->SetAttr("node_key4", std::move(list_named_attrs)); // tensor auto tensor_data1 = "qwertyui"; auto tensor1 = std::make_shared<GeTensor>(GeTensorDesc(GeShape({2, 2, 2}), FORMAT_NCHW, DT_INT8), (uint8_t *)tensor_data1, 8); auto tensor_data2 = "asdfqwertyui"; auto tensor2 = std::make_shared<GeTensor>(GeTensorDesc(GeShape({3, 2, 2}), FORMAT_ND, DT_UINT8), (uint8_t *)tensor_data2, 12); auto tensor_data3 = "ghjkasdfqwertyui"; auto tensor3 = std::make_shared<GeTensor>(GeTensorDesc(GeShape({4, 2, 2}), FORMAT_ND, DT_UINT16), (uint8_t *)tensor_data3, 16); node1_op->SetAttr("node_key5", GeAttrValue::CreateFrom<GeAttrValue::TENSOR>(tensor1)); node1_op->SetAttr("node_key6", GeAttrValue::CreateFrom<GeAttrValue::LIST_TENSOR>({tensor2, tensor3})); auto tensor_desc = GeTensorDesc(GeShape({2, 2, 2}), FORMAT_NCHW, DT_INT16); TensorUtils::SetSize(tensor_desc, 100); node1_op->SetAttr("node_key7", GeAttrValue::CreateFrom<GeAttrValue::TENSOR_DESC>(tensor_desc)); node1_op->SetAttr("node_key8", GeAttrValue::CreateFrom<GeAttrValue::LIST_TENSOR_DESC>( {GeTensorDesc(GeShape({2, 2, 2}), FORMAT_NCHW, DT_INT32), GeTensorDesc(GeShape({2, 2, 2}), FORMAT_NCHW, DT_UINT32), GeTensorDesc(GeShape({2, 2, 2}), FORMAT_NCHW, DT_INT64), GeTensorDesc(GeShape({2, 2, 2}), FORMAT_NCHW, DT_UINT64), GeTensorDesc(GeShape({2, 2, 2}), FORMAT_NCHW, DT_BOOL), GeTensorDesc(GeShape({2, 2, 2}), FORMAT_NCHW, DT_DOUBLE)})); LinkEdge(input, 0, node1, 0); LinkEdge(w1, 0, node1, 1); Graph graph = GraphUtils::CreateGraphFromComputeGraph(compute_graph); model.SetGraph(graph); Buffer buffer; ASSERT_EQ(model.Save(buffer), GRAPH_SUCCESS); EXPECT_TRUE(buffer.GetData() != nullptr); Model model2; ASSERT_EQ(Model::Load(buffer.GetData(), buffer.GetSize(), model2), GRAPH_SUCCESS); EXPECT_EQ(model2.GetName(), "model_name"); GeAttrValue::INT model_val1; AttrUtils::GetInt(&model2, "model_key1", model_val1); EXPECT_EQ(model_val1, 123); GeAttrValue::FLOAT model_val2; AttrUtils::GetFloat(&model2, "model_key2", model_val2); EXPECT_EQ(model_val2, (float)456.78f); GeAttrValue::STR model_val3; AttrUtils::GetStr(&model2, "model_key3", model_val3); EXPECT_EQ(model_val3, "abcd"); GeAttrValue::LIST_INT model_val4; AttrUtils::GetListInt(&model2, "model_key4", model_val4); CompareList(model_val4, {123, 456}); GeAttrValue::LIST_FLOAT model_val5; AttrUtils::GetListFloat(&model2, "model_key5", model_val5); CompareList(model_val5, {456.78f, 998.90f}); GeAttrValue::LIST_STR model_val6; AttrUtils::GetListStr(&model2, "model_key6", model_val6); CompareList(model_val6, {"abcd", "happy"}); GeAttrValue::BOOL model_val7; EXPECT_EQ(AttrUtils::GetBool(&model2, "model_key7", model_val7), true); EXPECT_EQ(model_val7, false); GeAttrValue::LIST_BOOL model_val8; AttrUtils::GetListBool(&model2, "model_key8", model_val8); CompareList(model_val8, {true, false}); auto graph2 = model2.GetGraph(); const auto &s_graph = GraphUtils::GetComputeGraph(graph2); ASSERT_TRUE(s_graph != nullptr); auto s_nodes = s_graph->GetDirectNode(); ASSERT_EQ(3, s_nodes.size()); auto s_input = s_nodes.at(0); auto s_w1 = s_nodes.at(1); auto s_nod1 = s_nodes.at(2); { auto s_op = s_input->GetOpDesc(); EXPECT_EQ(s_op->GetName(), "input"); EXPECT_EQ(s_op->GetType(), "Input"); auto s_input_descs = s_op->GetAllInputsDesc(); ASSERT_EQ(s_input_descs.size(), 0); auto s_output_descs = s_op->GetAllOutputsDesc(); ASSERT_EQ(s_output_descs.size(), 1); auto desc1 = s_output_descs.at(0); EXPECT_EQ(desc1.GetFormat(), FORMAT_NCHW); EXPECT_EQ(desc1.GetDataType(), DT_FLOAT); CompareShape(desc1.GetShape().GetDims(), vector<int64_t>{12, 32, 64, 64}); auto out_anchor = s_input->GetOutDataAnchor(0); auto peer_anchors = out_anchor->GetPeerInDataAnchors(); ASSERT_EQ(peer_anchors.size(), 1); auto peer_anchor = peer_anchors.at(0); ASSERT_EQ(peer_anchor->GetIdx(), 0); ASSERT_EQ(peer_anchor->GetOwnerNode(), s_nod1); } { auto s_op = s_w1->GetOpDesc(); EXPECT_EQ(s_op->GetName(), "w1"); EXPECT_EQ(s_op->GetType(), "ConstOp"); auto s_input_descs = s_op->GetAllInputsDesc(); ASSERT_EQ(s_input_descs.size(), 0); auto s_output_descs = s_op->GetAllOutputsDesc(); ASSERT_EQ(s_output_descs.size(), 1); auto desc1 = s_output_descs.at(0); EXPECT_EQ(desc1.GetFormat(), FORMAT_NC1HWC0); EXPECT_EQ(desc1.GetDataType(), DT_FLOAT16); CompareShape(desc1.GetShape().GetDims(), vector<int64_t>{12, 2, 64, 64, 16}); auto out_anchor = s_w1->GetOutDataAnchor(0); auto peer_anchors = out_anchor->GetPeerInDataAnchors(); ASSERT_EQ(peer_anchors.size(), 1); auto peer_anchor = peer_anchors.at(0); ASSERT_EQ(peer_anchor->GetIdx(), 1); ASSERT_EQ(peer_anchor->GetOwnerNode(), s_nod1); } { auto s_op = s_nod1->GetOpDesc(); EXPECT_EQ(s_op->GetName(), "node1"); EXPECT_EQ(s_op->GetType(), "Conv2D"); auto s_input_descs = s_op->GetAllInputsDesc(); ASSERT_EQ(s_input_descs.size(), 2); auto desc1 = s_input_descs.at(0); EXPECT_EQ(desc1.GetFormat(), FORMAT_NCHW); EXPECT_EQ(desc1.GetDataType(), DT_FLOAT); CompareShape(desc1.GetShape().GetDims(), vector<int64_t>{12, 32, 64, 64}); auto desc2 = s_input_descs.at(1); EXPECT_EQ(desc2.GetFormat(), FORMAT_NC1HWC0); EXPECT_EQ(desc2.GetDataType(), DT_FLOAT16); CompareShape(desc2.GetShape().GetDims(), vector<int64_t>{12, 2, 64, 64, 16}); auto s_output_descs = s_op->GetAllOutputsDesc(); ASSERT_EQ(s_output_descs.size(), 1); auto desc3 = s_output_descs.at(0); EXPECT_EQ(desc3.GetFormat(), FORMAT_NCHW); EXPECT_EQ(desc3.GetDataType(), DT_FLOAT); CompareShape(desc3.GetShape().GetDims(), vector<int64_t>{12, 32, 64, 64}); auto out_anchor = s_nod1->GetOutDataAnchor(0); auto peer_anchors = out_anchor->GetPeerInDataAnchors(); ASSERT_EQ(peer_anchors.size(), 0); // node attrs GeAttrValue::BYTES node_val1; AttrUtils::GetBytes(s_op, "node_key1", node_val1); ASSERT_EQ(node_val1.GetSize(), 10); GeAttrValue::LIST_BYTES node_val2; AttrUtils::GetListBytes(s_op, "node_key2", node_val2); ASSERT_EQ(node_val2.size(), 2); ASSERT_EQ(node_val2[0].GetSize(), 20); ASSERT_EQ(node_val2[1].GetSize(), 30); GeAttrValue s_named_attrs; s_op->GetAttr("node_key3", s_named_attrs); EXPECT_TRUE(NamedAttrsSimpleCmp(s_named_attrs, named_attrs1)); GeAttrValue s_list_named_attrs; s_op->GetAttr("node_key4", s_list_named_attrs); EXPECT_TRUE(NamedAttrsSimpleCmp(s_list_named_attrs, list_named_attrs)); ConstGeTensorPtr s_tensor; AttrUtils::GetTensor(s_op, "node_key5", s_tensor); ASSERT_TRUE(s_tensor != nullptr); string str((char *)s_tensor->GetData().data(), s_tensor->GetData().size()); EXPECT_EQ(str, "qwertyui"); vector<ConstGeTensorPtr> s_list_tensor; AttrUtils::GetListTensor(s_op, "node_key6", s_list_tensor); ASSERT_EQ(s_list_tensor.size(), 2); string str2((char *)s_list_tensor[0]->GetData().data(), s_list_tensor[0]->GetData().size()); EXPECT_EQ(str2, "asdfqwertyui"); string str3((char *)s_list_tensor[1]->GetData().data(), s_list_tensor[1]->GetData().size()); EXPECT_EQ(str3, "ghjkasdfqwertyui"); GeTensorDesc s_tensor_desc; AttrUtils::GetTensorDesc(s_op, "node_key7", s_tensor_desc); EXPECT_EQ(s_tensor_desc.GetFormat(), FORMAT_NCHW); EXPECT_EQ(s_tensor_desc.GetDataType(), DT_INT16); uint32_t size = 0; TensorUtils::GetSize(s_tensor_desc, size); EXPECT_EQ(size, 100); vector<GeTensorDesc> s_list_tensor_desc; AttrUtils::GetListTensorDesc(s_op, "node_key8", s_list_tensor_desc); ASSERT_EQ(s_list_tensor_desc.size(), 6); EXPECT_EQ(s_list_tensor_desc[0].GetDataType(), DT_INT32); EXPECT_EQ(s_list_tensor_desc[1].GetDataType(), DT_UINT32); EXPECT_EQ(s_list_tensor_desc[2].GetDataType(), DT_INT64); EXPECT_EQ(s_list_tensor_desc[3].GetDataType(), DT_UINT64); EXPECT_EQ(s_list_tensor_desc[4].GetDataType(), DT_BOOL); EXPECT_EQ(s_list_tensor_desc[5].GetDataType(), DT_DOUBLE); } } TEST(UtestGeModelSerialize, op_desc) { // node1_op auto node1_op = std::make_shared<OpDesc>("node1", "Conv2D"); node1_op->AddInputDesc(GeTensorDesc(GeShape({12, 32, 64, 64}), FORMAT_NCHW, DT_FLOAT)); node1_op->AddInputDesc(GeTensorDesc(GeShape({12, 2, 64, 64, 16}), FORMAT_NC1HWC0, DT_FLOAT16)); node1_op->AddOutputDesc(GeTensorDesc(GeShape({12, 32, 64, 64}), FORMAT_NCHW, DT_FLOAT)); // Attr set node1_op->SetAttr("node_key1", GeAttrValue::CreateFrom<GeAttrValue::BYTES>(Buffer(10))); node1_op->SetAttr("node_key2", GeAttrValue::CreateFrom<GeAttrValue::LIST_BYTES>({Buffer(20), Buffer(30)})); auto named_attrs1 = GeAttrValue::CreateFrom<GeAttrValue::NAMED_ATTRS>( CreateNamedAttrs("my_name", {{"int_val", GeAttrValue::CreateFrom<int64_t>(123)}, {"str_val", GeAttrValue::CreateFrom<string>("abc")}, {"float_val", GeAttrValue::CreateFrom<GeAttrValue::FLOAT>(345.345)}})); node1_op->SetAttr("node_key3", std::move(named_attrs1)); auto list_named_attrs = GeAttrValue::CreateFrom<GeAttrValue::LIST_NAMED_ATTRS>( {CreateNamedAttrs("my_name", {{"int_val", GeAttrValue::CreateFrom<int64_t>(123)}, {"float_val", GeAttrValue::CreateFrom<GeAttrValue::FLOAT>(345.345)}}), CreateNamedAttrs("my_name2", {{"str_val", GeAttrValue::CreateFrom<string>("abc")}, {"float_val", GeAttrValue::CreateFrom<GeAttrValue::FLOAT>(345.345)}})}); node1_op->SetAttr("node_key4", std::move(list_named_attrs)); ModelSerialize model_serialize; Buffer buffer = model_serialize.SerializeOpDesc(node1_op); EXPECT_TRUE(buffer.GetData() != nullptr); auto s_op = model_serialize.UnserializeOpDesc(buffer.GetData(), buffer.GetSize()); ASSERT_TRUE(s_op != nullptr); { EXPECT_EQ(s_op->GetName(), "node1"); EXPECT_EQ(s_op->GetType(), "Conv2D"); auto s_input_descs = s_op->GetAllInputsDesc(); ASSERT_EQ(s_input_descs.size(), 2); auto desc1 = s_input_descs.at(0); EXPECT_EQ(desc1.GetFormat(), FORMAT_NCHW); EXPECT_EQ(desc1.GetDataType(), DT_FLOAT); CompareShape(desc1.GetShape().GetDims(), vector<int64_t>{12, 32, 64, 64}); auto desc2 = s_input_descs.at(1); EXPECT_EQ(desc2.GetFormat(), FORMAT_NC1HWC0); EXPECT_EQ(desc2.GetDataType(), DT_FLOAT16); CompareShape(desc2.GetShape().GetDims(), vector<int64_t>{12, 2, 64, 64, 16}); auto s_output_descs = s_op->GetAllOutputsDesc(); ASSERT_EQ(s_output_descs.size(), 1); auto desc3 = s_output_descs.at(0); EXPECT_EQ(desc3.GetFormat(), FORMAT_NCHW); EXPECT_EQ(desc3.GetDataType(), DT_FLOAT); CompareShape(desc3.GetShape().GetDims(), vector<int64_t>{12, 32, 64, 64}); // node attrs GeAttrValue::BYTES node_val1; AttrUtils::GetBytes(s_op, "node_key1", node_val1); ASSERT_EQ(node_val1.GetSize(), 10); GeAttrValue::LIST_BYTES node_val2; AttrUtils::GetListBytes(s_op, "node_key2", node_val2); ASSERT_EQ(node_val2.size(), 2); ASSERT_EQ(node_val2[0].GetSize(), 20); ASSERT_EQ(node_val2[1].GetSize(), 30); GeAttrValue s_named_attrs; s_op->GetAttr("node_key3", s_named_attrs); EXPECT_TRUE(NamedAttrsSimpleCmp(s_named_attrs, named_attrs1)); GeAttrValue s_list_named_attrs; s_op->GetAttr("node_key4", s_list_named_attrs); EXPECT_TRUE(NamedAttrsSimpleCmp(s_list_named_attrs, list_named_attrs)); } } TEST(UtestGeModelSerialize, opdesc_as_attr_value) { // node1_op auto node1_op = std::make_shared<OpDesc>("node1", "Conv2D"); node1_op->AddInputDesc(GeTensorDesc(GeShape({12, 32, 64, 64}), FORMAT_NCHW, DT_FLOAT)); node1_op->AddInputDesc(GeTensorDesc(GeShape({12, 2, 64, 64, 16}), FORMAT_NC1HWC0, DT_FLOAT16)); node1_op->AddOutputDesc(GeTensorDesc(GeShape({12, 32, 64, 64}), FORMAT_NCHW, DT_FLOAT)); // Attr set node1_op->SetAttr("node_key1", GeAttrValue::CreateFrom<GeAttrValue::BYTES>(Buffer(10))); node1_op->SetAttr("node_key2", GeAttrValue::CreateFrom<GeAttrValue::LIST_BYTES>({Buffer(20), Buffer(30)})); auto named_attrs1 = GeAttrValue::CreateFrom<GeAttrValue::NAMED_ATTRS>( CreateNamedAttrs("my_name", {{"int_val", GeAttrValue::CreateFrom<int64_t>(123)}, {"str_val", GeAttrValue::CreateFrom<string>("abc")}, {"float_val", GeAttrValue::CreateFrom<GeAttrValue::FLOAT>(345.345)}})); node1_op->SetAttr("node_key3", std::move(named_attrs1)); auto list_named_attrs = GeAttrValue::CreateFrom<GeAttrValue::LIST_NAMED_ATTRS>( {CreateNamedAttrs("my_name", {{"int_val", GeAttrValue::CreateFrom<int64_t>(123)}, {"float_val", GeAttrValue::CreateFrom<GeAttrValue::FLOAT>(345.345)}}), CreateNamedAttrs("my_name2", {{"str_val", GeAttrValue::CreateFrom<string>("abc")}, {"float_val", GeAttrValue::CreateFrom<GeAttrValue::FLOAT>(345.345)}})}); node1_op->SetAttr("node_key4", std::move(list_named_attrs)); Model model; EXPECT_TRUE(AttrUtils::SetListOpDesc(&model, "my_key", vector<OpDescPtr>{node1_op})); EXPECT_TRUE(AttrUtils::SetListInt(&model, "my_key2", {123})); EXPECT_TRUE(AttrUtils::SetListBytes(&model, "my_key3", {Buffer(100)})); vector<OpDescPtr> op_list; EXPECT_FALSE(AttrUtils::GetListOpDesc(&model, "my_error_key", op_list)); EXPECT_FALSE(AttrUtils::GetListOpDesc(&model, "my_key2", op_list)); EXPECT_TRUE(AttrUtils::GetListOpDesc(&model, "my_key", op_list)); ASSERT_TRUE(op_list.size() > 0); auto s_op = op_list[0]; { EXPECT_EQ(s_op->GetName(), "node1"); EXPECT_EQ(s_op->GetType(), "Conv2D"); auto s_input_descs = s_op->GetAllInputsDesc(); ASSERT_EQ(s_input_descs.size(), 2); auto desc1 = s_input_descs.at(0); EXPECT_EQ(desc1.GetFormat(), FORMAT_NCHW); EXPECT_EQ(desc1.GetDataType(), DT_FLOAT); CompareShape(desc1.GetShape().GetDims(), vector<int64_t>{12, 32, 64, 64}); auto desc2 = s_input_descs.at(1); EXPECT_EQ(desc2.GetFormat(), FORMAT_NC1HWC0); EXPECT_EQ(desc2.GetDataType(), DT_FLOAT16); CompareShape(desc2.GetShape().GetDims(), vector<int64_t>{12, 2, 64, 64, 16}); auto s_output_descs = s_op->GetAllOutputsDesc(); ASSERT_EQ(s_output_descs.size(), 1); auto desc3 = s_output_descs.at(0); EXPECT_EQ(desc3.GetFormat(), FORMAT_NCHW); EXPECT_EQ(desc3.GetDataType(), DT_FLOAT); CompareShape(desc3.GetShape().GetDims(), vector<int64_t>{12, 32, 64, 64}); // node attrs GeAttrValue::BYTES node_val1; AttrUtils::GetBytes(s_op, "node_key1", node_val1); ASSERT_EQ(node_val1.GetSize(), 10); GeAttrValue::LIST_BYTES node_val2; AttrUtils::GetListBytes(s_op, "node_key2", node_val2); ASSERT_EQ(node_val2.size(), 2); ASSERT_EQ(node_val2[0].GetSize(), 20); ASSERT_EQ(node_val2[1].GetSize(), 30); GeAttrValue s_named_attrs; s_op->GetAttr("node_key3", s_named_attrs); EXPECT_TRUE(NamedAttrsSimpleCmp(s_named_attrs, named_attrs1)); GeAttrValue s_list_named_attrs; s_op->GetAttr("node_key4", s_list_named_attrs); EXPECT_TRUE(NamedAttrsSimpleCmp(s_list_named_attrs, list_named_attrs)); } } TEST(UtestGeModelSerialize, test_sub_graph) { Model model("model_name", "custom version3.0"); { auto compute_graph = std::make_shared<ComputeGraph>("graph_name"); // input auto input_op = std::make_shared<OpDesc>("test", "TestOp"); input_op->AddInputDesc(GeTensorDesc(GeShape({12, 32, 64, 64}), FORMAT_NCHW, DT_FLOAT)); auto input = CreateNode(input_op, compute_graph); Graph graph = GraphUtils::CreateGraphFromComputeGraph(compute_graph); model.SetGraph(graph); auto sub_compute_graph = std::make_shared<ComputeGraph>("sub_graph"); // input auto sub_graph_input_op = std::make_shared<OpDesc>("sub_graph_test", "TestOp2"); sub_graph_input_op->AddInputDesc(GeTensorDesc(GeShape({12, 32, 64, 64}), FORMAT_NCHW, DT_FLOAT)); auto sub_graph_input = CreateNode(sub_graph_input_op, sub_compute_graph); AttrUtils::SetGraph(input_op, "sub_graph", sub_compute_graph); } ModelSerialize serialize; auto buffer = serialize.SerializeModel(model); ASSERT_GE(buffer.GetSize(), 0); ASSERT_GE(serialize.GetSerializeModelSize(model), 0); auto model2 = serialize.UnserializeModel(buffer.GetData(), buffer.GetSize()); ASSERT_TRUE(model2.GetGraph().IsValid()); auto graph2 = GraphUtils::GetComputeGraph(model2.GetGraph()); EXPECT_EQ(graph2->GetName(), "graph_name"); auto nodes2 = graph2->GetDirectNode(); ASSERT_EQ(nodes2.size(), 1); auto node2 = nodes2.at(0); EXPECT_EQ(node2->GetName(), "test"); auto node2_op = node2->GetOpDesc(); EXPECT_EQ(node2_op->GetType(), "TestOp"); auto node2_input_descs = node2_op->GetAllInputsDesc(); ASSERT_EQ(node2_input_descs.size(), 1); auto node2_input_desc = node2_input_descs.at(0); ComputeGraphPtr sub_compute_graph2; ASSERT_TRUE(AttrUtils::GetGraph(node2_op, "sub_graph", sub_compute_graph2)); EXPECT_EQ(sub_compute_graph2->GetName(), "sub_graph"); auto sub_nodes2 = sub_compute_graph2->GetDirectNode(); ASSERT_EQ(sub_nodes2.size(), 1); auto sub_node2 = sub_nodes2.at(0); EXPECT_EQ(sub_node2->GetName(), "sub_graph_test"); ASSERT_EQ(sub_node2->GetAllInDataAnchors().size(), 1); auto sub_node_op2 = sub_node2->GetOpDesc(); EXPECT_EQ(sub_node_op2->GetType(), "TestOp2"); ASSERT_EQ(sub_node_op2->GetAllInputsDesc().size(), 1); auto sub_node2_input_desc = sub_node_op2->GetAllInputsDesc().at(0); EXPECT_EQ(sub_node2_input_desc.GetShape().GetDim(1), 32); } TEST(UtestGeModelSerialize, test_list_sub_graph) { Model model("model_name", "custom version3.0"); { auto compute_graph = std::make_shared<ComputeGraph>("graph_name"); // input auto input_op = std::make_shared<OpDesc>("test", "TestOp"); input_op->AddInputDesc(GeTensorDesc(GeShape({12, 32, 64, 64}), FORMAT_NCHW, DT_FLOAT)); auto input = CreateNode(input_op, compute_graph); Graph graph = GraphUtils::CreateGraphFromComputeGraph(compute_graph); model.SetGraph(graph); auto sub_compute_graph1 = std::make_shared<ComputeGraph>("sub_graph1"); // input auto sub_graph_input_op1 = std::make_shared<OpDesc>("sub_graph_test1", "TestOp2"); sub_graph_input_op1->AddInputDesc(GeTensorDesc(GeShape({12, 32, 64, 64}), FORMAT_NCHW, DT_FLOAT)); auto sub_graph_input1 = CreateNode(sub_graph_input_op1, sub_compute_graph1); auto sub_compute_graph2 = std::make_shared<ComputeGraph>("sub_graph2"); // input auto sub_graph_input_op2 = std::make_shared<OpDesc>("sub_graph_test2", "TestOp2"); sub_graph_input_op2->AddInputDesc(GeTensorDesc(GeShape({12, 32, 64, 64}), FORMAT_NCHW, DT_FLOAT)); auto sub_graph_input2 = CreateNode(sub_graph_input_op2, sub_compute_graph2); AttrUtils::SetListGraph(input_op, "sub_graph", vector<ComputeGraphPtr>{sub_compute_graph1, sub_compute_graph2}); } ModelSerialize serialize; auto buffer = serialize.SerializeModel(model); ASSERT_GE(buffer.GetSize(), 0); auto model2 = serialize.UnserializeModel(buffer.GetData(), buffer.GetSize()); ASSERT_TRUE(model2.GetGraph().IsValid()); auto graph2 = GraphUtils::GetComputeGraph(model2.GetGraph()); EXPECT_EQ(graph2->GetName(), "graph_name"); auto nodes2 = graph2->GetDirectNode(); ASSERT_EQ(nodes2.size(), 1); auto node2 = nodes2.at(0); auto node2_op = node2->GetOpDesc(); vector<ComputeGraphPtr> list_sub_compute_graph; ASSERT_TRUE(AttrUtils::GetListGraph(node2_op, "sub_graph", list_sub_compute_graph)); ASSERT_EQ(list_sub_compute_graph.size(), 2); EXPECT_EQ(list_sub_compute_graph[0]->GetName(), "sub_graph1"); EXPECT_EQ(list_sub_compute_graph[1]->GetName(), "sub_graph2"); auto sub_nodes21 = list_sub_compute_graph[0]->GetDirectNode(); ASSERT_EQ(sub_nodes21.size(), 1); auto sub_node21 = sub_nodes21.at(0); EXPECT_EQ(sub_node21->GetName(), "sub_graph_test1"); auto sub_nodes22 = list_sub_compute_graph[1]->GetDirectNode(); ASSERT_EQ(sub_nodes22.size(), 1); auto sub_node22 = sub_nodes22.at(0); EXPECT_EQ(sub_node22->GetName(), "sub_graph_test2"); } TEST(UtestGeModelSerialize, test_format) { Model model("model_name", "custom version3.0"); { auto compute_graph = std::make_shared<ComputeGraph>("graph_name"); // input auto input_op = std::make_shared<OpDesc>("test", "TestOp"); input_op->AddInputDesc(GeTensorDesc(GeShape({12, 32, 64, 64}), FORMAT_NCHW, DT_FLOAT)); input_op->AddInputDesc(GeTensorDesc(GeShape({12, 32, 64, 64}), FORMAT_NHWC, DT_FLOAT)); input_op->AddInputDesc(GeTensorDesc(GeShape({12, 32, 64, 64}), FORMAT_ND, DT_FLOAT)); input_op->AddInputDesc(GeTensorDesc(GeShape({12, 32, 64, 64}), FORMAT_NC1HWC0, DT_FLOAT)); input_op->AddInputDesc(GeTensorDesc(GeShape({12, 32, 64, 64}), FORMAT_FRACTAL_Z, DT_FLOAT)); input_op->AddInputDesc(GeTensorDesc(GeShape({12, 32, 64, 64}), FORMAT_NC1C0HWPAD, DT_FLOAT)); input_op->AddInputDesc(GeTensorDesc(GeShape({12, 32, 64, 64}), FORMAT_NHWC1C0, DT_FLOAT)); input_op->AddInputDesc(GeTensorDesc(GeShape({12, 32, 64, 64}), FORMAT_FSR_NCHW, DT_FLOAT)); input_op->AddInputDesc(GeTensorDesc(GeShape({12, 32, 64, 64}), FORMAT_FRACTAL_DECONV, DT_FLOAT)); input_op->AddInputDesc(GeTensorDesc(GeShape({12, 32, 64, 64}), FORMAT_BN_WEIGHT, DT_FLOAT)); input_op->AddInputDesc(GeTensorDesc(GeShape({12, 32, 64, 64}), FORMAT_CHWN, DT_FLOAT)); input_op->AddInputDesc(GeTensorDesc(GeShape({12, 32, 64, 64}), FORMAT_FILTER_HWCK, DT_FLOAT)); input_op->AddInputDesc(GeTensorDesc(GeShape({12, 32, 64, 64}), FORMAT_FRACTAL_Z_C04, DT_FLOAT)); auto input = CreateNode(input_op, compute_graph); model.SetGraph(GraphUtils::CreateGraphFromComputeGraph(compute_graph)); } ModelSerialize serialize; auto buffer = serialize.SerializeModel(model); ASSERT_GE(buffer.GetSize(), 0); auto model2 = serialize.UnserializeModel(buffer.GetData(), buffer.GetSize()); ASSERT_TRUE(model2.GetGraph().IsValid()); auto graph = model2.GetGraph(); ASSERT_TRUE(GraphUtils::GetComputeGraph(graph) != nullptr); ASSERT_EQ(GraphUtils::GetComputeGraph(graph)->GetDirectNode().size(), 1); auto op = GraphUtils::GetComputeGraph(graph)->GetDirectNode().at(0)->GetOpDesc(); auto input_descs = op->GetAllInputsDesc(); ASSERT_EQ(input_descs.size(), 13); EXPECT_EQ(input_descs.at(0).GetFormat(), FORMAT_NCHW); EXPECT_EQ(input_descs.at(1).GetFormat(), FORMAT_NHWC); EXPECT_EQ(input_descs.at(2).GetFormat(), FORMAT_ND); EXPECT_EQ(input_descs.at(3).GetFormat(), FORMAT_NC1HWC0); EXPECT_EQ(input_descs.at(4).GetFormat(), FORMAT_FRACTAL_Z); EXPECT_EQ(input_descs.at(5).GetFormat(), FORMAT_NC1C0HWPAD); EXPECT_EQ(input_descs.at(6).GetFormat(), FORMAT_NHWC1C0); EXPECT_EQ(input_descs.at(7).GetFormat(), FORMAT_FSR_NCHW); EXPECT_EQ(input_descs.at(8).GetFormat(), FORMAT_FRACTAL_DECONV); EXPECT_EQ(input_descs.at(9).GetFormat(), FORMAT_BN_WEIGHT); EXPECT_EQ(input_descs.at(10).GetFormat(), FORMAT_CHWN); EXPECT_EQ(input_descs.at(11).GetFormat(), FORMAT_FILTER_HWCK); EXPECT_EQ(input_descs.at(12).GetFormat(), FORMAT_FRACTAL_Z_C04); } TEST(UtestGeModelSerialize, test_control_edge) { Model model("model_name", "custom version3.0"); { auto compute_graph = std::make_shared<ComputeGraph>("graph_name"); // input auto input_op = std::make_shared<OpDesc>("test", "TestOp"); input_op->AddInputDesc(GeTensorDesc(GeShape({12, 32, 64, 64}), FORMAT_NCHW, DT_FLOAT)); auto input = CreateNode(input_op, compute_graph); // sink auto sink_op = std::make_shared<OpDesc>("test2", "Sink"); auto sink = CreateNode(sink_op, compute_graph); LinkEdge(sink, -1, input, -1); // sink2 auto sink_op2 = std::make_shared<OpDesc>("test3", "Sink"); auto sink2 = CreateNode(sink_op2, compute_graph); LinkEdge(sink2, -1, input, -1); // dest auto dest_op = std::make_shared<OpDesc>("test4", "Dest"); auto dest = CreateNode(dest_op, compute_graph); LinkEdge(input, -1, dest, -1); compute_graph->AddInputNode(sink); compute_graph->AddInputNode(sink2); compute_graph->AddOutputNode(dest); Graph graph = GraphUtils::CreateGraphFromComputeGraph(compute_graph); model.SetGraph(graph); } ModelSerialize serialize; auto buffer = serialize.SerializeModel(model); EXPECT_GE(buffer.GetSize(), 0); auto model2 = serialize.UnserializeModel(buffer.GetData(), buffer.GetSize()); ASSERT_TRUE(model2.GetGraph().IsValid()); auto graph = GraphUtils::GetComputeGraph(model2.GetGraph()); EXPECT_EQ(graph->GetName(), "graph_name"); auto nodes = graph->GetDirectNode(); ASSERT_EQ(nodes.size(), 4); auto node1 = nodes.at(0); auto sink = nodes.at(1); auto sink2 = nodes.at(2); auto dest = nodes.at(3); EXPECT_EQ(node1->GetName(), "test"); EXPECT_EQ(sink->GetName(), "test2"); ASSERT_EQ(node1->GetAllInDataAnchors().size(), 1); auto anchor1 = node1->GetAllInDataAnchors().at(0); EXPECT_EQ(anchor1->GetPeerAnchors().size(), 0); auto contorl_in_anchor1 = node1->GetInControlAnchor(); ASSERT_EQ(contorl_in_anchor1->GetPeerAnchors().size(), 2); EXPECT_EQ(contorl_in_anchor1->GetPeerAnchors().at(0)->GetOwnerNode(), sink); EXPECT_EQ(contorl_in_anchor1->GetPeerAnchors().at(1)->GetOwnerNode(), sink2); auto contorl_out_anchor1 = node1->GetOutControlAnchor(); ASSERT_EQ(contorl_out_anchor1->GetPeerAnchors().size(), 1); EXPECT_EQ(contorl_out_anchor1->GetPeerAnchors().at(0)->GetOwnerNode(), dest); auto input_nodes = graph->GetInputNodes(); ASSERT_EQ(input_nodes.size(), 2); EXPECT_EQ(input_nodes.at(0), sink); EXPECT_EQ(input_nodes.at(1), sink2); auto output_nodes = graph->GetOutputNodes(); ASSERT_EQ(output_nodes.size(), 1); EXPECT_EQ(output_nodes.at(0), dest); } TEST(UtestGeModelSerialize, test_serialize_graph) { auto compute_graph = std::make_shared<ComputeGraph>("graph_name"); { // input auto input_op = std::make_shared<OpDesc>("test", "TestOp"); input_op->AddInputDesc(GeTensorDesc(GeShape({12, 32, 64, 64}), FORMAT_NCHW, DT_FLOAT)); auto input = CreateNode(input_op, compute_graph); // sink auto sink_op = std::make_shared<OpDesc>("test2", "Sink"); auto sink = CreateNode(sink_op, compute_graph); LinkEdge(sink, -1, input, -1); // sink2 auto sink_op2 = std::make_shared<OpDesc>("test3", "Sink"); auto sink2 = CreateNode(sink_op2, compute_graph); LinkEdge(sink2, -1, input, -1); // dest auto dest_op = std::make_shared<OpDesc>("test4", "Dest"); auto dest = CreateNode(dest_op, compute_graph); LinkEdge(input, -1, dest, -1); compute_graph->AddInputNode(sink); compute_graph->AddInputNode(sink2); compute_graph->AddOutputNode(dest); } ModelSerialize serialize; auto buffer = serialize.SerializeGraph(compute_graph); EXPECT_GE(buffer.GetSize(), 0); auto graph = serialize.UnserializeGraph(buffer.GetData(), buffer.GetSize()); ASSERT_TRUE(graph != nullptr); EXPECT_EQ(graph->GetName(), "graph_name"); auto nodes = graph->GetDirectNode(); ASSERT_EQ(nodes.size(), 4); auto node1 = nodes.at(0); auto sink = nodes.at(1); auto sink2 = nodes.at(2); auto dest = nodes.at(3); EXPECT_EQ(node1->GetName(), "test"); EXPECT_EQ(sink->GetName(), "test2"); ASSERT_EQ(node1->GetAllInDataAnchors().size(), 1); auto anchor1 = node1->GetAllInDataAnchors().at(0); EXPECT_EQ(anchor1->GetPeerAnchors().size(), 0); auto contorl_in_anchor1 = node1->GetInControlAnchor(); ASSERT_EQ(contorl_in_anchor1->GetPeerAnchors().size(), 2); EXPECT_EQ(contorl_in_anchor1->GetPeerAnchors().at(0)->GetOwnerNode(), sink); EXPECT_EQ(contorl_in_anchor1->GetPeerAnchors().at(1)->GetOwnerNode(), sink2); auto contorl_out_anchor1 = node1->GetOutControlAnchor(); ASSERT_EQ(contorl_out_anchor1->GetPeerAnchors().size(), 1); EXPECT_EQ(contorl_out_anchor1->GetPeerAnchors().at(0)->GetOwnerNode(), dest); auto input_nodes = graph->GetInputNodes(); ASSERT_EQ(input_nodes.size(), 2); EXPECT_EQ(input_nodes.at(0), sink); EXPECT_EQ(input_nodes.at(1), sink2); auto output_nodes = graph->GetOutputNodes(); ASSERT_EQ(output_nodes.size(), 1); EXPECT_EQ(output_nodes.at(0), dest); } TEST(UtestGeModelSerialize, test_invalid_model) { { // empty graph Model model("model_name", "custom version3.0"); auto compute_graph = std::make_shared<ComputeGraph>("graph_name"); ModelSerialize serialize; auto buffer = serialize.SerializeModel(model); EXPECT_EQ(buffer.GetSize(), 0); } } TEST(UtestGeModelSerialize, test_invalid_graph) { { // empty graph ComputeGraphPtr graph = nullptr; ModelSerialize serialize; auto buffer = serialize.SerializeGraph(graph); EXPECT_EQ(buffer.GetSize(), 0); } } TEST(UtestGeModelSerialize, test_invalid_opdesc) { { // empty OpDesc OpDescPtr op_desc = nullptr; ModelSerialize serialize; auto buffer = serialize.SerializeOpDesc(op_desc); EXPECT_EQ(buffer.GetSize(), 0); } } TEST(UtestGeModelSerialize, test_invalid_tensor_desc) { { // valid test Model model("model_name", "custom version3.0"); auto compute_graph = std::make_shared<ComputeGraph>("graph_name"); // input auto input_op = std::make_shared<OpDesc>("test", "TestOp"); input_op->AddOutputDesc(GeTensorDesc(GeShape({12, 32, 64, 64}), FORMAT_NCHW, DT_FLOAT)); auto input = CreateNode(input_op, compute_graph); Graph graph = GraphUtils::CreateGraphFromComputeGraph(compute_graph); model.SetGraph(graph); ModelSerialize serialize; auto buffer = serialize.SerializeModel(model); EXPECT_GE(buffer.GetSize(), 0); } { // invalid format Model model("model_name", "custom version3.0"); auto compute_graph = std::make_shared<ComputeGraph>("graph_name"); // input auto input_op = std::make_shared<OpDesc>("test", "TestOp"); input_op->AddOutputDesc(GeTensorDesc(GeShape({12, 32, 64, 64}), FORMAT_RESERVED, DT_FLOAT)); // invalid format auto input = CreateNode(input_op, compute_graph); Graph graph = GraphUtils::CreateGraphFromComputeGraph(compute_graph); model.SetGraph(graph); ModelSerialize serialize; auto buffer = serialize.SerializeModel(model); ASSERT_GE(buffer.GetSize(), 0); auto model2 = serialize.UnserializeModel(buffer.GetData(), buffer.GetSize()); ASSERT_TRUE(model2.IsValid()); auto graph_new = GraphUtils::GetComputeGraph(model2.GetGraph()); ASSERT_TRUE(graph_new != nullptr); auto node_list_new = graph_new->GetAllNodes(); ASSERT_EQ(node_list_new.size(), 1); auto opdesc_new = node_list_new.at(0)->GetOpDesc(); ASSERT_TRUE(opdesc_new != nullptr); auto output_desc_list_new = opdesc_new->GetAllOutputsDesc(); ASSERT_EQ(output_desc_list_new.size(), 1); auto output_desc_new = output_desc_list_new.at(0); EXPECT_EQ(output_desc_new.GetDataType(), DT_FLOAT); EXPECT_EQ(output_desc_new.GetFormat(), FORMAT_RESERVED); } { // DT_UNDEFINED datatype Model model("model_name", "custom version3.0"); auto compute_graph = std::make_shared<ComputeGraph>("graph_name"); // input auto input_op = std::make_shared<OpDesc>("test", "TestOp"); input_op->AddOutputDesc(GeTensorDesc(GeShape({12, 32, 64, 64}), FORMAT_NCHW, DT_UNDEFINED)); auto input = CreateNode(input_op, compute_graph); Graph graph = GraphUtils::CreateGraphFromComputeGraph(compute_graph); model.SetGraph(graph); ModelSerialize serialize; auto buffer = serialize.SerializeModel(model); ASSERT_GE(buffer.GetSize(), 0); auto model2 = serialize.UnserializeModel(buffer.GetData(), buffer.GetSize()); ASSERT_TRUE(model2.IsValid()); auto graph_new = GraphUtils::GetComputeGraph(model2.GetGraph()); ASSERT_TRUE(graph_new != nullptr); auto node_list_new = graph_new->GetAllNodes(); ASSERT_EQ(node_list_new.size(), 1); auto opdesc_new = node_list_new.at(0)->GetOpDesc(); ASSERT_TRUE(opdesc_new != nullptr); auto output_desc_list_new = opdesc_new->GetAllOutputsDesc(); ASSERT_EQ(output_desc_list_new.size(), 1); auto output_desc_new = output_desc_list_new.at(0); EXPECT_EQ(output_desc_new.GetDataType(), DT_UNDEFINED); EXPECT_EQ(output_desc_new.GetFormat(), FORMAT_NCHW); } } TEST(UtestGeModelSerialize, test_invalid_attrs) { { // valid test Model model("model_name", "custom version3.0"); auto compute_graph = std::make_shared<ComputeGraph>("graph_name"); // input auto input_op = std::make_shared<OpDesc>("test", "TestOp"); input_op->AddOutputDesc(GeTensorDesc(GeShape({12, 32, 64, 64}), FORMAT_NCHW, DT_FLOAT)); GeAttrValue::NamedAttrs named_attrs; named_attrs.SetAttr("key1", GeAttrValue::CreateFrom<GeAttrValue::INT>(10)); AttrUtils::SetNamedAttrs(input_op, "key", named_attrs); auto input = CreateNode(input_op, compute_graph); Graph graph = GraphUtils::CreateGraphFromComputeGraph(compute_graph); model.SetGraph(graph); ModelSerialize serialize; auto buffer = serialize.SerializeModel(model); EXPECT_GE(buffer.GetSize(), 0); } { // none type Model model("model_name", "custom version3.0"); auto compute_graph = std::make_shared<ComputeGraph>("graph_name"); // input auto input_op = std::make_shared<OpDesc>("test", "TestOp"); input_op->AddOutputDesc(GeTensorDesc(GeShape({12, 32, 64, 64}), FORMAT_NCHW, DT_FLOAT)); GeAttrValue::NamedAttrs named_attrs; EXPECT_EQ(named_attrs.SetAttr("key1", GeAttrValue()), GRAPH_FAILED); } { // bytes attr len is 0 Model model("model_name", "custom version3.0"); auto compute_graph = std::make_shared<ComputeGraph>("graph_name"); // input auto input_op = std::make_shared<OpDesc>("test", "TestOp"); input_op->AddOutputDesc(GeTensorDesc(GeShape({12, 32, 64, 64}), FORMAT_NCHW, DT_FLOAT)); GeAttrValue::NamedAttrs named_attrs; named_attrs.SetAttr("key1", GeAttrValue::CreateFrom<GeAttrValue::BYTES>(GeAttrValue::BYTES(0))); AttrUtils::SetNamedAttrs(input_op, "key", named_attrs); auto input = CreateNode(input_op, compute_graph); Graph graph = GraphUtils::CreateGraphFromComputeGraph(compute_graph); model.SetGraph(graph); ModelSerialize serialize; auto buffer = serialize.SerializeModel(model); EXPECT_GE(buffer.GetSize(), 0); auto model2 = serialize.UnserializeModel(buffer.GetData(), buffer.GetSize()); EXPECT_TRUE(model2.IsValid()); } { // invalid list bytes attr Model model("model_name", "custom version3.0"); auto compute_graph = std::make_shared<ComputeGraph>("graph_name"); // input auto input_op = std::make_shared<OpDesc>("test", "TestOp"); input_op->AddOutputDesc(GeTensorDesc(GeShape({12, 32, 64, 64}), FORMAT_NCHW, DT_FLOAT)); GeAttrValue::NamedAttrs named_attrs; named_attrs.SetAttr("key1", GeAttrValue::CreateFrom<GeAttrValue::LIST_BYTES>({GeAttrValue::BYTES(0)})); AttrUtils::SetNamedAttrs(input_op, "key", named_attrs); auto input = CreateNode(input_op, compute_graph); Graph graph = GraphUtils::CreateGraphFromComputeGraph(compute_graph); model.SetGraph(graph); ModelSerialize serialize; auto buffer = serialize.SerializeModel(model); EXPECT_GE(buffer.GetSize(), 0); } { // invalid graph attr Model model("model_name", "custom version3.0"); auto compute_graph = std::make_shared<ComputeGraph>("graph_name"); // input auto input_op = std::make_shared<OpDesc>("test", "TestOp"); input_op->AddOutputDesc(GeTensorDesc(GeShape({12, 32, 64, 64}), FORMAT_NCHW, DT_FLOAT)); GeAttrValue::NamedAttrs named_attrs; EXPECT_EQ(named_attrs.SetAttr("key1", GeAttrValue::CreateFrom<GeAttrValue::GRAPH>(nullptr)), GRAPH_FAILED); GeAttrValue value; EXPECT_EQ(named_attrs.GetAttr("key1", value), GRAPH_FAILED); EXPECT_TRUE(value.IsEmpty()); } { // invalid list graph attr Model model("model_name", "custom version3.0"); auto compute_graph = std::make_shared<ComputeGraph>("graph_name"); // input auto input_op = std::make_shared<OpDesc>("test", "TestOp"); input_op->AddOutputDesc(GeTensorDesc(GeShape({12, 32, 64, 64}), FORMAT_NCHW, DT_FLOAT)); GeAttrValue::NamedAttrs named_attrs; EXPECT_EQ(named_attrs.SetAttr("key1", GeAttrValue::CreateFrom<GeAttrValue::LIST_GRAPH>({nullptr})), GRAPH_FAILED); GeAttrValue value; EXPECT_EQ(named_attrs.GetAttr("key1", value), GRAPH_FAILED); EXPECT_TRUE(value.IsEmpty()); } } TEST(UtestGeModelSerialize, test_model_serialize_imp_invalid_param) { ModelSerializeImp imp; EXPECT_FALSE(imp.SerializeModel(Model(), nullptr)); EXPECT_FALSE(imp.SerializeGraph(nullptr, nullptr)); EXPECT_FALSE(imp.SerializeNode(nullptr, nullptr)); EXPECT_FALSE(imp.SerializeOpDesc(nullptr, nullptr)); auto graph = std::make_shared<ComputeGraph>("test_graph"); auto node = graph->AddNode(std::make_shared<OpDesc>()); node->op_ = nullptr; proto::ModelDef model_def; Model model; model.SetGraph(GraphUtils::CreateGraphFromComputeGraph(graph)); EXPECT_FALSE(imp.SerializeModel(model, &model_def)); ModelSerialize serialize; EXPECT_EQ(serialize.GetSerializeModelSize(model), 0); } TEST(UtestGeModelSerialize, test_parse_node_false) { ModelSerializeImp imp; string node_index = "invalid_index"; string node_name = "name"; int32_t index = 1; EXPECT_EQ(imp.ParseNodeIndex(node_index, node_name, index), false); } TEST(UtestGeModelSerialize, test_invalid_tensor) { ModelSerializeImp imp; EXPECT_EQ(imp.SerializeTensor(nullptr, nullptr), false); try { ConstGeTensorPtr tensor_ptr = std::make_shared<GeTensor>(); EXPECT_EQ(imp.SerializeTensor(tensor_ptr, nullptr), false); } catch (...) { } } TEST(UTEST_ge_model_unserialize, test_invalid_tensor) { ModelSerializeImp imp; EXPECT_EQ(imp.SerializeTensor(nullptr, nullptr), false); try { ConstGeTensorPtr tensor_ptr = std::make_shared<GeTensor>(); EXPECT_EQ(imp.SerializeTensor(tensor_ptr, nullptr), false); } catch (...) { } } TEST(UTEST_ge_model_unserialize, test_invalid_TensorDesc) { { // valid proto::ModelDef mode_def; auto attrs = mode_def.mutable_attr(); proto::AttrDef *attr_def = &(*attrs)["key1"]; auto tensor_desc_attr = attr_def->mutable_td(); tensor_desc_attr->set_layout("NCHW"); tensor_desc_attr->set_dtype(proto::DataType::DT_INT8); ModelSerializeImp imp; Model model; EXPECT_TRUE(imp.UnserializeModel(model, mode_def)); } { // invalid layout proto::ModelDef mode_def; auto attrs = mode_def.mutable_attr(); proto::AttrDef *attr_def = &(*attrs)["key1"]; auto tensor_desc_attr = attr_def->mutable_td(); tensor_desc_attr->set_layout("InvalidLayout"); tensor_desc_attr->set_dtype(proto::DataType::DT_INT8); ModelSerializeImp imp; Model model; EXPECT_TRUE(imp.UnserializeModel(model, mode_def)); GeTensorDesc tensor_desc; EXPECT_TRUE(AttrUtils::GetTensorDesc(model, "key1", tensor_desc)); EXPECT_EQ(tensor_desc.GetFormat(), FORMAT_RESERVED); EXPECT_EQ(tensor_desc.GetDataType(), DT_INT8); } { // invalid datatype proto::ModelDef mode_def; auto attrs = mode_def.mutable_attr(); proto::AttrDef *attr_def = &(*attrs)["key1"]; auto tensor_desc_attr = attr_def->mutable_td(); // tensor desc tensor_desc_attr->set_layout("NHWC"); tensor_desc_attr->set_dtype((proto::DataType)100); ModelSerializeImp imp; Model model; EXPECT_TRUE(imp.UnserializeModel(model, mode_def)); GeTensorDesc tensor_desc; EXPECT_TRUE(AttrUtils::GetTensorDesc(model, "key1", tensor_desc)); EXPECT_EQ(tensor_desc.GetFormat(), FORMAT_NHWC); EXPECT_EQ(tensor_desc.GetDataType(), DT_UNDEFINED); } { // invalid datatype proto::ModelDef mode_def; auto attrs = mode_def.mutable_attr(); proto::AttrDef *attr_def = &(*attrs)["key1"]; auto tensor_desc_attr = attr_def->mutable_t()->mutable_desc(); // tensor tensor_desc_attr->set_layout("NHWC"); tensor_desc_attr->set_dtype((proto::DataType)100); ModelSerializeImp imp; Model model; EXPECT_TRUE(imp.UnserializeModel(model, mode_def)); ConstGeTensorPtr tensor; EXPECT_TRUE(AttrUtils::GetTensor(model, "key1", tensor)); ASSERT_TRUE(tensor != nullptr); auto tensor_desc = tensor->GetTensorDesc(); EXPECT_EQ(tensor_desc.GetFormat(), FORMAT_NHWC); EXPECT_EQ(tensor_desc.GetDataType(), DT_UNDEFINED); } { // invalid attrmap proto::ModelDef mode_def; auto attrs = mode_def.add_graph()->mutable_attr(); // graph attr proto::AttrDef *attr_def = &(*attrs)["key1"]; auto tensor_desc_attr = attr_def->mutable_t()->mutable_desc(); // tensor tensor_desc_attr->set_layout("NCHW"); tensor_desc_attr->set_dtype(proto::DataType::DT_INT8); auto attrs1 = tensor_desc_attr->mutable_attr(); auto attr1 = (*attrs1)["key2"]; // empty attr ModelSerializeImp imp; Model model; EXPECT_TRUE(imp.UnserializeModel(model, mode_def)); auto graph = GraphUtils::GetComputeGraph(model.GetGraph()); ASSERT_TRUE(graph != nullptr); ConstGeTensorPtr tensor; EXPECT_TRUE(AttrUtils::GetTensor(graph, "key1", tensor)); ASSERT_TRUE(tensor != nullptr); auto tensor_desc = tensor->GetTensorDesc(); GeAttrValue attr_value; EXPECT_EQ(tensor_desc.GetAttr("key2", attr_value), GRAPH_SUCCESS); EXPECT_EQ(attr_value.GetValueType(), GeAttrValue::VT_NONE); } { // invalid attrmap2 proto::ModelDef mode_def; auto attrs = mode_def.add_graph()->add_op()->mutable_attr(); // node attr proto::AttrDef *attr_def = &(*attrs)["key1"]; auto tensor_desc_attr = attr_def->mutable_t()->mutable_desc(); // tensor tensor_desc_attr->set_layout("NCHW"); tensor_desc_attr->set_dtype(proto::DataType::DT_INT8); auto attrs1 = tensor_desc_attr->mutable_attr(); auto attr1 = (*attrs1)["key2"].mutable_list(); // empty list attr ModelSerializeImp imp; Model model; EXPECT_TRUE(imp.UnserializeModel(model, mode_def)); auto graph = GraphUtils::GetComputeGraph(model.GetGraph()); ASSERT_TRUE(graph != nullptr); auto nodes = graph->GetAllNodes(); ASSERT_EQ(nodes.size(), 1); ConstGeTensorPtr tensor; EXPECT_TRUE(AttrUtils::GetTensor(nodes.at(0)->GetOpDesc(), "key1", tensor)); ASSERT_TRUE(tensor != nullptr); auto tensor_desc = tensor->GetTensorDesc(); GeAttrValue attr_value; EXPECT_EQ(tensor_desc.GetAttr("key2", attr_value), GRAPH_SUCCESS); EXPECT_EQ(attr_value.GetValueType(), GeAttrValue::VT_NONE); } } TEST(UTEST_ge_model_unserialize, test_invalid_attr) { { // invalid graph proto::ModelDef mode_def; auto attrs = mode_def.add_graph()->add_op()->mutable_attr(); // node attr proto::AttrDef *attr_def = &(*attrs)["key1"]; auto graph_attr = attr_def->mutable_g(); auto attrs_of_graph = graph_attr->mutable_attr(); auto tensor_val = (*attrs_of_graph)["key2"].mutable_td(); tensor_val->set_dtype(proto::DT_INT8); tensor_val->set_layout("invalidLayout"); ModelSerializeImp imp; Model model; EXPECT_TRUE(imp.UnserializeModel(model, mode_def)); auto graph = GraphUtils::GetComputeGraph(model.GetGraph()); ASSERT_TRUE(graph != nullptr); auto nodes = graph->GetAllNodes(); ASSERT_EQ(nodes.size(), 1); ComputeGraphPtr graph_attr_new; EXPECT_TRUE(AttrUtils::GetGraph(nodes.at(0)->GetOpDesc(), "key1", graph_attr_new)); ASSERT_TRUE(graph_attr_new != nullptr); GeTensorDesc tensor_desc1; EXPECT_TRUE(AttrUtils::GetTensorDesc(graph_attr_new, "key2", tensor_desc1)); EXPECT_EQ(tensor_desc1.GetFormat(), FORMAT_RESERVED); EXPECT_EQ(tensor_desc1.GetDataType(), DT_INT8); } { // invalid list graph proto::ModelDef mode_def; auto attrs = mode_def.add_graph()->add_op()->mutable_attr(); // node attr proto::AttrDef *attr_def = &(*attrs)["key1"]; attr_def->mutable_list()->set_val_type(ge::proto::AttrDef_ListValue_ListValueType_VT_LIST_GRAPH); auto graph_attr = attr_def->mutable_list()->add_g(); auto attrs_of_graph = graph_attr->mutable_attr(); auto tensor_val = (*attrs_of_graph)["key2"].mutable_td(); tensor_val->set_dtype(proto::DT_INT8); tensor_val->set_layout("invalidLayout"); ModelSerializeImp imp; Model model; EXPECT_TRUE(imp.UnserializeModel(model, mode_def)); auto graph = GraphUtils::GetComputeGraph(model.GetGraph()); ASSERT_TRUE(graph != nullptr); auto nodes = graph->GetAllNodes(); ASSERT_EQ(nodes.size(), 1); vector<ComputeGraphPtr> graph_list_attr; EXPECT_TRUE(AttrUtils::GetListGraph(nodes.at(0)->GetOpDesc(), "key1", graph_list_attr)); ASSERT_EQ(graph_list_attr.size(), 1); ASSERT_TRUE(graph_list_attr[0] != nullptr); GeTensorDesc tensor_desc1; EXPECT_TRUE(AttrUtils::GetTensorDesc(graph_list_attr[0], "key2", tensor_desc1)); EXPECT_EQ(tensor_desc1.GetFormat(), FORMAT_RESERVED); EXPECT_EQ(tensor_desc1.GetDataType(), DT_INT8); } { // invalid named_attrs proto::ModelDef mode_def; auto attrs = mode_def.add_graph()->add_op()->mutable_attr(); // node attr proto::AttrDef *attr_def = &(*attrs)["key1"]; auto graph_attr = attr_def->mutable_func(); auto attrs_of_graph = graph_attr->mutable_attr(); auto tensor_val = (*attrs_of_graph)["key2"].mutable_td(); tensor_val->set_dtype(proto::DT_INT8); tensor_val->set_layout("invalidLayout"); ModelSerializeImp imp; Model model; EXPECT_TRUE(imp.UnserializeModel(model, mode_def)); auto graph = GraphUtils::GetComputeGraph(model.GetGraph()); ASSERT_TRUE(graph != nullptr); auto nodes = graph->GetAllNodes(); ASSERT_EQ(nodes.size(), 1); GeAttrValue::NAMED_ATTRS named_attrs; EXPECT_TRUE(AttrUtils::GetNamedAttrs(nodes.at(0)->GetOpDesc(), "key1", named_attrs)); GeTensorDesc tensor_desc1; EXPECT_TRUE(AttrUtils::GetTensorDesc(named_attrs, "key2", tensor_desc1)); EXPECT_EQ(tensor_desc1.GetFormat(), FORMAT_RESERVED); EXPECT_EQ(tensor_desc1.GetDataType(), DT_INT8); } { // invalid list named_attrs proto::ModelDef mode_def; auto attrs = mode_def.add_graph()->add_op()->mutable_attr(); // node attr proto::AttrDef *attr_def = &(*attrs)["key1"]; attr_def->mutable_list()->set_val_type(ge::proto::AttrDef_ListValue_ListValueType_VT_LIST_NAMED_ATTRS); auto graph_attr = attr_def->mutable_list()->add_na(); auto attrs_of_graph = graph_attr->mutable_attr(); auto tensor_val = (*attrs_of_graph)["key2"].mutable_td(); tensor_val->set_dtype(proto::DT_INT8); tensor_val->set_layout("invalidLayout"); ModelSerializeImp imp; Model model; EXPECT_TRUE(imp.UnserializeModel(model, mode_def)); auto graph = GraphUtils::GetComputeGraph(model.GetGraph()); ASSERT_TRUE(graph != nullptr); auto nodes = graph->GetAllNodes(); ASSERT_EQ(nodes.size(), 1); GeAttrValue::LIST_NAMED_ATTRS named_attrs; EXPECT_TRUE(AttrUtils::GetListNamedAttrs(nodes.at(0)->GetOpDesc(), "key1", named_attrs)); ASSERT_EQ(named_attrs.size(), 1); GeTensorDesc tensor_desc1; EXPECT_TRUE(AttrUtils::GetTensorDesc(named_attrs.at(0), "key2", tensor_desc1)); EXPECT_EQ(tensor_desc1.GetFormat(), FORMAT_RESERVED); EXPECT_EQ(tensor_desc1.GetDataType(), DT_INT8); } { // invalid tensor_desc proto::ModelDef mode_def; auto attrs = mode_def.add_graph()->add_op()->mutable_attr(); // node attr proto::AttrDef *attr_def = &(*attrs)["key1"]; auto graph_attr = attr_def->mutable_td(); auto attrs_of_graph = graph_attr->mutable_attr(); auto tensor_val = (*attrs_of_graph)["key2"].mutable_td(); tensor_val->set_dtype(proto::DT_INT8); tensor_val->set_layout("invalidLayout"); ModelSerializeImp imp; Model model; EXPECT_TRUE(imp.UnserializeModel(model, mode_def)); auto graph = GraphUtils::GetComputeGraph(model.GetGraph()); ASSERT_TRUE(graph != nullptr); auto nodes = graph->GetAllNodes(); ASSERT_EQ(nodes.size(), 1); GeTensorDesc tensor_desc; EXPECT_TRUE(AttrUtils::GetTensorDesc(nodes.at(0)->GetOpDesc(), "key1", tensor_desc)); GeTensorDesc tensor_desc1; EXPECT_TRUE(AttrUtils::GetTensorDesc(tensor_desc, "key2", tensor_desc1)); EXPECT_EQ(tensor_desc1.GetFormat(), FORMAT_RESERVED); EXPECT_EQ(tensor_desc1.GetDataType(), DT_INT8); } { // invalid list tensor_desc proto::ModelDef mode_def; auto attrs = mode_def.add_graph()->add_op()->mutable_attr(); // node attr proto::AttrDef *attr_def = &(*attrs)["key1"]; attr_def->mutable_list()->set_val_type(ge::proto::AttrDef_ListValue_ListValueType_VT_LIST_TENSOR_DESC); auto graph_attr = attr_def->mutable_list()->add_td(); auto attrs_of_graph = graph_attr->mutable_attr(); auto tensor_val = (*attrs_of_graph)["key2"].mutable_td(); tensor_val->set_dtype(proto::DT_INT8); tensor_val->set_layout("invalidLayout"); ModelSerializeImp imp; Model model; EXPECT_TRUE(imp.UnserializeModel(model, mode_def)); auto graph = GraphUtils::GetComputeGraph(model.GetGraph()); ASSERT_TRUE(graph != nullptr); auto nodes = graph->GetAllNodes(); ASSERT_EQ(nodes.size(), 1); vector<GeTensorDesc> tensor_desc; EXPECT_TRUE(AttrUtils::GetListTensorDesc(nodes.at(0)->GetOpDesc(), "key1", tensor_desc)); ASSERT_EQ(tensor_desc.size(), 1); GeTensorDesc tensor_desc1; EXPECT_TRUE(AttrUtils::GetTensorDesc(tensor_desc.at(0), "key2", tensor_desc1)); EXPECT_EQ(tensor_desc1.GetFormat(), FORMAT_RESERVED); EXPECT_EQ(tensor_desc1.GetDataType(), DT_INT8); } { // invalid tensor proto::ModelDef mode_def; auto attrs = mode_def.add_graph()->add_op()->mutable_attr(); // node attr proto::AttrDef *attr_def = &(*attrs)["key1"]; auto graph_attr = attr_def->mutable_t()->mutable_desc(); auto attrs_of_graph = graph_attr->mutable_attr(); auto tensor_val = (*attrs_of_graph)["key2"].mutable_td(); tensor_val->set_dtype(proto::DT_INT8); tensor_val->set_layout("invalidLayout"); ModelSerializeImp imp; Model model; EXPECT_TRUE(imp.UnserializeModel(model, mode_def)); auto graph = GraphUtils::GetComputeGraph(model.GetGraph()); ASSERT_TRUE(graph != nullptr); auto nodes = graph->GetAllNodes(); ASSERT_EQ(nodes.size(), 1); ConstGeTensorPtr tensor; EXPECT_TRUE(AttrUtils::GetTensor(nodes.at(0)->GetOpDesc(), "key1", tensor)); GeTensorDesc tensor_desc1; EXPECT_TRUE(AttrUtils::GetTensorDesc(tensor->GetTensorDesc(), "key2", tensor_desc1)); EXPECT_EQ(tensor_desc1.GetFormat(), FORMAT_RESERVED); EXPECT_EQ(tensor_desc1.GetDataType(), DT_INT8); } { // invalid list tensor proto::ModelDef mode_def; auto attrs = mode_def.add_graph()->add_op()->mutable_attr(); // node attr proto::AttrDef *attr_def = &(*attrs)["key1"]; attr_def->mutable_list()->set_val_type(ge::proto::AttrDef_ListValue_ListValueType_VT_LIST_TENSOR); auto graph_attr = attr_def->mutable_list()->add_t()->mutable_desc(); auto attrs_of_graph = graph_attr->mutable_attr(); auto tensor_val = (*attrs_of_graph)["key2"].mutable_td(); tensor_val->set_dtype(proto::DT_INT8); tensor_val->set_layout("invalidLayout"); ModelSerializeImp imp; Model model; EXPECT_TRUE(imp.UnserializeModel(model, mode_def)); auto graph = GraphUtils::GetComputeGraph(model.GetGraph()); ASSERT_TRUE(graph != nullptr); auto nodes = graph->GetAllNodes(); ASSERT_EQ(nodes.size(), 1); vector<ConstGeTensorPtr> tensor; EXPECT_TRUE(AttrUtils::GetListTensor(nodes.at(0)->GetOpDesc(), "key1", tensor)); ASSERT_EQ(tensor.size(), 1); GeTensorDesc tensor_desc1; EXPECT_TRUE(AttrUtils::GetTensorDesc(tensor.at(0)->GetTensorDesc(), "key2", tensor_desc1)); EXPECT_EQ(tensor_desc1.GetFormat(), FORMAT_RESERVED); EXPECT_EQ(tensor_desc1.GetDataType(), DT_INT8); } { // invalid list tensor proto::GraphDef graph_def; auto attrs = graph_def.add_op()->mutable_attr(); // node attr proto::AttrDef *attr_def = &(*attrs)["key1"]; attr_def->mutable_list()->set_val_type(ge::proto::AttrDef_ListValue_ListValueType_VT_LIST_TENSOR); auto graph_attr = attr_def->mutable_list()->add_t()->mutable_desc(); auto attrs_of_graph = graph_attr->mutable_attr(); auto tensor_val = (*attrs_of_graph)["key2"].mutable_td(); tensor_val->set_dtype(proto::DT_INT8); tensor_val->set_layout("invalidLayout"); ModelSerializeImp imp; Buffer buffer(graph_def.ByteSizeLong()); graph_def.SerializeToArray(buffer.GetData(), static_cast<int>(buffer.GetSize())); ModelSerialize serialize; auto graph = serialize.UnserializeGraph(buffer.GetData(), buffer.GetSize()); ASSERT_TRUE(graph != nullptr); auto nodes = graph->GetAllNodes(); ASSERT_EQ(nodes.size(), 1); vector<ConstGeTensorPtr> tensor; EXPECT_TRUE(AttrUtils::GetListTensor(nodes.at(0)->GetOpDesc(), "key1", tensor)); ASSERT_EQ(tensor.size(), 1); GeTensorDesc tensor_desc1; EXPECT_TRUE(AttrUtils::GetTensorDesc(tensor.at(0)->GetTensorDesc(), "key2", tensor_desc1)); EXPECT_EQ(tensor_desc1.GetFormat(), FORMAT_RESERVED); EXPECT_EQ(tensor_desc1.GetDataType(), DT_INT8); } } TEST(UTEST_ge_model_unserialize, test_invalid_input_output) { // model invalid node input { proto::ModelDef model_def; auto op_def = model_def.add_graph()->add_op(); // node attr op_def->add_input("invalidNodeName:0"); Buffer buffer(model_def.ByteSizeLong()); model_def.SerializeToArray(buffer.GetData(), static_cast<int>(buffer.GetSize())); ModelSerialize serialize; auto model = serialize.UnserializeModel(buffer.GetData(), buffer.GetSize()); EXPECT_FALSE(model.IsValid()); } // model invalid node control input { proto::ModelDef model_def; auto op_def = model_def.add_graph()->add_op(); // node attr op_def->add_input("invalidNodeName:-1"); Buffer buffer(model_def.ByteSizeLong()); model_def.SerializeToArray(buffer.GetData(), static_cast<int>(buffer.GetSize())); ModelSerialize serialize; auto model = serialize.UnserializeModel(buffer.GetData(), buffer.GetSize()); EXPECT_FALSE(model.IsValid()); } // model invalid graph input { proto::ModelDef model_def; model_def.add_graph()->add_input("invalidNodeName:0"); Buffer buffer(model_def.ByteSizeLong()); model_def.SerializeToArray(buffer.GetData(), static_cast<int>(buffer.GetSize())); ModelSerialize serialize; auto model = serialize.UnserializeModel(buffer.GetData(), buffer.GetSize()); EXPECT_FALSE(model.IsValid()); } // model invalid graph input { proto::ModelDef model_def; model_def.add_graph()->add_output("invalidNodeName:0"); Buffer buffer(model_def.ByteSizeLong()); model_def.SerializeToArray(buffer.GetData(), static_cast<int>(buffer.GetSize())); ModelSerialize serialize; auto model = serialize.UnserializeModel(buffer.GetData(), buffer.GetSize()); EXPECT_FALSE(model.IsValid()); } // graph invalid node input { proto::GraphDef graph_def; auto op_def = graph_def.add_op(); // node attr op_def->add_input("invalidNodeName:0"); Buffer buffer(graph_def.ByteSizeLong()); graph_def.SerializeToArray(buffer.GetData(), static_cast<int>(buffer.GetSize())); ModelSerialize serialize; auto graph = serialize.UnserializeGraph(buffer.GetData(), buffer.GetSize()); EXPECT_FALSE(graph != nullptr); } // graph invalid node control input { proto::GraphDef graph_def; auto op_def = graph_def.add_op(); // node attr op_def->add_input("invalidNodeName:-1"); Buffer buffer(graph_def.ByteSizeLong()); graph_def.SerializeToArray(buffer.GetData(), static_cast<int>(buffer.GetSize())); ModelSerialize serialize; auto graph = serialize.UnserializeGraph(buffer.GetData(), buffer.GetSize()); EXPECT_FALSE(graph != nullptr); } // graph invalid graph input { proto::GraphDef graph_def; graph_def.add_input("invalidNodeName:0"); Buffer buffer(graph_def.ByteSizeLong()); graph_def.SerializeToArray(buffer.GetData(), static_cast<int>(buffer.GetSize())); ModelSerialize serialize; auto graph = serialize.UnserializeGraph(buffer.GetData(), buffer.GetSize()); EXPECT_FALSE(graph != nullptr); } // graph invalid graph output { proto::GraphDef graph_def; graph_def.add_output("invalidNodeName:0"); Buffer buffer(graph_def.ByteSizeLong()); graph_def.SerializeToArray(buffer.GetData(), static_cast<int>(buffer.GetSize())); ModelSerialize serialize; auto graph = serialize.UnserializeGraph(buffer.GetData(), buffer.GetSize()); EXPECT_FALSE(graph != nullptr); } // model invalid node input anchor { proto::ModelDef model_def; auto graph_def = model_def.add_graph(); auto node_def1 = graph_def->add_op(); // node attr node_def1->set_name("node1"); auto node_def2 = graph_def->add_op(); // node attr node_def2->add_input("node1:0"); Buffer buffer(model_def.ByteSizeLong()); model_def.SerializeToArray(buffer.GetData(), static_cast<int>(buffer.GetSize())); ModelSerialize serialize; auto model = serialize.UnserializeModel(buffer.GetData(), buffer.GetSize()); EXPECT_FALSE(model.IsValid()); } } TEST(UTEST_ge_model_unserialize, test_invalid_CodeBuffer) { { char buffer[100] = "sdfasf"; ModelSerialize serialize; auto graph = serialize.UnserializeGraph((uint8_t *)buffer, 100); EXPECT_FALSE(graph != nullptr); } { char buffer[100] = "sdfasf"; ModelSerialize serialize; auto model = serialize.UnserializeModel((uint8_t *)buffer, 100); EXPECT_FALSE(model.IsValid()); } { char buffer[100] = "sdfasf"; ModelSerialize serialize; auto op_desc = serialize.UnserializeOpDesc((uint8_t *)buffer, 100); EXPECT_FALSE(op_desc != nullptr); } { ModelSerialize serialize; auto graph = serialize.UnserializeGraph((uint8_t *)nullptr, 100); EXPECT_FALSE(graph != nullptr); } { ModelSerialize serialize; auto model = serialize.UnserializeModel((uint8_t *)nullptr, 100); EXPECT_FALSE(model.IsValid()); } { ModelSerialize serialize; auto op_desc = serialize.UnserializeOpDesc((uint8_t *)nullptr, 100); EXPECT_FALSE(op_desc != nullptr); } }
40.563389
118
0.704807
TommyLike
291fd98f7c6b94875b3190bd3ced10dbdf31a604
344
cc
C++
util/env_win_detail/win_misc.cc
tamaskenez/leveldb
fa5614c35a7c58051e5f1d26f50f0c632a7f3e19
[ "BSD-3-Clause" ]
null
null
null
util/env_win_detail/win_misc.cc
tamaskenez/leveldb
fa5614c35a7c58051e5f1d26f50f0c632a7f3e19
[ "BSD-3-Clause" ]
null
null
null
util/env_win_detail/win_misc.cc
tamaskenez/leveldb
fa5614c35a7c58051e5f1d26f50f0c632a7f3e19
[ "BSD-3-Clause" ]
null
null
null
#include "win_misc.h" void usleep(int usec) { Sleep((usec + 999)/1000); } int getpagesize(void) { SYSTEM_INFO si; GetSystemInfo(&si); return si.dwPageSize; } bool ftruncate(const winapi::File& fd, int64_t length) { bool b = fd.setFilePointerEx(length, NULL, FILE_BEGIN); if ( !b ) return false; return fd.setEndOfFile(); }
15.636364
57
0.677326
tamaskenez
2920c4da92e9e2b1a057b93a0efed11c7a96031e
900
hpp
C++
exchange/include/mmx/exchange/trade_pair_t.hpp
danpape/mmx-node
99bae72a5135c9b208af9f402c0259351e8da151
[ "Apache-2.0" ]
null
null
null
exchange/include/mmx/exchange/trade_pair_t.hpp
danpape/mmx-node
99bae72a5135c9b208af9f402c0259351e8da151
[ "Apache-2.0" ]
null
null
null
exchange/include/mmx/exchange/trade_pair_t.hpp
danpape/mmx-node
99bae72a5135c9b208af9f402c0259351e8da151
[ "Apache-2.0" ]
null
null
null
/* * trade_pair_t.hpp * * Created on: Jan 22, 2022 * Author: mad */ #ifndef INCLUDE_MMX_EXCHANGE_TRADE_PAIR_T_HPP_ #define INCLUDE_MMX_EXCHANGE_TRADE_PAIR_T_HPP_ #include <mmx/exchange/trade_pair_t.hxx> namespace mmx { namespace exchange { inline trade_pair_t trade_pair_t::reverse() const { trade_pair_t pair; pair.ask = bid; pair.bid = ask; return pair; } inline trade_pair_t trade_pair_t::create_ex(const addr_t& bid, const addr_t& ask) { trade_pair_t pair; pair.bid = bid; pair.ask = ask; return pair; } inline bool operator==(const trade_pair_t& lhs, const trade_pair_t& rhs) { return lhs.bid == rhs.bid && lhs.ask == rhs.ask; } inline bool operator<(const trade_pair_t& lhs, const trade_pair_t& rhs) { if(lhs.bid == rhs.bid) { return lhs.ask < rhs.ask; } return lhs.bid < rhs.bid; } } // exchange } // mmx #endif /* INCLUDE_MMX_EXCHANGE_TRADE_PAIR_T_HPP_ */
16.981132
74
0.714444
danpape
2921588b51ab75aa7da5bc357b046a477bfd1e5b
24,713
cc
C++
src/lib/fidl/cpp/tests/integration/wire_interop_tests.cc
fabio-d/fuchsia-stardock
e57f5d1cf015fe2294fc2a5aea704842294318d2
[ "BSD-2-Clause" ]
5
2022-01-10T20:22:17.000Z
2022-01-21T20:14:17.000Z
src/lib/fidl/cpp/tests/integration/wire_interop_tests.cc
fabio-d/fuchsia-stardock
e57f5d1cf015fe2294fc2a5aea704842294318d2
[ "BSD-2-Clause" ]
null
null
null
src/lib/fidl/cpp/tests/integration/wire_interop_tests.cc
fabio-d/fuchsia-stardock
e57f5d1cf015fe2294fc2a5aea704842294318d2
[ "BSD-2-Clause" ]
null
null
null
// Copyright 2021 The Fuchsia 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 <fidl/fidl.cpp.wire.interop.test/cpp/fidl.h> #include <lib/async-loop/cpp/loop.h> #include <lib/fidl/cpp/client.h> #include <lib/stdcompat/string_view.h> #include <zircon/assert.h> #include <vector> #include <zxtest/zxtest.h> namespace { class WireTestBase : public fidl::WireServer<fidl_cpp_wire_interop_test::Interop> { void RoundTrip(RoundTripRequestView request, RoundTripCompleter::Sync& completer) override { ZX_PANIC("Unreachable"); } void TryRoundTrip(TryRoundTripRequestView request, TryRoundTripCompleter::Sync& completer) override { ZX_PANIC("Unreachable"); } void OneWay(OneWayRequestView request, OneWayCompleter::Sync& completer) override { ZX_PANIC("Unreachable"); } }; class MockData { public: // Helpers to build mock domain objects and test that they are equal to expected. static fidl_cpp_wire_interop_test::Node MakeNaturalFile(); static fidl_cpp_wire_interop_test::wire::Node MakeWireFile(fidl::AnyArena& arena); static void CheckNaturalFile(const fidl_cpp_wire_interop_test::Node& node); static void CheckWireFile(const fidl_cpp_wire_interop_test::wire::Node& node); static fidl_cpp_wire_interop_test::Node MakeNaturalDir(); static fidl_cpp_wire_interop_test::wire::Node MakeWireDir(fidl::AnyArena& arena); static void CheckNaturalDir(const fidl_cpp_wire_interop_test::Node& node); static void CheckWireDir(const fidl_cpp_wire_interop_test::wire::Node& node); private: const static char kFileName[9]; static std::vector<uint8_t> kFileContent; static const char kDirName[8]; }; const char MockData::kFileName[9] = "foo file"; std::vector<uint8_t> MockData::kFileContent = {1, 2, 3}; const char MockData::kDirName[8] = "bar dir"; fidl_cpp_wire_interop_test::Node MockData::MakeNaturalFile() { fidl_cpp_wire_interop_test::Node node; node.name() = kFileName; node.kind() = fidl_cpp_wire_interop_test::Kind::WithFile({{.content = kFileContent}}); return node; } fidl_cpp_wire_interop_test::wire::Node MockData::MakeWireFile(fidl::AnyArena& arena) { auto kind = fidl_cpp_wire_interop_test::wire::Kind::WithFile(arena); kind.file().content = fidl::VectorView<uint8_t>::FromExternal(kFileContent); return fidl_cpp_wire_interop_test::wire::Node::Builder(arena).name(kFileName).kind(kind).Build(); } void MockData::CheckNaturalFile(const fidl_cpp_wire_interop_test::Node& node) { ASSERT_TRUE(node.name().has_value()); EXPECT_EQ(kFileName, node.name()); ASSERT_TRUE(node.kind().has_value()); EXPECT_EQ(fidl_cpp_wire_interop_test::Kind::Tag::kFile, node.kind()->Which()); EXPECT_EQ(kFileContent, node.kind()->file()->content()); } void MockData::CheckWireFile(const fidl_cpp_wire_interop_test::wire::Node& node) { ASSERT_TRUE(node.has_name()); EXPECT_EQ(fidl::StringView{kFileName}.get(), node.name().get()); ASSERT_TRUE(node.has_kind()); EXPECT_EQ(fidl_cpp_wire_interop_test::wire::Kind::Tag::kFile, node.kind().Which()); std::vector<uint8_t> content(node.kind().file().content.begin(), node.kind().file().content.end()); EXPECT_EQ(kFileContent, content); } fidl_cpp_wire_interop_test::Node MockData::MakeNaturalDir() { fidl_cpp_wire_interop_test::Node node; node.name() = kDirName; fidl_cpp_wire_interop_test::Node child = MakeNaturalFile(); fidl_cpp_wire_interop_test::Directory directory; directory.children() = std::make_unique<fidl_cpp_wire_interop_test::Children>(); directory.children()->elements().emplace_back(std::move(child)); node.kind() = fidl_cpp_wire_interop_test::Kind::WithDirectory(std::move(directory)); return node; } fidl_cpp_wire_interop_test::wire::Node MockData::MakeWireDir(fidl::AnyArena& arena) { auto node = fidl_cpp_wire_interop_test::wire::Node::Builder(arena) .name(kDirName) .kind(fidl_cpp_wire_interop_test::wire::Kind::WithDirectory(arena)) .Build(); fidl::ObjectView<fidl_cpp_wire_interop_test::wire::Children>& children = node.kind().directory().children; children.Allocate(arena); children->elements.Allocate(arena, 1); children->elements[0] = MakeWireFile(arena); return node; } void MockData::CheckNaturalDir(const fidl_cpp_wire_interop_test::Node& node) { ASSERT_TRUE(node.name().has_value()); EXPECT_EQ(kDirName, node.name()); ASSERT_TRUE(node.kind().has_value()); ASSERT_EQ(fidl_cpp_wire_interop_test::Kind::Tag::kDirectory, node.kind()->Which()); const fidl_cpp_wire_interop_test::Directory& dir = node.kind()->directory().value(); EXPECT_EQ(1, dir.children()->elements().size()); const fidl_cpp_wire_interop_test::Node& child = dir.children()->elements()[0]; CheckNaturalFile(child); } void MockData::CheckWireDir(const fidl_cpp_wire_interop_test::wire::Node& node) { EXPECT_TRUE(node.has_name()); EXPECT_EQ(fidl::StringView{kDirName}.get(), node.name().get()); EXPECT_TRUE(node.has_kind()); EXPECT_EQ(fidl_cpp_wire_interop_test::wire::Kind::Tag::kDirectory, node.kind().Which()); const fidl_cpp_wire_interop_test::wire::Directory& dir = node.kind().directory(); EXPECT_EQ(1, dir.children->elements.count()); const fidl_cpp_wire_interop_test::wire::Node& child = dir.children->elements[0]; CheckWireFile(child); } // Test fixture to simplify creating endpoints and a unified client to talk to // a wire domain object server. class UnifiedClientToWireServerBase : public zxtest::Test, public MockData { public: UnifiedClientToWireServerBase() : loop_(&kAsyncLoopConfigNeverAttachToThread) {} void SetUp() final { zx::status client_end = fidl::CreateEndpoints<fidl_cpp_wire_interop_test::Interop>(&server_end_); ASSERT_OK(client_end.status_value()); client_.Bind(std::move(*client_end), loop_.dispatcher(), GetEventHandler()); } virtual fidl::AsyncEventHandler<fidl_cpp_wire_interop_test::Interop>* GetEventHandler() = 0; async::Loop& loop() { return loop_; } fidl::ServerEnd<fidl_cpp_wire_interop_test::Interop>& server_end() { return server_end_; } fidl::Client<fidl_cpp_wire_interop_test::Interop>& client() { return client_; } private: async::Loop loop_; fidl::ServerEnd<fidl_cpp_wire_interop_test::Interop> server_end_; fidl::Client<fidl_cpp_wire_interop_test::Interop> client_; }; // Test fixture that does not care about events (besides the fact that there // should not be any errors). class UnifiedClientToWireServer : public UnifiedClientToWireServerBase { private: fidl::AsyncEventHandler<fidl_cpp_wire_interop_test::Interop>* GetEventHandler() final { return &event_handler_; } class FailOnClientError : public fidl::AsyncEventHandler<fidl_cpp_wire_interop_test::Interop> { // We should not observe any terminal error from the client during these tests. void on_fidl_error(fidl::UnbindInfo info) final { ADD_FATAL_FAILURE("Detected client error during test: %s", info.FormatDescription().c_str()); } }; FailOnClientError event_handler_; }; // Test round-tripping a file node. TEST_F(UnifiedClientToWireServer, RoundTrip) { class Server : public WireTestBase { public: void RoundTrip(RoundTripRequestView request, RoundTripCompleter::Sync& completer) final { CheckWireFile(request->node); num_calls++; completer.Reply(request->node); } int num_calls = 0; }; Server server; fidl::BindServer(loop().dispatcher(), std::move(server_end()), &server); { // Test with natural domain objects. auto node = MakeNaturalFile(); fidl_cpp_wire_interop_test::InteropRoundTripRequest request{std::move(node)}; bool got_response = false; client() ->RoundTrip(std::move(request)) .ThenExactlyOnce([&](fidl::Result<fidl_cpp_wire_interop_test::Interop::RoundTrip>& result) { ASSERT_TRUE(result.is_ok()); CheckNaturalFile(result->node()); got_response = true; }); ASSERT_OK(loop().RunUntilIdle()); EXPECT_EQ(1, server.num_calls); EXPECT_TRUE(got_response); } { // Test with wire domain objects. fidl::Arena arena; auto node = MakeWireFile(arena); bool got_response = false; client().wire()->RoundTrip(node).ThenExactlyOnce( [&](fidl::WireUnownedResult<fidl_cpp_wire_interop_test::Interop::RoundTrip>& result) { if (!result.ok()) { FAIL("RoundTrip failed: %s", result.error().FormatDescription().c_str()); return; } auto* response = result.Unwrap(); CheckWireFile(response->node); got_response = true; }); ASSERT_OK(loop().RunUntilIdle()); EXPECT_EQ(2, server.num_calls); EXPECT_TRUE(got_response); } } // Test round-tripping a directory node with error syntax. TEST_F(UnifiedClientToWireServer, TryRoundTrip) { class Server : public WireTestBase { public: void TryRoundTrip(TryRoundTripRequestView request, TryRoundTripCompleter::Sync& completer) final { CheckWireDir(request->node); num_calls++; if (reply_with_error) { completer.ReplyError(ZX_ERR_INVALID_ARGS); } else { completer.ReplySuccess(request->node); } } bool reply_with_error = false; int num_calls = 0; }; Server server; fidl::BindServer(loop().dispatcher(), std::move(server_end()), &server); { // Test with natural domain objects, success case. auto node = MakeNaturalDir(); fidl_cpp_wire_interop_test::InteropTryRoundTripRequest request{std::move(node)}; bool got_response = false; client() ->TryRoundTrip(std::move(request)) .ThenExactlyOnce( [&](fidl::Result<fidl_cpp_wire_interop_test::Interop::TryRoundTrip>& result) { ASSERT_TRUE(result.is_ok()); fidl_cpp_wire_interop_test::InteropTryRoundTripResponse payload = std::move(result.value()); fidl_cpp_wire_interop_test::Node node = payload.node(); CheckNaturalDir(node); got_response = true; }); ASSERT_OK(loop().RunUntilIdle()); EXPECT_EQ(1, server.num_calls); EXPECT_TRUE(got_response); } { // Test with wire domain objects, success case. fidl::Arena arena; auto node = MakeWireDir(arena); bool got_response = false; client().wire()->TryRoundTrip(node).ThenExactlyOnce( [&](fidl::WireUnownedResult<fidl_cpp_wire_interop_test::Interop::TryRoundTrip>& result) { if (!result.ok()) { FAIL("TryRoundTrip failed: %s", result.error().FormatDescription().c_str()); return; } auto* response = result.Unwrap(); ASSERT_TRUE(response->result.is_response()); CheckWireDir(response->result.response().node); got_response = true; }); ASSERT_OK(loop().RunUntilIdle()); EXPECT_EQ(2, server.num_calls); EXPECT_TRUE(got_response); } server.reply_with_error = true; { // Test with natural domain objects, error case. auto node = MakeNaturalDir(); fidl_cpp_wire_interop_test::InteropTryRoundTripRequest request{std::move(node)}; bool got_response = false; client() ->TryRoundTrip(std::move(request)) .ThenExactlyOnce( [&](fidl::Result<fidl_cpp_wire_interop_test::Interop::TryRoundTrip>& result) { ASSERT_FALSE(result.is_ok()); ASSERT_TRUE(result.is_error()); fidl::AnyErrorIn<fidl_cpp_wire_interop_test::Interop::TryRoundTrip> error = result.error_value(); ASSERT_TRUE(error.is_application_error()); EXPECT_STATUS(ZX_ERR_INVALID_ARGS, error.application_error()); got_response = true; }); ASSERT_OK(loop().RunUntilIdle()); EXPECT_EQ(3, server.num_calls); EXPECT_TRUE(got_response); } { // Test with wire domain objects, error case. fidl::Arena arena; auto node = MakeWireDir(arena); bool got_response = false; client().wire()->TryRoundTrip(node).ThenExactlyOnce( [&](fidl::WireUnownedResult<fidl_cpp_wire_interop_test::Interop::TryRoundTrip>& result) { if (!result.ok()) { FAIL("TryRoundTrip failed: %s", result.error().FormatDescription().c_str()); return; } auto* response = result.Unwrap(); ASSERT_TRUE(response->result.is_err()); EXPECT_STATUS(ZX_ERR_INVALID_ARGS, response->result.err()); got_response = true; }); ASSERT_OK(loop().RunUntilIdle()); EXPECT_EQ(4, server.num_calls); EXPECT_TRUE(got_response); } } // Test sending a one way call. TEST_F(UnifiedClientToWireServer, OneWay) { class Server : public WireTestBase { public: void OneWay(OneWayRequestView request, OneWayCompleter::Sync& completer) override { CheckWireFile(request->node); num_calls++; } int num_calls = 0; }; Server server; fidl::BindServer(loop().dispatcher(), std::move(server_end()), &server); { // Test with natural domain objects. fitx::result<fidl::Error> result = client()->OneWay({MakeNaturalFile()}); ASSERT_TRUE(result.is_ok()); ASSERT_OK(loop().RunUntilIdle()); EXPECT_EQ(1, server.num_calls); } { // Test with wire domain objects. fidl::Arena arena; fidl::Status status = client().wire()->OneWay(MakeWireFile(arena)); ASSERT_TRUE(status.ok()); ASSERT_OK(loop().RunUntilIdle()); EXPECT_EQ(2, server.num_calls); } } // Test fixture that checks events. class UnifiedClientToWireServerWithEventHandler : public UnifiedClientToWireServerBase { public: int num_events() const { return event_handler_.num_events(); } private: class ExpectOnNodeEvent : public fidl::AsyncEventHandler<fidl_cpp_wire_interop_test::Interop> { public: int num_events() const { return num_events_; } private: // We should not observe any terminal error from the client during these tests. void on_fidl_error(fidl::UnbindInfo info) final { ADD_FATAL_FAILURE("Detected client error during test: %s", info.FormatDescription().c_str()); } void OnNode(fidl::Event<fidl_cpp_wire_interop_test::Interop::OnNode>& event) final { CheckNaturalDir(event.node()); num_events_++; } int num_events_ = 0; }; fidl::AsyncEventHandler<fidl_cpp_wire_interop_test::Interop>* GetEventHandler() final { return &event_handler_; } ExpectOnNodeEvent event_handler_; }; TEST_F(UnifiedClientToWireServerWithEventHandler, OnNode) { class Server : public WireTestBase {}; Server server; auto binding = fidl::BindServer(loop().dispatcher(), std::move(server_end()), &server); EXPECT_EQ(0, num_events()); // Send an event. fidl::Arena arena; auto node = MakeWireDir(arena); fidl::Status status = fidl::WireSendEvent(binding)->OnNode(node); ASSERT_OK(status.status()); // Test receiving natural domain objects. ASSERT_OK(loop().RunUntilIdle()); EXPECT_EQ(1, num_events()); } class NaturalTestBase : public fidl::Server<fidl_cpp_wire_interop_test::Interop> { void RoundTrip(RoundTripRequest& request, RoundTripCompleter::Sync& completer) override { ZX_PANIC("Unreachable"); } void TryRoundTrip(TryRoundTripRequest& request, TryRoundTripCompleter::Sync& completer) override { ZX_PANIC("Unreachable"); } void OneWay(OneWayRequest& request, OneWayCompleter::Sync& completer) override { ZX_PANIC("Unreachable"); } }; // Test fixture to simplify creating endpoints and a wire client to talk to // a natural server. class WireClientToNaturalServerBase : public zxtest::Test, public MockData { public: WireClientToNaturalServerBase() : loop_(&kAsyncLoopConfigNeverAttachToThread) {} void SetUp() final { zx::status client_end = fidl::CreateEndpoints<fidl_cpp_wire_interop_test::Interop>(&server_end_); ASSERT_OK(client_end.status_value()); client_.Bind(std::move(*client_end), loop_.dispatcher(), GetEventHandler()); } template <typename ServerImpl> static auto CheckErrorsWhenUnbound() { return [](ServerImpl* impl, fidl::UnbindInfo info, fidl::ServerEnd<fidl_cpp_wire_interop_test::Interop> server_end) { if (info.is_user_initiated()) return; if (info.is_dispatcher_shutdown()) return; if (info.is_peer_closed()) return; ADD_FATAL_FAILURE("Detected server error during test: %s", info.FormatDescription().c_str()); }; } virtual fidl::WireAsyncEventHandler<fidl_cpp_wire_interop_test::Interop>* GetEventHandler() = 0; async::Loop& loop() { return loop_; } fidl::ServerEnd<fidl_cpp_wire_interop_test::Interop>& server_end() { return server_end_; } fidl::WireClient<fidl_cpp_wire_interop_test::Interop>& client() { return client_; } private: async::Loop loop_; fidl::ServerEnd<fidl_cpp_wire_interop_test::Interop> server_end_; fidl::WireClient<fidl_cpp_wire_interop_test::Interop> client_; }; // Test fixture that does not care about events (besides the fact that there // should not be any errors). class WireClientToNaturalServer : public WireClientToNaturalServerBase { private: fidl::WireAsyncEventHandler<fidl_cpp_wire_interop_test::Interop>* GetEventHandler() final { return &event_handler_; } class FailOnClientError : public fidl::WireAsyncEventHandler<fidl_cpp_wire_interop_test::Interop> { // We should not observe any terminal error from the client during these tests. void on_fidl_error(fidl::UnbindInfo info) final { ADD_FATAL_FAILURE("Detected client error during test: %s", info.FormatDescription().c_str()); } }; FailOnClientError event_handler_; }; // Test round-tripping a file node. TEST_F(WireClientToNaturalServer, RoundTrip) { class Server : public NaturalTestBase { public: void RoundTrip(RoundTripRequest& request, RoundTripCompleter::Sync& completer) final { CheckNaturalFile(request.node()); num_calls++; completer.Reply(std::move(request.node())); } int num_calls = 0; }; Server server; fidl::BindServer(loop().dispatcher(), std::move(server_end()), &server, CheckErrorsWhenUnbound<Server>()); fidl::Arena arena; auto node = MakeWireFile(arena); bool got_response = false; client()->RoundTrip(node).ThenExactlyOnce( [&](fidl::WireUnownedResult<fidl_cpp_wire_interop_test::Interop::RoundTrip>& result) { if (!result.ok()) { FAIL("RoundTrip failed: %s", result.error().FormatDescription().c_str()); return; } auto* response = result.Unwrap(); CheckWireFile(response->node); got_response = true; }); ASSERT_OK(loop().RunUntilIdle()); EXPECT_EQ(1, server.num_calls); EXPECT_TRUE(got_response); } // Test round-tripping a directory node with error syntax. TEST_F(WireClientToNaturalServer, TryRoundTrip) { class Server : public NaturalTestBase { public: void TryRoundTrip(TryRoundTripRequest& request, TryRoundTripCompleter::Sync& completer) final { CheckNaturalDir(request.node()); num_calls++; // TODO(fxbug.dev/91363): ReplySuccess/ReplyError. if (reply_with_error) { completer.Reply(fitx::error(ZX_ERR_INVALID_ARGS)); } else { completer.Reply(fitx::ok(std::move(request.node()))); } } bool reply_with_error = false; int num_calls = 0; }; Server server; fidl::BindServer(loop().dispatcher(), std::move(server_end()), &server, CheckErrorsWhenUnbound<Server>()); { // Test success case. fidl::Arena arena; auto node = MakeWireDir(arena); bool got_response = false; client()->TryRoundTrip(node).ThenExactlyOnce( [&](fidl::WireUnownedResult<fidl_cpp_wire_interop_test::Interop::TryRoundTrip>& result) { if (!result.ok()) { FAIL("TryRoundTrip failed: %s", result.error().FormatDescription().c_str()); return; } auto* response = result.Unwrap(); ASSERT_TRUE(response->result.is_response()); CheckWireDir(response->result.response().node); got_response = true; }); ASSERT_OK(loop().RunUntilIdle()); EXPECT_EQ(1, server.num_calls); EXPECT_TRUE(got_response); } server.reply_with_error = true; { // Test error case. fidl::Arena arena; auto node = MakeWireDir(arena); bool got_response = false; client()->TryRoundTrip(node).ThenExactlyOnce( [&](fidl::WireUnownedResult<fidl_cpp_wire_interop_test::Interop::TryRoundTrip>& result) { if (!result.ok()) { FAIL("TryRoundTrip failed: %s", result.error().FormatDescription().c_str()); return; } auto* response = result.Unwrap(); ASSERT_TRUE(response->result.is_err()); EXPECT_STATUS(ZX_ERR_INVALID_ARGS, response->result.err()); got_response = true; }); ASSERT_OK(loop().RunUntilIdle()); EXPECT_EQ(2, server.num_calls); EXPECT_TRUE(got_response); } } // Test receiving a one way call. TEST_F(WireClientToNaturalServer, OneWay) { class Server : public NaturalTestBase { public: void OneWay(OneWayRequest& request, OneWayCompleter::Sync& completer) override { CheckNaturalFile(request.node()); num_calls++; } int num_calls = 0; }; Server server; fidl::BindServer(loop().dispatcher(), std::move(server_end()), &server, CheckErrorsWhenUnbound<Server>()); fidl::Arena arena; fidl::Status status = client()->OneWay(MakeWireFile(arena)); ASSERT_TRUE(status.ok()); ASSERT_OK(loop().RunUntilIdle()); EXPECT_EQ(1, server.num_calls); } // Test fixture that checks events. class WireClientToNaturalServerWithEventHandler : public WireClientToNaturalServerBase { public: int num_events() const { return event_handler_.num_events(); } private: class ExpectOnNodeEvent : public fidl::WireAsyncEventHandler<fidl_cpp_wire_interop_test::Interop> { public: int num_events() const { return num_events_; } private: // We should not observe any terminal error from the client during these tests. void on_fidl_error(fidl::UnbindInfo info) final { ADD_FATAL_FAILURE("Detected client error during test: %s", info.FormatDescription().c_str()); } void OnNode(fidl::WireEvent<fidl_cpp_wire_interop_test::Interop::OnNode>* event) final { CheckWireDir(event->node); num_events_++; } int num_events_ = 0; }; fidl::WireAsyncEventHandler<fidl_cpp_wire_interop_test::Interop>* GetEventHandler() final { return &event_handler_; } ExpectOnNodeEvent event_handler_; }; // Test sending an event over a |fidl::ServerEnd|. TEST_F(WireClientToNaturalServerWithEventHandler, SendOnNodeEventOverServerEnd) { EXPECT_EQ(0, num_events()); // Test sending the event with natural types. { fidl_cpp_wire_interop_test::Node node = MakeNaturalDir(); fitx::result result = fidl::SendEvent(server_end())->OnNode(node); EXPECT_TRUE(result.is_ok(), "%s", result.error_value().FormatDescription().c_str()); EXPECT_OK(loop().RunUntilIdle()); EXPECT_EQ(1, num_events()); } // Test sending the event with wire types. { fidl::Arena arena; fidl_cpp_wire_interop_test::wire::Node node = MakeWireDir(arena); fidl::Status status = fidl::WireSendEvent(server_end())->OnNode(node); EXPECT_OK(status.status()); EXPECT_OK(loop().RunUntilIdle()); EXPECT_EQ(2, num_events()); } } // Test sending an event over a |fidl::ServerBindingRef|. TEST_F(WireClientToNaturalServerWithEventHandler, SendOnNodeEventOverServerBindingRef) { EXPECT_EQ(0, num_events()); class Server : public NaturalTestBase {}; Server server; fidl::ServerBindingRef binding_ref = fidl::BindServer(loop().dispatcher(), std::move(server_end()), &server); // Test sending the event with natural types. { fidl_cpp_wire_interop_test::Node node = MakeNaturalDir(); fitx::result result = fidl::SendEvent(binding_ref)->OnNode(node); EXPECT_TRUE(result.is_ok(), "%s", result.error_value().FormatDescription().c_str()); EXPECT_OK(loop().RunUntilIdle()); EXPECT_EQ(1, num_events()); } // Test sending the event with wire types. { fidl::Arena arena; fidl_cpp_wire_interop_test::wire::Node node = MakeWireDir(arena); fidl::Status status = fidl::WireSendEvent(binding_ref)->OnNode(node); EXPECT_OK(status.status()); EXPECT_OK(loop().RunUntilIdle()); EXPECT_EQ(2, num_events()); } } } // namespace
35.405444
100
0.695423
fabio-d
2922f187282f30413f91382b64bb5d76fa4692dd
443
cc
C++
doc/tutorial/src/tut5.2/tut.cc
wmeddie/frovedis
c134e5e64114799cc7c265c72525ff98d06b49c1
[ "BSD-2-Clause" ]
null
null
null
doc/tutorial/src/tut5.2/tut.cc
wmeddie/frovedis
c134e5e64114799cc7c265c72525ff98d06b49c1
[ "BSD-2-Clause" ]
null
null
null
doc/tutorial/src/tut5.2/tut.cc
wmeddie/frovedis
c134e5e64114799cc7c265c72525ff98d06b49c1
[ "BSD-2-Clause" ]
null
null
null
#include <frovedis.hpp> #include <frovedis/dataframe.hpp> int main(int argc, char* argv[]){ frovedis::use_frovedis use(argc, argv); auto t = frovedis::make_dftable_loadtext("./t.csv", {"int", "double", "string"}, {"c1", "c2", "c3"}); auto t2 = t.select({"c2", "c3"}); t2.show(); t2.drop("c2"); t2.show(); t2.rename("c3","cx"); t2.show(); }
23.315789
69
0.478555
wmeddie
2926fd1df903e9a28702599c86aeb5cad26468a7
4,628
cpp
C++
src/graph/widgets/CPositionedWindow.cpp
SindenDev/3dimviewer
e23a3147edc35034ef4b75eae9ccdcbc7192b1a1
[ "Apache-2.0" ]
6
2020-04-14T16:10:55.000Z
2021-05-21T07:13:55.000Z
src/graph/widgets/CPositionedWindow.cpp
SindenDev/3dimviewer
e23a3147edc35034ef4b75eae9ccdcbc7192b1a1
[ "Apache-2.0" ]
null
null
null
src/graph/widgets/CPositionedWindow.cpp
SindenDev/3dimviewer
e23a3147edc35034ef4b75eae9ccdcbc7192b1a1
[ "Apache-2.0" ]
2
2020-07-24T16:25:38.000Z
2021-01-19T09:23:18.000Z
/////////////////////////////////////////////////////////////////////////////// // $Id$ // // 3DimViewer // Lightweight 3D DICOM viewer. // // Copyright 2008-2016 3Dim Laboratory s.r.o. // // 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 <graph/widgets/CPositionedWindow.h> /////////////////////////////////////////////////////////////////////////////// // void scene::CPositionedWindow::setWindowManager(scene::CSizeableWindowManager * wm) { // VPL_ASSERT( wm ); if( !wm ) { return; } // Connect to the signal m_conSizeChanged = wm->getSigSizeChanged().connect( this, &scene::CPositionedWindow::onWMSizeChanged ); // Update window size onWMSizeChanged( wm->getWidth(), wm->getHeight() ); } /////////////////////////////////////////////////////////////////////////////// // scene::CPositionedWindow::CPositionedWindow(void) : m_widthType( NONE ) , m_heightType( NONE ) , m_xType( NONE ) , m_yType( NONE ) , m_xOriginType( NONE ) , m_yOriginType( NONE ) , m_width( 0.0f ) , m_height( 0.0f ) , m_x( 0.0f ) , m_y( 0.0f ) , m_ox( 0.0f ) , m_oy( 0.0f ) { } /////////////////////////////////////////////////////////////////////////////// // void scene::CPositionedWindow::onWMSizeChanged(int wmw, int wmh) { int w(0), h(0), x(0), y(0), ox(0), oy(0); // Call window to update its size/origin information this->recomputeSizes(); // Recompute window size this->computeSize( wmw, wmh, w, h ); // Compute window origin this->computeOrigin( wmw, wmh, w, h, ox, oy ); // Compute new window position this->computePosition( wmw, wmh, ox, oy, x, y ); // Call update updateWindowSizePosition( w, h, x, y ); } /////////////////////////////////////////////////////////////////////////////// // void scene::CPositionedWindow::computeSize(int wmw, int wmh, int &w, int &h) { // compute new window width switch( m_widthType ) { case NONE: case PROPORTIONAL_WINDOW: break; case PROPORTIONAL_WM: w = 0.01 * m_width * wmw; break; case FIXED: w = m_width; break; } // Compute new window height switch( m_heightType ) { case NONE: case PROPORTIONAL_WINDOW: break; case PROPORTIONAL_WM: h = 0.01 * m_height * wmh; break; case FIXED: h = m_height; break; } } /////////////////////////////////////////////////////////////////////////////// // void scene::CPositionedWindow::computeOrigin(int wmw, int wmh, int ww, int wh, int &ox, int &oy) { // compute new window x origin switch( m_xOriginType ) { case NONE: break; case PROPORTIONAL_WINDOW: ox = 0.01 * m_ox * ww; break; case PROPORTIONAL_WM: ox = 0.01 * m_ox * wmw; break; case FIXED: ox = m_ox; break; } // Compute new window y origin switch( m_yOriginType ) { case NONE: break; case PROPORTIONAL_WINDOW: oy = 0.01 * m_oy * wh; break; case PROPORTIONAL_WM: oy = 0.01 * m_oy * wmh; break; case FIXED: ox = m_ox; break; } } /////////////////////////////////////////////////////////////////////////////// // void scene::CPositionedWindow::computePosition(int wmw, int wmh, int ox, int oy, int &x, int &y) { // compute new window x position switch( m_xType ) { case NONE: break; case PROPORTIONAL_WINDOW: break; case PROPORTIONAL_WM: x = 0.01 * m_x * wmw + ox; break; case FIXED: x = m_x + ox; break; } // Compute new window height switch( m_yType ) { case NONE: break; case PROPORTIONAL_WINDOW: break; case PROPORTIONAL_WM: y = 0.01 * m_y * wmh + oy; break; case FIXED: y = m_y + oy; break; } }
23.373737
109
0.496327
SindenDev
292739efd9703d89374817bef87839e7442adc25
542
cc
C++
FWCore/Framework/src/EndPathStatusInserter.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
13
2015-11-30T15:49:45.000Z
2022-02-08T16:11:30.000Z
FWCore/Framework/src/EndPathStatusInserter.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
640
2015-02-11T18:55:47.000Z
2022-03-31T14:12:23.000Z
FWCore/Framework/src/EndPathStatusInserter.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
51
2015-08-11T21:01:40.000Z
2022-03-30T07:31:34.000Z
#include "FWCore/Framework/src/EndPathStatusInserter.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Utilities/interface/StreamID.h" #include "DataFormats/Common/interface/EndPathStatus.h" #include <memory> namespace edm { EndPathStatusInserter::EndPathStatusInserter(unsigned int) : token_{produces<EndPathStatus>()} {} void EndPathStatusInserter::produce(StreamID, edm::Event& event, edm::EventSetup const&) const { //Puts a default constructed EndPathStatus event.emplace(token_); } } // namespace edm
31.882353
99
0.771218
ckamtsikis
2928a326a82c08362714a0ba79fe33d1e93ded0f
6,246
cpp
C++
Chapter08/CognitiveCamera/CognitiveCamera/src/main.cpp
PacktPublishing/Artificial-Intelligence-for-IoT-Cookbook
c2f522c2a1dbb78c99e05abc3c0e8706618f4353
[ "MIT" ]
19
2019-11-06T08:00:03.000Z
2022-01-01T20:02:40.000Z
Chapter08/CognitiveCamera/CognitiveCamera/src/main.cpp
PacktPublishing/Artificial-Intelligence-for-IoT-Cookbook
c2f522c2a1dbb78c99e05abc3c0e8706618f4353
[ "MIT" ]
null
null
null
Chapter08/CognitiveCamera/CognitiveCamera/src/main.cpp
PacktPublishing/Artificial-Intelligence-for-IoT-Cookbook
c2f522c2a1dbb78c99e05abc3c0e8706618f4353
[ "MIT" ]
9
2020-02-17T23:44:16.000Z
2022-02-03T15:26:46.000Z
#include "WiFi.h" #include "esp_camera.h" //#include "esp_timer.h" //#include "img_converters.h" //#include "soc/soc.h" // Disable brownour problems //#include "soc/rtc_cntl_reg.h" // Disable brownour problems //#include "driver/rtc_io.h" //#include <StringArray.h> //#include <SPIFFS.h> //#include <FS.h> // Replace with your network credentials const char* ssid = ""; const char* password = ""; // Photo File Name to save in SPIFFS #define FILE_PHOTO "/photo.jpg" // OV2640 camera module pins (CAMERA_MODEL_AI_THINKER) #define PWDN_GPIO_NUM -1 #define RESET_GPIO_NUM -1 #define XCLK_GPIO_NUM 4 #define SIOD_GPIO_NUM 18 #define SIOC_GPIO_NUM 23 #define Y9_GPIO_NUM 36 #define Y8_GPIO_NUM 37 #define Y7_GPIO_NUM 38 #define Y6_GPIO_NUM 39 #define Y5_GPIO_NUM 35 #define Y4_GPIO_NUM 14 #define Y3_GPIO_NUM 13 #define Y2_GPIO_NUM 34 #define VSYNC_GPIO_NUM 5 #define HREF_GPIO_NUM 27 #define PCLK_GPIO_NUM 25 void setup() { // Serial port for debugging purposes Serial.begin(115200); // Connect to Wi-Fi WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(5000); Serial.println(WiFi.status()); WiFi.begin(ssid, password); delay(500); Serial.println("Connecting to WiFi..."); } /* if (!SPIFFS.begin(true)) { Serial.println("An Error has occurred while mounting SPIFFS"); // ESP.restart(); } else { delay(500); Serial.println("SPIFFS mounted successfully"); } */ // Print ESP32 Local IP Address Serial.print("IP Address: http://"); Serial.println(WiFi.localIP()); // Turn-off the 'brownout detector' //WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); /* // OV2640 camera module camera_config_t config; config.ledc_channel = LEDC_CHANNEL_0; config.ledc_timer = LEDC_TIMER_0; config.pin_d0 = Y2_GPIO_NUM; config.pin_d1 = Y3_GPIO_NUM; config.pin_d2 = Y4_GPIO_NUM; config.pin_d3 = Y5_GPIO_NUM; config.pin_d4 = Y6_GPIO_NUM; config.pin_d5 = Y7_GPIO_NUM; config.pin_d6 = Y8_GPIO_NUM; config.pin_d7 = Y9_GPIO_NUM; config.pin_xclk = XCLK_GPIO_NUM; config.pin_pclk = PCLK_GPIO_NUM; config.pin_vsync = VSYNC_GPIO_NUM; config.pin_href = HREF_GPIO_NUM; config.pin_sscb_sda = SIOD_GPIO_NUM; config.pin_sscb_scl = SIOC_GPIO_NUM; config.pin_pwdn = PWDN_GPIO_NUM; config.pin_reset = RESET_GPIO_NUM; config.xclk_freq_hz = 20000000; config.pixel_format = PIXFORMAT_JPEG; if (psramFound()) { config.frame_size = FRAMESIZE_UXGA; config.jpeg_quality = 10; config.fb_count = 2; } else { config.frame_size = FRAMESIZE_SVGA; config.jpeg_quality = 12; config.fb_count = 1; } // Camera init esp_err_t err = esp_camera_init(&config); if (err != ESP_OK) { Serial.printf("Camera init failed with error 0x%x", err); //ESP.restart(); } */ } /* // Check if photo capture was successful bool checkPhoto( fs::FS &fs ) { File f_pic = fs.open( FILE_PHOTO ); unsigned int pic_sz = f_pic.size(); return ( pic_sz > 100 ); } /* // Capture Photo and Save it to SPIFFS void capturePhotoSaveSpiffs( void ) { camera_fb_t * fb = NULL; // pointer bool ok = 0; // Boolean indicating if the picture has been taken correctly do { // Take a photo with the camera Serial.println("Taking a photo..."); fb = esp_camera_fb_get(); if (!fb) { Serial.println("Camera capture failed"); return; } // Photo file name /* Serial.printf("Picture file name: %s\n", FILE_PHOTO); File file = SPIFFS.open(FILE_PHOTO, FILE_WRITE); // Insert the data in the photo file if (!file) { Serial.println("Failed to open file in writing mode"); } else { file.write(fb->buf, fb->len); // payload (image), payload length Serial.print("The picture has been saved in "); Serial.print(FILE_PHOTO); Serial.print(" - Size: "); Serial.print(file.size()); Serial.println(" bytes"); } // Close the file file.close(); esp_camera_fb_return(fb); // check if file has been correctly saved in SPIFFS ok = checkPhoto(SPIFFS); } while ( !ok ); } */ /* void sendPhoto(void) { File file = SPIFFS.open(FILE_PHOTO, FILE_READ); String start_request = ""; String end_request = ""; //headers = {'Prediction-Key': '9c5da3f162c04c45b85be1eb5c2ca33b', 'Content-Type':'application/octet-stream'} start_request = start_request + "\n--AaB03x\n" + "\nPrediction-Key: 9c5da3f162c04c45b85be1eb5c2ca33b\n" + "\nContent-Type: application/octet-stream\n\n"; end_request = end_request + "\n--AaB03x--\n"; uint16_t full_length; full_length = start_request.length() + file.size() + end_request.length(); WiFiClient client; if (!client.connect("https://aibenchtest.cognitiveservices.azure.com/customvision/v3.0/Prediction/YOURPROJECTID/detect/iterations/Iteration1/image", 80)) { Serial.println("Connected FILED!"); return; } /* url = 'https://aibenchtest.cognitiveservices.azure.com/customvision/v3.0/Prediction/YOURPROECTID/detect/iterations/Iteration1/image' #payload = {'client_id': 1} files = {'file': file} r = requests.post(url, data=file, headers=headers) json_data = r.json() */ /* Serial.println("Connected ok!"); client.println("POST /Home/Index HTTP/1.1"); client.println("Host: example.com"); client.println("User-Agent: ESP32"); client.println("Content-Type: application/octet-stream"); client.print("Content-Length: "); client.println(full_length); client.println(); client.print(start_request); while (file.available()){ client.write(file.read()); } Serial.println(">>><<<"); client.println(end_request); } */ void loop() { // capturePhotoSaveSpiffs(); delay(10000); Serial.println("loop"); // put your main code here, to run repeatedly: /* file = open('images/drink1/cap0.jpg', 'rb') url = 'https://YOURCOGNITIVESERVICESNAME.cognitiveservices.azure.com/customvision/v3.0/Prediction/YOURPROJECTID/detect/iterations/Iteration1/image' headers = {'Prediction-Key': 'YOURPREDICTIONKEY', 'Content-Type':'application/octet-stream'} #payload = {'client_id': 1} files = {'file': file} r = requests.post(url, data=file, headers=headers) json_data = r.json() */ }
25.185484
155
0.682197
PacktPublishing
292c33e3752b32af894fab2470a5e26ae45f7175
11,507
cc
C++
Source/Plugins/GraphicsPlugins/BladeTerrain/source/TerrainBlock.cc
OscarGame/blade
6987708cb011813eb38e5c262c7a83888635f002
[ "MIT" ]
146
2018-12-03T08:08:17.000Z
2022-03-21T06:04:06.000Z
Source/Plugins/GraphicsPlugins/BladeTerrain/source/TerrainBlock.cc
huangx916/blade
3fa398f4d32215bbc7e292d61e38bb92aad1ee1c
[ "MIT" ]
1
2019-01-18T03:35:49.000Z
2019-01-18T03:36:08.000Z
Source/Plugins/GraphicsPlugins/BladeTerrain/source/TerrainBlock.cc
huangx916/blade
3fa398f4d32215bbc7e292d61e38bb92aad1ee1c
[ "MIT" ]
31
2018-12-03T10:32:43.000Z
2021-10-04T06:31:44.000Z
/******************************************************************** created: 2010/05/13 filename: TerrainBlock.cc author: Crazii purpose: *********************************************************************/ #include <BladePCH.h> #include <interface/IGraphicsSystem.h> #include <interface/IRenderQueue.h> #include "TerrainBufferManager.h" #include "TerrainBlock.h" #include "BlockQuery.h" namespace Blade { static const uint BLOCK_UPDATE_LOD = 0x01; static const uint BLOCK_UPDATE_INDICES = 0x02; ////////////////////////////////////////////////////////////////////////// TerrainBlock::TerrainBlock(index_t x,index_t z, ITerrainTile* parent) :mParent(parent) ,mFixedLOD(INVALID_FIXED_LOD) ,mLODLevel(0) ,mLODDiffIndex(LODDI_NONE) ,mMaterialLOD(0) { mUpdateFlags |= CUF_DEFAULT_VISIBLE | CUF_VISIBLE_UPDATE; mSpaceFlags = CSF_CONTENT | CSF_SHADOWCASTER; const TERRAIN_INFO& GTInfo = TerrainConfigManager::getSingleton().getTerrainInfo(); mBlockIndex.mX = (uint16)x; mBlockIndex.mZ = (uint16)z; mBlockIndex.mIndex = (uint32)( mBlockIndex.mX + mBlockIndex.mZ*GTInfo.mBlocksPerTileSide); const TILE_INFO& tileInfo = mParent->getTileInfo(); GraphicsGeometry& geometry = tileInfo.mRenderGeomBuffer[ this->getBlockIndex() ]; geometry.reset(); //setup render geometry geometry.useIndexBuffer(true); geometry.mIndexBuffer = NULL; geometry.mIndexCount = 0; geometry.mIndexStart = 0; geometry.mVertexSource = tileInfo.mVertexSource; geometry.mVertexDecl = TerrainConfigManager::getRenderType().getVertexDeclaration(); geometry.mVertexCount = (uint32)TerrainConfigManager::getSingleton().getTerrainBlockVertexCount(); geometry.mVertexStart = 0; geometry.mPrimitiveType = GraphicsGeometry::GPT_TRIANGLE_LIST; #if BLADE_DEBUG mQueued = 0; #endif if( IGraphicsSystem::getSingleton().getCurrentProfile() > BTString("2_0") ) tileInfo.mScene->getMaterialLODUpdater()->addForLODUpdate(this); } TerrainBlock::~TerrainBlock() { if(mParent->getTileInfo().mScene != NULL) mParent->getTileInfo().mScene->getMaterialLODUpdater()->removeFromLODUpdate(this); } /************************************************************************/ /* SpaceContent overrides */ /************************************************************************/ ////////////////////////////////////////////////////////////////////////// void TerrainBlock::updateRender(IRenderQueue* queue) { const TILE_INFO& tileInfo = mParent->getTileInfo(); assert(tileInfo.mMaterialLODCount == 0 || mMaterialLOD < tileInfo.mMaterialLODCount); if(tileInfo.mLODMaterials != NULL && mMaterialLOD < tileInfo.mMaterialLODCount) { TerrainConfigManager& tcm = static_cast<TerrainConfigManager&>(*mParent->getConfigManager()); ITerrainBatchCombiner* combiner = tcm.getBatchCombiner(); IRenderQueue* redirect = mParent->getTileInfo().mOutputBuffer; if (redirect != NULL && combiner->needCombine(queue) ) { #if BLADE_DEBUG //assert(mQueued == 0); mQueued = 1; #endif redirect->addRenderable(this); } else { this->updateIndexBuffer(); queue->addRenderable(this); } } } ////////////////////////////////////////////////////////////////////////// void TerrainBlock::visibleUpdateImpl(const Vector3& cameraPos) { uint8& updateMask = mParent->getTileInfo().mUpdatedMask[this->getBlockIndex()]; if (updateMask & BLOCK_UPDATE_LOD) //multiple camera update optimize. return; updateMask |= BLOCK_UPDATE_LOD; #define ADAPTIVE_FIXED_LOD 0 //TODO: use adaptive fixed LOD will need morph height for adapted level. #if !ADAPTIVE_FIXED_LOD if (mFixedLOD != INVALID_FIXED_LOD) mLODLevel = mFixedLOD; else #endif { //Vector3 CameraDir = cameraRotation*Vector3::NEGATIVE_UNIT_Z; //Vector3 Vec = mPostion - cameraPos; //scalar dist = Vec.dotProduct(CameraDir); //mLODLevel = TerrainConfigManager::getSingleton().getLODLevelByDistance(dist); //get LOD level only at horizontal dimension //to avoid LOD level gap, when height different is too large Vector3 position = mWorldAABB.getCenter(); Vector2 pos2(position.x, position.z); Vector2 camPos2(cameraPos.x, cameraPos.z); scalar SqrDist = pos2.getSquaredDistance(camPos2); mLODLevel = static_cast<TerrainConfigManager*>(mParent->getConfigManager())->getLODLevelBySquaredDistance(SqrDist); } #if ADAPTIVE_FIXED_LOD if (mFixedLOD != INVALID_FIXED_LOD) { if (mFixedLOD == TerrainConfigManager::getSingleton().getFlatLODLevel()) mLODLevel = std::max<uint8>(mFixedLOD, mLODLevel); else // mLODLevel = std::min<uint8>(mFixedLOD, mLODLevel); } #endif #if BLADE_DEBUG if(mLastLODLevel != mLODLevel) mLastLODLevel = mLODLevel; mQueued = 0; #endif } ////////////////////////////////////////////////////////////////////////// bool TerrainBlock::queryNearestPoint(SpaceQuery& query, scalar& distance) const { //transform ray to local space (actually it's tile's local space, not block's local space, because block's all vertices are in tile's space) StaticHandle<SpaceQuery> transformed = query.clone(this->getWorldTransform().getInverse()); const TERRAIN_POSITION_DATA_Y* vposition = mParent->getSoftHeightPositionData(); const TERRAIN_POSITION_DATA_XZ* hposition = TerrainBufferManager::getSingleton().getSoftHorizontalPositionBuffer(); const TerrainQueryIndexGroup* group = mParent->getQueryIndexBuffer(); size_t blockSize = TerrainConfigManager::getSingleton().getTerrainBlockSize(); BlockQuery blockQuery; blockQuery.initialize(vposition + mVertexStart, hposition + mVertexStart, group, mBlockIndex.mX*blockSize, mBlockIndex.mZ*blockSize); AABB localAABB = this->getWorldAABB(); localAABB.offset(-mParent->getStartPos()); blockQuery.setAABB(localAABB); BlockVolumeQuery q(this->getWorldTransform()[3], *transformed, mLODLevel, (LOD_DI)mLODDiffIndex); q.mDistance = distance; bool ret = blockQuery.raycastPoint(q); if (ret) { //skip scale since not scale for terrain blocks distance = q.mDistance; } return ret; } ////////////////////////////////////////////////////////////////////////// bool TerrainBlock::intersectTriangles(SpaceQuery& query, POS_VOL contentPos/* = PV_INTERSECTED*/) const { bool result = false; //transform the volume from world space to local space StaticHandle<SpaceQuery> transformed = query.clone( this->getWorldTransform().getInverse() ); const TERRAIN_POSITION_DATA_Y* vposition = mParent->getSoftHeightPositionData(); const TERRAIN_POSITION_DATA_XZ* hposition = TerrainBufferManager::getSingleton().getSoftHorizontalPositionBuffer(); const TerrainQueryIndexGroup* group = mParent->getQueryIndexBuffer(); size_t blockSize = TerrainConfigManager::getSingleton().getTerrainBlockSize(); BlockQuery blockQuery; blockQuery.initialize(vposition+mVertexStart, hposition+mVertexStart, group, mBlockIndex.mX*blockSize, mBlockIndex.mZ*blockSize); AABB localAABB = this->getWorldAABB(); localAABB.offset(-mParent->getStartPos()); blockQuery.setAABB(localAABB); BlockVolumeQuery q(this->getWorldTransform()[3], *transformed, mLODLevel, (LOD_DI)mLODDiffIndex); result = blockQuery.intersect(q, contentPos); return result; } /************************************************************************/ /* custom methods */ /************************************************************************/ ////////////////////////////////////////////////////////////////////////// void TerrainBlock::setVertexOffsetCount(index_t startVertex, size_t count) { mVertexStart = startVertex; mVertexCount = (uint16)count; } ////////////////////////////////////////////////////////////////////////// void TerrainBlock::updateIndexBuffer(bool force/* = false*/) { uint8& updateMask = mParent->getTileInfo().mUpdatedMask[this->getBlockIndex()]; if ((updateMask & BLOCK_UPDATE_INDICES) && !force) //multiple camera update optimize return; updateMask |= BLOCK_UPDATE_INDICES; TerrainConfigManager& tcm = static_cast<TerrainConfigManager&>(*mParent->getConfigManager()); ILODComparator* LODCmp = tcm.getIndexGenerator(); LODDiff diff; FixedLODDiff fixedDiff; TerrainBlock* up = mParent->getTerrainBlock((int)this->getBlockX(), (int)this->getBlockZ()-1); if (up != NULL && (fixedDiff.t=(int8)LODCmp->compareLOD(up->getCurrentLODLevel(), mLODLevel)) > 0 && !up->isFixedLOD()) diff.setUpDiff(); TerrainBlock* left = mParent->getTerrainBlock((int)this->getBlockX()-1, (int)this->getBlockZ()); if (left != NULL && (fixedDiff.l=(int8)LODCmp->compareLOD(left->getCurrentLODLevel(), mLODLevel)) > 0 && !left->isFixedLOD()) diff.setLeftDiff(); TerrainBlock* down = mParent->getTerrainBlock((int)this->getBlockX(), (int)this->getBlockZ()+1); if (down != NULL && (fixedDiff.b=(int8)LODCmp->compareLOD(down->getCurrentLODLevel(), mLODLevel)) > 0 && !down->isFixedLOD() ) diff.setDownDiff(); TerrainBlock* right = mParent->getTerrainBlock((int)this->getBlockX()+1, (int)this->getBlockZ()); if (right != NULL && (fixedDiff.r=(int8)LODCmp->compareLOD(right->getCurrentLODLevel(), mLODLevel)) > 0 && !right->isFixedLOD()) diff.setRightDiff(); GraphicsGeometry& geometry = mParent->getTileInfo().mRenderGeomBuffer[this->getBlockIndex()]; if (mFixedLOD != INVALID_FIXED_LOD && fixedDiff.isValid() && mLODLevel == tcm.getFlatLODLevel()) { //adaption only work for one side(flat or cliff), disable flat LOD adaption int8 specialDiff = (int8)LODCmp->compareLOD(tcm.getCliffLODLevel(), mLODLevel); if (std::abs(specialDiff) > 1) { assert(mLODLevel >= 1u); if (fixedDiff.l == specialDiff && left != NULL && left->isFixedLOD()) fixedDiff.l = 0; if (fixedDiff.t == specialDiff && up != NULL && up->isFixedLOD() ) fixedDiff.t = 0; if (fixedDiff.r == specialDiff && right != NULL && right->isFixedLOD()) fixedDiff.r = 0; if (fixedDiff.b == specialDiff && down != NULL && down->isFixedLOD()) fixedDiff.b = 0; } } if (mFixedLOD != INVALID_FIXED_LOD && mLODLevel == mFixedLOD && fixedDiff.isValid()) geometry.mIndexBuffer = mParent->getFixedIndexBuffer(mLODLevel, fixedDiff, this->getBlockIndex(), geometry.mIndexStart, geometry.mIndexCount); else { mLODDiffIndex = (uint8)LODDiff::generateDifferenceIndex(diff); #if BLADE_DEBUG if (mLastLODDiffIndex != mLODDiffIndex) mLastLODDiffIndex = mLODDiffIndex; #endif geometry.mIndexBuffer = mParent->getIndexBuffer(mLODLevel, (LOD_DI)mLODDiffIndex, this->getBlockIndex(), geometry.mIndexStart, geometry.mIndexCount); } geometry.mIndexCount = (uint32)geometry.mIndexBuffer->getIndexCount(); geometry.mVertexStart = (uint32)mVertexStart; geometry.mVertexCount = (uint32)mVertexCount; } ////////////////////////////////////////////////////////////////////////// void TerrainBlock::updateMaterial() { const TILE_INFO& tileInfo = mParent->getTileInfo(); assert(tileInfo.mMaterialLODCount > 0); if (mMaterialLOD >= tileInfo.mMaterialLODCount) mMaterialLOD = tileInfo.mMaterialLODCount - 1u; } ////////////////////////////////////////////////////////////////////////// void TerrainBlock::cacheOut() { assert(this->getSpace() == NULL); //mParent->getTileInfo().mScene->getMaterialLODUpdater()->removeFromLODUpdate(this); this->setElement(NULL); } }//namespace Blade
39.954861
152
0.656644
OscarGame
292d58375aa0a24f7cc246038919d9346209326d
2,449
hpp
C++
lib/runtime/public/atelier/hash.hpp
giranath/atelier
e1b9056b6f930979c03057bba306005943cf1b12
[ "MIT" ]
null
null
null
lib/runtime/public/atelier/hash.hpp
giranath/atelier
e1b9056b6f930979c03057bba306005943cf1b12
[ "MIT" ]
null
null
null
lib/runtime/public/atelier/hash.hpp
giranath/atelier
e1b9056b6f930979c03057bba306005943cf1b12
[ "MIT" ]
null
null
null
#ifndef ATELIER_RUNTIME_HASH_HPP #define ATELIER_RUNTIME_HASH_HPP #include "runtime_export.hpp" #include <cstdint> #include <iterator> #include <type_traits> #include <string_view> namespace at { // Current default Hash function is fnv1a inline namespace fnv1a { /** * Hash a range of bytes * @tparam It The iterator on the range of byte * @param begin The first iterator on the range * @param end The iterator after the last on the range * @return The hash value of the range * @note FNV-1a implementation */ template<typename It> [[nodiscard]] constexpr uint64_t hash(It begin, It end) noexcept { using iterator_value_type = typename std::iterator_traits<It>::value_type; static_assert(std::is_convertible_v<iterator_value_type, uint8_t>, "Iterator must be on bytes"); constexpr const uint64_t fnv_offset_basis = 0xcbf29ce484222325; constexpr const uint64_t fnv_prime = 0x00000100000001B3; uint64_t h = fnv_offset_basis; for (; begin != end; ++begin) { h ^= static_cast<uint8_t>(*begin); h *= fnv_prime; } return h; } /** * Hash a string * @param str The string to hash * @return The hash value of the string */ [[nodiscard]] constexpr uint64_t hash(std::string_view str) noexcept { return hash(str.begin(), str.end()); } /** * Hash a memory block * @param memory The memory block to hash * @param size The size of the memory block * @return The hash value for this memory block */ [[nodiscard]] ATELIER_RUNTIME_EXPORT uint64_t hash(const void* memory, std::size_t size) noexcept; } namespace literals { /** * String literals to create compile time hash * @param str The string to hash * @param length The length of the string to hash * @return The hashed value of the string */ [[nodiscard]] constexpr uint64_t operator ""_h(const char* str, std::size_t length) { return hash(std::string_view{str, length}); } } /** * Combine two hashes * @param h1 The first hash to combine with h2 * @param h2 The second hash to combine with h1 * @return A new hash constructed from two other hashes * @note The order used to combine hashes is important * Implementation based on this stack overflow answer: https://stackoverflow.com/a/27952689 */ [[nodiscard]] constexpr uint64_t hash_combine(uint64_t h1, uint64_t h2) noexcept { const uint64_t combined_hash = h1 ^ h2 + 0x9e3779b97f4a7c16 + (h1 << 6) + (h1 >> 2); return combined_hash; } } #endif
25.247423
100
0.716211
giranath
292ed96e6b0f49d1171d85f28473c10f4acfee32
658
cpp
C++
src/debug/stdmsg.cpp
mirpm/mirp-avr
ff2521b8ccd5314e7f7c357dd36982d9c954a30d
[ "Apache-2.0" ]
1
2017-04-12T20:00:00.000Z
2017-04-12T20:00:00.000Z
src/debug/stdmsg.cpp
mirpm/mirp-avr
ff2521b8ccd5314e7f7c357dd36982d9c954a30d
[ "Apache-2.0" ]
null
null
null
src/debug/stdmsg.cpp
mirpm/mirp-avr
ff2521b8ccd5314e7f7c357dd36982d9c954a30d
[ "Apache-2.0" ]
null
null
null
#include "stdmsg.h" /* * Initialises the standard messaging debug system */ bool StdMsg::Init() { UART::Init(); return true; } /* * Sends a warning via stdmsg and hex codes */ bool StdMsg::SendWarning(msg warning) { UART::PutChar(warning.type[0]); UART::PutChar(warning.type[1]); UART::PutChar(warning.eid); UART::PutChar(warning.msg); UART::PutChar('\n'); return true; } /* * Compares two commands, returns true if they are * the same and vice versa */ bool StdMsg::CommandCompare(command a, command b) { if(a.type[0] == b.type[0]) if(a.type[1] == b.type[1]) if(a.msg == a.msg) return true; return false; }
18.277778
51
0.636778
mirpm
292ede574b22b7ab5f41ac7c70ce1c9159eb3906
16,477
cpp
C++
src/v_pfx.cpp
351ELEC/lzdoom
2ee3ea91bc9c052b3143f44c96d85df22851426f
[ "RSA-MD" ]
2
2018-01-18T21:30:20.000Z
2018-01-19T02:24:46.000Z
src/v_pfx.cpp
351ELEC/lzdoom
2ee3ea91bc9c052b3143f44c96d85df22851426f
[ "RSA-MD" ]
4
2021-09-02T00:05:17.000Z
2021-09-07T14:56:12.000Z
src/v_pfx.cpp
351ELEC/lzdoom
2ee3ea91bc9c052b3143f44c96d85df22851426f
[ "RSA-MD" ]
1
2021-09-28T19:03:39.000Z
2021-09-28T19:03:39.000Z
/* ** v_pfx.cpp ** Pixel format conversion routines ** **--------------------------------------------------------------------------- ** Copyright 1998-2006 Randy Heit ** 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. ** 3. The name of the author may not be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "doomtype.h" #include "i_system.h" #include "v_palette.h" #include "v_pfx.h" PfxUnion GPfxPal; PfxState GPfx; static bool AnalyzeMask (uint32_t mask, uint8_t *shift); static void Palette16Generic (const PalEntry *pal); static void Palette16R5G5B5 (const PalEntry *pal); static void Palette16R5G6B5 (const PalEntry *pal); static void Palette32Generic (const PalEntry *pal); static void Palette32RGB (const PalEntry *pal); static void Palette32BGR (const PalEntry *pal); static void Scale8 (uint8_t *src, int srcpitch, void *destin, int destpitch, int destwidth, int destheight, fixed_t xstep, fixed_t ystep, fixed_t xfrac, fixed_t yfrac); static void Convert8 (uint8_t *src, int srcpitch, void *destin, int destpitch, int destwidth, int destheight, fixed_t xstep, fixed_t ystep, fixed_t xfrac, fixed_t yfrac); static void Convert16 (uint8_t *src, int srcpitch, void *destin, int destpitch, int destwidth, int destheight, fixed_t xstep, fixed_t ystep, fixed_t xfrac, fixed_t yfrac); static void Convert24 (uint8_t *src, int srcpitch, void *destin, int destpitch, int destwidth, int destheight, fixed_t xstep, fixed_t ystep, fixed_t xfrac, fixed_t yfrac); static void Convert32 (uint8_t *src, int srcpitch, void *destin, int destpitch, int destwidth, int destheight, fixed_t xstep, fixed_t ystep, fixed_t xfrac, fixed_t yfrac); void PfxState::SetFormat (int bits, uint32_t redMask, uint32_t greenMask, uint32_t blueMask) { switch (bits) { case -8: Convert = Scale8; SetPalette = NULL; break; case 8: Convert = Convert8; SetPalette = NULL; break; case 16: if (redMask == 0x7c00 && greenMask == 0x03e0 && blueMask == 0x001f) { SetPalette = Palette16R5G5B5; } else if (redMask == 0xf800 && greenMask == 0x07e0 && blueMask == 0x001f) { SetPalette = Palette16R5G6B5; } else { SetPalette = Palette16Generic; } Convert = Convert16; Masks.Bits16.Red = (uint16_t)redMask; Masks.Bits16.Green = (uint16_t)greenMask; Masks.Bits16.Blue = (uint16_t)blueMask; break; case 24: if (redMask == 0xff0000 && greenMask == 0x00ff00 && blueMask == 0x0000ff) { SetPalette = Palette32RGB; Convert = Convert24; } else if (redMask == 0x0000ff && greenMask == 0x00ff00 && blueMask == 0xff0000) { SetPalette = Palette32BGR; Convert = Convert24; } else { I_FatalError ("24-bit displays are only supported if they are RGB or BGR"); }; break; case 32: if (redMask == 0xff0000 && greenMask == 0x00ff00 && blueMask == 0x0000ff) { SetPalette = Palette32RGB; } else if (redMask == 0x0000ff && greenMask == 0x00ff00 && blueMask == 0xff0000) { SetPalette = Palette32BGR; } else { SetPalette = Palette32Generic; } Convert = Convert32; Masks.Bits32.Red = redMask; Masks.Bits32.Green = greenMask; Masks.Bits32.Blue = blueMask; break; default: I_FatalError ("Can't draw to %d-bit displays", bits); } if (bits != 8 && bits != -8) { RedLeft = AnalyzeMask (redMask, &RedShift); GreenLeft = AnalyzeMask (greenMask, &GreenShift); BlueLeft = AnalyzeMask (blueMask, &BlueShift); } } static bool AnalyzeMask (uint32_t mask, uint8_t *shiftout) { uint8_t shift = 0; if (mask >= 0xff) { while (mask > 0xff) { shift++; mask >>= 1; } *shiftout = shift; return true; } else { while (mask < 0xff) { shift++; mask <<= 1; } *shiftout = shift; return false; } } // Palette converters ------------------------------------------------------ static void Palette16Generic (const PalEntry *pal) { uint16_t *p16; int i; for (p16 = GPfxPal.Pal16, i = 256; i != 0; i--, pal++, p16++) { uint16_t rpart, gpart, bpart; if (GPfx.RedLeft) rpart = pal->r << GPfx.RedShift; else rpart = pal->r >> GPfx.RedShift; if (GPfx.GreenLeft) gpart = pal->g << GPfx.GreenShift; else gpart = pal->g >> GPfx.GreenShift; if (GPfx.BlueLeft) bpart = pal->b << GPfx.BlueShift; else bpart = pal->b >> GPfx.BlueShift; *p16 = (rpart & GPfx.Masks.Bits16.Red) | (gpart & GPfx.Masks.Bits16.Green) | (bpart & GPfx.Masks.Bits16.Blue); } } static void Palette16R5G5B5 (const PalEntry *pal) { uint16_t *p16; int i; for (p16 = GPfxPal.Pal16, i = 256; i != 0; i--, pal++, p16++) { *p16 = ((pal->r << 7) & 0x7c00) | ((pal->g << 2) & 0x03e0) | ((pal->b >> 3) & 0x001f); } } static void Palette16R5G6B5 (const PalEntry *pal) { uint16_t *p16; int i; for (p16 = GPfxPal.Pal16, i = 256; i != 0; i--, pal++, p16++) { *p16 = ((pal->r << 8) & 0xf800) | ((pal->g << 3) & 0x07e0) | ((pal->b >> 3) & 0x001f); } } static void Palette32Generic (const PalEntry *pal) { uint32_t *p32; int i; for (p32 = GPfxPal.Pal32, i = 256; i != 0; i--, pal++, p32++) { uint32_t rpart, gpart, bpart; if (GPfx.RedLeft) rpart = pal->r << GPfx.RedShift; else rpart = pal->r >> GPfx.RedShift; if (GPfx.GreenLeft) gpart = pal->g << GPfx.GreenShift; else gpart = pal->g >> GPfx.GreenShift; if (GPfx.BlueLeft) bpart = pal->b << GPfx.BlueShift; else bpart = pal->b >> GPfx.BlueShift; *p32 = (rpart & GPfx.Masks.Bits32.Red) | (gpart & GPfx.Masks.Bits32.Green) | (bpart & GPfx.Masks.Bits32.Blue); } } static void Palette32RGB (const PalEntry *pal) { memcpy (GPfxPal.Pal32, pal, 256*4); } static void Palette32BGR (const PalEntry *pal) { uint32_t *p32; int i; for (p32 = GPfxPal.Pal32, i = 256; i != 0; i--, pal++, p32++) { *p32 = (pal->r) | (pal->g << 8) | (pal->b << 16); } } // Bitmap converters ------------------------------------------------------- static void Scale8 (uint8_t *src, int srcpitch, void *destin, int destpitch, int destwidth, int destheight, fixed_t xstep, fixed_t ystep, fixed_t xfrac, fixed_t yfrac) { if ((destwidth | destheight) == 0) { return; } int x, y, savedx; uint8_t *dest = (uint8_t *)destin; if (xstep == FRACUNIT && ystep == FRACUNIT) { for (y = destheight; y != 0; y--) { memcpy(dest, src, destwidth); dest += destpitch; src += srcpitch; } } else if (xstep == FRACUNIT/2 && ystep == FRACUNIT/2) { uint8_t *dest2 = dest + destpitch; destpitch = destpitch * 2 - destwidth; srcpitch -= destwidth / 2; for (y = destheight / 2; y != 0; --y) { for (x = destwidth / 2; x != 0; --x) { uint8_t foo = src[0]; dest[0] = foo; dest[1] = foo; dest2[0] = foo; dest2[1] = foo; dest += 2; dest2 += 2; src += 1; } dest += destpitch; dest2 += destpitch; src += srcpitch; } } else if (xstep == FRACUNIT/4 && ystep == FRACUNIT/4) { int gap = destpitch * 4 - destwidth; srcpitch -= destwidth / 4; for (y = destheight / 4; y != 0; --y) { for (uint8_t *end = dest + destpitch; dest != end; dest += 4) { uint8_t foo = src[0]; dest[0] = foo; dest[1] = foo; dest[2] = foo; dest[3] = foo; dest[0 + destpitch] = foo; dest[1 + destpitch] = foo; dest[2 + destpitch] = foo; dest[3 + destpitch] = foo; dest[0 + destpitch*2] = foo; dest[1 + destpitch*2] = foo; dest[2 + destpitch*2] = foo; dest[3 + destpitch*2] = foo; dest[0 + destpitch*3] = foo; dest[1 + destpitch*3] = foo; dest[2 + destpitch*3] = foo; dest[3 + destpitch*3] = foo; src += 1; } dest += gap; src += srcpitch; } } else { destpitch -= destwidth; for (y = destheight; y != 0; y--) { fixed_t xf = xfrac; x = destwidth; while (((size_t)dest & 3) && x != 0) { *dest++ = src[xf >> FRACBITS]; xf += xstep; x--; } for (savedx = x, x >>= 2; x != 0; x--) { uint32_t work; #ifdef __BIG_ENDIAN__ work = src[xf >> FRACBITS] << 24; xf += xstep; work |= src[xf >> FRACBITS] << 16; xf += xstep; work |= src[xf >> FRACBITS] << 8; xf += xstep; work |= src[xf >> FRACBITS]; xf += xstep; #else work = src[xf >> FRACBITS]; xf += xstep; work |= src[xf >> FRACBITS] << 8; xf += xstep; work |= src[xf >> FRACBITS] << 16; xf += xstep; work |= src[xf >> FRACBITS] << 24; xf += xstep; #endif *(uint32_t *)dest = work; dest += 4; } for (savedx &= 3; savedx != 0; savedx--, xf += xstep) { *dest++ = src[xf >> FRACBITS]; } yfrac += ystep; while (yfrac >= FRACUNIT) { yfrac -= FRACUNIT; src += srcpitch; } dest += destpitch; } } } static void Convert8 (uint8_t *src, int srcpitch, void *destin, int destpitch, int destwidth, int destheight, fixed_t xstep, fixed_t ystep, fixed_t xfrac, fixed_t yfrac) { if ((destwidth | destheight) == 0) { return; } int x, y, savedx; uint8_t *dest = (uint8_t *)destin; destpitch -= destwidth; if (xstep == FRACUNIT && ystep == FRACUNIT) { srcpitch -= destwidth; for (y = destheight; y != 0; y--) { x = destwidth; while (((size_t)dest & 3) && x != 0) { *dest++ = GPfxPal.Pal8[*src++]; x--; } for (savedx = x, x >>= 2; x != 0; x--) { *(uint32_t *)dest = #ifdef __BIG_ENDIAN__ (GPfxPal.Pal8[src[0]] << 24) | (GPfxPal.Pal8[src[1]] << 16) | (GPfxPal.Pal8[src[2]] << 8) | (GPfxPal.Pal8[src[3]]); #else (GPfxPal.Pal8[src[0]]) | (GPfxPal.Pal8[src[1]] << 8) | (GPfxPal.Pal8[src[2]] << 16) | (GPfxPal.Pal8[src[3]] << 24); #endif dest += 4; src += 4; } for (savedx &= 3; savedx != 0; savedx--) { *dest++ = GPfxPal.Pal8[*src++]; } dest += destpitch; src += srcpitch; } } else { for (y = destheight; y != 0; y--) { fixed_t xf = xfrac; x = destwidth; while (((size_t)dest & 3) && x != 0) { *dest++ = GPfxPal.Pal8[src[xf >> FRACBITS]]; xf += xstep; x--; } for (savedx = x, x >>= 2; x != 0; x--) { uint32_t work; #ifdef __BIG_ENDIAN__ work = GPfxPal.Pal8[src[xf >> FRACBITS]] << 24; xf += xstep; work |= GPfxPal.Pal8[src[xf >> FRACBITS]] << 16; xf += xstep; work |= GPfxPal.Pal8[src[xf >> FRACBITS]] << 8; xf += xstep; work |= GPfxPal.Pal8[src[xf >> FRACBITS]]; xf += xstep; #else work = GPfxPal.Pal8[src[xf >> FRACBITS]]; xf += xstep; work |= GPfxPal.Pal8[src[xf >> FRACBITS]] << 8; xf += xstep; work |= GPfxPal.Pal8[src[xf >> FRACBITS]] << 16; xf += xstep; work |= GPfxPal.Pal8[src[xf >> FRACBITS]] << 24; xf += xstep; #endif *(uint32_t *)dest = work; dest += 4; } for (savedx &= 3; savedx != 0; savedx--, xf += xstep) { *dest++ = GPfxPal.Pal8[src[xf >> FRACBITS]]; } yfrac += ystep; while (yfrac >= FRACUNIT) { yfrac -= FRACUNIT; src += srcpitch; } dest += destpitch; } } } static void Convert16 (uint8_t *src, int srcpitch, void *destin, int destpitch, int destwidth, int destheight, fixed_t xstep, fixed_t ystep, fixed_t xfrac, fixed_t yfrac) { if ((destwidth | destheight) == 0) { return; } int x, y, savedx; uint16_t *dest = (uint16_t *)destin; destpitch = (destpitch >> 1) - destwidth; if (xstep == FRACUNIT && ystep == FRACUNIT) { srcpitch -= destwidth; for (y = destheight; y != 0; y--) { x = destwidth; if ((size_t)dest & 1) { x--; *dest++ = GPfxPal.Pal16[*src++]; } for (savedx = x, x >>= 1; x != 0; x--) { *(uint32_t *)dest = #ifdef __BIG_ENDIAN__ (GPfxPal.Pal16[src[0]] << 16) | (GPfxPal.Pal16[src[1]]); #else (GPfxPal.Pal16[src[0]]) | (GPfxPal.Pal16[src[1]] << 16); #endif dest += 2; src += 2; } if (savedx & 1) { *dest++ = GPfxPal.Pal16[*src++]; } dest += destpitch; src += srcpitch; } } else { for (y = destheight; y != 0; y--) { fixed_t xf = xfrac; x = destwidth; if ((size_t)dest & 1) { *dest++ = GPfxPal.Pal16[src[xf >> FRACBITS]]; xf += xstep; x--; } for (savedx = x, x >>= 1; x != 0; x--) { uint32_t work; #ifdef __BIG_ENDIAN__ work = GPfxPal.Pal16[src[xf >> FRACBITS]] << 16; xf += xstep; work |= GPfxPal.Pal16[src[xf >> FRACBITS]]; xf += xstep; #else work = GPfxPal.Pal16[src[xf >> FRACBITS]]; xf += xstep; work |= GPfxPal.Pal16[src[xf >> FRACBITS]] << 16; xf += xstep; #endif *(uint32_t *)dest = work; dest += 2; } if (savedx & 1) { *dest++ = GPfxPal.Pal16[src[xf >> FRACBITS]]; } yfrac += ystep; while (yfrac >= FRACUNIT) { yfrac -= FRACUNIT; src += srcpitch; } dest += destpitch; } } } static void Convert24 (uint8_t *src, int srcpitch, void *destin, int destpitch, int destwidth, int destheight, fixed_t xstep, fixed_t ystep, fixed_t xfrac, fixed_t yfrac) { if ((destwidth | destheight) == 0) { return; } int x, y; uint8_t *dest = (uint8_t *)destin; destpitch = destpitch - destwidth*3; if (xstep == FRACUNIT && ystep == FRACUNIT) { srcpitch -= destwidth; for (y = destheight; y != 0; y--) { for (x = destwidth; x != 0; x--) { uint8_t *pe = GPfxPal.Pal24[src[0]]; dest[0] = pe[0]; dest[1] = pe[1]; dest[2] = pe[2]; dest += 3; src++; } dest += destpitch; src += srcpitch; } } else { for (y = destheight; y != 0; y--) { fixed_t xf = xfrac; for (x = destwidth; x != 0; x--) { uint8_t *pe = GPfxPal.Pal24[src[xf >> FRACBITS]]; dest[0] = pe[0]; dest[1] = pe[1]; dest[2] = pe[2]; xf += xstep; dest += 2; } yfrac += ystep; while (yfrac >= FRACUNIT) { yfrac -= FRACUNIT; src += srcpitch; } dest += destpitch; } } } static void Convert32 (uint8_t *src, int srcpitch, void *destin, int destpitch, int destwidth, int destheight, fixed_t xstep, fixed_t ystep, fixed_t xfrac, fixed_t yfrac) { if ((destwidth | destheight) == 0) { return; } int x, y, savedx; uint32_t *dest = (uint32_t *)destin; destpitch = (destpitch >> 2) - destwidth; if (xstep == FRACUNIT && ystep == FRACUNIT) { srcpitch -= destwidth; for (y = destheight; y != 0; y--) { for (savedx = x = destwidth, x >>= 3; x != 0; x--) { dest[0] = GPfxPal.Pal32[src[0]]; dest[1] = GPfxPal.Pal32[src[1]]; dest[2] = GPfxPal.Pal32[src[2]]; dest[3] = GPfxPal.Pal32[src[3]]; dest[4] = GPfxPal.Pal32[src[4]]; dest[5] = GPfxPal.Pal32[src[5]]; dest[6] = GPfxPal.Pal32[src[6]]; dest[7] = GPfxPal.Pal32[src[7]]; dest += 8; src += 8; } for (x = savedx & 7; x != 0; x--) { *dest++ = GPfxPal.Pal32[*src++]; } dest += destpitch; src += srcpitch; } } else { for (y = destheight; y != 0; y--) { fixed_t xf = xfrac; for (savedx = x = destwidth, x >>= 1; x != 0; x--) { dest[0] = GPfxPal.Pal32[src[xf >> FRACBITS]]; xf += xstep; dest[1] = GPfxPal.Pal32[src[xf >> FRACBITS]]; xf += xstep; dest += 2; } if (savedx & 1) { *dest++ = GPfxPal.Pal32[src[xf >> FRACBITS]]; } yfrac += ystep; while (yfrac >= FRACUNIT) { yfrac -= FRACUNIT; src += srcpitch; } dest += destpitch; } } }
23.914369
92
0.583237
351ELEC
292fe05715f4cbbbcb23adb5d800e2d309725b75
1,240
cpp
C++
Leetcode/Q138.cpp
kingium/Leetcode
f23029637f3a16545f15abcd8eafa8eadd56f146
[ "Unlicense" ]
1
2019-01-21T09:05:32.000Z
2019-01-21T09:05:32.000Z
Leetcode/Q138.cpp
kingium/Leetcode
f23029637f3a16545f15abcd8eafa8eadd56f146
[ "Unlicense" ]
1
2019-08-08T09:58:02.000Z
2019-08-08T09:58:02.000Z
Leetcode/Q138.cpp
goldsail/Leetcode
f23029637f3a16545f15abcd8eafa8eadd56f146
[ "Unlicense" ]
null
null
null
/* // Definition for a Node. class Node { public: int val; Node* next; Node* random; Node() {} Node(int _val, Node* _next, Node* _random) { val = _val; next = _next; random = _random; } }; */ class Solution { public: Node* copyRandomList(Node* head) { this->nodeMap = unordered_map<Node *, Node *>(); if (head == nullptr) { return nullptr; } copyRandomList_(head); return nodeMap[head]; } // Call this function when curr does not exist in the nodeMap void copyRandomList_(Node *curr) { nodeMap[curr] = new Node(curr->val, nullptr, nullptr); Node *next = curr->next; if (next != nullptr) { if (nodeMap.find(next) == nodeMap.end()) { copyRandomList_(next); } nodeMap[curr]->next = nodeMap[next]; } Node *random = curr->random; if (random != nullptr) { if (nodeMap.find(random) == nodeMap.end()) { copyRandomList_(random); } nodeMap[curr]->random = nodeMap[random]; } } private: unordered_map<Node *, Node *> nodeMap; };
22.545455
65
0.504032
kingium
a0955b149daa0b7e685e0bf3372985371779237d
5,012
cpp
C++
src/kernel/tengine/arm64/tengine_conv_2d_wino.cpp
mapnn/mapnn
fcd5ae04b9b9df809281882872842daaf5a35db0
[ "Apache-2.0" ]
2
2021-01-01T02:01:11.000Z
2022-02-15T02:50:44.000Z
src/kernel/tengine/arm64/tengine_conv_2d_wino.cpp
mapnn/mapnn
fcd5ae04b9b9df809281882872842daaf5a35db0
[ "Apache-2.0" ]
null
null
null
src/kernel/tengine/arm64/tengine_conv_2d_wino.cpp
mapnn/mapnn
fcd5ae04b9b9df809281882872842daaf5a35db0
[ "Apache-2.0" ]
null
null
null
/* Copyright 2020 The Mapnn Team. 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 "tengine_kernel.h" #include <executor/operator/arm64/conv/winograd/wino_trans_ker.h> #include <executor/operator/arm64/conv/winograd/wino_trans_inp.h> #include <executor/operator/arm64/conv/winograd/wino_sgemm.h> #include <executor/operator/arm64/conv/winograd/conv_2d_wino.h> #define TILE 4 namespace mapnn { void tengine_conv_2d_wino::init(const Tensors& ins, Tensor& out, Tensors& tmp, Operator& op) { Conv conv(op); L1CHW input(ins[0]); L1CHW output(out); L1VAB temp0(tmp[0]); L1VAB temp1(tmp[1]); const int extented_filter_h = conv.hdilation * (conv.hkernel - 1) + 1; const int extented_filter_w = conv.wdilation * (conv.wkernel - 1) + 1; const int output_xy = output.hw; const int kernel_size = input.c * conv.hkernel * conv.wkernel; output.c = conv.outch; output.h = (input.h - extented_filter_h) / conv.hstride + 1; output.w = (input.w - extented_filter_w) / conv.wstride + 1; int block_h = (output.h + TILE - 1) / TILE; int block_w = (output.w + TILE - 1) / TILE; int block_hw = block_h * block_w; int padded_inh = TILE * block_h + 2; int padded_inw = TILE * block_w + 2; int pad_inhw = padded_inh * padded_inw; int inp_padded_size = (input.c * pad_inhw + 2); temp0.u = 1; temp0.v = 1; temp0.a = inp_padded_size; temp1.u = 1; temp1.v = 1; temp1.a = ELEM_SIZE * input.c * block_hw + 32; } void tengine_conv_2d_wino::run(const Tensors& ins, Tensor& out, Tensors& tmp, Operator& op) { Conv conv(op); L1CHW output(out); L1CHW input(ins[0]); L1VAB weight(ins[1]); L111W biast(ins[2]); L1VAB temp0(tmp[0]); L1VAB temp1(tmp[1]); int pad_h0 = 0; int pad_w0 = 0; int cpu_type = TYPE_A53; int activation = -1; float* input_org = input.data; int input_c = input.c; int input_h = input.h; int input_w = input.w; int inp_chw = input_c * input_h * input_w; float* output_org = output.data; int output_h = output.h; int output_w = output.w; int output_c = output.c; int out_hw = output_h * output_w; int out_chw = out_hw * output_c; int output_n = 1; int block_h = (output_h + TILE - 1) / TILE; int block_w = (output_w + TILE - 1) / TILE; int block_hw = block_h * block_w; int padded_inh = TILE * block_h + 2; int padded_inw = TILE * block_w + 2; int pad_inhw = padded_inh * padded_inw; int nn_block = block_hw / BLOCK_HW_UNIT; int resi_block = nn_block * BLOCK_HW_UNIT; int resi_w = block_w * TILE - output_w; int resi_h = block_h * TILE - output_h; float* kernel_interleaved = weight.data; float* input_padded = temp0.data; float* trans_inp = temp1.data; float* bias = biast.data; int bias_term = biast.data != NULL; int block_4 = (block_hw+3)/4; int L2_CACHE_SIZE = (cpu_type == TYPE_A53) ? 512 * 1024 : 1024 * 1024; int L2_n = L2_CACHE_SIZE * 0.3 / (ELEM_SIZE * input_c * sizeof(float)); L2_n = L2_n > 16 ? (L2_n & -16) : 16; int cout_count16 = output_c/16; int cout_nn16 = cout_count16*16; for(int n = 0; n < output_n; n++) { float* input = input_org + n * inp_chw; float* output = output_org + n * out_chw; // pad_trans_interleave_inp pad_input1(input, input_padded, input_c, input_h, input_w, padded_inh, padded_inw, pad_h0, pad_w0); tran_input_4block(input_padded, trans_inp, input_c, 0, nn_block, block_w, pad_inhw, padded_inw); if(resi_block != block_hw) tran_input_resi_block(input_padded, trans_inp, input_c, nn_block, resi_block, block_hw, block_w, pad_inhw, padded_inw); wino_sgemm_4x16(kernel_interleaved, trans_inp, output, bias, bias_term, input_c, cpu_type, 0, cout_nn16, 0, block_hw, block_h, block_w, out_hw, output_w, resi_h, resi_w, activation); if(cout_nn16!=output_c) { wino_sgemm_4x4(kernel_interleaved, trans_inp, output, bias, bias_term, input_c, cpu_type, cout_nn16,output_c , 0, block_hw, block_h, block_w, out_hw, output_w, resi_h, resi_w, activation); } } } }
37.969697
125
0.627893
mapnn
a0985c4b23376a6bcf7e633ff0a6a998a3c5a33c
358
cpp
C++
SourceCode/Chapter 04/Pr4-3.cpp
aceiro/poo2019
0f93d22296f43a8b024a346f510c00314817d2cf
[ "MIT" ]
1
2019-04-09T18:29:38.000Z
2019-04-09T18:29:38.000Z
SourceCode/Chapter 04/Pr4-3.cpp
aceiro/poo2019
0f93d22296f43a8b024a346f510c00314817d2cf
[ "MIT" ]
null
null
null
SourceCode/Chapter 04/Pr4-3.cpp
aceiro/poo2019
0f93d22296f43a8b024a346f510c00314817d2cf
[ "MIT" ]
null
null
null
// This program demonstrates how a misplaced semicolon // prematurely terminates an if statement. #include <iostream> using namespace std; int main() { int x = 0, y = 10; cout << "x is " << x << " and y is " << y << endl; if (x > y); // Error! Misplaced semicolon cout << "x is greater than y\n"; //This is always executed. return 0; }
25.571429
65
0.611732
aceiro
a098bf05abd1e3447dd861cc5fea1e2a4991f270
20,767
cc
C++
runtime/reflection_test.cc
lifansama/xposed_art_n
ec3fbe417d74d4664cec053d91dd4e3881176374
[ "MIT" ]
234
2017-07-18T05:30:27.000Z
2022-01-07T02:21:31.000Z
runtime/reflection_test.cc
lifansama/xposed_art_n
ec3fbe417d74d4664cec053d91dd4e3881176374
[ "MIT" ]
21
2017-07-18T04:56:09.000Z
2018-08-10T17:32:16.000Z
runtime/reflection_test.cc
lifansama/xposed_art_n
ec3fbe417d74d4664cec053d91dd4e3881176374
[ "MIT" ]
56
2017-07-18T10:37:10.000Z
2022-01-07T02:19:22.000Z
/* * Copyright (C) 2011 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 "reflection.h" #include <float.h> #include <limits.h> #include "ScopedLocalRef.h" #include "art_method-inl.h" #include "common_compiler_test.h" #include "scoped_thread_state_change.h" namespace art { // TODO: Convert to CommonRuntimeTest. Currently MakeExecutable is used. class ReflectionTest : public CommonCompilerTest { protected: virtual void SetUp() { CommonCompilerTest::SetUp(); vm_ = Runtime::Current()->GetJavaVM(); // Turn on -verbose:jni for the JNI tests. // gLogVerbosity.jni = true; vm_->AttachCurrentThread(&env_, nullptr); ScopedLocalRef<jclass> aioobe(env_, env_->FindClass("java/lang/ArrayIndexOutOfBoundsException")); CHECK(aioobe.get() != nullptr); aioobe_ = reinterpret_cast<jclass>(env_->NewGlobalRef(aioobe.get())); ScopedLocalRef<jclass> ase(env_, env_->FindClass("java/lang/ArrayStoreException")); CHECK(ase.get() != nullptr); ase_ = reinterpret_cast<jclass>(env_->NewGlobalRef(ase.get())); ScopedLocalRef<jclass> sioobe(env_, env_->FindClass("java/lang/StringIndexOutOfBoundsException")); CHECK(sioobe.get() != nullptr); sioobe_ = reinterpret_cast<jclass>(env_->NewGlobalRef(sioobe.get())); } void CleanUpJniEnv() { if (aioobe_ != nullptr) { env_->DeleteGlobalRef(aioobe_); aioobe_ = nullptr; } if (ase_ != nullptr) { env_->DeleteGlobalRef(ase_); ase_ = nullptr; } if (sioobe_ != nullptr) { env_->DeleteGlobalRef(sioobe_); sioobe_ = nullptr; } } virtual void TearDown() { CleanUpJniEnv(); CommonCompilerTest::TearDown(); } jclass GetPrimitiveClass(char descriptor) { ScopedObjectAccess soa(env_); mirror::Class* c = class_linker_->FindPrimitiveClass(descriptor); CHECK(c != nullptr); return soa.AddLocalReference<jclass>(c); } void ReflectionTestMakeExecutable(ArtMethod** method, mirror::Object** receiver, bool is_static, const char* method_name, const char* method_signature) SHARED_REQUIRES(Locks::mutator_lock_) { const char* class_name = is_static ? "StaticLeafMethods" : "NonStaticLeafMethods"; jobject jclass_loader(LoadDex(class_name)); Thread* self = Thread::Current(); StackHandleScope<2> hs(self); Handle<mirror::ClassLoader> class_loader( hs.NewHandle( ScopedObjectAccessUnchecked(self).Decode<mirror::ClassLoader*>(jclass_loader))); if (is_static) { MakeExecutable(ScopedObjectAccessUnchecked(self).Decode<mirror::ClassLoader*>(jclass_loader), class_name); } else { MakeExecutable(nullptr, "java.lang.Class"); MakeExecutable(nullptr, "java.lang.Object"); MakeExecutable(ScopedObjectAccessUnchecked(self).Decode<mirror::ClassLoader*>(jclass_loader), class_name); } mirror::Class* c = class_linker_->FindClass(self, DotToDescriptor(class_name).c_str(), class_loader); CHECK(c != nullptr); *method = is_static ? c->FindDirectMethod(method_name, method_signature, sizeof(void*)) : c->FindVirtualMethod(method_name, method_signature, sizeof(void*)); CHECK(method != nullptr); if (is_static) { *receiver = nullptr; } else { // Ensure class is initialized before allocating object StackHandleScope<1> hs2(self); Handle<mirror::Class> h_class(hs2.NewHandle(c)); bool initialized = class_linker_->EnsureInitialized(self, h_class, true, true); CHECK(initialized); *receiver = c->AllocObject(self); } // Start runtime. bool started = runtime_->Start(); CHECK(started); self->TransitionFromSuspendedToRunnable(); } void InvokeNopMethod(bool is_static) { ScopedObjectAccess soa(env_); ArtMethod* method; mirror::Object* receiver; ReflectionTestMakeExecutable(&method, &receiver, is_static, "nop", "()V"); ScopedLocalRef<jobject> receiver_ref(soa.Env(), soa.AddLocalReference<jobject>(receiver)); InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), nullptr); } void InvokeIdentityByteMethod(bool is_static) { ScopedObjectAccess soa(env_); ArtMethod* method; mirror::Object* receiver; ReflectionTestMakeExecutable(&method, &receiver, is_static, "identity", "(B)B"); ScopedLocalRef<jobject> receiver_ref(soa.Env(), soa.AddLocalReference<jobject>(receiver)); jvalue args[1]; args[0].b = 0; JValue result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_EQ(0, result.GetB()); args[0].b = -1; result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_EQ(-1, result.GetB()); args[0].b = SCHAR_MAX; result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_EQ(SCHAR_MAX, result.GetB()); static_assert(SCHAR_MIN == -128, "SCHAR_MIN unexpected"); args[0].b = SCHAR_MIN; result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_EQ(SCHAR_MIN, result.GetB()); } void InvokeIdentityIntMethod(bool is_static) { ScopedObjectAccess soa(env_); ArtMethod* method; mirror::Object* receiver; ReflectionTestMakeExecutable(&method, &receiver, is_static, "identity", "(I)I"); ScopedLocalRef<jobject> receiver_ref(soa.Env(), soa.AddLocalReference<jobject>(receiver)); jvalue args[1]; args[0].i = 0; JValue result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_EQ(0, result.GetI()); args[0].i = -1; result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_EQ(-1, result.GetI()); args[0].i = INT_MAX; result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_EQ(INT_MAX, result.GetI()); args[0].i = INT_MIN; result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_EQ(INT_MIN, result.GetI()); } void InvokeIdentityDoubleMethod(bool is_static) { ScopedObjectAccess soa(env_); ArtMethod* method; mirror::Object* receiver; ReflectionTestMakeExecutable(&method, &receiver, is_static, "identity", "(D)D"); ScopedLocalRef<jobject> receiver_ref(soa.Env(), soa.AddLocalReference<jobject>(receiver)); jvalue args[1]; args[0].d = 0.0; JValue result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_DOUBLE_EQ(0.0, result.GetD()); args[0].d = -1.0; result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_DOUBLE_EQ(-1.0, result.GetD()); args[0].d = DBL_MAX; result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_DOUBLE_EQ(DBL_MAX, result.GetD()); args[0].d = DBL_MIN; result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_DOUBLE_EQ(DBL_MIN, result.GetD()); } void InvokeSumIntIntMethod(bool is_static) { ScopedObjectAccess soa(env_); ArtMethod* method; mirror::Object* receiver; ReflectionTestMakeExecutable(&method, &receiver, is_static, "sum", "(II)I"); ScopedLocalRef<jobject> receiver_ref(soa.Env(), soa.AddLocalReference<jobject>(receiver)); jvalue args[2]; args[0].i = 1; args[1].i = 2; JValue result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_EQ(3, result.GetI()); args[0].i = -2; args[1].i = 5; result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_EQ(3, result.GetI()); args[0].i = INT_MAX; args[1].i = INT_MIN; result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_EQ(-1, result.GetI()); args[0].i = INT_MAX; args[1].i = INT_MAX; result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_EQ(-2, result.GetI()); } void InvokeSumIntIntIntMethod(bool is_static) { ScopedObjectAccess soa(env_); ArtMethod* method; mirror::Object* receiver; ReflectionTestMakeExecutable(&method, &receiver, is_static, "sum", "(III)I"); ScopedLocalRef<jobject> receiver_ref(soa.Env(), soa.AddLocalReference<jobject>(receiver)); jvalue args[3]; args[0].i = 0; args[1].i = 0; args[2].i = 0; JValue result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_EQ(0, result.GetI()); args[0].i = 1; args[1].i = 2; args[2].i = 3; result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_EQ(6, result.GetI()); args[0].i = -1; args[1].i = 2; args[2].i = -3; result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_EQ(-2, result.GetI()); args[0].i = INT_MAX; args[1].i = INT_MIN; args[2].i = INT_MAX; result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_EQ(2147483646, result.GetI()); args[0].i = INT_MAX; args[1].i = INT_MAX; args[2].i = INT_MAX; result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_EQ(2147483645, result.GetI()); } void InvokeSumIntIntIntIntMethod(bool is_static) { ScopedObjectAccess soa(env_); ArtMethod* method; mirror::Object* receiver; ReflectionTestMakeExecutable(&method, &receiver, is_static, "sum", "(IIII)I"); ScopedLocalRef<jobject> receiver_ref(soa.Env(), soa.AddLocalReference<jobject>(receiver)); jvalue args[4]; args[0].i = 0; args[1].i = 0; args[2].i = 0; args[3].i = 0; JValue result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_EQ(0, result.GetI()); args[0].i = 1; args[1].i = 2; args[2].i = 3; args[3].i = 4; result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_EQ(10, result.GetI()); args[0].i = -1; args[1].i = 2; args[2].i = -3; args[3].i = 4; result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_EQ(2, result.GetI()); args[0].i = INT_MAX; args[1].i = INT_MIN; args[2].i = INT_MAX; args[3].i = INT_MIN; result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_EQ(-2, result.GetI()); args[0].i = INT_MAX; args[1].i = INT_MAX; args[2].i = INT_MAX; args[3].i = INT_MAX; result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_EQ(-4, result.GetI()); } void InvokeSumIntIntIntIntIntMethod(bool is_static) { ScopedObjectAccess soa(env_); ArtMethod* method; mirror::Object* receiver; ReflectionTestMakeExecutable(&method, &receiver, is_static, "sum", "(IIIII)I"); ScopedLocalRef<jobject> receiver_ref(soa.Env(), soa.AddLocalReference<jobject>(receiver)); jvalue args[5]; args[0].i = 0; args[1].i = 0; args[2].i = 0; args[3].i = 0; args[4].i = 0; JValue result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_EQ(0, result.GetI()); args[0].i = 1; args[1].i = 2; args[2].i = 3; args[3].i = 4; args[4].i = 5; result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_EQ(15, result.GetI()); args[0].i = -1; args[1].i = 2; args[2].i = -3; args[3].i = 4; args[4].i = -5; result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_EQ(-3, result.GetI()); args[0].i = INT_MAX; args[1].i = INT_MIN; args[2].i = INT_MAX; args[3].i = INT_MIN; args[4].i = INT_MAX; result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_EQ(2147483645, result.GetI()); args[0].i = INT_MAX; args[1].i = INT_MAX; args[2].i = INT_MAX; args[3].i = INT_MAX; args[4].i = INT_MAX; result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_EQ(2147483643, result.GetI()); } void InvokeSumDoubleDoubleMethod(bool is_static) { ScopedObjectAccess soa(env_); ArtMethod* method; mirror::Object* receiver; ReflectionTestMakeExecutable(&method, &receiver, is_static, "sum", "(DD)D"); ScopedLocalRef<jobject> receiver_ref(soa.Env(), soa.AddLocalReference<jobject>(receiver)); jvalue args[2]; args[0].d = 0.0; args[1].d = 0.0; JValue result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_DOUBLE_EQ(0.0, result.GetD()); args[0].d = 1.0; args[1].d = 2.0; result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_DOUBLE_EQ(3.0, result.GetD()); args[0].d = 1.0; args[1].d = -2.0; result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_DOUBLE_EQ(-1.0, result.GetD()); args[0].d = DBL_MAX; args[1].d = DBL_MIN; result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_DOUBLE_EQ(1.7976931348623157e308, result.GetD()); args[0].d = DBL_MAX; args[1].d = DBL_MAX; result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_DOUBLE_EQ(INFINITY, result.GetD()); } void InvokeSumDoubleDoubleDoubleMethod(bool is_static) { ScopedObjectAccess soa(env_); ArtMethod* method; mirror::Object* receiver; ReflectionTestMakeExecutable(&method, &receiver, is_static, "sum", "(DDD)D"); ScopedLocalRef<jobject> receiver_ref(soa.Env(), soa.AddLocalReference<jobject>(receiver)); jvalue args[3]; args[0].d = 0.0; args[1].d = 0.0; args[2].d = 0.0; JValue result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_DOUBLE_EQ(0.0, result.GetD()); args[0].d = 1.0; args[1].d = 2.0; args[2].d = 3.0; result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_DOUBLE_EQ(6.0, result.GetD()); args[0].d = 1.0; args[1].d = -2.0; args[2].d = 3.0; result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_DOUBLE_EQ(2.0, result.GetD()); } void InvokeSumDoubleDoubleDoubleDoubleMethod(bool is_static) { ScopedObjectAccess soa(env_); ArtMethod* method; mirror::Object* receiver; ReflectionTestMakeExecutable(&method, &receiver, is_static, "sum", "(DDDD)D"); ScopedLocalRef<jobject> receiver_ref(soa.Env(), soa.AddLocalReference<jobject>(receiver)); jvalue args[4]; args[0].d = 0.0; args[1].d = 0.0; args[2].d = 0.0; args[3].d = 0.0; JValue result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_DOUBLE_EQ(0.0, result.GetD()); args[0].d = 1.0; args[1].d = 2.0; args[2].d = 3.0; args[3].d = 4.0; result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_DOUBLE_EQ(10.0, result.GetD()); args[0].d = 1.0; args[1].d = -2.0; args[2].d = 3.0; args[3].d = -4.0; result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_DOUBLE_EQ(-2.0, result.GetD()); } void InvokeSumDoubleDoubleDoubleDoubleDoubleMethod(bool is_static) { ScopedObjectAccess soa(env_); ArtMethod* method; mirror::Object* receiver; ReflectionTestMakeExecutable(&method, &receiver, is_static, "sum", "(DDDDD)D"); ScopedLocalRef<jobject> receiver_ref(soa.Env(), soa.AddLocalReference<jobject>(receiver)); jvalue args[5]; args[0].d = 0.0; args[1].d = 0.0; args[2].d = 0.0; args[3].d = 0.0; args[4].d = 0.0; JValue result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_DOUBLE_EQ(0.0, result.GetD()); args[0].d = 1.0; args[1].d = 2.0; args[2].d = 3.0; args[3].d = 4.0; args[4].d = 5.0; result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_DOUBLE_EQ(15.0, result.GetD()); args[0].d = 1.0; args[1].d = -2.0; args[2].d = 3.0; args[3].d = -4.0; args[4].d = 5.0; result = InvokeWithJValues(soa, receiver_ref.get(), soa.EncodeMethod(method), args); EXPECT_DOUBLE_EQ(3.0, result.GetD()); } JavaVMExt* vm_; JNIEnv* env_; jclass aioobe_; jclass ase_; jclass sioobe_; }; TEST_F(ReflectionTest, StaticMainMethod) { TEST_DISABLED_FOR_READ_BARRIER_WITH_OPTIMIZING_FOR_UNSUPPORTED_INSTRUCTION_SETS(); ScopedObjectAccess soa(Thread::Current()); jobject jclass_loader = LoadDex("Main"); StackHandleScope<1> hs(soa.Self()); Handle<mirror::ClassLoader> class_loader( hs.NewHandle(soa.Decode<mirror::ClassLoader*>(jclass_loader))); CompileDirectMethod(class_loader, "Main", "main", "([Ljava/lang/String;)V"); mirror::Class* klass = class_linker_->FindClass(soa.Self(), "LMain;", class_loader); ASSERT_TRUE(klass != nullptr); ArtMethod* method = klass->FindDirectMethod("main", "([Ljava/lang/String;)V", sizeof(void*)); ASSERT_TRUE(method != nullptr); // Start runtime. bool started = runtime_->Start(); CHECK(started); soa.Self()->TransitionFromSuspendedToRunnable(); jvalue args[1]; args[0].l = nullptr; InvokeWithJValues(soa, nullptr, soa.EncodeMethod(method), args); } TEST_F(ReflectionTest, StaticNopMethod) { InvokeNopMethod(true); } TEST_F(ReflectionTest, NonStaticNopMethod) { InvokeNopMethod(false); } TEST_F(ReflectionTest, StaticIdentityByteMethod) { InvokeIdentityByteMethod(true); } TEST_F(ReflectionTest, NonStaticIdentityByteMethod) { InvokeIdentityByteMethod(false); } TEST_F(ReflectionTest, StaticIdentityIntMethod) { InvokeIdentityIntMethod(true); } TEST_F(ReflectionTest, NonStaticIdentityIntMethod) { InvokeIdentityIntMethod(false); } TEST_F(ReflectionTest, StaticIdentityDoubleMethod) { InvokeIdentityDoubleMethod(true); } TEST_F(ReflectionTest, NonStaticIdentityDoubleMethod) { InvokeIdentityDoubleMethod(false); } TEST_F(ReflectionTest, StaticSumIntIntMethod) { InvokeSumIntIntMethod(true); } TEST_F(ReflectionTest, NonStaticSumIntIntMethod) { InvokeSumIntIntMethod(false); } TEST_F(ReflectionTest, StaticSumIntIntIntMethod) { InvokeSumIntIntIntMethod(true); } TEST_F(ReflectionTest, NonStaticSumIntIntIntMethod) { InvokeSumIntIntIntMethod(false); } TEST_F(ReflectionTest, StaticSumIntIntIntIntMethod) { InvokeSumIntIntIntIntMethod(true); } TEST_F(ReflectionTest, NonStaticSumIntIntIntIntMethod) { InvokeSumIntIntIntIntMethod(false); } TEST_F(ReflectionTest, StaticSumIntIntIntIntIntMethod) { InvokeSumIntIntIntIntIntMethod(true); } TEST_F(ReflectionTest, NonStaticSumIntIntIntIntIntMethod) { InvokeSumIntIntIntIntIntMethod(false); } TEST_F(ReflectionTest, StaticSumDoubleDoubleMethod) { InvokeSumDoubleDoubleMethod(true); } TEST_F(ReflectionTest, NonStaticSumDoubleDoubleMethod) { InvokeSumDoubleDoubleMethod(false); } TEST_F(ReflectionTest, StaticSumDoubleDoubleDoubleMethod) { InvokeSumDoubleDoubleDoubleMethod(true); } TEST_F(ReflectionTest, NonStaticSumDoubleDoubleDoubleMethod) { InvokeSumDoubleDoubleDoubleMethod(false); } TEST_F(ReflectionTest, StaticSumDoubleDoubleDoubleDoubleMethod) { InvokeSumDoubleDoubleDoubleDoubleMethod(true); } TEST_F(ReflectionTest, NonStaticSumDoubleDoubleDoubleDoubleMethod) { InvokeSumDoubleDoubleDoubleDoubleMethod(false); } TEST_F(ReflectionTest, StaticSumDoubleDoubleDoubleDoubleDoubleMethod) { InvokeSumDoubleDoubleDoubleDoubleDoubleMethod(true); } TEST_F(ReflectionTest, NonStaticSumDoubleDoubleDoubleDoubleDoubleMethod) { InvokeSumDoubleDoubleDoubleDoubleDoubleMethod(false); } } // namespace art
32.963492
99
0.67901
lifansama
a0992cbad30cb80cec144a1003368325c5368475
20,901
hxx
C++
com/ole32/com/dcomrem/call.hxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
com/ole32/com/dcomrem/call.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
com/ole32/com/dcomrem/call.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+------------------------------------------------------------------- // // File: call.hxx // // Contents: Support for canceling DCOM calls // // Classes: CCallTable // CMessageCall // CAsyncCall // // History: 14-May-97 Gopalk Created // History: 13-Nov-98 pdejong added Enable/Disable Cancel // //-------------------------------------------------------------------- #ifndef _CALL_HXX_ #define _CALL_HXX_ #include <pgalloc.hxx> #include <destobj.hxx> #include <objidl.h> // SChannelHookInfo #define CALLENTRIES_PER_PAGE 100 #define CALLS_PER_PAGE 100 #define DEB_CALL DEB_USER1 #define DEB_CANCEL DEB_USER2 #define DEB_LOOP DEB_USER3 #define RPC_E_CALL_NESTED E_FAIL #define RPC_E_CALL_NOTSYNCHRONOUS E_FAIL const DWORD CALLFLAG_CALLCOMPLETED = DCOM_CALL_COMPLETE; const DWORD CALLFLAG_CALLCANCELED = DCOM_CALL_CANCELED; const DWORD CALLFLAG_USERMODEBITS = DCOM_CALL_COMPLETE | DCOM_CALL_CANCELED; const DWORD CALLFLAG_CALLDISPATCHED = 0x00010000; const DWORD CALLFLAG_WOWMSGARRIVED = 0x00020000; const DWORD CALLFLAG_CALLFINISHED = 0x00040000; const DWORD CALLFLAG_CANCELISSUED = 0x00080000; const DWORD CALLFLAG_CLIENTNOTWAITING = 0x00100000; const DWORD CALLFLAG_INDESTRUCTOR = 0x00200000; const DWORD CALLFLAG_STATHREAD = 0x00400000; const DWORD CALLFLAG_WOWTHREAD = 0x00800000; const DWORD CALLFLAG_CALLSENT = 0x01000000; const DWORD CALLFLAG_CLIENTASYNC = 0x02000000; const DWORD CALLFLAG_SERVERASYNC = 0x04000000; const DWORD CALLFLAG_SIGNALED = 0x08000000; const DWORD CALLFLAG_ONCALLSTACK = 0x10000000; const DWORD CALLFLAG_CANCELENABLED = 0x20000000; const DWORD CALLFLAG_ERRORFROMPOLICY = 0x40000000; class CAsyncCall; class CCtxCall; class CChannelObject; // critical section guarding call objects extern COleStaticMutexSem gCallLock; extern BOOL gfChannelProcessInitialized; void SignalTheClient(CAsyncCall *pCall); //+------------------------------------------------------------------- // // Class: CCallTable, public // // Synopsis: Global Call Table. // // Notes: Table of registered Call objects // // History: 14-May-97 Gopalk Created // //-------------------------------------------------------------------- class CCallTable { public: // Functionality methods HRESULT PushCallObject(ICancelMethodCalls *pObject) { Win4Assert(pObject); return SetEntry(pObject); } ICancelMethodCalls *PopCallObject(ICancelMethodCalls *pObject) { return ClearEntry(pObject); } ICancelMethodCalls *GetEntry(DWORD dwThreadId); void CancelPendingCalls(); // Initialization and cleanup methods void Initialize(); void Cleanup(); void PrivateCleanup(); private: HRESULT SetEntry(ICancelMethodCalls *pObject); ICancelMethodCalls *ClearEntry(ICancelMethodCalls *pObject); ULONG m_cCalls; // Number of calls using the table static BOOL m_fInitialized; // Set when initialized static CPageAllocator m_Allocator; // Allocator for call entries }; extern CCallTable gCallTbl; // Global call table /* Type definitions. */ typedef enum EChannelState { // The channel on the client side held by the remote handler. client_cs = 0x1, // The channels on the client side held by proxies. proxy_cs = 0x2, // The server channels held by remote handlers. server_cs = 0x4, // Flag to indicate that the channel may be used on any thread. freethreaded_cs = 0x8, // The server and client are in this process. process_local_cs = 0x20, // Set when free buffer must call UnlockClient locked_cs = 0x40, // Call server on client's thread neutral_cs = 0x100, // Convert sync call to async to avoid blocking fake_async_cs = 0x200, // Use application security, set blanket called app_security_cs = 0x400, // The server and client are in the same thread thread_local_cs = 0x800, #ifdef _WIN64 // NDR Transfer Syntax Negotiation happened on the channel syntax_negotiate_cs = 0x1000 #if DBG == 1 , #endif #endif #if DBG == 1 // leave the NA to enter the MTA leave_natomta_cs = 0x2000, // leave the NA to enter the STA leave_natosta_cs = 0x4000 #endif } EChannelState; typedef enum { none_ss, pending_ss, signaled_ss, failed_ss } ESignalState; // Forward declaration of ClientCall class CClientCall; class CChannelHandle; class CCliModalLoop; //----------------------------------------------------------------- // // Class: CMessageCall // // Purpose: This class adds a message to the call info. The // proxie's message is copied so the call can be // canceled without stray pointer references. // //----------------------------------------------------------------- class CMessageCall : public ICancelMethodCalls, public IMessageParam { public: // Constructor and destructor CMessageCall(); protected: virtual ~CMessageCall(); virtual void UninitCallObject(); public: // called before a call starts and after a call completes. virtual HRESULT InitCallObject(CALLCATEGORY callcat, RPCOLEMESSAGE *message, DWORD flags, REFIPID ipidServer, DWORD destctx, COMVERSION version, CChannelHandle *handle); // IUnknown methods STDMETHOD(QueryInterface)(REFIID riid, LPVOID *ppv) = 0; STDMETHOD_(ULONG,AddRef)(void) = 0; STDMETHOD_(ULONG,Release)(void) = 0; // ICancelMethodCalls methods STDMETHOD(Cancel)(ULONG ulSeconds) = 0; STDMETHOD(TestCancel)(void) = 0; // Virtual methods needed by every call type for cancel support virtual void CallCompleted ( HRESULT hrRet ) = 0; virtual void CallFinished () = 0; virtual HRESULT CanDispatch () = 0; virtual HRESULT WOWMsgArrived () = 0; virtual HRESULT GetState ( DWORD *pdwState ) = 0; virtual BOOL IsCallDispatched() = 0; virtual BOOL IsCallCompleted () = 0; virtual BOOL IsCallCanceled () = 0; virtual BOOL IsCancelIssued () = 0; virtual BOOL HasWOWMsgArrived() = 0; virtual BOOL IsClientWaiting () = 0; virtual void AckCancel () = 0; virtual HRESULT Cancel (BOOL fModalLoop, ULONG ulTimeout) = 0; virtual HRESULT AdvCancel () = 0; virtual void Abort() { Win4Assert(!"Abort Called"); } // Query methods BOOL ClientAsync() { return _iFlags & CALLFLAG_CLIENTASYNC; } BOOL ServerAsync() { return _iFlags & CALLFLAG_SERVERASYNC; } BOOL CancelEnabled() { return _iFlags & CALLFLAG_CANCELENABLED; } BOOL IsClientSide() { return !(_iFlags & server_cs); } BOOL FakeAsync() { return _iFlags & fake_async_cs; } BOOL FreeThreaded() { return _iFlags & freethreaded_cs; } void Lock() { _iFlags |= locked_cs; } #if DBG == 1 void SetNAToMTAFlag() {_iFlags |= leave_natomta_cs;} void ResetNAToMTAFlag(){_iFlags &= ~leave_natomta_cs;} BOOL IsNAToMTAFlagSet(){ return _iFlags & leave_natomta_cs;} void SetNAToSTAFlag() {_iFlags |= leave_natosta_cs;} void ResetNAToSTAFlag(){_iFlags &= ~leave_natosta_cs;} BOOL IsNAToSTAFlagSet(){ return _iFlags & leave_natosta_cs;} #endif BOOL Locked() { return _iFlags & locked_cs; } BOOL Neutral() { return _iFlags & neutral_cs; } BOOL ProcessLocal() { return _iFlags & process_local_cs; } BOOL ThreadLocal() { return _iFlags & thread_local_cs; } BOOL Proxy() { return _iFlags & proxy_cs; } BOOL Server() { return _iFlags & server_cs; } // Get methods DWORD GetTimeout(); DWORD GetDestCtx() { return _destObj.GetDestCtx(); } COMVERSION &GetComVersion() { return _destObj.GetComVersion(); } CCtxCall *GetClientCtxCall() { return m_pClientCtxCall; } CCtxCall *GetServerCtxCall() { return m_pServerCtxCall; } BOOL GetErrorFromPolicy() { return (_iFlags & CALLFLAG_ERRORFROMPOLICY); } HRESULT SetCallerhWnd(); HWND GetCallerhWnd() { return _hWndCaller; } HANDLE GetEvent() { return _hEvent; } CALLCATEGORY GetCallCategory(){ return _callcat; } HRESULT GetResult() { return _hResult; } void SetResult(HRESULT hr) { _hResult = hr; } DWORD GetFault() { return _server_fault; } void SetFault(DWORD fault) { _server_fault = fault; } IPID & GetIPID() { return _ipid; } HANDLE GetSxsActCtx() { return _hSxsActCtx; } // Set methods void SetThreadLocal(BOOL fThreadLocal); void SetClientCtxCall(CCtxCall *pCtxCall) { m_pClientCtxCall = pCtxCall; } void SetServerCtxCall(CCtxCall *pCtxCall) { m_pServerCtxCall = pCtxCall; } void SetClientAsync() { _iFlags |= CALLFLAG_CLIENTASYNC; } void SetServerAsync() { _iFlags |= CALLFLAG_SERVERASYNC; } void SetCancelEnabled() { _iFlags |= CALLFLAG_CANCELENABLED; } void SetErrorFromPolicy() { _iFlags |= CALLFLAG_ERRORFROMPOLICY; } void ResetErrorFromPolicy() { _iFlags &= ~CALLFLAG_ERRORFROMPOLICY; } void SetSxsActCtx(HANDLE hCtx); // Other methods HRESULT RslvCancel(DWORD &dwSignal, HRESULT hrIn, BOOL fPostMsg, CCliModalLoop *pCML); protected: // Call object fields CALLCATEGORY _callcat; // call category DWORD _iFlags; // EChannelState SCODE _hResult; // HRESULT or exception code HANDLE _hEvent; // caller wait event HWND _hWndCaller;// caller apartment hWnd (only used InWow) IPID _ipid; // ipid of interface call is being made on HANDLE _hSxsActCtx;// Activation context active in the caller's context public: // Channel fields DWORD _server_fault; CDestObject _destObj; void *_pHeader; CChannelHandle *_pHandle; handle_t _hRpc; // Call handle (not binding handle). IUnknown *_pContext; // Structure RPCOLEMESSAGE message; SChannelHookCallInfo hook; DWORD _dwErrorBufSize; protected: // Cancel fields ULONG m_ulCancelTimeout; // Seconds to wait before canceling the call DWORD m_dwStartCount; // Tick count at the time the call was made CCtxCall *m_pClientCtxCall; // Client side context call object CCtxCall *m_pServerCtxCall; // Server side context call object }; inline void CMessageCall::SetSxsActCtx(HANDLE hCtx) { if (_hSxsActCtx != INVALID_HANDLE_VALUE) ReleaseActCtx(_hSxsActCtx); _hSxsActCtx = hCtx; if (_hSxsActCtx != INVALID_HANDLE_VALUE) AddRefActCtx(_hSxsActCtx); } inline void CMessageCall::SetThreadLocal( BOOL fTL ) { if (fTL) _iFlags |= thread_local_cs; else _iFlags &= ~thread_local_cs; } //----------------------------------------------------------------- // // Class: CAsyncCall // // Purpose: This class adds an async handle to a message call. // Async calls need the message handle in addition to // all the other stuff. // //----------------------------------------------------------------- class CAsyncCall : public CMessageCall { public: // Constructor and destructor CAsyncCall(); CAsyncCall(ULONG refs) { _iRefCount = refs; _pChnlObj = NULL; _pContext = NULL; #if DBG == 1 _dwSignature = 0; #endif } virtual ~CAsyncCall(); public: // called before a call starts and after a call completes. HRESULT InitCallObject(CALLCATEGORY callcat, RPCOLEMESSAGE *message, DWORD flags, REFIPID ipidServer, DWORD destctx, COMVERSION version, CChannelHandle *handle); void UninitCallObject(); static CMessageCall *AllocCallFromList(); BOOL ReturnCallToList(CAsyncCall *pCall); static void Cleanup ( void ); void ServerReply ( void ); // IUnknown methods STDMETHOD(QueryInterface)(REFIID riid, LPVOID *ppv); STDMETHOD_(ULONG,AddRef)(void); STDMETHOD_(ULONG,Release)(void); // ICancelMethodCalls methods STDMETHOD(Cancel)(ULONG ulSeconds); STDMETHOD(TestCancel)(void); // CMessageCall methods void CallCompleted(HRESULT hrRet); void CallFinished(); HRESULT CallSent(); HRESULT CanDispatch(); HRESULT WOWMsgArrived(); HRESULT GetState(DWORD *pdwState); BOOL IsCallDispatched() { return _lFlags & CALLFLAG_CALLDISPATCHED; } BOOL IsCallCompleted () { return _lFlags & CALLFLAG_CALLCOMPLETED; } BOOL IsCallCanceled () { return _lFlags & CALLFLAG_CALLCANCELED; } BOOL IsCancelIssued () { return _lFlags & CALLFLAG_CANCELISSUED; } BOOL HasWOWMsgArrived() { return _lFlags & CALLFLAG_WOWMSGARRIVED; } BOOL IsClientWaiting () { return !(_lFlags & CALLFLAG_CLIENTNOTWAITING); } void AckCancel(); HRESULT Cancel(BOOL fModalLoop, ULONG ulTimeout); HRESULT AdvCancel(); BOOL IsCallSent() { return _lFlags & CALLFLAG_CALLSENT; }; void InitClientHwnd(); HRESULT InitForSendComplete(); void CallCompleted(BOOL *pCanceled); #if DBG==1 void Signaled() {_lFlags |= CALLFLAG_SIGNALED;} BOOL IsSignaled() {return _lFlags & CALLFLAG_SIGNALED;} #endif #if DBG==1 DWORD _dwSignature; #endif DWORD _iRefCount; DWORD _lFlags; CChannelObject *_pChnlObj; void *_pRequestBuffer; DWORD _lApt; RPC_ASYNC_STATE _AsyncState; HWND _hwndSTA; CAsyncCall* _pNext; // Debug field to track async calls that are signalled twice or freed with // a pending signal. ESignalState _eSignalState; private: static CAsyncCall *_aList[CALLCACHE_SIZE]; static DWORD _iNext; }; inline CMessageCall *CAsyncCall::AllocCallFromList() { CMessageCall *pCall = NULL; ASSERT_LOCK_NOT_HELD(gCallLock); LOCK(gCallLock); if (_iNext > 0 && _iNext < CALLCACHE_SIZE+1) { // Get the last entry from the cache. _iNext--; pCall = _aList[_iNext]; _aList[_iNext] = NULL; } UNLOCK(gCallLock); ASSERT_LOCK_NOT_HELD(gCallLock); return pCall; } inline BOOL CAsyncCall::ReturnCallToList(CAsyncCall *pCall) { // Add the structure to the list if the list is not full and // if the process is still initialized (since latent threads may try // to return stuff). BOOL fRet = FALSE; ASSERT_LOCK_NOT_HELD(gCallLock); LOCK(gCallLock); if (_iNext < CALLCACHE_SIZE && gfChannelProcessInitialized) { _aList[_iNext] = pCall; _iNext++; fRet = TRUE; // don't need to memfree } UNLOCK(gCallLock); ASSERT_LOCK_NOT_HELD(gCallLock); return fRet; } inline void CAsyncCall::AckCancel() { ASSERT_LOCK_HELD(gCallLock); _lFlags &= ~CALLFLAG_CANCELISSUED; ASSERT_LOCK_HELD(gCallLock); } inline void CAsyncCall::ServerReply() { Win4Assert( _hRpc != NULL ); if (_hResult != S_OK) { I_RpcAsyncAbortCall( &_AsyncState, _hResult ); } else { // Ignore errors because replies can fail. message.reserved1 = _hRpc; I_RpcSend( (RPC_MESSAGE *) &message ); } } //+------------------------------------------------------------------- // // Class: CClientCall, public // // Synopsis: Default Call Object on the client side // // Notes: Default call object that is used by the channel on the // client side for standard marshaled calls. // REVIEW: We need a mechanism for handlers to overide // installation of the above default call object // // History: 26-June-97 Gopalk Created // //-------------------------------------------------------------------- class CClientCall : public CMessageCall { public: // Constructor and destructor CClientCall(); CClientCall(ULONG cRefs) : m_cRefs(cRefs) {} virtual ~CClientCall(); // called before a call starts and after a call completes. HRESULT InitCallObject(CALLCATEGORY callcat, RPCOLEMESSAGE *message, DWORD flags, REFIPID ipidServer, DWORD destctx, COMVERSION version, CChannelHandle *handle); void UninitCallObject(); // Operators void *operator new(size_t size); void operator delete(void *pv); // Cleanup method static void Cleanup(); // IUnknown methods STDMETHOD(QueryInterface)(REFIID riid, LPVOID *ppv); STDMETHOD_(ULONG,AddRef)(void); STDMETHOD_(ULONG,Release)(void); // ICancelMethodCalls methods STDMETHOD(Cancel)(ULONG ulSeconds); STDMETHOD(TestCancel)(void); // CMessageCall methods void CallCompleted(HRESULT hrRet); void CallFinished(); HRESULT CanDispatch(); HRESULT WOWMsgArrived(); HRESULT GetState(DWORD *pdwState); BOOL IsCallDispatched() { return(m_dwFlags & CALLFLAG_CALLDISPATCHED); } BOOL IsCallCompleted() { return(m_dwFlags & CALLFLAG_CALLCOMPLETED); } BOOL IsCallCanceled() { return(m_dwFlags & CALLFLAG_CALLCANCELED); } BOOL IsCancelIssued() { return(m_dwFlags & CALLFLAG_CANCELISSUED); } BOOL HasWOWMsgArrived() { return(m_dwFlags & CALLFLAG_WOWMSGARRIVED); } BOOL IsClientWaiting() { return(!(m_dwFlags & CALLFLAG_CLIENTNOTWAITING)); } void AckCancel() { ASSERT_LOCK_HELD(gCallLock); m_dwFlags &= ~CALLFLAG_CANCELISSUED; ASSERT_LOCK_HELD(gCallLock); } HRESULT Cancel(BOOL fModalLoop, ULONG ulTimeout); HRESULT AdvCancel(); private: // Private member variables ULONG m_cRefs; // References DWORD m_dwFlags; // State bits HANDLE m_hThread; // Handle to the thread making RPC call DWORD m_dwThreadId; // ThreadId of the thread making COM call #if DBG==1 DWORD m_dwSignature; // Signature of call control object DWORD m_dwWorkerThreadId; // ThreadId of the thread making the call #endif static void *_aList[CALLCACHE_SIZE]; static DWORD _iNext; }; /***************************************************************************/ /* Externals. */ DWORD _stdcall ComSignal ( void *pParam ); void ThreadSignal(struct _RPC_ASYNC_STATE *hAsync, void *Context, RPC_ASYNC_EVENT eVent ); INTERNAL GetCallObject (BOOL fAsync, CMessageCall **ppCall); INTERNAL ReleaseMarshalBuffer( RPCOLEMESSAGE *pMessage, IUnknown *punk, BOOL fOutParams ); #endif // _CALL_HXX_
34.151961
105
0.572748
npocmaka
a09a2b4f05ad623f8c253e4b604db59e5ec42fc4
290
cpp
C++
GeneticEvolution/main.cpp
nikluep/genetic-evo
c1556a9d5c7098b8a6b4392469b442cee718b6f3
[ "MIT" ]
null
null
null
GeneticEvolution/main.cpp
nikluep/genetic-evo
c1556a9d5c7098b8a6b4392469b442cee718b6f3
[ "MIT" ]
null
null
null
GeneticEvolution/main.cpp
nikluep/genetic-evo
c1556a9d5c7098b8a6b4392469b442cee718b6f3
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <SFML/Graphics.hpp> #include "Network.h" #include "Stage.h" int main() { Stage stage(3, 3000); sf::RenderWindow window(sf::VideoMode(1920, 1080), "Genetic Drone Evolution"); stage.init(window); stage.run(); return 0; }
16.111111
82
0.655172
nikluep
a09ada727d0b0e3a0d4a992f965706237158a599
5,559
cxx
C++
src/Cxx/PolyData/ColorDisconnectedRegionsDemo.cxx
ajpmaclean/vtk-examples
1a55fc8c6af67a3c07791807c7d1ec0ab97607a2
[ "Apache-2.0" ]
81
2020-08-10T01:44:30.000Z
2022-03-23T06:46:36.000Z
src/Cxx/PolyData/ColorDisconnectedRegionsDemo.cxx
ajpmaclean/vtk-examples
1a55fc8c6af67a3c07791807c7d1ec0ab97607a2
[ "Apache-2.0" ]
2
2020-09-12T17:33:52.000Z
2021-04-15T17:33:09.000Z
src/Cxx/PolyData/ColorDisconnectedRegionsDemo.cxx
ajpmaclean/vtk-examples
1a55fc8c6af67a3c07791807c7d1ec0ab97607a2
[ "Apache-2.0" ]
27
2020-08-17T07:09:30.000Z
2022-02-15T03:44:58.000Z
#include <vtkActor.h> #include <vtkCamera.h> #include <vtkInteractorStyleTrackballCamera.h> #include <vtkLookupTable.h> #include <vtkNamedColors.h> #include <vtkNew.h> #include <vtkPointData.h> #include <vtkPolyDataConnectivityFilter.h> #include <vtkPolyDataMapper.h> #include <vtkProperty.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkRenderer.h> #include <vtkSmartPointer.h> #include <vtkSphereSource.h> #include <vtkMinimalStandardRandomSequence.h> #include <vtkBYUReader.h> #include <vtkOBJReader.h> #include <vtkPLYReader.h> #include <vtkPolyDataReader.h> #include <vtkSTLReader.h> #include <vtkXMLPolyDataReader.h> //#include <random> #include <vtksys/SystemTools.hxx> namespace { vtkSmartPointer<vtkPolyData> ReadPolyData(const char* fileName); void RandomColors(vtkLookupTable* lut, int numberOfColors); } // namespace int main(int argc, char* argv[]) { vtkSmartPointer<vtkPolyData> polyData = ReadPolyData(argc > 1 ? argv[1] : ""); vtkNew<vtkNamedColors> colors; vtkNew<vtkPolyDataConnectivityFilter> connectivityFilter; connectivityFilter->SetInputData(polyData); connectivityFilter->SetExtractionModeToAllRegions(); connectivityFilter->ColorRegionsOn(); connectivityFilter->Update(); // Visualize auto numberOfRegions = connectivityFilter->GetNumberOfExtractedRegions(); vtkNew<vtkLookupTable> lut; lut->SetNumberOfTableValues(std::max(numberOfRegions, 10)); lut->Build(); RandomColors(lut, numberOfRegions); vtkNew<vtkPolyDataMapper> mapper; mapper->SetInputConnection(connectivityFilter->GetOutputPort()); mapper->SetScalarRange(connectivityFilter->GetOutput() ->GetPointData() ->GetArray("RegionId") ->GetRange()); mapper->SetLookupTable(lut); mapper->Update(); vtkNew<vtkActor> actor; actor->SetMapper(mapper); vtkNew<vtkRenderer> renderer; renderer->UseHiddenLineRemovalOn(); renderer->AddActor(actor); renderer->SetBackground(colors->GetColor3d("Silver").GetData()); // Create a useful view renderer->ResetCamera(); renderer->GetActiveCamera()->Azimuth(30); renderer->GetActiveCamera()->Elevation(30); renderer->GetActiveCamera()->Dolly(1.2); renderer->ResetCameraClippingRange(); vtkNew<vtkRenderWindow> renderWindow; renderWindow->AddRenderer(renderer); renderWindow->SetSize(640, 480); renderWindow->SetWindowName("ColorDisconnectedRegions"); vtkNew<vtkInteractorStyleTrackballCamera> style; vtkNew<vtkRenderWindowInteractor> interactor; interactor->SetInteractorStyle(style); interactor->SetRenderWindow(renderWindow); renderWindow->Render(); interactor->Initialize(); interactor->Start(); return EXIT_SUCCESS; } namespace { vtkSmartPointer<vtkPolyData> ReadPolyData(const char* fileName) { vtkSmartPointer<vtkPolyData> polyData; std::string extension = vtksys::SystemTools::GetFilenameLastExtension(std::string(fileName)); if (extension == ".ply") { vtkNew<vtkPLYReader> reader; reader->SetFileName(fileName); reader->Update(); polyData = reader->GetOutput(); } else if (extension == ".vtp") { vtkNew<vtkXMLPolyDataReader> reader; reader->SetFileName(fileName); reader->Update(); polyData = reader->GetOutput(); } else if (extension == ".obj") { vtkNew<vtkOBJReader> reader; reader->SetFileName(fileName); reader->Update(); polyData = reader->GetOutput(); } else if (extension == ".stl") { vtkNew<vtkSTLReader> reader; reader->SetFileName(fileName); reader->Update(); polyData = reader->GetOutput(); } else if (extension == ".vtk") { vtkNew<vtkPolyDataReader> reader; reader->SetFileName(fileName); reader->Update(); polyData = reader->GetOutput(); } else if (extension == ".g") { vtkNew<vtkBYUReader> reader; reader->SetGeometryFileName(fileName); reader->Update(); polyData = reader->GetOutput(); } else { vtkNew<vtkSphereSource> source; source->Update(); polyData = source->GetOutput(); } return polyData; } void RandomColors(vtkLookupTable* lut, int numberOfColors) { // Fill in a few known colors, the rest will be generated if needed vtkNew<vtkNamedColors> colors; lut->SetTableValue(0, colors->GetColor4d("Gold").GetData()); lut->SetTableValue(1, colors->GetColor4d("Banana").GetData()); lut->SetTableValue(2, colors->GetColor4d("Tomato").GetData()); lut->SetTableValue(3, colors->GetColor4d("Wheat").GetData()); lut->SetTableValue(4, colors->GetColor4d("Lavender").GetData()); lut->SetTableValue(5, colors->GetColor4d("Flesh").GetData()); lut->SetTableValue(6, colors->GetColor4d("Raspberry").GetData()); lut->SetTableValue(7, colors->GetColor4d("Salmon").GetData()); lut->SetTableValue(8, colors->GetColor4d("Mint").GetData()); lut->SetTableValue(9, colors->GetColor4d("Peacock").GetData()); // If the number of colors is larger than the number of specified colors, // generate some random colors. vtkNew<vtkMinimalStandardRandomSequence> randomSequence; randomSequence->SetSeed(4355412); if (numberOfColors > 9) { for (auto i = 10; i < numberOfColors; ++i) { double r, g, b; r = randomSequence->GetRangeValue(0.6, 1.0); randomSequence->Next(); g = randomSequence->GetRangeValue(0.6, 1.0); randomSequence->Next(); b = randomSequence->GetRangeValue(0.6, 1.0); randomSequence->Next(); lut->SetTableValue(i, r, g, b, 1.0); } } } } // namespace
30.048649
80
0.706422
ajpmaclean
a0a497ab0c143d4db16f543dce6e56df6180c43b
2,476
cpp
C++
2021/20/a.cpp
kidonm/advent-of-code
b304d99d60dcdd9d67105964f2c6a6d8729ecfd6
[ "Apache-2.0" ]
null
null
null
2021/20/a.cpp
kidonm/advent-of-code
b304d99d60dcdd9d67105964f2c6a6d8729ecfd6
[ "Apache-2.0" ]
null
null
null
2021/20/a.cpp
kidonm/advent-of-code
b304d99d60dcdd9d67105964f2c6a6d8729ecfd6
[ "Apache-2.0" ]
null
null
null
#include <algorithm> #include <iostream> #include <map> #include <queue> #include <set> #include <sstream> #include <string> #include <unordered_map> #include <unordered_set> #include <vector> using namespace std; typedef unsigned long long ull; typedef pair<int, int> ipair; typedef vector<int> coord; void widen(deque<deque<char>> &img, int times, char c) { for (auto &row : img) { for (int i = 0; i < times; i++) { row.push_front(c); row.push_back(c); } } deque<char> r(img[0].size(), c); for (int i = 0; i < times; i++) { img.push_front(r); img.push_back(r); } }; void print(deque<deque<char>> &img) { for (auto row : img) { for (auto col : row) { printf("%c", col); } printf("\n"); } printf("\n"); } int index(int i, int j, deque<deque<char>> &src, char frame) { int ix = 0; int m = src.size(); int n = src[0].size(); for (int di : {-1, 0, 1}) { for (int dj : {-1, 0, 1}) { int bit = 0; if (i + di >= 0 && i + di < m && j + dj >= 0 && j + dj < n) { bit = src[i + di][j + dj] == '.' ? 0 : 1; } else { bit = frame == '.' ? 0 : 1; } // printf("%d", bit); ix += bit; // ix *= 2; if (dj == 1 && di == 1) continue; ix *= 2; } } // ix /= 2; return ix; // dst[i][j] = code[ix]; } int main() { int times = 2; string code; deque<deque<char>> img; getline(cin, code); string s; getline(cin, s); while (getline(cin, s)) { deque<char> tmp; for (char c : s) { tmp.push_back(c); } img.push_back(tmp); } // printf("index: %d", index(2, 2, img)); // return 0; // printf("%lu %lu\n", img.size(), img[0].size()); // return 0; char frame = '.'; widen(img, 2, frame); for (int t = 0; t < times; t++) { deque<deque<char>> next(img); // print(img); for (int i = 0; i < img.size(); i++) { for (int j = 0; j < img[0].size(); j++) { next[i][j] = code[index(i, j, img, frame)]; } } // char frame = t % 2 == 1 ? code[0] : code[code.size() - 1]; // if (code[0] == '.') frame = '.'; // printf("here\n"); img = next; frame = img[0][0]; // print(img); widen(img, 1, frame); } print(img); int sum = 0; for (int i = 0; i < img.size(); i++) { for (int j = 0; j < img[0].size(); j++) { if (img[i][j] == '#') sum++; } } printf("%lu %lu %d\n", img.size(), img[0].size(), sum); return 0; }
19.650794
67
0.477787
kidonm
a0a5b3992667fc8fada24388edf98ad6c2695f94
960
cpp
C++
src/utils.cpp
QwantResearch/text-nlu
862eaa41dd4c80688b857ffe0209cef994d18b1b
[ "Apache-2.0" ]
null
null
null
src/utils.cpp
QwantResearch/text-nlu
862eaa41dd4c80688b857ffe0209cef994d18b1b
[ "Apache-2.0" ]
6
2019-08-22T13:36:20.000Z
2020-06-02T13:13:27.000Z
src/utils.cpp
QwantResearch/text-nlu
862eaa41dd4c80688b857ffe0209cef994d18b1b
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 Qwant Research. Licensed under the terms of the Apache 2.0 // license. See LICENSE in the project root. #include "utils.h" void printCookies(const Pistache::Http::Request &req) { auto cookies = req.cookies(); const std::string indent(4, ' '); std::cout << "Cookies: [" << std::endl; for (const auto &c : cookies) { std::cout << indent << c.name << " = " << c.value << std::endl; } std::cout << "]" << std::endl; } const std::string currentDateTime() { time_t now = time(0); struct tm tstruct; char buf[80]; tstruct = *localtime(&now); // Visit http://en.cppreference.com/w/cpp/chrono/c/strftime // for more information about date/time format strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct); return buf; } namespace Generic { void handleReady(const Pistache::Rest::Request &req, Pistache::Http::ResponseWriter response) { response.send(Pistache::Http::Code::Ok, "1"); } } // namespace Generic
28.235294
97
0.65
QwantResearch
a0a5ef886fba1e320663486b9c6a451dabd8a65e
10,427
cpp
C++
src/shogun/labels/MultilabelLabels.cpp
Arpit2601/shogun
e509f8c57f47dc74b3f791d450a70b770d11582a
[ "BSD-3-Clause" ]
1
2019-10-02T11:10:08.000Z
2019-10-02T11:10:08.000Z
src/shogun/labels/MultilabelLabels.cpp
Arpit2601/shogun
e509f8c57f47dc74b3f791d450a70b770d11582a
[ "BSD-3-Clause" ]
null
null
null
src/shogun/labels/MultilabelLabels.cpp
Arpit2601/shogun
e509f8c57f47dc74b3f791d450a70b770d11582a
[ "BSD-3-Clause" ]
1
2020-06-02T09:15:40.000Z
2020-06-02T09:15:40.000Z
/* * Copyright (C) 2013 Zuse-Institute-Berlin (ZIB) * Copyright (C) 2013-2014 Thoralf Klein * Written (W) 2013-2014 Thoralf Klein * 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. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the Shogun Development Team. */ #include <shogun/labels/MultilabelLabels.h> #include <shogun/io/SGIO.h> // for require, io::print, etc using namespace shogun; CMultilabelLabels::CMultilabelLabels() : CLabels() { init(0, 1); } CMultilabelLabels::CMultilabelLabels(int32_t num_classes) : CLabels() { init(0, num_classes); } CMultilabelLabels::CMultilabelLabels(int32_t num_labels, int32_t num_classes) : CLabels() { init(num_labels, num_classes); } CMultilabelLabels::~CMultilabelLabels() { delete[] m_labels; } void CMultilabelLabels::init(int32_t num_labels, int32_t num_classes) { require(num_labels >= 0, "num_labels={} should be >= 0", num_labels); require(num_classes > 0, "num_classes={} should be > 0", num_classes); // This one does consider the contained labels, so its simply BROKEN // Can be disabled as SG_ADD(&m_num_labels, "m_num_labels", "number of labels"); SG_ADD(&m_num_classes, "m_num_classes", "number of classes"); // SG_ADD((CSGObject**) &m_labels, "m_labels", "The labels"); // Can only be enabled after this issue has been solved: // https://github.com/shogun-toolbox/shogun/issues/1972 /* this->m_parameters->add(&m_num_labels, "m_num_labels", "Number of labels."); this->m_parameters->add(&m_num_classes, "m_num_classes", "Number of classes."); this->m_parameters->add_vector(&m_labels, &m_num_labels, "labels_array", "The label vectors for all (num_labels) outputs."); */ m_num_labels = num_labels; m_num_classes = num_classes; m_labels = new SGVector <int32_t>[m_num_labels]; } bool CMultilabelLabels::is_valid() const { for (int32_t label_j = 0; label_j < get_num_labels(); label_j++) { if (!CMath::is_sorted(m_labels[label_j])) return false; int32_t c_len = m_labels[label_j].vlen; if (c_len <= 0) { continue; } if (m_labels[label_j].vector[0] < 0) return false; if (m_labels[label_j].vector[c_len - 1] >= get_num_classes()) return false; } return true; } void CMultilabelLabels::ensure_valid(const char* context) { require( is_valid(), "Multilabel labels need to be sorted and in [0, num_classes-1]."); } int32_t CMultilabelLabels::get_num_labels() const { return m_num_labels; } int32_t CMultilabelLabels::get_num_classes() const { return m_num_classes; } void CMultilabelLabels::set_labels(SGVector <int32_t> * labels) { for (int32_t label_j = 0; label_j < m_num_labels; label_j++) { m_labels[label_j] = labels[label_j]; } ensure_valid("set_labels()"); } SGVector <int32_t> ** CMultilabelLabels::get_class_labels() const { SGVector <int32_t> ** labels_list = SG_MALLOC(SGVector <int32_t> *, get_num_classes()); int32_t * num_label_idx = SG_MALLOC(int32_t, get_num_classes()); for (int32_t class_i = 0; class_i < get_num_classes(); class_i++) { num_label_idx[class_i] = 0; } for (int32_t label_j = 0; label_j < get_num_labels(); label_j++) { for (int32_t c_pos = 0; c_pos < m_labels[label_j].vlen; c_pos++) { int32_t class_i = m_labels[label_j][c_pos]; require(class_i < get_num_classes(), "class_i exceeded number of classes"); num_label_idx[class_i]++; } } for (int32_t class_i = 0; class_i < get_num_classes(); class_i++) { labels_list[class_i] = new SGVector <int32_t> (num_label_idx[class_i]); } SG_FREE(num_label_idx); int32_t * next_label_idx = SG_MALLOC(int32_t, get_num_classes()); for (int32_t class_i = 0; class_i < get_num_classes(); class_i++) { next_label_idx[class_i] = 0; } for (int32_t label_j = 0; label_j < get_num_labels(); label_j++) { for (int32_t c_pos = 0; c_pos < m_labels[label_j].vlen; c_pos++) { // get class_i of current position int32_t class_i = m_labels[label_j][c_pos]; require(class_i < get_num_classes(), "class_i exceeded number of classes"); // next free element in m_classes[class_i]: int32_t l_pos = next_label_idx[class_i]; require(l_pos < labels_list[class_i]->size(), "l_pos exceeded length of label list"); next_label_idx[class_i]++; // finally, story label_j into class-column (*labels_list[class_i])[l_pos] = label_j; } } SG_FREE(next_label_idx); return labels_list; } SGMatrix<int32_t> CMultilabelLabels::get_labels() const { if (m_num_labels==0) return SGMatrix<int32_t>(); int32_t n_outputs = m_labels[0].vlen; SGMatrix<int32_t> labels(m_num_labels, n_outputs); for (int32_t i=0; i<m_num_labels; i++) { require(m_labels[i].vlen==n_outputs, "This function is valid only for multiclass multiple output lables."); for (int32_t j=0; j<n_outputs; j++) labels(i,j) = m_labels[i][j]; } return labels; } SGVector <int32_t> CMultilabelLabels::get_label(int32_t j) { require(j < get_num_labels(), "label index j={} should be within [{},{}[", j, 0, get_num_labels()); return m_labels[j]; } template <class S, class D> SGVector <D> CMultilabelLabels::to_dense (SGVector <S> * sparse, int32_t dense_len, D d_true, D d_false) { SGVector <D> dense(dense_len); dense.set_const(d_false); for (int32_t i = 0; i < sparse->vlen; i++) { S index = (*sparse)[i]; require(index < dense_len, "class index exceeded length of dense vector"); dense[index] = d_true; } return dense; } template SGVector <int32_t> CMultilabelLabels::to_dense <int32_t, int32_t> (SGVector <int32_t> *, int32_t, int32_t, int32_t); template SGVector <float64_t> CMultilabelLabels::to_dense <int32_t, float64_t> (SGVector <int32_t> *, int32_t, float64_t, float64_t); void CMultilabelLabels::set_label(int32_t j, SGVector <int32_t> label) { require(j < get_num_labels(), "label index j={} should be within [{},{}[", j, 0, get_num_labels()); m_labels[j] = label; } void CMultilabelLabels::set_class_labels(SGVector <int32_t> ** labels_list) { int32_t * num_class_idx = SG_MALLOC(int32_t , get_num_labels()); for (int32_t label_j = 0; label_j < get_num_labels(); label_j++) { num_class_idx[label_j] = 0; } for (int32_t class_i = 0; class_i < get_num_classes(); class_i++) { for (int32_t l_pos = 0; l_pos < labels_list[class_i]->vlen; l_pos++) { int32_t label_j = (*labels_list[class_i])[l_pos]; require(label_j < get_num_labels(), "class_i={}/{} :: label_j={}/{} (l_pos={})", class_i, get_num_classes(), label_j, get_num_labels(), l_pos); num_class_idx[label_j]++; } } for (int32_t label_j = 0; label_j < get_num_labels(); label_j++) { m_labels[label_j].resize_vector(num_class_idx[label_j]); } SG_FREE(num_class_idx); int32_t * next_class_idx = SG_MALLOC(int32_t , get_num_labels()); for (int32_t label_j = 0; label_j < get_num_labels(); label_j++) { next_class_idx[label_j] = 0; } for (int32_t class_i = 0; class_i < get_num_classes(); class_i++) { for (int32_t l_pos = 0; l_pos < labels_list[class_i]->vlen; l_pos++) { // get class_i of current position int32_t label_j = (*labels_list[class_i])[l_pos]; require(label_j < get_num_labels(), "class_i={}/{} :: label_j={}/{} (l_pos={})", class_i, get_num_classes(), label_j, get_num_labels(), l_pos); // next free element in m_labels[label_j]: int32_t c_pos = next_class_idx[label_j]; require(c_pos < m_labels[label_j].size(), "c_pos exceeded length of labels vector"); next_class_idx[label_j]++; // finally, story label_j into class-column m_labels[label_j][c_pos] = class_i; } } SG_FREE(next_class_idx); return; } void CMultilabelLabels::display() const { SGVector <int32_t> ** labels_list = get_class_labels(); io::print("printing {} binary label vectors for {} multilabels:\n", get_num_classes(), get_num_labels()); for (int32_t class_i = 0; class_i < get_num_classes(); class_i++) { io::print(" yC_{{class_i={}}}", class_i); SGVector <float64_t> dense = to_dense <int32_t, float64_t> (labels_list[class_i], get_num_labels(), +1, -1); dense.display_vector(""); delete labels_list[class_i]; } SG_FREE(labels_list); io::print("printing {} binary class vectors for {} labels:\n", get_num_labels(), get_num_classes()); for (int32_t j = 0; j < get_num_labels(); j++) { io::print(" y_{{j={}}}", j); SGVector <float64_t> dense = to_dense <int32_t , float64_t> (&m_labels[j], get_num_classes(), +1, -1); dense.display_vector(""); } return; }
28.803867
94
0.670279
Arpit2601
a0a9e505188887a284101e987186aa4132c14925
436
cc
C++
cnd/cnd.modelimpl/test/unit/data/org/netbeans/modules/cnd/modelimpl/trace/FileModelTest/throw_const.cc
leginee/netbeans
814ad30e2d0a094f4aa3813bcbb5323a95a0b1d6
[ "Apache-2.0" ]
null
null
null
cnd/cnd.modelimpl/test/unit/data/org/netbeans/modules/cnd/modelimpl/trace/FileModelTest/throw_const.cc
leginee/netbeans
814ad30e2d0a094f4aa3813bcbb5323a95a0b1d6
[ "Apache-2.0" ]
null
null
null
cnd/cnd.modelimpl/test/unit/data/org/netbeans/modules/cnd/modelimpl/trace/FileModelTest/throw_const.cc
leginee/netbeans
814ad30e2d0a094f4aa3813bcbb5323a95a0b1d6
[ "Apache-2.0" ]
null
null
null
class Exception {}; namespace ns { class Throwable {}; } void foo_1() throw (const char) { } void foo_2() throw (const char&) { } void foo_3() throw (Exception) { } void foo_4() throw (const Exception&) { } void foo_5() throw (const ns::Throwable&) { } void foo_6() throw () { } int fun1(int, int); int (*fp_fun1)(int, int) = fun1; // An extremely perverted one void foo_7() throw (int (*)(int, int)) { throw fp_fun1; }
13.212121
43
0.62156
leginee
a0ade4bec71fb7f7fca99354d0ae7f796d1cc511
10,330
cpp
C++
test/TestParticleGPU.cpp
MaxZZG/RadProps
bd95421430fc266ee88d0480069f7d20be1414f6
[ "MIT" ]
null
null
null
test/TestParticleGPU.cpp
MaxZZG/RadProps
bd95421430fc266ee88d0480069f7d20be1414f6
[ "MIT" ]
null
null
null
test/TestParticleGPU.cpp
MaxZZG/RadProps
bd95421430fc266ee88d0480069f7d20be1414f6
[ "MIT" ]
null
null
null
/* * Copyright (c) 2014-2017 The University of Utah * * 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. */ /* Orion Sky Lawlor, olawlor@acm.org, 9/23/2000 Computes so-called "Mie scattering" for a homogenous sphere of arbitrary size illuminated by coherent harmonic radiation. */ #include <radprops/Particles.h> #include <test/TestHelper.h> #include <iostream> #include <iomanip> #include <vector> #include <ctime> #include <string> #include "cuda.h" using namespace std; using namespace RadProps; bool cpu_gpu_compare(const double* gpuValues, const double* cpuValues, const size_t n, const double t_cpu, const double t_gpu) { double *hostValues; hostValues = (double*)malloc(sizeof(double) * n); cudaError_t err= cudaMemcpy( hostValues, gpuValues, sizeof(double) * n, cudaMemcpyDeviceToHost ); cudaThreadSynchronize(); for (int i=0; i<n; ++i) { if (std::abs((hostValues[i] - cpuValues[i]) / cpuValues[i]) > 1e-8) { std::cout << cpuValues[i] << " - " <<hostValues[i] << "\n"; return false; } } std::cout <<" npts = " << n << "\t" << "time CPU = " << t_cpu << ", GPU = " << t_gpu << " => CPU/GPU = " << t_cpu / t_gpu << std::endl; return true; } bool time_it2D(const ParticleRadCoeffs& pcoeff, const ParticleRadCoeffs3D& pcoeff3D, const size_t n) { TestHelper status(true); std::vector<double> wavelength, radius, temperature, iRreal; for (int i=0; i<n ; i++) { wavelength. push_back(double(rand())/double(RAND_MAX) * 1e-6); radius. push_back(double(rand())/double(RAND_MAX) * 1e-6); temperature.push_back(double(rand())/double(RAND_MAX) * 1000 + 300); iRreal. push_back(double(rand())/double(RAND_MAX)); } // GPU variables double *gpuWavelength, *gpuRadius, *gpuTemperature, *gpuiRreal; cudaMalloc((void**) &gpuWavelength, sizeof(double) * n); cudaMalloc((void**) &gpuRadius, sizeof(double) * n); cudaMalloc((void**) &gpuTemperature, sizeof(double) * n); cudaMalloc((void**) &gpuiRreal, sizeof(double) * n); cudaMemcpy(gpuWavelength , &wavelength[0], sizeof(double) * n, cudaMemcpyHostToDevice); cudaMemcpy(gpuRadius , &radius[0], sizeof(double) * n, cudaMemcpyHostToDevice); cudaMemcpy(gpuTemperature , &temperature[0],sizeof(double) * n, cudaMemcpyHostToDevice); cudaMemcpy(gpuiRreal , &gpuiRreal[0], sizeof(double) * n, cudaMemcpyHostToDevice); cudaThreadSynchronize(); double *gpuValues; cudaMalloc((void**) &gpuValues, sizeof(double) * n); std::clock_t start; double t_cpu, t_gpu; string modelname; modelname = "abs_spectral_coeff"; std::vector<double> cpuValues; cpuValues.clear(); // 2D // Run on CPU start = std::clock(); for( int unsigned i=0; i<n; ++i ) cpuValues.push_back(pcoeff.abs_spectral_coeff(wavelength[i], radius[i])); t_cpu = std::clock() - start; // Run on GPU start = std::clock(); pcoeff.gpu_abs_spectral_coeff(gpuValues, gpuWavelength, gpuRadius, n); t_gpu = std::clock() - start; status( cpu_gpu_compare(gpuValues, &cpuValues[0], n, t_cpu, t_gpu), modelname); // 3D cpuValues.clear(); start = std::clock(); for( int unsigned i=0; i<n; ++i ) cpuValues.push_back(pcoeff3D.abs_spectral_coeff(wavelength[i], radius[i], iRreal[i])); t_cpu = std::clock() - start; start = std::clock(); pcoeff3D.gpu_abs_spectral_coeff(gpuValues, gpuWavelength, gpuRadius, gpuiRreal, n); t_gpu = std::clock() - start; status( cpu_gpu_compare(gpuValues, &cpuValues[0], n, t_cpu, t_gpu), modelname + " 3D"); modelname = "scattering_spectral_coeff"; cpuValues.clear(); // 2D // Run on CPU start = std::clock(); for( int unsigned i=0; i<n; ++i ) cpuValues[i] = pcoeff.scattering_spectral_coeff(wavelength[i], radius[i]); t_cpu = std::clock() - start; // Run on GPU start = std::clock(); pcoeff.gpu_scattering_spectral_coeff(gpuValues, gpuWavelength, gpuRadius, n); t_gpu = std::clock() - start; status( cpu_gpu_compare(gpuValues, &cpuValues[0], n, t_cpu, t_gpu), modelname); // 3D // Run on CPU cpuValues.clear(); start = std::clock(); for( int unsigned i=0; i<n; ++i ) cpuValues[i] = pcoeff3D.scattering_spectral_coeff(wavelength[i], radius[i], iRreal[i]); t_cpu = std::clock() - start; // Run on GPU start = std::clock(); pcoeff3D.gpu_scattering_spectral_coeff(gpuValues, gpuWavelength, gpuRadius, gpuiRreal, n); t_gpu = std::clock() - start; status( cpu_gpu_compare(gpuValues, &cpuValues[0], n, t_cpu, t_gpu), modelname + " 3D"); // ----------- planck_abs_coeff // 2D // Run on CPU modelname = "planck_abs_coeff"; cpuValues.clear(); start = std::clock(); for( int unsigned i=0; i<n; ++i ) cpuValues.push_back(pcoeff.planck_abs_coeff(radius[i], temperature[i])); t_cpu = std::clock() - start; // Run on GPU start = std::clock(); pcoeff.gpu_planck_abs_coeff(gpuValues, gpuRadius, gpuTemperature, n); t_gpu = std::clock() - start; status( cpu_gpu_compare(gpuValues, &cpuValues[0], n, t_cpu, t_gpu), modelname); // 3D // Run on CPU cpuValues.clear(); start = std::clock(); for( int unsigned i=0; i<n; ++i ) cpuValues.push_back(pcoeff3D.planck_abs_coeff(radius[i], temperature[i], iRreal[i])); t_cpu = std::clock() - start; // Run on GPU start = std::clock(); pcoeff3D.gpu_planck_abs_coeff(gpuValues, gpuRadius, gpuTemperature,gpuiRreal, n); t_gpu = std::clock() - start; status( cpu_gpu_compare(gpuValues, &cpuValues[0], n, t_cpu, t_gpu), modelname + " 3D"); // ----------- planck_sca_coeff // Run on CPU modelname = "planck_sca_coeff"; cpuValues.clear(); start = std::clock(); for( int unsigned i=0; i<n; ++i ) cpuValues.push_back(pcoeff.planck_sca_coeff(radius[i], temperature[i])); t_cpu = std::clock() - start; // Run on GPU start = std::clock(); pcoeff.gpu_planck_sca_coeff(gpuValues, gpuRadius, gpuTemperature, n); t_gpu = std::clock() - start; status( cpu_gpu_compare(gpuValues, &cpuValues[0], n, t_cpu, t_gpu), modelname); // 3D cpuValues.clear(); start = std::clock(); for( int unsigned i=0; i<n; ++i ) cpuValues.push_back(pcoeff3D.planck_sca_coeff(radius[i], temperature[i], iRreal[i])); t_cpu = std::clock() - start; // Run on GPU start = std::clock(); pcoeff3D.gpu_planck_sca_coeff(gpuValues, gpuRadius, gpuTemperature, gpuiRreal, n); t_gpu = std::clock() - start; status( cpu_gpu_compare(gpuValues, &cpuValues[0], n, t_cpu, t_gpu), modelname + " 3D"); // ----------- ross_abs_coeff // 2D // Run on CPU modelname = "ross_abs_coeff"; cpuValues.clear(); start = std::clock(); for( int unsigned i=0; i<n; ++i ) cpuValues.push_back(pcoeff.ross_abs_coeff(radius[i], temperature[i])); t_cpu = std::clock() - start; // Run on GPU start = std::clock(); pcoeff.gpu_ross_abs_coeff(gpuValues, gpuRadius, gpuTemperature, n); t_gpu = std::clock() - start; // compare CPU and GPU results status( cpu_gpu_compare(gpuValues, &cpuValues[0], n, t_cpu, t_gpu), modelname); // 3D cpuValues.clear(); start = std::clock(); for( int unsigned i=0; i<n; ++i ) cpuValues.push_back(pcoeff3D.ross_abs_coeff(radius[i], temperature[i], iRreal[i])); t_cpu = std::clock() - start; // Run on GPU start = std::clock(); pcoeff3D.gpu_ross_abs_coeff(gpuValues, gpuRadius, gpuTemperature, gpuiRreal, n); t_gpu = std::clock() - start; status( cpu_gpu_compare(gpuValues, &cpuValues[0], n, t_cpu, t_gpu), modelname + " 3D"); // ----------- ross_sca_coeff // Run on CPU modelname = "ross_sca_coeff"; cpuValues.clear(); start = std::clock(); for( int unsigned i=0; i<n; ++i ) cpuValues.push_back(pcoeff.ross_sca_coeff(radius[i], temperature[i])); t_cpu = std::clock() - start; // Run on GPU start = std::clock(); pcoeff.gpu_ross_sca_coeff(gpuValues, gpuRadius, gpuTemperature, n); t_gpu = std::clock() - start; status( cpu_gpu_compare(gpuValues, &cpuValues[0], n, t_cpu, t_gpu), modelname); // 3D cpuValues.clear(); start = std::clock(); for( int unsigned i=0; i<n; ++i ) cpuValues.push_back(pcoeff3D.ross_sca_coeff(radius[i], temperature[i], iRreal[i])); t_cpu = std::clock() - start; // Run on GPU start = std::clock(); pcoeff3D.gpu_ross_sca_coeff(gpuValues, gpuRadius, gpuTemperature, gpuiRreal, n); t_gpu = std::clock() - start; status( cpu_gpu_compare(gpuValues, &cpuValues[0], n, t_cpu, t_gpu), modelname + " 3D"); return status.ok(); cudaFree( gpuWavelength ); cudaFree( gpuRadius ); cudaFree( gpuTemperature ); cudaFree( gpuiRreal ); cudaFree( gpuValues ); } //============================================================================== int main( int argc, char* argv[] ) { TestHelper status(true); try{ complex<double> rCoal, rCoallo, rCoalhi; rCoal =complex<double>(2.0,-0.6); rCoallo =complex<double>(0,0); rCoalhi =complex<double>(1,1); ParticleRadCoeffs P2(rCoal,1e-7,1e-4,10,1); std::cout << " 2D table is made! \n"; ParticleRadCoeffs3D P3(rCoallo, rCoalhi,5,1e-7,1e-4,5,1); std::cout << " 3D table is made! \n"; status (time_it2D(P2, P3, 2), " Checking GPU versus CPU results "); if( status.ok() ){ cout << "PASS" << endl; return 0; } } catch( std::exception& err ){ cout << err.what() << endl; } cout << "FAIL" << endl; return -1; }
39.277567
144
0.664569
MaxZZG
a0b17fdc2b25afc15f9cb4fcc46280e41d7c67a6
3,724
hpp
C++
willow/include/popart/alias/aliasmodelgrower.hpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
61
2020-07-06T17:11:46.000Z
2022-03-12T14:42:51.000Z
willow/include/popart/alias/aliasmodelgrower.hpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
1
2021-02-25T01:30:29.000Z
2021-11-09T11:13:14.000Z
willow/include/popart/alias/aliasmodelgrower.hpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
6
2020-07-15T12:33:13.000Z
2021-11-07T06:55:00.000Z
// Copyright (c) 2021 Graphcore Ltd. All rights reserved. #ifndef GUARD_NEURALNET_ALIAS_ALIAS_MODEL_GROWER_HPP #define GUARD_NEURALNET_ALIAS_ALIAS_MODEL_GROWER_HPP #include <functional> #include <memory> #include <popart/alias/aliasmodel.hpp> namespace popart { /** * An enum type that determines whether topological constraints are added to * an alias model. **/ enum class DataDependenciesOnly { // Only add data constraints. Yes, // Add data constraints and additional topological constraints. No }; /** * Class that contains some methods for creating `AliasModel` instances via a * `AliasModelGrowInterface`. It takes such an interface by reference and * grows it by calling, e.g., `Op::growAliasModel` on certain specific ops. **/ class AliasModelGrower final { public: /** * Grow the default AliasModel. **/ AliasModelGrower(AliasModel &aliasModel); /** * Get non-owning reference to grown AliasModel. **/ AliasModel &getAliasModelRef(); /** * Return owning AliasModel associated with this instance. Calling this * function leaves the grower without an AliasModel and growing further grow * functions without such a model will raise an exception. **/ std::unique_ptr<AliasModel> getAliasModel(); /** * Set the AliasModel we are growing. **/ void setAliasModel(std::unique_ptr<AliasModel> aliasModel); /** * Grow an alias model that contains all tensors in a PopART Graph. This * mapping will include every PopART op and Tensor in the Graph. * \param graph The PopART Graph object to construct a mapping for. * \param dataDepsOnly Flag to indicate whether to add only data dependencies * or whether to also add topocological constraints. **/ void growFullGraph(const Graph &graph, DataDependenciesOnly dataDepsOnly); /** * Construct a mapping from tensors in a PopART Graph to an alias model that * is guaranteed to contain a mapping for any tensor that alias the * `tensorId` parameter (and ops that separate them) but may also contain * other tensors that do not alias it. * * The purpose of this function is to provide an alternative to * `getFullAliasModel` for when you do not require a whole mapping. * * \param graph The PopART Graph object to construct a mapping for. * \param tensorId The PopART Tensor used to determine which part of the *PopART graph to create a mapping for. \param dataDepsOnly Flag to indicate *whether to add only data dependencies or whether to also add topocological *constraints. **/ void growPartialGraph(const Graph &graph, const TensorId &tensorId, DataDependenciesOnly dataDepsOnly); private: /** * Data type that dictates whether we check at runtime whether a tensor that *is produced by an op may be added via `insertTensor`. When growing the alias * model for a full graph you would expect these tensors to be added by *growing their producer. **/ enum class AllowInsertingProducedTensors { // Produced tensors may be added via `insertTensor`. Yes = 0, // Producer tensors must be added by their producer. No }; /// Add a tensor to the AliasModel. void addTensor(const Graph &graph, Tensor *t, AllowInsertingProducedTensors allow); /// Add an Op to the AliasModel. void addAliaserOp(const Graph &graph, Op *op, AllowInsertingProducedTensors allow); /// Add topological constraints to the AliasModel. void addAliaserConstraints(const Graph &graph, const std::vector<Op *> &opSubset); // The grow interface reference. std::reference_wrapper<AliasModel> aliasModel; }; } // namespace popart #endif
33.25
80
0.718582
gglin001
a0b657ae7123fe48ac77fe7f4b2ad76c374283f9
27,674
cc
C++
src/SinCosOps.cc
oseikuffuor1/mgmol
5442962959a54c919a5e18c4e78db6ce41ee8f4e
[ "BSD-3-Clause-LBNL", "FSFAP" ]
null
null
null
src/SinCosOps.cc
oseikuffuor1/mgmol
5442962959a54c919a5e18c4e78db6ce41ee8f4e
[ "BSD-3-Clause-LBNL", "FSFAP" ]
null
null
null
src/SinCosOps.cc
oseikuffuor1/mgmol
5442962959a54c919a5e18c4e78db6ce41ee8f4e
[ "BSD-3-Clause-LBNL", "FSFAP" ]
null
null
null
// Copyright (c) 2017, Lawrence Livermore National Security, LLC and // UT-Battelle, LLC. // Produced at the Lawrence Livermore National Laboratory and the Oak Ridge // National Laboratory. // LLNL-CODE-743438 // All rights reserved. // This file is part of MGmol. For details, see https://github.com/llnl/mgmol. // Please also read this link https://github.com/llnl/mgmol/LICENSE #include "SinCosOps.h" #include "ExtendedGridOrbitals.h" #include "FunctionsPacking.h" #include "LocGridOrbitals.h" #include "MGmol_MPI.h" using namespace std; template <class T> void SinCosOps<T>::compute(const T& orbitals, vector<vector<double>>& a) { assert(a.size() == 6); compute_tm_.start(); const pb::Grid& grid(orbitals.grid_); const int numst = orbitals.numst(); const int dim0 = grid.dim(0); const int dim1 = grid.dim(1); const int dim2 = grid.dim(2); int n2 = numst * numst; int loc_length = dim0 / orbitals.subdivx_; assert(loc_length > 0); assert(loc_length <= dim0); int incx = dim1 * dim2; int incy = dim2; vector<double> sinx; vector<double> siny; vector<double> sinz; vector<double> cosx; vector<double> cosy; vector<double> cosz; grid.getSinCosFunctions(sinx, siny, sinz, cosx, cosy, cosz); const int size = orbitals.chromatic_number(); for (short iloc = 0; iloc < orbitals.subdivx_; iloc++) { for (int icolor = 0; icolor < size; icolor++) { const int i = orbitals.overlapping_gids_[iloc][icolor]; if (i != -1) { const ORBDTYPE* const ppsii = orbitals.psi(icolor); for (int jstate = 0; jstate <= icolor; jstate++) { const int j = orbitals.overlapping_gids_[iloc][jstate]; if (j != -1) { const ORBDTYPE* const ppsij = orbitals.psi(jstate); double atmp[6] = { 0., 0., 0., 0., 0., 0. }; const int ixend = loc_length * (iloc + 1); for (int ix = loc_length * iloc; ix < ixend; ix++) { const double cosix = cosx[ix]; const double sinix = sinx[ix]; const int offsetx = ix * incx; for (int iy = 0; iy < dim1; iy++) { const double cosiy = cosy[iy]; const double siniy = siny[iy]; const int offset = offsetx + iy * incy; for (int iz = 0; iz < dim2; iz++) { const int index = offset + iz; const double alpha = (double)ppsij[index] * (double)ppsii[index]; atmp[0] += alpha * cosix; atmp[1] += alpha * sinix; atmp[2] += alpha * cosiy; atmp[3] += alpha * siniy; atmp[4] += alpha * cosz[iz]; atmp[5] += alpha * sinz[iz]; } } } const int ji = j * numst + i; const int ij = i * numst + j; a[0][ji] = a[0][ij] += atmp[0]; a[1][ji] = a[1][ij] += atmp[1]; a[2][ji] = a[2][ij] += atmp[2]; a[3][ji] = a[3][ij] += atmp[3]; a[4][ji] = a[4][ij] += atmp[4]; a[5][ji] = a[5][ij] += atmp[5]; } } } } } MGmol_MPI& mmpi = *(MGmol_MPI::instance()); for (short i = 0; i < 6; i++) { mmpi.split_allreduce_sums_double(&a[i][0], n2); my_dscal(n2, grid.vel(), &a[i][0]); } compute_tm_.stop(); } template <class T> void SinCosOps<T>::computeSquare(const T& orbitals, vector<vector<double>>& a) { assert(a.size() == 6); for (short i = 0; i < 6; i++) assert(a[i].size() > 0); compute_tm_.start(); const pb::Grid& grid(orbitals.grid_); const int numst = orbitals.numst_; const int n2 = numst * numst; const int dim0 = grid.dim(0); const int dim1 = grid.dim(1); const int dim2 = grid.dim(2); int loc_length = dim0 / orbitals.subdivx_; assert(loc_length > 0); assert(loc_length <= dim0); const int xoff = grid.istart(0); const int yoff = grid.istart(1); const int zoff = grid.istart(2); const double hhx = 2. * M_PI / (double)grid.gdim(0); const double hhy = 2. * M_PI / (double)grid.gdim(1); const double hhz = 2. * M_PI / (double)grid.gdim(2); int incx = dim1 * dim2; int incy = dim2; const double inv_2pi = 0.5 * M_1_PI; const double alphax = grid.ll(0) * grid.ll(0) * inv_2pi * inv_2pi; const double alphay = grid.ll(1) * grid.ll(1) * inv_2pi * inv_2pi; const double alphaz = grid.ll(2) * grid.ll(2) * inv_2pi * inv_2pi; vector<double> sinx2, siny2, sinz2, cosx2, cosy2, cosz2; sinx2.resize(dim0); cosx2.resize(dim0); siny2.resize(dim1); cosy2.resize(dim1); sinz2.resize(dim2); cosz2.resize(dim2); for (int i = 0; i < dim0; i++) { const double tmp = sin((double)(xoff + i) * hhx); sinx2[i] = tmp * tmp * alphax; cosx2[i] = (1. - tmp * tmp) * alphax; } for (int i = 0; i < dim1; i++) { const double tmp = sin((double)(yoff + i) * hhy); siny2[i] = tmp * tmp * alphay; cosy2[i] = (1. - tmp * tmp) * alphay; } for (int i = 0; i < dim2; i++) { const double tmp = sin((double)(zoff + i) * hhz); sinz2[i] = tmp * tmp * alphaz; cosz2[i] = (1. - tmp * tmp) * alphaz; } const int size = orbitals.chromatic_number(); for (short iloc = 0; iloc < orbitals.subdivx_; iloc++) { for (int icolor = 0; icolor < size; icolor++) { int i = orbitals.overlapping_gids_[iloc][icolor]; if (i != -1) for (int jstate = 0; jstate <= icolor; jstate++) { int j = orbitals.overlapping_gids_[iloc][jstate]; if (j != -1) { double atmp[6] = { 0., 0., 0., 0., 0., 0. }; for (int ix = loc_length * iloc; ix < loc_length * (iloc + 1); ix++) for (int iy = 0; iy < dim1; iy++) for (int iz = 0; iz < dim2; iz++) { int index = ix * incx + iy * incy + iz; double alpha = orbitals.psi(jstate)[index] * orbitals.psi(icolor)[index]; atmp[0] += alpha * cosx2[ix]; atmp[1] += alpha * sinx2[ix]; atmp[2] += alpha * cosy2[iy]; atmp[3] += alpha * siny2[iy]; atmp[4] += alpha * cosz2[iz]; atmp[5] += alpha * sinz2[iz]; } int ji = j * numst + i; int ij = i * numst + j; a[0][ji] = a[0][ij] += atmp[0]; a[1][ji] = a[1][ij] += atmp[1]; a[2][ji] = a[2][ij] += atmp[2]; a[3][ji] = a[3][ij] += atmp[3]; a[4][ji] = a[4][ij] += atmp[4]; a[5][ji] = a[5][ij] += atmp[5]; } } } } MGmol_MPI& mmpi = *(MGmol_MPI::instance()); for (short i = 0; i < 6; i++) { mmpi.split_allreduce_sums_double(&a[i][0], n2); my_dscal(n2, grid.vel(), &a[i][0]); } compute_tm_.stop(); } template <class T> void SinCosOps<T>::computeSquare1D( const T& orbitals, vector<vector<double>>& a, const int dim_index) { assert(a.size() == 2); for (short i = 0; i < 2; i++) assert(a[i].size() > 0); compute_tm_.start(); const pb::Grid& grid(orbitals.grid_); const int numst = orbitals.numst_; const int dim = grid.dim(dim_index); const int dim0 = grid.dim(0); const int dim1 = grid.dim(1); const int dim2 = grid.dim(2); int n2 = numst * numst; int loc_length = dim0 / orbitals.subdivx_; assert(loc_length > 0); assert(loc_length <= dim0); const int off = grid.istart(dim_index); const double hh = 2. * M_PI / (double)grid.gdim(dim_index); int incx = dim1 * dim2; int incy = dim2; const double inv_2pi = 0.5 * M_1_PI; const double alphax = grid.ll(dim_index) * grid.ll(dim_index) * inv_2pi * inv_2pi; vector<double> sinx2(dim); vector<double> cosx2(dim); for (int i = 0; i < dim; i++) { const double tmp = sin((double)(off + i) * hh); sinx2[i] = tmp * tmp * alphax; cosx2[i] = (1. - tmp * tmp) * alphax; } const int size = orbitals.chromatic_number(); for (short iloc = 0; iloc < orbitals.subdivx_; iloc++) { for (int icolor = 0; icolor < size; icolor++) { int i = orbitals.overlapping_gids_[iloc][icolor]; if (i != -1) for (int jstate = 0; jstate <= icolor; jstate++) { int j = orbitals.overlapping_gids_[iloc][jstate]; if (j != -1) { double atmp[2] = { 0., 0. }; for (int ix = loc_length * iloc; ix < loc_length * (iloc + 1); ix++) for (int iy = 0; iy < dim1; iy++) for (int iz = 0; iz < dim2; iz++) { int dindex[3] = { ix, iy, iz }; int index = ix * incx + iy * incy + iz; double alpha = orbitals.psi(jstate)[index] * orbitals.psi(icolor)[index]; atmp[0] += alpha * cosx2[dindex[dim_index]]; atmp[1] += alpha * sinx2[dindex[dim_index]]; } int ji = j * numst + i; int ij = i * numst + j; a[0][ji] = a[0][ij] += atmp[0]; a[1][ji] = a[1][ij] += atmp[1]; } } } } MGmol_MPI& mmpi = *(MGmol_MPI::instance()); for (int i = 0; i < 2; i++) { mmpi.split_allreduce_sums_double(&a[i][0], n2); my_dscal(n2, grid.vel(), &a[i][0]); } compute_tm_.stop(); } template <class T> void SinCosOps<T>::compute1D( const T& orbitals, vector<vector<double>>& a, const int dim_index) { assert(a.size() == 2); for (short i = 0; i < 2; i++) assert(a[i].size() > 0); compute_tm_.start(); const pb::Grid& grid(orbitals.grid_); const int numst = orbitals.numst_; const int dim = grid.dim(dim_index); const int dim0 = grid.dim(0); const int dim1 = grid.dim(1); const int dim2 = grid.dim(2); int n2 = numst * numst; int loc_length = dim0 / orbitals.subdivx_; assert(loc_length > 0); assert(loc_length <= dim0); int incx = dim1 * dim2; int incy = dim2; const int off = grid.istart(dim_index); const double hh = 2. * M_PI / (double)grid.gdim(dim_index); const double inv_2pi = 0.5 * M_1_PI; const double alphax = grid.ll(dim_index) * inv_2pi; vector<double> sinx(dim); for (int i = 0; i < dim; i++) sinx[i] = sin(double(off + i) * hh) * alphax; vector<double> cosx(dim); for (int i = 0; i < dim; i++) cosx[i] = cos(double(off + i) * hh) * alphax; const int size = orbitals.chromatic_number(); for (short iloc = 0; iloc < orbitals.subdivx_; iloc++) { for (int icolor = 0; icolor < size; icolor++) { const int i = orbitals.overlapping_gids_[iloc][icolor]; if (i != -1) { const ORBDTYPE* const ppsii = orbitals.psi(icolor); for (int jstate = 0; jstate <= icolor; jstate++) { const int j = orbitals.overlapping_gids_[iloc][jstate]; if (j != -1) { const ORBDTYPE* const ppsij = orbitals.psi(jstate); double atmp[2] = { 0., 0. }; const int ixend = loc_length * (iloc + 1); for (int ix = loc_length * iloc; ix < ixend; ix++) for (int iy = 0; iy < dim1; iy++) for (int iz = 0; iz < dim2; iz++) { int dindex[3] = { ix, iy, iz }; const int index = ix * incx + iy * incy + iz; const double alpha = (double)ppsij[index] * (double)ppsii[index]; atmp[0] += alpha * cosx[dindex[dim_index]]; atmp[1] += alpha * sinx[dindex[dim_index]]; } const int ji = j * numst + i; const int ij = i * numst + j; a[0][ji] = a[0][ij] += atmp[0]; a[1][ji] = a[1][ij] += atmp[1]; } } } } } MGmol_MPI& mmpi = *(MGmol_MPI::instance()); for (short i = 0; i < 2; i++) { mmpi.split_allreduce_sums_double(&a[i][0], n2); my_dscal(n2, grid.vel(), &a[i][0]); } compute_tm_.stop(); } template <class T> void SinCosOps<T>::computeDiag2states( const T& orbitals, vector<vector<double>>& a, const int st1, const int st2) { assert(st1 >= 0); assert(st2 >= 0); assert(st1 != st2); compute_tm_.start(); const pb::Grid& grid(orbitals.grid_); const int st[2] = { st1, st2 }; const int dim0 = grid.dim(0); const int dim1 = grid.dim(1); const int dim2 = grid.dim(2); short color_st[2] = { -1, -1 }; for (short ic = 0; ic < 2; ++ic) { color_st[ic] = orbitals.getColor(st[ic]); } int loc_length = dim0 / orbitals.subdivx_; assert(loc_length > 0); assert(loc_length <= dim0); int incx = dim1 * dim2; int incy = dim2; vector<double> sinx; vector<double> siny; vector<double> sinz; vector<double> cosx; vector<double> cosy; vector<double> cosz; grid.getSinCosFunctions(sinx, siny, sinz, cosx, cosy, cosz); double norm2[2] = { 0., 0. }; for (short ic = 0; ic < 2; ic++) { const short mycolor = color_st[ic]; if (mycolor >= 0) for (short iloc = 0; iloc < orbitals.subdivx_; iloc++) { if (orbitals.overlapping_gids_[iloc][mycolor] == st[ic]) { const ORBDTYPE* const ppsii = orbitals.psi(mycolor); assert(ppsii != nullptr); double atmp[6] = { 0., 0., 0., 0., 0., 0. }; const int ixend = loc_length * (iloc + 1); for (int ix = loc_length * iloc; ix < ixend; ix++) for (int iy = 0; iy < dim1; iy++) for (int iz = 0; iz < dim2; iz++) { const int index = ix * incx + iy * incy + iz; const double alpha = (double)ppsii[index] * (double)ppsii[index]; atmp[0] += alpha * cosx[ix]; atmp[1] += alpha * sinx[ix]; atmp[2] += alpha * cosy[iy]; atmp[3] += alpha * siny[iy]; atmp[4] += alpha * cosz[iz]; atmp[5] += alpha * sinz[iz]; norm2[ic] += alpha; } a[0][ic] += atmp[0]; a[1][ic] += atmp[1]; a[2][ic] += atmp[2]; a[3][ic] += atmp[3]; a[4][ic] += atmp[4]; a[5][ic] += atmp[5]; } } } MGmol_MPI& mmpi = *(MGmol_MPI::instance()); for (short i = 0; i < 6; i++) { mmpi.split_allreduce_sums_double(&a[i][0], 2); my_dscal(2, grid.vel(), &a[i][0]); } compute_tm_.stop(); } template <class T> void SinCosOps<T>::compute2states( const T& orbitals, vector<vector<double>>& a, const int st1, const int st2) { assert(a.size() == 6); assert(st1 >= 0); assert(st2 >= 0); compute_tm_.start(); const pb::Grid& grid(orbitals.grid_); const int st[2] = { st1, st2 }; int color_st[2] = { -1, -1 }; for (short ic = 0; ic < 2; ++ic) { color_st[ic] = orbitals.getColor(st[ic]); } const int dim0 = grid.dim(0); const int dim1 = grid.dim(1); const int dim2 = grid.dim(2); int n2 = 4; int loc_length = dim0 / orbitals.subdivx_; assert(loc_length > 0); assert(loc_length <= dim0); int incx = dim1 * dim2; int incy = dim2; vector<double> sinx; vector<double> siny; vector<double> sinz; vector<double> cosx; vector<double> cosy; vector<double> cosz; grid.getSinCosFunctions(sinx, siny, sinz, cosx, cosy, cosz); for (int ic = 0; ic < 2; ic++) { const int mycolor = color_st[ic]; if (mycolor >= 0) for (short iloc = 0; iloc < orbitals.subdivx_; iloc++) { if (orbitals.overlapping_gids_[iloc][mycolor] == st[ic]) { const ORBDTYPE* const ppsii = orbitals.psi(mycolor); assert(ppsii != nullptr); for (int jc = 0; jc <= ic; jc++) if (color_st[jc] >= 0) { if (orbitals.overlapping_gids_[iloc][color_st[jc]] == st[jc]) { const ORBDTYPE* const ppsij = orbitals.psi(color_st[jc]); assert(ppsij != nullptr); double atmp[6] = { 0., 0., 0., 0., 0., 0. }; const int ixend = loc_length * (iloc + 1); for (int ix = loc_length * iloc; ix < ixend; ix++) for (int iy = 0; iy < dim1; iy++) for (int iz = 0; iz < dim2; iz++) { const int index = ix * incx + iy * incy + iz; const double alpha = (double)ppsij[index] * (double)ppsii[index]; atmp[0] += alpha * cosx[ix]; atmp[1] += alpha * sinx[ix]; atmp[2] += alpha * cosy[iy]; atmp[3] += alpha * siny[iy]; atmp[4] += alpha * cosz[iz]; atmp[5] += alpha * sinz[iz]; } const int ji = jc * 2 + ic; const int ij = ic * 2 + jc; a[0][ji] = a[0][ij] += atmp[0]; a[1][ji] = a[1][ij] += atmp[1]; a[2][ji] = a[2][ij] += atmp[2]; a[3][ji] = a[3][ij] += atmp[3]; a[4][ji] = a[4][ij] += atmp[4]; a[5][ji] = a[5][ij] += atmp[5]; } } } } } MGmol_MPI& mmpi = *(MGmol_MPI::instance()); for (short i = 0; i < 6; i++) { mmpi.split_allreduce_sums_double(&a[i][0], n2); my_dscal(n2, grid.vel(), &a[i][0]); } compute_tm_.stop(); } template <class T> void SinCosOps<T>::compute( const T& orbitals1, const T& orbitals2, vector<vector<double>>& a) { assert(a.size() == 6); compute_tm_.start(); const pb::Grid& grid(orbitals1.grid_); const int numst = orbitals1.numst_; int n2 = numst * numst; const int dim0 = grid.dim(0); const int dim1 = grid.dim(1); const int dim2 = grid.dim(2); int loc_length = dim0 / orbitals1.subdivx_; assert(loc_length > 0); assert(loc_length <= dim0); int incx = dim1 * dim2; int incy = dim2; vector<double> sinx; vector<double> siny; vector<double> sinz; vector<double> cosx; vector<double> cosy; vector<double> cosz; grid.getSinCosFunctions(sinx, siny, sinz, cosx, cosy, cosz); for (short iloc = 0; iloc < orbitals1.subdivx_; iloc++) { for (int color = 0; color < orbitals1.chromatic_number(); color++) { int i = orbitals1.overlapping_gids_[iloc][color]; if (i != -1) for (int jstate = 0; jstate < orbitals2.chromatic_number(); jstate++) { int j = orbitals2.overlapping_gids_[iloc][jstate]; if (j != -1) { double atmp[6] = { 0., 0., 0., 0., 0., 0. }; for (int ix = loc_length * iloc; ix < loc_length * (iloc + 1); ix++) for (int iy = 0; iy < dim1; iy++) for (int iz = 0; iz < dim2; iz++) { const int index = ix * incx + iy * incy + iz; const double alpha = (double)orbitals1.psi(color)[index] * (double)orbitals2.psi( jstate)[index]; atmp[0] += alpha * cosx[ix]; atmp[1] += alpha * sinx[ix]; atmp[2] += alpha * cosy[iy]; atmp[3] += alpha * siny[iy]; atmp[4] += alpha * cosz[iz]; atmp[5] += alpha * sinz[iz]; } int ij = j * numst + i; // row i, column j a[0][ij] += atmp[0]; a[1][ij] += atmp[1]; a[2][ij] += atmp[2]; a[3][ij] += atmp[3]; a[4][ij] += atmp[4]; a[5][ij] += atmp[5]; } } } } MGmol_MPI& mmpi = *(MGmol_MPI::instance()); for (short i = 0; i < 6; i++) { mmpi.split_allreduce_sums_double(&a[i][0], n2); my_dscal(n2, grid.vel(), &a[i][0]); } compute_tm_.stop(); } template <class T> void SinCosOps<T>::computeDiag(const T& orbitals, VariableSizeMatrix<sparserow>& mat, const bool normalized_functions) { compute_tm_.start(); const pb::Grid& grid(orbitals.grid_); const int dim0 = grid.dim(0); const int dim1 = grid.dim(1); const int dim2 = grid.dim(2); int loc_length = dim0 / orbitals.subdivx_; assert(loc_length > 0); assert(loc_length <= dim0); int incx = dim1 * dim2; int incy = dim2; vector<double> sinx; vector<double> siny; vector<double> sinz; vector<double> cosx; vector<double> cosy; vector<double> cosz; grid.getSinCosFunctions(sinx, siny, sinz, cosx, cosy, cosz); vector<vector<double>> inv_norms2; if (!normalized_functions) { orbitals.computeInvNorms2(inv_norms2); } // initialize sparse ordering of rows to match local overlap regions // This is necessary for computing correct moves in moveTo() mat.setupSparseRows(orbitals.getAllOverlappingGids()); const int size = orbitals.chromatic_number(); for (short iloc = 0; iloc < orbitals.subdivx_; iloc++) { for (short icolor = 0; icolor < size; icolor++) { int gid = orbitals.overlapping_gids_[iloc][icolor]; if (gid != -1) { const ORBDTYPE* const psii = orbitals.psi(icolor); double atmp[6] = { 0., 0., 0., 0., 0., 0. }; for (int ix = loc_length * iloc; ix < loc_length * (iloc + 1); ix++) for (int iy = 0; iy < dim1; iy++) for (int iz = 0; iz < dim2; iz++) { const int index = ix * incx + iy * incy + iz; const double alpha = (double)psii[index] * (double)psii[index]; atmp[0] += alpha * cosx[ix]; atmp[1] += alpha * sinx[ix]; atmp[2] += alpha * cosy[iy]; atmp[3] += alpha * siny[iy]; atmp[4] += alpha * cosz[iz]; atmp[5] += alpha * sinz[iz]; } if (!normalized_functions) { for (int col = 0; col < 6; col++) atmp[col] *= inv_norms2[iloc][icolor]; } for (int col = 0; col < 6; col++) mat.insertMatrixElement(gid, col, atmp[col], ADD, true); } } } /* scale data */ mat.scale(grid.vel()); /* gather data */ Mesh* mymesh = Mesh::instance(); const pb::Grid& mygrid = mymesh->grid(); const pb::PEenv& myPEenv = mymesh->peenv(); double domain[3] = { mygrid.ll(0), mygrid.ll(1), mygrid.ll(2) }; double maxr = orbitals.getMaxR(); DataDistribution distributor("Distributor4SinCos", maxr, myPEenv, domain); distributor.augmentLocalData(mat, true); compute_tm_.stop(); } template class SinCosOps<LocGridOrbitals>; template class SinCosOps<ExtendedGridOrbitals>;
34.292441
80
0.422346
oseikuffuor1
a0b6d49deda766258341b2b10a34eec487dc0f69
551
cpp
C++
Prim/PrimCheckLock.cpp
UltimateScript/FOG
edc96d916fc299f0a822f8c534a4e7487c0e3ea2
[ "BSD-3-Clause" ]
null
null
null
Prim/PrimCheckLock.cpp
UltimateScript/FOG
edc96d916fc299f0a822f8c534a4e7487c0e3ea2
[ "BSD-3-Clause" ]
2
2021-07-07T17:31:49.000Z
2021-07-16T11:40:38.000Z
Prim/PrimCheckLock.cpp
OuluLinux/FOG
edc96d916fc299f0a822f8c534a4e7487c0e3ea2
[ "BSD-3-Clause" ]
null
null
null
#include <Prim/PrimIncludeAll.h> #ifndef NO_PRIM_CHECKS int PrimCheckLock::_check_locks = 0; // Number of locks in force. #endif // // Return the debug checking control variable. // bool& PrimCheckLock::debug_check() { static PrimGetEnv<bool> debugCheck("PrimCheckLock::debug_check", debug_full_check()); return debugCheck; } // // Return the debug full check control variable. // bool& PrimCheckLock::debug_full_check() { static PrimGetEnv<bool> debugFullCheck("PrimCheckLock::debug_full_check", false); return debugFullCheck; }
21.192308
86
0.744102
UltimateScript
a0b7aa4bba66d43409216d479bc364403f3cdbcd
11,276
cpp
C++
pj_tflite_hand_mediapipe/ImageProcessor/HandLandmarkEngine.cpp
bjarkirafn/play_with_tflite
ab20bcfa79f1bbcf1cb5d8e2887df6253ef0a0c0
[ "Apache-2.0" ]
1
2021-01-13T00:52:14.000Z
2021-01-13T00:52:14.000Z
pj_tflite_hand_mediapipe/ImageProcessor/HandLandmarkEngine.cpp
bjarkirafn/play_with_tflite
ab20bcfa79f1bbcf1cb5d8e2887df6253ef0a0c0
[ "Apache-2.0" ]
null
null
null
pj_tflite_hand_mediapipe/ImageProcessor/HandLandmarkEngine.cpp
bjarkirafn/play_with_tflite
ab20bcfa79f1bbcf1cb5d8e2887df6253ef0a0c0
[ "Apache-2.0" ]
null
null
null
/*** Include ***/ /* for general */ #include <cstdint> #include <cstdlib> #define _USE_MATH_DEFINES #include <cmath> #include <cstring> #include <string> #include <vector> #include <array> #include <algorithm> #include <chrono> #include <fstream> /* for OpenCV */ #include <opencv2/opencv.hpp> /* for My modules */ #include "CommonHelper.h" #include "InferenceHelper.h" #include "HandLandmarkEngine.h" /*** Macro ***/ #define TAG "HandLandmarkEngine" #define PRINT(...) COMMON_HELPER_PRINT(TAG, __VA_ARGS__) #define PRINT_E(...) COMMON_HELPER_PRINT_E(TAG, __VA_ARGS__) /* Model parameters */ #define MODEL_NAME "hand_landmark.tflite" /*** Function ***/ int32_t HandLandmarkEngine::initialize(const std::string& workDir, const int32_t numThreads) { /* Set model information */ std::string modelFilename = workDir + "/model/" + MODEL_NAME; /* Set input tensor info */ m_inputTensorList.clear(); InputTensorInfo inputTensorInfo; inputTensorInfo.name = "input_1"; inputTensorInfo.tensorType = TensorInfo::TENSOR_TYPE_FP32; inputTensorInfo.tensorDims.batch = 1; inputTensorInfo.tensorDims.width = 256; inputTensorInfo.tensorDims.height = 256; inputTensorInfo.tensorDims.channel = 3; inputTensorInfo.dataType = InputTensorInfo::DATA_TYPE_IMAGE; inputTensorInfo.normalize.mean[0] = 0.0f; /* normalized to[0.f, 1.f] (hand_landmark_cpu.pbtxt) */ inputTensorInfo.normalize.mean[1] = 0.0f; inputTensorInfo.normalize.mean[2] = 0.0f; inputTensorInfo.normalize.norm[0] = 1.0f; inputTensorInfo.normalize.norm[1] = 1.0f; inputTensorInfo.normalize.norm[2] = 1.0f; m_inputTensorList.push_back(inputTensorInfo); /* Set output tensor info */ m_outputTensorList.clear(); OutputTensorInfo outputTensorInfo; outputTensorInfo.tensorType = TensorInfo::TENSOR_TYPE_FP32; outputTensorInfo.name = "ld_21_3d"; m_outputTensorList.push_back(outputTensorInfo); outputTensorInfo.name = "output_handflag"; m_outputTensorList.push_back(outputTensorInfo); outputTensorInfo.name = "output_handedness"; m_outputTensorList.push_back(outputTensorInfo); /* Create and Initialize Inference Helper */ //m_inferenceHelper.reset(InferenceHelper::create(InferenceHelper::OPEN_CV)); //m_inferenceHelper.reset(InferenceHelper::create(InferenceHelper::TENSOR_RT)); //m_inferenceHelper.reset(InferenceHelper::create(InferenceHelper::NCNN)); //m_inferenceHelper.reset(InferenceHelper::create(InferenceHelper::MNN)); m_inferenceHelper.reset(InferenceHelper::create(InferenceHelper::TENSORFLOW_LITE)); //m_inferenceHelper.reset(InferenceHelper::create(InferenceHelper::TENSORFLOW_LITE_EDGETPU)); //m_inferenceHelper.reset(InferenceHelper::create(InferenceHelper::TENSORFLOW_LITE_GPU)); //m_inferenceHelper.reset(InferenceHelper::create(InferenceHelper::TENSORFLOW_LITE_XNNPACK)); if (!m_inferenceHelper) { return RET_ERR; } if (m_inferenceHelper->setNumThread(numThreads) != InferenceHelper::RET_OK) { m_inferenceHelper.reset(); return RET_ERR; } if (m_inferenceHelper->initialize(modelFilename, m_inputTensorList, m_outputTensorList) != InferenceHelper::RET_OK) { m_inferenceHelper.reset(); return RET_ERR; } /* Check if input tensor info is set */ for (const auto& inputTensorInfo : m_inputTensorList) { if ((inputTensorInfo.tensorDims.width <= 0) || (inputTensorInfo.tensorDims.height <= 0) || inputTensorInfo.tensorType == TensorInfo::TENSOR_TYPE_NONE) { PRINT_E("Invalid tensor size\n"); m_inferenceHelper.reset(); return RET_ERR; } } return RET_OK; } int32_t HandLandmarkEngine::finalize() { if (!m_inferenceHelper) { PRINT_E("Inference helper is not created\n"); return RET_ERR; } m_inferenceHelper->finalize(); return RET_OK; } int32_t HandLandmarkEngine::invoke(const cv::Mat& originalMat, int32_t palmX, int32_t palmY, int32_t palmW, int32_t palmH, float palmRotation, RESULT& result) { if (!m_inferenceHelper) { PRINT_E("Inference helper is not created\n"); return RET_ERR; } /*** PreProcess ***/ const auto& tPreProcess0 = std::chrono::steady_clock::now(); InputTensorInfo& inputTensorInfo = m_inputTensorList[0]; /* Rotate palm image */ cv::Mat rotatedImage; cv::RotatedRect rect(cv::Point(palmX + palmW / 2, palmY + palmH / 2), cv::Size(palmW, palmH), palmRotation * 180.f / static_cast<float>(M_PI)); cv::Mat trans = cv::getRotationMatrix2D(rect.center, rect.angle, 1.0); cv::Mat srcRot; cv::warpAffine(originalMat, srcRot, trans, originalMat.size()); cv::getRectSubPix(srcRot, rect.size, rect.center, rotatedImage); //cv::imshow("rotatedImage", rotatedImage); /* Resize image */ cv::Mat imgSrc; cv::resize(rotatedImage, imgSrc, cv::Size(inputTensorInfo.tensorDims.width, inputTensorInfo.tensorDims.height)); #ifndef CV_COLOR_IS_RGB cv::cvtColor(imgSrc, imgSrc, cv::COLOR_BGR2RGB); #endif inputTensorInfo.data = imgSrc.data; inputTensorInfo.dataType = InputTensorInfo::DATA_TYPE_IMAGE; inputTensorInfo.imageInfo.width = imgSrc.cols; inputTensorInfo.imageInfo.height = imgSrc.rows; inputTensorInfo.imageInfo.channel = imgSrc.channels(); inputTensorInfo.imageInfo.cropX = 0; inputTensorInfo.imageInfo.cropY = 0; inputTensorInfo.imageInfo.cropWidth = imgSrc.cols; inputTensorInfo.imageInfo.cropHeight = imgSrc.rows; inputTensorInfo.imageInfo.isBGR = false; inputTensorInfo.imageInfo.swapColor = false; if (m_inferenceHelper->preProcess(m_inputTensorList) != InferenceHelper::RET_OK) { return RET_ERR; } const auto& tPreProcess1 = std::chrono::steady_clock::now(); /*** Inference ***/ const auto& tInference0 = std::chrono::steady_clock::now(); if (m_inferenceHelper->invoke(m_outputTensorList) != InferenceHelper::RET_OK) { return RET_ERR; } const auto& tInference1 = std::chrono::steady_clock::now(); /*** PostProcess ***/ const auto& tPostProcess0 = std::chrono::steady_clock::now(); /* Retrieve the result */ HAND_LANDMARK& handLandmark = result.handLandmark; handLandmark.handflag = m_outputTensorList[1].getDataAsFloat()[0]; handLandmark.handedness = m_outputTensorList[2].getDataAsFloat()[0]; const float *ld21 = m_outputTensorList[0].getDataAsFloat(); //printf("%f %f\n", m_outputTensorHandflag->getDataAsFloat()[0], m_outputTensorHandedness->getDataAsFloat()[0]); for (int32_t i = 0; i < 21; i++) { handLandmark.pos[i].x = ld21[i * 3 + 0] / inputTensorInfo.tensorDims.width; // 0.0 - 1.0 handLandmark.pos[i].y = ld21[i * 3 + 1] / inputTensorInfo.tensorDims.height; // 0.0 - 1.0 handLandmark.pos[i].z = ld21[i * 3 + 2] * 1; // Scale Z coordinate as X. (-100 - 100???) todo //printf("%f\n", m_outputTensorLd21->getDataAsFloat()[i]); //cv::circle(originalMat, cv::Point(m_outputTensorLd21->getDataAsFloat()[i * 3 + 0], m_outputTensorLd21->getDataAsFloat()[i * 3 + 1]), 5, cv::Scalar(255, 255, 0), 1); } /* Fix landmark rotation */ for (int32_t i = 0; i < 21; i++) { handLandmark.pos[i].x *= rotatedImage.cols; // coordinate on rotatedImage handLandmark.pos[i].y *= rotatedImage.rows; } rotateLandmark(handLandmark, palmRotation, rotatedImage.cols, rotatedImage.rows); // coordinate on thei nput image /* Calculate palm rectangle from Landmark */ transformLandmarkToRect(handLandmark); handLandmark.rect.rotation = calculateRotation(handLandmark); for (int32_t i = 0; i < 21; i++) { handLandmark.pos[i].x += palmX; handLandmark.pos[i].y += palmY; } handLandmark.rect.x += palmX; handLandmark.rect.y += palmY; const auto& tPostProcess1 = std::chrono::steady_clock::now(); /* Return the results */ result.timePreProcess = static_cast<std::chrono::duration<double>>(tPreProcess1 - tPreProcess0).count() * 1000.0; result.timeInference = static_cast<std::chrono::duration<double>>(tInference1 - tInference0).count() * 1000.0; result.timePostProcess = static_cast<std::chrono::duration<double>>(tPostProcess1 - tPostProcess0).count() * 1000.0;; return RET_OK; } void HandLandmarkEngine::rotateLandmark(HAND_LANDMARK& handLandmark, float rotationRad, int32_t imageWidth, int32_t imageHeight) { for (int32_t i = 0; i < 21; i++) { float x = handLandmark.pos[i].x - imageWidth / 2.f; float y = handLandmark.pos[i].y - imageHeight / 2.f; handLandmark.pos[i].x = x * std::cos(rotationRad) - y * std::sin(rotationRad) + imageWidth / 2.f; handLandmark.pos[i].y = x * std::sin(rotationRad) + y * std::cos(rotationRad) + imageHeight / 2.f; //handLandmark.pos[i].x = std::min(handLandmark.pos[i].x, 1.f); //handLandmark.pos[i].y = std::min(handLandmark.pos[i].y, 1.f); }; } float HandLandmarkEngine::calculateRotation(const HAND_LANDMARK& handLandmark) { // Reference: mediapipe\graphs\hand_tracking\calculators\hand_detections_to_rects_calculator.cc constexpr int32_t kWristJoint = 0; constexpr int32_t kMiddleFingerPIPJoint = 12; constexpr int32_t kIndexFingerPIPJoint = 8; constexpr int32_t kRingFingerPIPJoint = 16; constexpr float target_angle_ = static_cast<float>(M_PI) * 0.5f; const float x0 = handLandmark.pos[kWristJoint].x; const float y0 = handLandmark.pos[kWristJoint].y; float x1 = (handLandmark.pos[kMiddleFingerPIPJoint].x + handLandmark.pos[kMiddleFingerPIPJoint].x) / 2.f; float y1 = (handLandmark.pos[kMiddleFingerPIPJoint].y + handLandmark.pos[kMiddleFingerPIPJoint].y) / 2.f; x1 = (x1 + handLandmark.pos[kMiddleFingerPIPJoint].x) / 2.f; y1 = (y1 + handLandmark.pos[kMiddleFingerPIPJoint].y) / 2.f; float rotation; rotation = target_angle_ - std::atan2(-(y1 - y0), x1 - x0); rotation = rotation - 2 * static_cast<float>(M_PI) * std::floor((rotation - (-static_cast<float>(M_PI))) / (2 * static_cast<float>(M_PI))); return rotation; } void HandLandmarkEngine::transformLandmarkToRect(HAND_LANDMARK &handLandmark) { constexpr float shift_x = 0.0f; constexpr float shift_y = -0.0f; constexpr float scale_x = 1.8f; // tuned parameter by looking constexpr float scale_y = 1.8f; float width = 0; float height = 0; float x_center = 0; float y_center = 0; float xmin = handLandmark.pos[0].x; float xmax = handLandmark.pos[0].x; float ymin = handLandmark.pos[0].y; float ymax = handLandmark.pos[0].y; for (int32_t i = 0; i < 21; i++) { if (handLandmark.pos[i].x < xmin) xmin = handLandmark.pos[i].x; if (handLandmark.pos[i].x > xmax) xmax = handLandmark.pos[i].x; if (handLandmark.pos[i].y < ymin) ymin = handLandmark.pos[i].y; if (handLandmark.pos[i].y > ymax) ymax = handLandmark.pos[i].y; } width = xmax - xmin; height = ymax - ymin; x_center = (xmax + xmin) / 2.f; y_center = (ymax + ymin) / 2.f; width *= scale_x; height *= scale_y; float long_side = std::max(width, height); /* for hand is closed */ //float palmDistance = powf(handLandmark.pos[0].x - handLandmark.pos[9].x, 2) + powf(handLandmark.pos[0].y - handLandmark.pos[9].y, 2); //palmDistance = sqrtf(palmDistance); //long_side = std::max(long_side, palmDistance); handLandmark.rect.width = (long_side * 1); handLandmark.rect.height = (long_side * 1); handLandmark.rect.x = (x_center - handLandmark.rect.width / 2); handLandmark.rect.y = (y_center - handLandmark.rect.height / 2); }
39.426573
169
0.715945
bjarkirafn
a0ba8241d34a89a56e6b9642cda3a1bb4b9153b0
7,351
cpp
C++
src/internal/modbusTcpSlave.cpp
baggior/SmartHome_GATEWAY
14fd80e701d92ef79ee2289af40d8334fa48c154
[ "MIT" ]
1
2018-03-06T10:31:09.000Z
2018-03-06T10:31:09.000Z
src/internal/modbusTcpSlave.cpp
baggior/SmartHome_GATEWAY
14fd80e701d92ef79ee2289af40d8334fa48c154
[ "MIT" ]
4
2018-02-05T15:58:19.000Z
2018-11-05T10:11:50.000Z
src/internal/modbusTcpSlave.cpp
baggior/SmartHome_GATEWAY
14fd80e701d92ef79ee2289af40d8334fa48c154
[ "MIT" ]
null
null
null
#include "Arduino.h" #include "modbusTcpSlave.h" // WiFiServer mbServer(MODBUSIP_PORT); #define TCP_TIMEOUT_MS RTU_TIMEOUT * 2 ModbusTcpSlave::ModbusTcpSlave(_ApplicationLogger& logger, uint16_t port = MODBUSIP_PORT, bool _isDebug = false) : mbServer(port), mLogger(logger), isDebug(_isDebug) { mbServer.begin(); mbServer.setNoDelay(true); #ifdef ESP32 mbServer.setTimeout(TCP_TIMEOUT_MS / 1000); #endif for (uint8_t i = 0 ; i < FRAME_COUNT; i++) mbFrame[i].status = frameStatus::empty; for (uint8_t i = 0 ; i < CLIENT_NUM; i++) clientOnLine[i].onLine = false; } ModbusTcpSlave::~ModbusTcpSlave() { } void ModbusTcpSlave::waitNewClient(void) { // see if the old customers are alive if not alive then release them for (uint8_t i = 0 ; i < CLIENT_NUM; i++) { //find free/disconnected spot if (clientOnLine[i].onLine && !clientOnLine[i].client.connected()) { clientOnLine[i].client.stop(); // clientOnLine[i].onLine = false; this->mLogger.debug (("\tClient stopped: [%d]\n"), i); } // else clientOnLine[i].client.flush(); } if (mbServer.hasClient()) { bool clientAdded = false; for(uint8_t i = 0 ; i < CLIENT_NUM; i++) { if( !clientOnLine[i].onLine) { clientOnLine[i].client = mbServer.available(); clientOnLine[i].client.setNoDelay(true); //disable delay feature algorithm clientOnLine[i].onLine = true; clientAdded = true; if(this->isDebug) { this->mLogger.debug (("\tNew Client: [%d] remote Ip: %s\n"), i, clientOnLine[i].client.remoteIP().toString().c_str()); } break; } } if (!clientAdded) // If there was no place for a new client { //no free/disconnected spot so reject this->mLogger.error (("\tToo many Clients reject the new connection \n") ); mbServer.available().stop(); // clientOnLine[0].client.stop(); // clientOnLine[0].client = mbServer.available(); } } } void ModbusTcpSlave::readDataClient(void) { for(uint8_t i = 0; i < CLIENT_NUM; i++) { if(clientOnLine[i].onLine) { if(clientOnLine[i].client.available()) { this->readFrameClient(clientOnLine[i].client, i); } } } } void ModbusTcpSlave::readFrameClient(WiFiClient client, uint8_t nClient) { size_t available = client.available(); if ((available < TCP_BUFFER_SIZE) && (available > 11)) { size_t len = available; uint8_t buf[len]; size_t count = 0; while(client.available()) { buf[count] = client.read(); count++; } count =0; smbap mbap; mbapUnpack(&mbap, &buf[0]); if(this->isDebug) { this->mLogger.debug (("\tPaket in : len TCP data [%d] Len mbap pak [%d], UnitId [%d], TI [%d] \n"), len, mbap._len, mbap._ui, mbap._ti); } // checking for glued requests. (wizards are requested for 4 requests) while((count < len ) && ((len - count) <= (size_t) (mbap._len + TCP_MBAP_SIZE)) && (mbap._pi ==0)) { smbFrame * pmbFrame = this->getFreeBuffer(); if(pmbFrame == 0) break; // if there is no free buffer then we reduce the parsing pmbFrame->nClient = nClient; if(mbap._ui==0) { // UnitId = 0 => broadcast modbus message pmbFrame->status = frameStatus::readyToSendRtuNoReply; } else { pmbFrame->status = frameStatus::readyToSendRtu; } pmbFrame->len = mbap._len + TCP_MBAP_SIZE; pmbFrame->millis = millis(); for (uint16_t j = 0; j < (pmbFrame->len); j++) pmbFrame->buffer[j] = buf[j]; count += pmbFrame->len; mbapUnpack(&mbap, &buf[count]); } } else { this->mLogger.error (("\tTCP client [%d] data count invalid : %d\n"), nClient, available); // uint16_t tmp = client.available(); while(client.available()) client.read(); } } void ModbusTcpSlave::writeFrameClient(void) { smbFrame * pmbFrame = this->getReadyToSendTcpBuffer(); if(pmbFrame) { uint8_t cli = pmbFrame->nClient; size_t len = pmbFrame->len; if(! clientOnLine[cli].client.connected() ) { this->mLogger.warn (("\tERROR writeFrameClient: writing to a disconnected client: %d"), cli); return; } size_t written = clientOnLine[cli].client.write(&pmbFrame->buffer[0], len); // write to TCP client if(this->isDebug) { this->mLogger.debug (("\twritten data buffer to TCP client: %d, len=%d\n"), cli, len ); } if(written!= len) { this->mLogger.error (("\tERROR writeFrameClient: writing buffer [%d] to RTU client len_to_write=%d, written=%d\n"), cli, len, written); } // delay(1); // yield(); clientOnLine[cli].client.flush(); pmbFrame->status = frameStatus::empty; } } // void ModbusTcpSlave::task() // { // waitNewClient(); // yield(); // readDataClient(); // yield(); // writeFrameClient(); // yield(); // timeoutBufferCleanup(); // } void ModbusTcpSlave::timeoutBufferCleanup() { // Cleaning the buffers for(uint8_t i = 0; i < FRAME_COUNT; i++) { if(mbFrame[i].status != frameStatus::empty ) { if (millis() - mbFrame[i].millis > RTU_TIMEOUT) { mbFrame[i].status = frameStatus::empty; // this->mLogger.printf (("\tRTU_TIMEOUT -> Del pack.\n")); this->mLogger.error (("\tRTU_TIMEOUT -> Del pack.\n")); } } } } ModbusTcpSlave::smbFrame * ModbusTcpSlave::getFreeBuffer () { static uint8_t scanBuff = 0; while (mbFrame[scanBuff].status != frameStatus::empty) { scanBuff++; if(scanBuff >= FRAME_COUNT) { this->mLogger.error (("\tNo Free buffer\n")); scanBuff = 0; return 0; } } //init frame mbFrame[scanBuff].nClient=0; mbFrame[scanBuff].len=0; mbFrame[scanBuff].millis=0; mbFrame[scanBuff].guessedReponseLen=0; mbFrame[scanBuff].ascii_response_buffer=""; return &mbFrame[scanBuff]; } ModbusTcpSlave::smbFrame * ModbusTcpSlave::getReadyToSendRtuBuffer () { uint8_t pointer = 255; uint8_t pointerMillis = 0; for(uint8_t i = 0; i < FRAME_COUNT; i++) { if(mbFrame[i].status == frameStatus::readyToSendRtu || mbFrame[i].status == frameStatus::readyToSendRtuNoReply) { // check if current buffer is older if ( pointerMillis < (millis() - mbFrame[i].millis)) { pointerMillis = millis() - mbFrame[i].millis; pointer = i; } } } if (pointer != 255) return &mbFrame[pointer]; //returns the LEAST RECENTLY modified frame buffer else return NULL; } ModbusTcpSlave::smbFrame * ModbusTcpSlave::getWaitFromRtuBuffer () { for(uint8_t i = 0; i < FRAME_COUNT; i++) { if(mbFrame[i].status == frameStatus::waitFromRtu ) return &mbFrame[i]; } return NULL; } ModbusTcpSlave::smbFrame *ModbusTcpSlave::getReadyToSendTcpBuffer () { for(uint8_t i = 0; i < FRAME_COUNT; i++) { if(mbFrame[i].status == frameStatus::readyToSendTcp ) return &mbFrame[i]; } return NULL; } void ModbusTcpSlave::mbapUnpack(smbap* pmbap, uint8_t * buff ) { pmbap->_ti = *(buff + 0) << 8 | *(buff + 1); pmbap->_pi = *(buff + 2) << 8 | *(buff + 3); pmbap->_len = *(buff + 4) << 8 | *(buff + 5); pmbap->_ui = *(buff + 6); }
26.828467
141
0.604544
baggior
a0bcee208db558a96a7b980ad65f41f7427f3692
2,093
cpp
C++
NorthstarDedicatedTest/version.cpp
r-ex/NorthstarLauncher
14bc1b6ac7425934cb9fdfbcc522c720d512b370
[ "MIT" ]
null
null
null
NorthstarDedicatedTest/version.cpp
r-ex/NorthstarLauncher
14bc1b6ac7425934cb9fdfbcc522c720d512b370
[ "MIT" ]
null
null
null
NorthstarDedicatedTest/version.cpp
r-ex/NorthstarLauncher
14bc1b6ac7425934cb9fdfbcc522c720d512b370
[ "MIT" ]
null
null
null
#include "version.h" #include "pch.h" char version[16]; char NSUserAgent[32]; void InitialiseVersion() { HRSRC hResInfo; DWORD dwSize; HGLOBAL hResData; LPVOID pRes, pResCopy; UINT uLen = 0; VS_FIXEDFILEINFO* lpFfi = NULL; HINSTANCE hInst = ::GetModuleHandle(NULL); hResInfo = FindResourceW(hInst, MAKEINTRESOURCE(1), RT_VERSION); if (hResInfo != NULL) { dwSize = SizeofResource(hInst, hResInfo); hResData = LoadResource(hInst, hResInfo); if (hResData != NULL) { pRes = LockResource(hResData); pResCopy = LocalAlloc(LMEM_FIXED, dwSize); if (pResCopy != 0) { CopyMemory(pResCopy, pRes, dwSize); VerQueryValueW(pResCopy, L"\\", (LPVOID*)&lpFfi, &uLen); DWORD dwFileVersionMS = lpFfi->dwFileVersionMS; DWORD dwFileVersionLS = lpFfi->dwFileVersionLS; DWORD dwLeftMost = HIWORD(dwFileVersionMS); DWORD dwSecondLeft = LOWORD(dwFileVersionMS); DWORD dwSecondRight = HIWORD(dwFileVersionLS); DWORD dwRightMost = LOWORD(dwFileVersionLS); // We actually use the rightmost integer do determine whether or not we're a debug/dev build // If it is set to 1 (as in resources.rc), we are a dev build // On github CI, we set this 1 to a 0 automatically as we replace the 0.0.0.1 with the real version number if (dwRightMost == 1) { sprintf(version, "%d.%d.%d.%d+dev", dwLeftMost, dwSecondLeft, dwSecondRight, dwRightMost); sprintf(NSUserAgent, "R2Northstar/%d.%d.%d+dev", dwLeftMost, dwSecondLeft, dwSecondRight); } else { sprintf(version, "%d.%d.%d.%d", dwLeftMost, dwSecondLeft, dwSecondRight, dwRightMost); sprintf(NSUserAgent, "R2Northstar/%d.%d.%d", dwLeftMost, dwSecondLeft, dwSecondRight); } UnlockResource(hResData); FreeResource(hResData); LocalFree(pResCopy); return; } UnlockResource(hResData); FreeResource(hResData); LocalFree(pResCopy); } } // Could not locate version info for whatever reason spdlog::error("Failed to load version info:\n{}", std::system_category().message(GetLastError())); sprintf(NSUserAgent, "R2Northstar/0.0.0"); }
31.712121
110
0.698041
r-ex
a0bdfd8f762fc66b4df84cdd9e62f37418311e2e
1,248
cpp
C++
Music Player/Using c++/Data sturcutre Project/Data sturcutre Project/Source.cpp
rafay99-epic/University-Projects
49cbd2c1e5e5879dd1dd2364301e35fd5c0bba81
[ "MIT" ]
null
null
null
Music Player/Using c++/Data sturcutre Project/Data sturcutre Project/Source.cpp
rafay99-epic/University-Projects
49cbd2c1e5e5879dd1dd2364301e35fd5c0bba81
[ "MIT" ]
null
null
null
Music Player/Using c++/Data sturcutre Project/Data sturcutre Project/Source.cpp
rafay99-epic/University-Projects
49cbd2c1e5e5879dd1dd2364301e35fd5c0bba81
[ "MIT" ]
null
null
null
#include "music.h" #include<iostream> #include<string> #include<fstream> using namespace std; int main() { Node n; int count{}; int choice; char yes; int const size = 3; int i = 0; music_data s; fstream data("music.txt", ios::out); ifstream take("music.txt"); take >> count; do { cout << endl << " " << "=====MENU=====" << endl; cout << endl << " " << "1.To Enter the data in to the File. " << endl; cout << endl << " " << "2.To display all of the data." << endl; cout << endl << " " << "Enter the choice: "; cin >> choice; switch (choice) { case 1: do { cout << endl << " " << "Enter the name of the song: "; cin.ignore(); getline(cin, s.name); cout << endl << " " << "Enter the name of movie: "; cin.ignore(); getline(cin, s.movie); cout << endl << " " << "Enter the name of the Singer: "; cin.ignore(); getline(cin, s.singer); data.write(reinterpret_cast<char*>(&s), sizeof(s)); cout << endl << " " << "Do you like to store the data again: "; cin >> yes; } while (yes == 'Y' && 1 < 3); for (int i = 0; i < count; i++) { take >> n.array[i]; } break; default: break; } } while (choice!=3); system("pause"); return 0; }
20.459016
73
0.525641
rafay99-epic
a0bf0cbb58f91c85aa99a45764c32649855ed115
5,926
hpp
C++
aslam_backend_expressions/include/aslam/backend/CacheExpression.hpp
ethz-asl/aslam_optimizer
8e9dd18f9f0d8af461e88e108a3beda2003daf11
[ "BSD-3-Clause" ]
33
2017-04-26T13:30:49.000Z
2022-02-25T01:52:22.000Z
aslam_backend_expressions/include/aslam/backend/CacheExpression.hpp
ethz-asl/aslam_optimizer
8e9dd18f9f0d8af461e88e108a3beda2003daf11
[ "BSD-3-Clause" ]
15
2017-02-14T16:02:31.000Z
2020-05-12T06:07:22.000Z
aslam_backend_expressions/include/aslam/backend/CacheExpression.hpp
ethz-asl/aslam_optimizer
8e9dd18f9f0d8af461e88e108a3beda2003daf11
[ "BSD-3-Clause" ]
8
2017-06-28T04:17:08.000Z
2021-04-10T04:58:36.000Z
/* * CacheExpression.hpp * * Created on: 08.03.2016 * Author: Ulrich Schwesinger */ #ifndef INCLUDE_ASLAM_BACKEND_CACHEEXPRESSION_HPP_ #define INCLUDE_ASLAM_BACKEND_CACHEEXPRESSION_HPP_ // boost includes #include <boost/thread.hpp> // Eigen includes #include <Eigen/Dense> // aslam_backend includes #include <aslam/Exceptions.hpp> // self includes #include <aslam/backend/DesignVariable.hpp> #include <aslam/backend/JacobianContainerSparse.hpp> #include <aslam/backend/JacobianContainerPrescale.hpp> #include <aslam/backend/CacheInterface.hpp> namespace aslam { namespace backend { template<int IRows, int ICols, typename TScalar> class GenericMatrixExpressionNode; /** * \class CacheExpressionNode * \brief Wraps an expression into a cache data structure to avoid duplicate * computation of error and Jacobian values * * \tparam ExpressionNode Type of the expression node * \tparam Dimensions Dimensionality of the design variables */ template <typename ExpressionNode, int Dimension> class CacheExpressionNode : public CacheInterface, public ExpressionNode { public: template <typename Expression> friend Expression toCacheExpression(const Expression& expr); public: virtual ~CacheExpressionNode() { } protected: typename ExpressionNode::value_t evaluateImplementation() const override { if (!_isCacheValidV) { boost::mutex::scoped_lock lock(_mutexV); if (!_isCacheValidV) // could be updated by another thread in the meantime { _v = _node->evaluate(); _isCacheValidV = true; } } return _v; } void evaluateJacobiansImplementation(JacobianContainer & outJacobians) const override { updateJacobian(); _jc.addTo(outJacobians); } virtual void getDesignVariablesImplementation(DesignVariable::set_t & designVariables) const override { _node->getDesignVariables(designVariables); } private: CacheExpressionNode(const boost::shared_ptr<ExpressionNode>& e) : CacheInterface(), ExpressionNode(), _node(e) { } void updateJacobian() const { if (!_isCacheValidJ) { boost::mutex::scoped_lock lock(_mutexJ); if (!_isCacheValidJ) // could be updated by another thread in the meantime { _jc.setZero(); _node->evaluateJacobians(_jc); _isCacheValidJ = true; } } } private: mutable typename ExpressionNode::value_t _v; /// \brief Cache for error values mutable JacobianContainerSparse<Dimension> _jc = JacobianContainerSparse<Dimension>(Dimension); /// \brief Cache for Jacobians boost::shared_ptr<ExpressionNode> _node; /// \brief Wrapped expression node, stored to delegate evaluation calls mutable boost::mutex _mutexV; /// \brief Mutex for error value write operations mutable boost::mutex _mutexJ; /// \brief Mutex for Jacobian write operations }; template<int IRows, int ICols, int Dimension, typename TScalar> class CacheExpressionNode< GenericMatrixExpressionNode<IRows, ICols, TScalar>, Dimension > : public CacheInterface, public GenericMatrixExpressionNode<IRows, ICols, TScalar> { public: template <typename Expression> friend Expression toCacheExpression(const Expression& expr); typedef GenericMatrixExpressionNode<IRows, ICols, TScalar> ExpressionNode; public: virtual ~CacheExpressionNode() { } protected: void evaluateImplementation() const override { if (!_isCacheValidV) { boost::mutex::scoped_lock lock(_mutexV); if (!_isCacheValidV) // could be updated by another thread in the meantime { this->_currentValue = _node->evaluate(); _isCacheValidV = true; } } } void evaluateJacobiansImplementation(JacobianContainer & outJacobians, const typename ExpressionNode::differential_t & chainRuleDifferential) const override { updateJacobian(); _jc.addTo((JacobianContainer&)applyDifferentialToJacobianContainer(outJacobians, chainRuleDifferential, IRows)); } virtual void getDesignVariablesImplementation(DesignVariable::set_t & designVariables) const override { _node->getDesignVariables(designVariables); } private: CacheExpressionNode(const boost::shared_ptr<ExpressionNode>& e) : CacheInterface(), ExpressionNode(), _node(e) { } void updateJacobian() const { if (!_isCacheValidJ) { boost::mutex::scoped_lock lock(_mutexJ); if (!_isCacheValidJ) // could be updated by another thread in the meantime { _jc.setZero(); _node->evaluateJacobians(_jc, IdentityDifferential<typename ExpressionNode::tangent_vector_t, TScalar>()); _isCacheValidJ = true; } } } private: mutable JacobianContainerSparse<IRows> _jc = JacobianContainerSparse<IRows>(IRows); /// \brief Cache for Jacobians boost::shared_ptr<ExpressionNode> _node; /// \brief Wrapped expression node, stored to delegate evaluation calls mutable boost::mutex _mutexV; /// \brief Mutex for error value write operations mutable boost::mutex _mutexJ; /// \brief Mutex for Jacobian write operations }; /** * \brief Converts a regular expression to a cache expression and registers the expression * in the corresponding design variables in order to allow the design variables to * invalidate the cache * * @param expr original expression * \tparam Expression expression type * @return Cached expression */ template <typename Expression> Expression toCacheExpression(const Expression& expr) { boost::shared_ptr< CacheExpressionNode<typename Expression::node_t, Expression::Dimension> > node (new CacheExpressionNode<typename Expression::node_t, Expression::Dimension>(expr.root())); DesignVariable::set_t dvs; node->getDesignVariables(dvs); for (auto dv : dvs) dv->registerCacheExpressionNode(node); return Expression(node); } } /* namespace aslam */ } /* namespace backend */ #endif /* INCLUDE_ASLAM_BACKEND_CACHEEXPRESSION_HPP_ */
29.192118
173
0.737091
ethz-asl
a0c0cd560571faf57abe861fc2187a746284e5d8
5,128
cpp
C++
libs/foe_model/src/animation.cpp
StableCoder/foe-engine
5d49696a46c119e708dc4055b99e18194bcd4c4f
[ "Apache-2.0" ]
4
2021-04-09T13:11:22.000Z
2022-03-26T07:29:31.000Z
libs/foe_model/src/animation.cpp
StableCoder/foe-engine
5d49696a46c119e708dc4055b99e18194bcd4c4f
[ "Apache-2.0" ]
null
null
null
libs/foe_model/src/animation.cpp
StableCoder/foe-engine
5d49696a46c119e708dc4055b99e18194bcd4c4f
[ "Apache-2.0" ]
1
2022-02-10T14:51:00.000Z
2022-02-10T14:51:00.000Z
/* Copyright (C) 2020 George Cave. 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 <foe/model/animation.hpp> glm::vec3 interpolatePosition(double time, foeNodeAnimationChannel const *pAnimationChannel) { // If there's no keys, return no position if (pAnimationChannel->positionKeys.empty()) { return glm::vec3(0.f); } // If there's only one key, OR the time is before the first key, return the first key if (pAnimationChannel->positionKeys.size() == 1 || time < pAnimationChannel->positionKeys[0].time) { return pAnimationChannel->positionKeys[0].value; } size_t index = 0; for (size_t i = 1; i < pAnimationChannel->positionKeys.size(); ++i) { if (time < pAnimationChannel->positionKeys[i].time) { break; } index = i; } // If it's the last key, return it alone if (index == pAnimationChannel->positionKeys.size() - 1) { return pAnimationChannel->positionKeys[index].value; } // If here, we're interpolating between two keys size_t nextIndex = index + 1; double deltaTime = pAnimationChannel->positionKeys[nextIndex].time - pAnimationChannel->positionKeys[index].time; // The percentage through between the keyframes we're at double factorTime = (time - pAnimationChannel->positionKeys[index].time) / deltaTime; glm::vec3 const &startPos = pAnimationChannel->positionKeys[index].value; glm::vec3 const &endPos = pAnimationChannel->positionKeys[nextIndex].value; return startPos + ((endPos - startPos) * static_cast<float>(factorTime)); } glm::quat interpolateRotation(double time, foeNodeAnimationChannel const *pAnimationChannel) { // If there's no keys, return no rotation if (pAnimationChannel->rotationKeys.empty()) { return glm::vec3(0.f); } // If there's only one key, OR the time is before the first key, return the first key if (pAnimationChannel->rotationKeys.size() == 1 || time < pAnimationChannel->rotationKeys[0].time) { return pAnimationChannel->rotationKeys[0].value; } size_t index = 0; for (size_t i = 1; i < pAnimationChannel->rotationKeys.size(); ++i) { if (time < pAnimationChannel->rotationKeys[i].time) { break; } index = i; } // If it's the last key, return it alone if (index == pAnimationChannel->rotationKeys.size() - 1) { return pAnimationChannel->rotationKeys[index].value; } // If here, we're interpolating between two keys size_t nextIndex = index + 1; double deltaTime = pAnimationChannel->rotationKeys[nextIndex].time - pAnimationChannel->rotationKeys[index].time; // The percentage through between the keyframes we're at double factorTime = (time - pAnimationChannel->rotationKeys[index].time) / deltaTime; glm::quat const &startPos = pAnimationChannel->rotationKeys[index].value; glm::quat const &endPos = pAnimationChannel->rotationKeys[nextIndex].value; return startPos + ((endPos - startPos) * static_cast<float>(factorTime)); } glm::vec3 interpolateScaling(double time, foeNodeAnimationChannel const *pAnimationChannel) { // If there's no keys, return no scaling if (pAnimationChannel->scalingKeys.empty()) { return glm::vec3(1.f); } // If there's only one key, OR the time is before the first key, return the first key if (pAnimationChannel->scalingKeys.size() == 1 || time < pAnimationChannel->scalingKeys[0].time) { return pAnimationChannel->scalingKeys[0].value; } size_t index = 0; for (size_t i = 1; i < pAnimationChannel->scalingKeys.size(); ++i) { if (time < pAnimationChannel->scalingKeys[i].time) { break; } index = i; } // If it's the last key, return it alone if (index == pAnimationChannel->scalingKeys.size() - 1) { return pAnimationChannel->scalingKeys[index].value; } // If here, we're interpolating between two keys size_t nextIndex = index + 1; double deltaTime = pAnimationChannel->scalingKeys[nextIndex].time - pAnimationChannel->scalingKeys[index].time; // The percentage through between the keyframes we're at double factorTime = (time - pAnimationChannel->scalingKeys[index].time) / deltaTime; glm::vec3 const &startPos = pAnimationChannel->scalingKeys[index].value; glm::vec3 const &endPos = pAnimationChannel->scalingKeys[nextIndex].value; return startPos + ((endPos - startPos) * static_cast<float>(factorTime)); }
38.268657
100
0.674337
StableCoder
a0c1081b9154764a0b406f369daefa67ff15aa10
8,726
cpp
C++
3rdparty/GPSTk/core/lib/GNSSEph/EphemerisRange.cpp
mfkiwl/ICE
e660d031bb1bcea664db1de4946fd8781be5b627
[ "MIT" ]
50
2019-10-12T01:22:20.000Z
2022-02-15T23:28:26.000Z
3rdparty/GPSTk/core/lib/GNSSEph/EphemerisRange.cpp
wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation
2f1ff054b7c5059da80bb3b2f80c05861a02cc36
[ "MIT" ]
null
null
null
3rdparty/GPSTk/core/lib/GNSSEph/EphemerisRange.cpp
wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation
2f1ff054b7c5059da80bb3b2f80c05861a02cc36
[ "MIT" ]
14
2019-11-05T01:50:29.000Z
2021-08-06T06:23:44.000Z
//============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 3.0 of the License, or // any later version. // // The GPSTk is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with GPSTk; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA // // Copyright 2004, The University of Texas at Austin // //============================================================================ //============================================================================ // //This software developed by Applied Research Laboratories at the University of //Texas at Austin, under contract to an agency or agencies within the U.S. //Department of Defense. The U.S. Government retains all rights to use, //duplicate, distribute, disclose, or release this software. // //Pursuant to DoD Directive 523024 // // DISTRIBUTION STATEMENT A: This software has been approved for public // release, distribution is unlimited. // //============================================================================= /** * @file EphemerisRange.cpp * Computation of range and associated quantities from EphemerisStore, * given receiver position and time. */ #include "EphemerisRange.hpp" #include "MiscMath.hpp" #include "GPSEllipsoid.hpp" #include "GNSSconstants.hpp" #include "GNSSconstants.hpp" using namespace std; using namespace gpstk; namespace gpstk { // Compute the corrected range at RECEIVE time, from receiver at position Rx, // to the GPS satellite given by SatID sat, as well as all the CER quantities, // given the nominal receive time tr_nom and an EphemerisStore. Note that this // routine does not intrinsicly account for the receiver clock error // like the ComputeAtTransmitTime routine does. double CorrectedEphemerisRange::ComputeAtReceiveTime( const CommonTime& tr_nom, const Position& Rx, const SatID sat, const XvtStore<SatID>& Eph) { try { int nit; double tof,tof_old; GPSEllipsoid ellipsoid; nit = 0; tof = 0.07; // initial guess 70ms do { // best estimate of transmit time transmit = tr_nom; transmit -= tof; tof_old = tof; // get SV position try { svPosVel = Eph.getXvt(sat, transmit); } catch(InvalidRequest& e) { GPSTK_RETHROW(e); } rotateEarth(Rx); // update raw range and time of flight rawrange = RSS(svPosVel.x[0]-Rx.X(), svPosVel.x[1]-Rx.Y(), svPosVel.x[2]-Rx.Z()); tof = rawrange/ellipsoid.c(); } while(ABS(tof-tof_old)>1.e-13 && ++nit<5); updateCER(Rx); return (rawrange-svclkbias-relativity); } catch(gpstk::Exception& e) { GPSTK_RETHROW(e); } } // end CorrectedEphemerisRange::ComputeAtReceiveTime // Compute the corrected range at TRANSMIT time, from receiver at position Rx, // to the GPS satellite given by SatID sat, as well as all the CER quantities, // given the nominal receive time tr_nom and an EphemerisStore, as well as // the raw measured pseudorange. double CorrectedEphemerisRange::ComputeAtTransmitTime( const CommonTime& tr_nom, const double& pr, const Position& Rx, const SatID sat, const XvtStore<SatID>& Eph) { try { CommonTime tt; // 0-th order estimate of transmit time = receiver - pseudorange/c transmit = tr_nom; transmit -= pr/C_MPS; tt = transmit; // correct for SV clock for(int i=0; i<2; i++) { // get SV position try { svPosVel = Eph.getXvt(sat,tt); } catch(InvalidRequest& e) { GPSTK_RETHROW(e); } tt = transmit; // remove clock bias and relativity correction tt -= (svPosVel.clkbias + svPosVel.relcorr); } rotateEarth(Rx); // raw range rawrange = RSS(svPosVel.x[0]-Rx.X(), svPosVel.x[1]-Rx.Y(), svPosVel.x[2]-Rx.Z()); updateCER(Rx); return (rawrange-svclkbias-relativity); } catch(gpstk::Exception& e) { GPSTK_RETHROW(e); } } // end CorrectedEphemerisRange::ComputeAtTransmitTime double CorrectedEphemerisRange::ComputeAtTransmitTime( const CommonTime& tr_nom, const Position& Rx, const SatID sat, const XvtStore<SatID>& Eph) { try { gpstk::GPSEllipsoid gm; svPosVel = Eph.getXvt(sat, tr_nom); double pr = svPosVel.preciseRho(Rx, gm); return ComputeAtTransmitTime(tr_nom, pr, Rx, sat, Eph); } catch(gpstk::Exception& e) { GPSTK_RETHROW(e); } } double CorrectedEphemerisRange::ComputeAtTransmitSvTime( const CommonTime& tt_nom, const double& pr, const Position& rx, const SatID sat, const XvtStore<SatID>& eph) { try { Position trx(rx); trx.asECEF(); svPosVel = eph.getXvt(sat, tt_nom); // compute rotation angle in the time of signal transit // While this is quite similiar to rotateEarth, its not the same // and jcl doesn't know which is really correct // BWT this uses the measured pseudorange, corrected for SV clock and // relativity, to compute the time of flight; rotateEarth uses the value // computed from the receiver position and the ephemeris. They should be // very nearly the same, and multiplying by angVel/c should make the angle // of rotation very nearly identical. GPSEllipsoid ell; double range(pr/ell.c() - svPosVel.clkbias - svPosVel.relcorr); double rotation_angle = -ell.angVelocity() * range; svPosVel.x[0] = svPosVel.x[0] - svPosVel.x[1] * rotation_angle; svPosVel.x[1] = svPosVel.x[1] + svPosVel.x[0] * rotation_angle; svPosVel.x[2] = svPosVel.x[2]; rawrange = trx.slantRange(svPosVel.x); updateCER(trx); return rawrange - svclkbias - relativity; } catch (Exception& e) { GPSTK_RETHROW(e); } } void CorrectedEphemerisRange::updateCER(const Position& Rx) { relativity = svPosVel.computeRelativityCorrection() * C_MPS; svclkbias = svPosVel.clkbias * C_MPS; svclkdrift = svPosVel.clkdrift * C_MPS; cosines[0] = (Rx.X()-svPosVel.x[0])/rawrange; cosines[1] = (Rx.Y()-svPosVel.x[1])/rawrange; cosines[2] = (Rx.Z()-svPosVel.x[2])/rawrange; Position SV(svPosVel); elevation = Rx.elevation(SV); azimuth = Rx.azimuth(SV); elevationGeodetic = Rx.elevationGeodetic(SV); azimuthGeodetic = Rx.azimuthGeodetic(SV); } void CorrectedEphemerisRange::rotateEarth(const Position& Rx) { GPSEllipsoid ellipsoid; double tof = RSS(svPosVel.x[0]-Rx.X(), svPosVel.x[1]-Rx.Y(), svPosVel.x[2]-Rx.Z())/ellipsoid.c(); double wt = ellipsoid.angVelocity()*tof; double sx = ::cos(wt)*svPosVel.x[0] + ::sin(wt)*svPosVel.x[1]; double sy = -::sin(wt)*svPosVel.x[0] + ::cos(wt)*svPosVel.x[1]; svPosVel.x[0] = sx; svPosVel.x[1] = sy; sx = ::cos(wt)*svPosVel.v[0] + ::sin(wt)*svPosVel.v[1]; sy = -::sin(wt)*svPosVel.v[0] + ::cos(wt)*svPosVel.v[1]; svPosVel.v[0] = sx; svPosVel.v[1] = sy; } double RelativityCorrection(const Xvt& svPosVel) { // relativity correction // dtr = -2*dot(R,V)/(c*c) = -4.4428e-10(s/sqrt(m)) * ecc * sqrt(A(m)) * sinE // compute it separately here, in units seconds. double dtr = ( -2.0 *( svPosVel.x[0] * svPosVel.v[0] + svPosVel.x[1] * svPosVel.v[1] + svPosVel.x[2] * svPosVel.v[2] ) / C_MPS ) / C_MPS; return dtr; } } // namespace gpstk
33.43295
84
0.578157
mfkiwl
a0c9490eb5ffbd3024b4491dda6703d2d72a8d27
1,750
cpp
C++
code/3rdParty/ogdf/src/ogdf/lib/abacus/row.cpp
turbanoff/qvge
53508adadb4ca566c011b2b41d432030a5fa5fac
[ "MIT" ]
3
2021-09-14T08:11:37.000Z
2022-03-04T15:42:07.000Z
code/3rdParty/ogdf/src/ogdf/lib/abacus/row.cpp
turbanoff/qvge
53508adadb4ca566c011b2b41d432030a5fa5fac
[ "MIT" ]
2
2021-12-04T17:09:53.000Z
2021-12-16T08:57:25.000Z
code/3rdParty/ogdf/src/ogdf/lib/abacus/row.cpp
turbanoff/qvge
53508adadb4ca566c011b2b41d432030a5fa5fac
[ "MIT" ]
2
2021-06-22T08:21:54.000Z
2021-07-07T06:57:22.000Z
/*!\file * \author Matthias Elf * * \par License: * This file is part of ABACUS - A Branch And CUt System * Copyright (C) 1995 - 2003 * University of Cologne, Germany * * \par * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * \par * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * \par * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * \see http://www.gnu.org/copyleft/gpl.html */ #include <ogdf/lib/abacus/row.h> namespace abacus { std::ostream &operator<<(std::ostream& out, const Row &rhs) { double eps = rhs.glob_->machineEps(); const int rhsNnz = rhs.nnz(); for (int i = 0; i < rhsNnz; i++) { int s = rhs.support(i); double c = rhs.coeff(i); char sign; if (c < 0.0) { sign = '-'; c = -c; } else sign = '+'; if (i > 0 || sign == '-') // do not print first \a '+' of row out << sign << ' '; if (c < 1.0 - eps || 1.0 + eps < c) // do not print coefficient 1 out << c << ' '; out << 'x' << s << ' '; if (i && !(i % 10)) out << std::endl; } return out << rhs.sense_ << ' ' << rhs.rhs(); } void Row::copy(const Row &row) { sense_ = row.sense_; rhs_ = row.rhs_; SparVec::copy(row); } }
24.647887
76
0.627429
turbanoff
a0cca9a4ea3564c21c01f31d5a2b3beed2a53c10
626
cpp
C++
lab1/Zad6/main.cpp
fgulan/ooup-fer
f5df4ba2ab55e52c7475089b4f71c0e244e88162
[ "MIT" ]
null
null
null
lab1/Zad6/main.cpp
fgulan/ooup-fer
f5df4ba2ab55e52c7475089b4f71c0e244e88162
[ "MIT" ]
null
null
null
lab1/Zad6/main.cpp
fgulan/ooup-fer
f5df4ba2ab55e52c7475089b4f71c0e244e88162
[ "MIT" ]
null
null
null
// // main.cpp // Zad6 // // Created by Filip Gulan on 31/03/16. // Copyright © 2016 FIlip Gulan. All rights reserved. // #include <iostream> typedef int (*PTRFUN)(); class B { public: virtual int prva() = 0; virtual int druga() = 0; }; class D: public B { public: virtual int prva() { return 0; } virtual int druga() { return 42; } }; int main(int argc, const char * argv[]) { D *obj = new D(); size_t *vTable = *(size_t**)obj; int prva = ((PTRFUN) vTable[0])(); int druga = ((PTRFUN) vTable[1])(); printf("Prva: %d\nDruga: %d\n", prva, druga); }
14.904762
54
0.543131
fgulan
a0d1966a5f0f687659b75e2e06f569152b0a7a11
1,748
cpp
C++
leetcode99.cpp
SJTUGavinLiu/Leetcodes
99d4010bc34e78d22e3c8b6436e4489a7d1338da
[ "MIT" ]
null
null
null
leetcode99.cpp
SJTUGavinLiu/Leetcodes
99d4010bc34e78d22e3c8b6436e4489a7d1338da
[ "MIT" ]
null
null
null
leetcode99.cpp
SJTUGavinLiu/Leetcodes
99d4010bc34e78d22e3c8b6436e4489a7d1338da
[ "MIT" ]
null
null
null
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void recoverTree(TreeNode* root) { if(!root) return; stack<TreeNode*> st; vector<int> res; st.push(root); TreeNode* p = root; while(p->left) { st.push(p->left); p = p->left; } TreeNode* p1 = NULL; TreeNode* p2 = NULL; TreeNode* q; int flag = 0; int pre = 0; while(!st.empty()) { p = st.top(); st.pop(); q = p->right; while(q) { st.push(q); q = q->left; } if(!p1 && p->val > st.top()->val) { p1 = p; TreeNode* tmp = st.top(); st.pop(); q = tmp->right; while(q) { st.push(q); q = q->left; } if(st.empty() || st.top()->val > p1->val) { p2 = tmp; break; } flag = 1; pre = tmp->val; continue; } if(flag && !p2 && (st.empty() || p->val < pre)) { p2 = p; break; } pre = p->val; } int tmp = p1->val; p1->val = p2->val; p2->val = tmp; return ; } };
20.091954
59
0.306636
SJTUGavinLiu
a0d2c4eba9be4d74b5122054bc41d60203387dbe
573
cc
C++
ODWROTNO.cc
hkktr/POLSKI-SPOJ
59f7e0be99fca6532681c2ca01c8a7d97c6b5eed
[ "Unlicense" ]
1
2021-02-01T11:21:56.000Z
2021-02-01T11:21:56.000Z
ODWROTNO.cc
hkktr/POLSKI-SPOJ
59f7e0be99fca6532681c2ca01c8a7d97c6b5eed
[ "Unlicense" ]
null
null
null
ODWROTNO.cc
hkktr/POLSKI-SPOJ
59f7e0be99fca6532681c2ca01c8a7d97c6b5eed
[ "Unlicense" ]
1
2022-01-28T15:25:45.000Z
2022-01-28T15:25:45.000Z
// C++ (gcc 8.3) #include <iostream> #include <tuple> std::tuple<int, int, int> ExtendedGCD(int a, int b) { if (a == 0) return std::make_tuple(0, 1, b); int x, y, gcd; std::tie(x, y, gcd) = ExtendedGCD(b % a, a); return std::make_tuple(y - (b / a) * x, x, gcd); } int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); int t; std::cin >> t; int p, n; while (--t >= 0) { std::cin >> p >> n; int y{std::get<1>(ExtendedGCD(p, n))}; if (y < 0) y -= ((y - p + 1) / p) * p; std::cout << y << "\n"; } return 0; }
18.483871
53
0.506108
hkktr
a0d4693a070316b4f3e9c3941bbe77b0c081a6b3
40,854
cpp
C++
export/windows/obj/src/lime/utils/Assets.cpp
arturspon/zombie-killer
07848c5006916e9079537a3d703ffe3740afaa5a
[ "MIT" ]
null
null
null
export/windows/obj/src/lime/utils/Assets.cpp
arturspon/zombie-killer
07848c5006916e9079537a3d703ffe3740afaa5a
[ "MIT" ]
null
null
null
export/windows/obj/src/lime/utils/Assets.cpp
arturspon/zombie-killer
07848c5006916e9079537a3d703ffe3740afaa5a
[ "MIT" ]
1
2021-07-16T22:57:01.000Z
2021-07-16T22:57:01.000Z
// Generated by Haxe 4.0.0-rc.2+77068e10c #include <hxcpp.h> #ifndef INCLUDED_StringTools #include <StringTools.h> #endif #ifndef INCLUDED_haxe_IMap #include <haxe/IMap.h> #endif #ifndef INCLUDED_haxe_ds_StringMap #include <haxe/ds/StringMap.h> #endif #ifndef INCLUDED_haxe_io_Bytes #include <haxe/io/Bytes.h> #endif #ifndef INCLUDED_lime_app_Application #include <lime/app/Application.h> #endif #ifndef INCLUDED_lime_app_Future #include <lime/app/Future.h> #endif #ifndef INCLUDED_lime_app_IModule #include <lime/app/IModule.h> #endif #ifndef INCLUDED_lime_app_Module #include <lime/app/Module.h> #endif #ifndef INCLUDED_lime_app_Promise_lime_utils_AssetLibrary #include <lime/app/Promise_lime_utils_AssetLibrary.h> #endif #ifndef INCLUDED_lime_app__Event_Void_Void #include <lime/app/_Event_Void_Void.h> #endif #ifndef INCLUDED_lime_graphics_Image #include <lime/graphics/Image.h> #endif #ifndef INCLUDED_lime_graphics_ImageBuffer #include <lime/graphics/ImageBuffer.h> #endif #ifndef INCLUDED_lime_media_AudioBuffer #include <lime/media/AudioBuffer.h> #endif #ifndef INCLUDED_lime_text_Font #include <lime/text/Font.h> #endif #ifndef INCLUDED_lime_utils_AssetCache #include <lime/utils/AssetCache.h> #endif #ifndef INCLUDED_lime_utils_AssetLibrary #include <lime/utils/AssetLibrary.h> #endif #ifndef INCLUDED_lime_utils_AssetManifest #include <lime/utils/AssetManifest.h> #endif #ifndef INCLUDED_lime_utils_Assets #include <lime/utils/Assets.h> #endif #ifndef INCLUDED_lime_utils_Log #include <lime/utils/Log.h> #endif #ifndef INCLUDED_lime_utils_Preloader #include <lime/utils/Preloader.h> #endif HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_46_exists,"lime.utils.Assets","exists",0x1d422f71,"lime.utils.Assets.exists","lime/utils/Assets.hx",46,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_71_getAsset,"lime.utils.Assets","getAsset",0x8d49da4f,"lime.utils.Assets.getAsset","lime/utils/Assets.hx",71,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_157_getAudioBuffer,"lime.utils.Assets","getAudioBuffer",0x84c07015,"lime.utils.Assets.getAudioBuffer","lime/utils/Assets.hx",157,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_168_getBytes,"lime.utils.Assets","getBytes",0x24a878ca,"lime.utils.Assets.getBytes","lime/utils/Assets.hx",168,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_179_getFont,"lime.utils.Assets","getFont",0x6eb05e50,"lime.utils.Assets.getFont","lime/utils/Assets.hx",179,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_191_getImage,"lime.utils.Assets","getImage",0x24798fba,"lime.utils.Assets.getImage","lime/utils/Assets.hx",191,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_195_getLibrary,"lime.utils.Assets","getLibrary",0xdfc4ad1a,"lime.utils.Assets.getLibrary","lime/utils/Assets.hx",195,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_211_getPath,"lime.utils.Assets","getPath",0x7541e626,"lime.utils.Assets.getPath","lime/utils/Assets.hx",211,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_243_getText,"lime.utils.Assets","getText",0x77e9cd2e,"lime.utils.Assets.getText","lime/utils/Assets.hx",243,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_247_hasLibrary,"lime.utils.Assets","hasLibrary",0x1b170ed6,"lime.utils.Assets.hasLibrary","lime/utils/Assets.hx",247,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_257_isLocal,"lime.utils.Assets","isLocal",0x6de3bdec,"lime.utils.Assets.isLocal","lime/utils/Assets.hx",257,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_275_isValidAudio,"lime.utils.Assets","isValidAudio",0xfba1fa19,"lime.utils.Assets.isValidAudio","lime/utils/Assets.hx",275,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_282_isValidImage,"lime.utils.Assets","isValidImage",0x918aa09e,"lime.utils.Assets.isValidImage","lime/utils/Assets.hx",282,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_286_list,"lime.utils.Assets","list",0x96ec2eb3,"lime.utils.Assets.list","lime/utils/Assets.hx",286,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_303_loadAsset,"lime.utils.Assets","loadAsset",0x8c6c0f75,"lime.utils.Assets.loadAsset","lime/utils/Assets.hx",303,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_355_loadAsset,"lime.utils.Assets","loadAsset",0x8c6c0f75,"lime.utils.Assets.loadAsset","lime/utils/Assets.hx",355,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_376_loadAudioBuffer,"lime.utils.Assets","loadAudioBuffer",0xa72805bb,"lime.utils.Assets.loadAudioBuffer","lime/utils/Assets.hx",376,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_381_loadBytes,"lime.utils.Assets","loadBytes",0x23caadf0,"lime.utils.Assets.loadBytes","lime/utils/Assets.hx",381,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_386_loadFont,"lime.utils.Assets","loadFont",0xbb998fea,"lime.utils.Assets.loadFont","lime/utils/Assets.hx",386,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_391_loadImage,"lime.utils.Assets","loadImage",0x239bc4e0,"lime.utils.Assets.loadImage","lime/utils/Assets.hx",391,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_425_loadLibrary,"lime.utils.Assets","loadLibrary",0x93baf7c0,"lime.utils.Assets.loadLibrary","lime/utils/Assets.hx",425,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_446_loadLibrary,"lime.utils.Assets","loadLibrary",0x93baf7c0,"lime.utils.Assets.loadLibrary","lime/utils/Assets.hx",446,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_395_loadLibrary,"lime.utils.Assets","loadLibrary",0x93baf7c0,"lime.utils.Assets.loadLibrary","lime/utils/Assets.hx",395,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_455_loadText,"lime.utils.Assets","loadText",0xc4d2fec8,"lime.utils.Assets.loadText","lime/utils/Assets.hx",455,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_459_registerLibrary,"lime.utils.Assets","registerLibrary",0xb6301ea3,"lime.utils.Assets.registerLibrary","lime/utils/Assets.hx",459,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_481_unloadLibrary,"lime.utils.Assets","unloadLibrary",0xc816d6c7,"lime.utils.Assets.unloadLibrary","lime/utils/Assets.hx",481,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_512___cacheBreak,"lime.utils.Assets","__cacheBreak",0xe7faf592,"lime.utils.Assets.__cacheBreak","lime/utils/Assets.hx",512,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_516___libraryNotFound,"lime.utils.Assets","__libraryNotFound",0x7dfa37b5,"lime.utils.Assets.__libraryNotFound","lime/utils/Assets.hx",516,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_534_library_onChange,"lime.utils.Assets","library_onChange",0x3a89dec8,"lime.utils.Assets.library_onChange","lime/utils/Assets.hx",534,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_39_boot,"lime.utils.Assets","boot",0x90549687,"lime.utils.Assets.boot","lime/utils/Assets.hx",39,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_40_boot,"lime.utils.Assets","boot",0x90549687,"lime.utils.Assets.boot","lime/utils/Assets.hx",40,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_42_boot,"lime.utils.Assets","boot",0x90549687,"lime.utils.Assets.boot","lime/utils/Assets.hx",42,0x95055f23) HX_LOCAL_STACK_FRAME(_hx_pos_df5754140b017d9f_43_boot,"lime.utils.Assets","boot",0x90549687,"lime.utils.Assets.boot","lime/utils/Assets.hx",43,0x95055f23) namespace lime{ namespace utils{ void Assets_obj::__construct() { } Dynamic Assets_obj::__CreateEmpty() { return new Assets_obj; } void *Assets_obj::_hx_vtable = 0; Dynamic Assets_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< Assets_obj > _hx_result = new Assets_obj(); _hx_result->__construct(); return _hx_result; } bool Assets_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x2b49805f; } ::lime::utils::AssetCache Assets_obj::cache; ::lime::app::_Event_Void_Void Assets_obj::onChange; ::String Assets_obj::defaultRootPath; ::haxe::ds::StringMap Assets_obj::libraries; ::haxe::ds::StringMap Assets_obj::libraryPaths; bool Assets_obj::exists(::String id,::String type){ HX_STACKFRAME(&_hx_pos_df5754140b017d9f_46_exists) HXLINE( 48) if (hx::IsNull( type )) { HXLINE( 50) type = HX_("BINARY",01,68,8e,9f); } HXLINE( 53) ::String id1 = id; HXDLIN( 53) int colonIndex = id1.indexOf(HX_(":",3a,00,00,00),null()); HXDLIN( 53) ::String symbol_libraryName = id1.substring(0,colonIndex); HXDLIN( 53) ::String symbol_symbolName = id1.substring((colonIndex + 1),null()); HXDLIN( 53) ::lime::utils::AssetLibrary symbol_library = ::lime::utils::Assets_obj::getLibrary(symbol_libraryName); HXLINE( 55) if (hx::IsNotNull( symbol_library )) { HXLINE( 57) return symbol_library->exists(symbol_symbolName,type); } HXLINE( 61) return false; } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Assets_obj,exists,return ) ::Dynamic Assets_obj::getAsset(::String id,::String type,bool useCache){ HX_STACKFRAME(&_hx_pos_df5754140b017d9f_71_getAsset) HXLINE( 73) bool _hx_tmp; HXDLIN( 73) if (useCache) { HXLINE( 73) _hx_tmp = ::lime::utils::Assets_obj::cache->enabled; } else { HXLINE( 73) _hx_tmp = false; } HXDLIN( 73) if (_hx_tmp) { HXLINE( 75) ::String _hx_switch_0 = type; if ( (_hx_switch_0==HX_("BINARY",01,68,8e,9f)) || (_hx_switch_0==HX_("TEXT",ad,94,ba,37)) ){ HXLINE( 79) useCache = false; HXDLIN( 79) goto _hx_goto_1; } if ( (_hx_switch_0==HX_("FONT",cf,25,81,2e)) ){ HXLINE( 82) ::Dynamic font = ::lime::utils::Assets_obj::cache->font->get(id); HXLINE( 84) if (hx::IsNotNull( font )) { HXLINE( 86) return font; } HXLINE( 81) goto _hx_goto_1; } if ( (_hx_switch_0==HX_("IMAGE",3b,57,57,3b)) ){ HXLINE( 90) ::lime::graphics::Image image = ( ( ::lime::graphics::Image)(::lime::utils::Assets_obj::cache->image->get(id)) ); HXLINE( 92) if (::lime::utils::Assets_obj::isValidImage(image)) { HXLINE( 94) return image; } HXLINE( 89) goto _hx_goto_1; } if ( (_hx_switch_0==HX_("MUSIC",85,08,49,8e)) || (_hx_switch_0==HX_("SOUND",af,c4,ba,fe)) ){ HXLINE( 98) ::lime::media::AudioBuffer audio = ( ( ::lime::media::AudioBuffer)(::lime::utils::Assets_obj::cache->audio->get(id)) ); HXLINE( 100) if (::lime::utils::Assets_obj::isValidAudio(audio)) { HXLINE( 102) return audio; } HXLINE( 97) goto _hx_goto_1; } if ( (_hx_switch_0==HX_("TEMPLATE",3a,78,cd,05)) ){ HXLINE( 106) HX_STACK_DO_THROW((HX_("Not sure how to get template: ",a1,19,8c,ad) + id)); HXDLIN( 106) goto _hx_goto_1; } /* default */{ HXLINE( 109) return null(); } _hx_goto_1:; } HXLINE( 113) ::String id1 = id; HXDLIN( 113) int colonIndex = id1.indexOf(HX_(":",3a,00,00,00),null()); HXDLIN( 113) ::String symbol_libraryName = id1.substring(0,colonIndex); HXDLIN( 113) ::String symbol_symbolName = id1.substring((colonIndex + 1),null()); HXDLIN( 113) ::lime::utils::AssetLibrary symbol_library = ::lime::utils::Assets_obj::getLibrary(symbol_libraryName); HXLINE( 115) if (hx::IsNotNull( symbol_library )) { HXLINE( 117) if (symbol_library->exists(symbol_symbolName,type)) { HXLINE( 119) if (symbol_library->isLocal(symbol_symbolName,type)) { HXLINE( 121) ::Dynamic asset = symbol_library->getAsset(symbol_symbolName,type); HXLINE( 123) bool _hx_tmp1; HXDLIN( 123) if (useCache) { HXLINE( 123) _hx_tmp1 = ::lime::utils::Assets_obj::cache->enabled; } else { HXLINE( 123) _hx_tmp1 = false; } HXDLIN( 123) if (_hx_tmp1) { HXLINE( 125) ::lime::utils::Assets_obj::cache->set(id,type,asset); } HXLINE( 128) return asset; } else { HXLINE( 132) ::lime::utils::Log_obj::error((((type + HX_(" asset \"",d2,25,2a,5d)) + id) + HX_("\" exists, but only asynchronously",dc,ca,f2,dd)),hx::SourceInfo(HX_("lime/utils/Assets.hx",23,5f,05,95),132,HX_("lime.utils.Assets",39,6e,7e,b0),HX_("getAsset",7a,79,10,86))); } } else { HXLINE( 137) ::lime::utils::Log_obj::error(((((HX_("There is no ",e5,bb,ab,c5) + type) + HX_(" asset with an ID of \"",95,f2,3a,0d)) + id) + HX_("\"",22,00,00,00)),hx::SourceInfo(HX_("lime/utils/Assets.hx",23,5f,05,95),137,HX_("lime.utils.Assets",39,6e,7e,b0),HX_("getAsset",7a,79,10,86))); } } else { HXLINE( 142) ::String _hx_tmp2 = ::lime::utils::Assets_obj::_hx___libraryNotFound(symbol_libraryName); HXDLIN( 142) ::lime::utils::Log_obj::error(_hx_tmp2,hx::SourceInfo(HX_("lime/utils/Assets.hx",23,5f,05,95),142,HX_("lime.utils.Assets",39,6e,7e,b0),HX_("getAsset",7a,79,10,86))); } HXLINE( 146) return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC3(Assets_obj,getAsset,return ) ::lime::media::AudioBuffer Assets_obj::getAudioBuffer(::String id,hx::Null< bool > __o_useCache){ bool useCache = __o_useCache.Default(true); HX_STACKFRAME(&_hx_pos_df5754140b017d9f_157_getAudioBuffer) HXDLIN( 157) return ( ( ::lime::media::AudioBuffer)(::lime::utils::Assets_obj::getAsset(id,HX_("SOUND",af,c4,ba,fe),useCache)) ); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Assets_obj,getAudioBuffer,return ) ::haxe::io::Bytes Assets_obj::getBytes(::String id){ HX_STACKFRAME(&_hx_pos_df5754140b017d9f_168_getBytes) HXDLIN( 168) return ( ( ::haxe::io::Bytes)(::lime::utils::Assets_obj::getAsset(id,HX_("BINARY",01,68,8e,9f),false)) ); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Assets_obj,getBytes,return ) ::lime::text::Font Assets_obj::getFont(::String id,hx::Null< bool > __o_useCache){ bool useCache = __o_useCache.Default(true); HX_STACKFRAME(&_hx_pos_df5754140b017d9f_179_getFont) HXDLIN( 179) return ( ( ::lime::text::Font)(::lime::utils::Assets_obj::getAsset(id,HX_("FONT",cf,25,81,2e),useCache)) ); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Assets_obj,getFont,return ) ::lime::graphics::Image Assets_obj::getImage(::String id,hx::Null< bool > __o_useCache){ bool useCache = __o_useCache.Default(true); HX_STACKFRAME(&_hx_pos_df5754140b017d9f_191_getImage) HXDLIN( 191) return ( ( ::lime::graphics::Image)(::lime::utils::Assets_obj::getAsset(id,HX_("IMAGE",3b,57,57,3b),useCache)) ); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Assets_obj,getImage,return ) ::lime::utils::AssetLibrary Assets_obj::getLibrary(::String name){ HX_STACKFRAME(&_hx_pos_df5754140b017d9f_195_getLibrary) HXLINE( 196) bool _hx_tmp; HXDLIN( 196) if (hx::IsNotNull( name )) { HXLINE( 196) _hx_tmp = (name == HX_("",00,00,00,00)); } else { HXLINE( 196) _hx_tmp = true; } HXDLIN( 196) if (_hx_tmp) { HXLINE( 198) name = HX_("default",c1,d8,c3,9b); } HXLINE( 201) return ( ( ::lime::utils::AssetLibrary)(::lime::utils::Assets_obj::libraries->get(name)) ); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Assets_obj,getLibrary,return ) ::String Assets_obj::getPath(::String id){ HX_STACKFRAME(&_hx_pos_df5754140b017d9f_211_getPath) HXLINE( 213) ::String id1 = id; HXDLIN( 213) int colonIndex = id1.indexOf(HX_(":",3a,00,00,00),null()); HXDLIN( 213) ::String symbol_libraryName = id1.substring(0,colonIndex); HXDLIN( 213) ::String symbol_symbolName = id1.substring((colonIndex + 1),null()); HXDLIN( 213) ::lime::utils::AssetLibrary symbol_library = ::lime::utils::Assets_obj::getLibrary(symbol_libraryName); HXLINE( 215) if (hx::IsNotNull( symbol_library )) { HXLINE( 217) if (symbol_library->exists(symbol_symbolName,null())) { HXLINE( 219) return symbol_library->getPath(symbol_symbolName); } else { HXLINE( 223) ::lime::utils::Log_obj::error(((HX_("There is no asset with an ID of \"",b0,92,42,96) + id) + HX_("\"",22,00,00,00)),hx::SourceInfo(HX_("lime/utils/Assets.hx",23,5f,05,95),223,HX_("lime.utils.Assets",39,6e,7e,b0),HX_("getPath",5b,95,d4,1c))); } } else { HXLINE( 228) ::String _hx_tmp = ::lime::utils::Assets_obj::_hx___libraryNotFound(symbol_libraryName); HXDLIN( 228) ::lime::utils::Log_obj::error(_hx_tmp,hx::SourceInfo(HX_("lime/utils/Assets.hx",23,5f,05,95),228,HX_("lime.utils.Assets",39,6e,7e,b0),HX_("getPath",5b,95,d4,1c))); } HXLINE( 232) return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Assets_obj,getPath,return ) ::String Assets_obj::getText(::String id){ HX_STACKFRAME(&_hx_pos_df5754140b017d9f_243_getText) HXDLIN( 243) return ( (::String)(::lime::utils::Assets_obj::getAsset(id,HX_("TEXT",ad,94,ba,37),false)) ); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Assets_obj,getText,return ) bool Assets_obj::hasLibrary(::String name){ HX_STACKFRAME(&_hx_pos_df5754140b017d9f_247_hasLibrary) HXLINE( 248) bool _hx_tmp; HXDLIN( 248) if (hx::IsNotNull( name )) { HXLINE( 248) _hx_tmp = (name == HX_("",00,00,00,00)); } else { HXLINE( 248) _hx_tmp = true; } HXDLIN( 248) if (_hx_tmp) { HXLINE( 250) name = HX_("default",c1,d8,c3,9b); } HXLINE( 253) return ::lime::utils::Assets_obj::libraries->exists(name); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Assets_obj,hasLibrary,return ) bool Assets_obj::isLocal(::String id,::String type,hx::Null< bool > __o_useCache){ bool useCache = __o_useCache.Default(true); HX_STACKFRAME(&_hx_pos_df5754140b017d9f_257_isLocal) HXLINE( 259) bool _hx_tmp; HXDLIN( 259) if (useCache) { HXLINE( 259) _hx_tmp = ::lime::utils::Assets_obj::cache->enabled; } else { HXLINE( 259) _hx_tmp = false; } HXDLIN( 259) if (_hx_tmp) { HXLINE( 261) if (::lime::utils::Assets_obj::cache->exists(id,type)) { HXLINE( 261) return true; } } HXLINE( 264) ::String id1 = id; HXDLIN( 264) int colonIndex = id1.indexOf(HX_(":",3a,00,00,00),null()); HXDLIN( 264) ::String symbol_libraryName = id1.substring(0,colonIndex); HXDLIN( 264) ::String symbol_symbolName = id1.substring((colonIndex + 1),null()); HXDLIN( 264) ::lime::utils::AssetLibrary symbol_library = ::lime::utils::Assets_obj::getLibrary(symbol_libraryName); HXLINE( 265) if (hx::IsNotNull( symbol_library )) { HXLINE( 265) return symbol_library->isLocal(symbol_symbolName,type); } else { HXLINE( 265) return false; } HXDLIN( 265) return false; } STATIC_HX_DEFINE_DYNAMIC_FUNC3(Assets_obj,isLocal,return ) bool Assets_obj::isValidAudio( ::lime::media::AudioBuffer buffer){ HX_STACKFRAME(&_hx_pos_df5754140b017d9f_275_isValidAudio) HXDLIN( 275) return hx::IsNotNull( buffer ); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Assets_obj,isValidAudio,return ) bool Assets_obj::isValidImage( ::lime::graphics::Image image){ HX_STACKFRAME(&_hx_pos_df5754140b017d9f_282_isValidImage) HXDLIN( 282) if (hx::IsNotNull( image )) { HXDLIN( 282) return hx::IsNotNull( image->buffer ); } else { HXDLIN( 282) return false; } HXDLIN( 282) return false; } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Assets_obj,isValidImage,return ) ::Array< ::String > Assets_obj::list(::String type){ HX_STACKFRAME(&_hx_pos_df5754140b017d9f_286_list) HXLINE( 287) ::Array< ::String > items = ::Array_obj< ::String >::__new(0); HXLINE( 289) { HXLINE( 289) ::Dynamic library = ::lime::utils::Assets_obj::libraries->iterator(); HXDLIN( 289) while(( (bool)(library->__Field(HX_("hasNext",6d,a5,46,18),hx::paccDynamic)()) )){ HXLINE( 289) ::lime::utils::AssetLibrary library1 = ( ( ::lime::utils::AssetLibrary)(library->__Field(HX_("next",f3,84,02,49),hx::paccDynamic)()) ); HXLINE( 291) ::Array< ::String > libraryItems = library1->list(type); HXLINE( 293) if (hx::IsNotNull( libraryItems )) { HXLINE( 295) items = items->concat(libraryItems); } } } HXLINE( 299) return items; } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Assets_obj,list,return ) ::lime::app::Future Assets_obj::loadAsset(::String id,::String type,bool useCache){ HX_STACKFRAME(&_hx_pos_df5754140b017d9f_303_loadAsset) HXLINE( 305) bool _hx_tmp; HXDLIN( 305) if (useCache) { HXLINE( 305) _hx_tmp = ::lime::utils::Assets_obj::cache->enabled; } else { HXLINE( 305) _hx_tmp = false; } HXDLIN( 305) if (_hx_tmp) { HXLINE( 307) ::String _hx_switch_0 = type; if ( (_hx_switch_0==HX_("BINARY",01,68,8e,9f)) || (_hx_switch_0==HX_("TEXT",ad,94,ba,37)) ){ HXLINE( 311) useCache = false; HXDLIN( 311) goto _hx_goto_16; } if ( (_hx_switch_0==HX_("FONT",cf,25,81,2e)) ){ HXLINE( 314) ::Dynamic font = ::lime::utils::Assets_obj::cache->font->get(id); HXLINE( 316) if (hx::IsNotNull( font )) { HXLINE( 318) return ::lime::app::Future_obj::withValue(font); } HXLINE( 313) goto _hx_goto_16; } if ( (_hx_switch_0==HX_("IMAGE",3b,57,57,3b)) ){ HXLINE( 322) ::lime::graphics::Image image = ( ( ::lime::graphics::Image)(::lime::utils::Assets_obj::cache->image->get(id)) ); HXLINE( 324) if (::lime::utils::Assets_obj::isValidImage(image)) { HXLINE( 326) return ::lime::app::Future_obj::withValue(image); } HXLINE( 321) goto _hx_goto_16; } if ( (_hx_switch_0==HX_("MUSIC",85,08,49,8e)) || (_hx_switch_0==HX_("SOUND",af,c4,ba,fe)) ){ HXLINE( 330) ::lime::media::AudioBuffer audio = ( ( ::lime::media::AudioBuffer)(::lime::utils::Assets_obj::cache->audio->get(id)) ); HXLINE( 332) if (::lime::utils::Assets_obj::isValidAudio(audio)) { HXLINE( 334) return ::lime::app::Future_obj::withValue(audio); } HXLINE( 329) goto _hx_goto_16; } if ( (_hx_switch_0==HX_("TEMPLATE",3a,78,cd,05)) ){ HXLINE( 338) HX_STACK_DO_THROW((HX_("Not sure how to get template: ",a1,19,8c,ad) + id)); HXDLIN( 338) goto _hx_goto_16; } /* default */{ HXLINE( 341) return null(); } _hx_goto_16:; } HXLINE( 345) ::String id1 = id; HXDLIN( 345) int colonIndex = id1.indexOf(HX_(":",3a,00,00,00),null()); HXDLIN( 345) ::String symbol_libraryName = id1.substring(0,colonIndex); HXDLIN( 345) ::String symbol_symbolName = id1.substring((colonIndex + 1),null()); HXDLIN( 345) ::lime::utils::AssetLibrary symbol_library = ::lime::utils::Assets_obj::getLibrary(symbol_libraryName); HXLINE( 347) if (hx::IsNotNull( symbol_library )) { HXLINE( 349) if (symbol_library->exists(symbol_symbolName,type)) { HXLINE( 351) ::lime::app::Future future = symbol_library->loadAsset(symbol_symbolName,type); HXLINE( 353) bool _hx_tmp1; HXDLIN( 353) if (useCache) { HXLINE( 353) _hx_tmp1 = ::lime::utils::Assets_obj::cache->enabled; } else { HXLINE( 353) _hx_tmp1 = false; } HXDLIN( 353) if (_hx_tmp1) { HX_BEGIN_LOCAL_FUNC_S2(hx::LocalFunc,_hx_Closure_0,::String,id,::String,type) HXARGC(1) void _hx_run( ::Dynamic asset){ HX_STACKFRAME(&_hx_pos_df5754140b017d9f_355_loadAsset) HXLINE( 355) ::lime::utils::Assets_obj::cache->set(id,type,asset); } HX_END_LOCAL_FUNC1((void)) HXLINE( 355) future->onComplete( ::Dynamic(new _hx_Closure_0(id,type))); } HXLINE( 358) return future; } else { HXLINE( 362) return ::lime::app::Future_obj::withError(((((HX_("There is no ",e5,bb,ab,c5) + type) + HX_(" asset with an ID of \"",95,f2,3a,0d)) + id) + HX_("\"",22,00,00,00))); } } else { HXLINE( 367) return ::lime::app::Future_obj::withError(::lime::utils::Assets_obj::_hx___libraryNotFound(symbol_libraryName)); } HXLINE( 347) return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC3(Assets_obj,loadAsset,return ) ::lime::app::Future Assets_obj::loadAudioBuffer(::String id,hx::Null< bool > __o_useCache){ bool useCache = __o_useCache.Default(true); HX_STACKFRAME(&_hx_pos_df5754140b017d9f_376_loadAudioBuffer) HXDLIN( 376) return ::lime::utils::Assets_obj::loadAsset(id,HX_("SOUND",af,c4,ba,fe),useCache); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Assets_obj,loadAudioBuffer,return ) ::lime::app::Future Assets_obj::loadBytes(::String id){ HX_STACKFRAME(&_hx_pos_df5754140b017d9f_381_loadBytes) HXDLIN( 381) return ::lime::utils::Assets_obj::loadAsset(id,HX_("BINARY",01,68,8e,9f),false); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Assets_obj,loadBytes,return ) ::lime::app::Future Assets_obj::loadFont(::String id,hx::Null< bool > __o_useCache){ bool useCache = __o_useCache.Default(true); HX_STACKFRAME(&_hx_pos_df5754140b017d9f_386_loadFont) HXDLIN( 386) return ::lime::utils::Assets_obj::loadAsset(id,HX_("FONT",cf,25,81,2e),useCache); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Assets_obj,loadFont,return ) ::lime::app::Future Assets_obj::loadImage(::String id,hx::Null< bool > __o_useCache){ bool useCache = __o_useCache.Default(true); HX_STACKFRAME(&_hx_pos_df5754140b017d9f_391_loadImage) HXDLIN( 391) return ::lime::utils::Assets_obj::loadAsset(id,HX_("IMAGE",3b,57,57,3b),useCache); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Assets_obj,loadImage,return ) ::lime::app::Future Assets_obj::loadLibrary(::String id){ HX_BEGIN_LOCAL_FUNC_S2(hx::LocalFunc,_hx_Closure_0,::String,id, ::lime::app::Promise_lime_utils_AssetLibrary,promise) HXARGC(1) void _hx_run( ::lime::utils::AssetManifest manifest){ HX_GC_STACKFRAME(&_hx_pos_df5754140b017d9f_425_loadLibrary) HXLINE( 426) if (hx::IsNull( manifest )) { HXLINE( 428) promise->error(((HX_("Cannot parse asset manifest for library \"",cf,1e,cc,48) + id) + HX_("\"",22,00,00,00))); HXLINE( 429) return; } HXLINE( 432) ::lime::utils::AssetLibrary library1 = ::lime::utils::AssetLibrary_obj::fromManifest(manifest); HXLINE( 434) if (hx::IsNull( library1 )) { HXLINE( 436) promise->error(((HX_("Cannot open library \"",44,cc,55,e7) + id) + HX_("\"",22,00,00,00))); } else { HXLINE( 440) ::lime::utils::Assets_obj::libraries->set(id,library1); HXLINE( 441) library1->onChange->add(::lime::utils::Assets_obj::onChange->dispatch_dyn(),null(),null()); HXLINE( 442) ::lime::app::Future _hx_tmp = library1->load(); HXDLIN( 442) promise->completeWith(_hx_tmp); } } HX_END_LOCAL_FUNC1((void)) HX_BEGIN_LOCAL_FUNC_S2(hx::LocalFunc,_hx_Closure_1,::String,id, ::lime::app::Promise_lime_utils_AssetLibrary,promise) HXARGC(1) void _hx_run( ::Dynamic _){ HX_GC_STACKFRAME(&_hx_pos_df5754140b017d9f_446_loadLibrary) HXLINE( 446) promise->error(((HX_("There is no asset library with an ID of \"",8b,06,e2,9a) + id) + HX_("\"",22,00,00,00))); } HX_END_LOCAL_FUNC1((void)) HX_GC_STACKFRAME(&_hx_pos_df5754140b017d9f_395_loadLibrary) HXLINE( 396) ::lime::app::Promise_lime_utils_AssetLibrary promise = ::lime::app::Promise_lime_utils_AssetLibrary_obj::__alloc( HX_CTX ); HXLINE( 399) ::lime::utils::AssetLibrary library = ::lime::utils::Assets_obj::getLibrary(id); HXLINE( 401) if (hx::IsNotNull( library )) { HXLINE( 403) return library->load(); } HXLINE( 406) ::String path = id; HXLINE( 407) ::String rootPath = null(); HXLINE( 409) if (::lime::utils::Assets_obj::libraryPaths->exists(id)) { HXLINE( 411) path = ::lime::utils::Assets_obj::libraryPaths->get_string(id); HXLINE( 412) rootPath = ::lime::utils::Assets_obj::defaultRootPath; } else { HXLINE( 416) if (::StringTools_obj::endsWith(path,HX_(".bundle",30,4a,b8,4e))) { HXLINE( 418) path = (path + HX_("/library.json",2a,a7,07,47)); } HXLINE( 421) path = ::lime::utils::Assets_obj::_hx___cacheBreak(path); } HXLINE( 424) ::lime::utils::AssetManifest_obj::loadFromFile(path,rootPath)->onComplete( ::Dynamic(new _hx_Closure_0(id,promise)))->onError( ::Dynamic(new _hx_Closure_1(id,promise))); HXLINE( 450) return promise->future; } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Assets_obj,loadLibrary,return ) ::lime::app::Future Assets_obj::loadText(::String id){ HX_STACKFRAME(&_hx_pos_df5754140b017d9f_455_loadText) HXDLIN( 455) return ::lime::utils::Assets_obj::loadAsset(id,HX_("TEXT",ad,94,ba,37),false); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Assets_obj,loadText,return ) void Assets_obj::registerLibrary(::String name, ::lime::utils::AssetLibrary library){ HX_STACKFRAME(&_hx_pos_df5754140b017d9f_459_registerLibrary) HXLINE( 460) if (::lime::utils::Assets_obj::libraries->exists(name)) { HXLINE( 462) if (hx::IsEq( ::lime::utils::Assets_obj::libraries->get(name),library )) { HXLINE( 464) return; } else { HXLINE( 468) ::lime::utils::Assets_obj::unloadLibrary(name); } } HXLINE( 472) if (hx::IsNotNull( library )) { HXLINE( 474) library->onChange->add(::lime::utils::Assets_obj::library_onChange_dyn(),null(),null()); } HXLINE( 477) ::lime::utils::Assets_obj::libraries->set(name,library); } STATIC_HX_DEFINE_DYNAMIC_FUNC2(Assets_obj,registerLibrary,(void)) void Assets_obj::unloadLibrary(::String name){ HX_STACKFRAME(&_hx_pos_df5754140b017d9f_481_unloadLibrary) HXLINE( 483) ::lime::utils::AssetLibrary library = ( ( ::lime::utils::AssetLibrary)(::lime::utils::Assets_obj::libraries->get(name)) ); HXLINE( 485) if (hx::IsNotNull( library )) { HXLINE( 487) ::lime::utils::Assets_obj::cache->clear((name + HX_(":",3a,00,00,00))); HXLINE( 488) library->onChange->remove(::lime::utils::Assets_obj::library_onChange_dyn()); HXLINE( 489) library->unload(); } HXLINE( 492) ::lime::utils::Assets_obj::libraries->remove(name); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Assets_obj,unloadLibrary,(void)) ::String Assets_obj::_hx___cacheBreak(::String path){ HX_STACKFRAME(&_hx_pos_df5754140b017d9f_512___cacheBreak) HXDLIN( 512) return path; } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Assets_obj,_hx___cacheBreak,return ) ::String Assets_obj::_hx___libraryNotFound(::String name){ HX_STACKFRAME(&_hx_pos_df5754140b017d9f_516___libraryNotFound) HXLINE( 517) bool _hx_tmp; HXDLIN( 517) if (hx::IsNotNull( name )) { HXLINE( 517) _hx_tmp = (name == HX_("",00,00,00,00)); } else { HXLINE( 517) _hx_tmp = true; } HXDLIN( 517) if (_hx_tmp) { HXLINE( 519) name = HX_("default",c1,d8,c3,9b); } HXLINE( 522) bool _hx_tmp1; HXDLIN( 522) bool _hx_tmp2; HXDLIN( 522) if (hx::IsNotNull( ::lime::app::Application_obj::current )) { HXLINE( 522) _hx_tmp2 = hx::IsNotNull( ::lime::app::Application_obj::current->_hx___preloader ); } else { HXLINE( 522) _hx_tmp2 = false; } HXDLIN( 522) if (_hx_tmp2) { HXLINE( 522) _hx_tmp1 = !(::lime::app::Application_obj::current->_hx___preloader->complete); } else { HXLINE( 522) _hx_tmp1 = false; } HXDLIN( 522) if (_hx_tmp1) { HXLINE( 524) return ((HX_("There is no asset library named \"",a1,83,5f,51) + name) + HX_("\", or it is not yet preloaded",db,ac,d4,2f)); } else { HXLINE( 528) return ((HX_("There is no asset library named \"",a1,83,5f,51) + name) + HX_("\"",22,00,00,00)); } HXLINE( 522) return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Assets_obj,_hx___libraryNotFound,return ) void Assets_obj::library_onChange(){ HX_STACKFRAME(&_hx_pos_df5754140b017d9f_534_library_onChange) HXLINE( 535) ::lime::utils::Assets_obj::cache->clear(null()); HXLINE( 536) ::lime::utils::Assets_obj::onChange->dispatch(); } STATIC_HX_DEFINE_DYNAMIC_FUNC0(Assets_obj,library_onChange,(void)) Assets_obj::Assets_obj() { } bool Assets_obj::__GetStatic(const ::String &inName, Dynamic &outValue, hx::PropertyAccess inCallProp) { switch(inName.length) { case 4: if (HX_FIELD_EQ(inName,"list") ) { outValue = list_dyn(); return true; } break; case 5: if (HX_FIELD_EQ(inName,"cache") ) { outValue = ( cache ); return true; } break; case 6: if (HX_FIELD_EQ(inName,"exists") ) { outValue = exists_dyn(); return true; } break; case 7: if (HX_FIELD_EQ(inName,"getFont") ) { outValue = getFont_dyn(); return true; } if (HX_FIELD_EQ(inName,"getPath") ) { outValue = getPath_dyn(); return true; } if (HX_FIELD_EQ(inName,"getText") ) { outValue = getText_dyn(); return true; } if (HX_FIELD_EQ(inName,"isLocal") ) { outValue = isLocal_dyn(); return true; } break; case 8: if (HX_FIELD_EQ(inName,"onChange") ) { outValue = ( onChange ); return true; } if (HX_FIELD_EQ(inName,"getAsset") ) { outValue = getAsset_dyn(); return true; } if (HX_FIELD_EQ(inName,"getBytes") ) { outValue = getBytes_dyn(); return true; } if (HX_FIELD_EQ(inName,"getImage") ) { outValue = getImage_dyn(); return true; } if (HX_FIELD_EQ(inName,"loadFont") ) { outValue = loadFont_dyn(); return true; } if (HX_FIELD_EQ(inName,"loadText") ) { outValue = loadText_dyn(); return true; } break; case 9: if (HX_FIELD_EQ(inName,"libraries") ) { outValue = ( libraries ); return true; } if (HX_FIELD_EQ(inName,"loadAsset") ) { outValue = loadAsset_dyn(); return true; } if (HX_FIELD_EQ(inName,"loadBytes") ) { outValue = loadBytes_dyn(); return true; } if (HX_FIELD_EQ(inName,"loadImage") ) { outValue = loadImage_dyn(); return true; } break; case 10: if (HX_FIELD_EQ(inName,"getLibrary") ) { outValue = getLibrary_dyn(); return true; } if (HX_FIELD_EQ(inName,"hasLibrary") ) { outValue = hasLibrary_dyn(); return true; } break; case 11: if (HX_FIELD_EQ(inName,"loadLibrary") ) { outValue = loadLibrary_dyn(); return true; } break; case 12: if (HX_FIELD_EQ(inName,"libraryPaths") ) { outValue = ( libraryPaths ); return true; } if (HX_FIELD_EQ(inName,"isValidAudio") ) { outValue = isValidAudio_dyn(); return true; } if (HX_FIELD_EQ(inName,"isValidImage") ) { outValue = isValidImage_dyn(); return true; } if (HX_FIELD_EQ(inName,"__cacheBreak") ) { outValue = _hx___cacheBreak_dyn(); return true; } break; case 13: if (HX_FIELD_EQ(inName,"unloadLibrary") ) { outValue = unloadLibrary_dyn(); return true; } break; case 14: if (HX_FIELD_EQ(inName,"getAudioBuffer") ) { outValue = getAudioBuffer_dyn(); return true; } break; case 15: if (HX_FIELD_EQ(inName,"defaultRootPath") ) { outValue = ( defaultRootPath ); return true; } if (HX_FIELD_EQ(inName,"loadAudioBuffer") ) { outValue = loadAudioBuffer_dyn(); return true; } if (HX_FIELD_EQ(inName,"registerLibrary") ) { outValue = registerLibrary_dyn(); return true; } break; case 16: if (HX_FIELD_EQ(inName,"library_onChange") ) { outValue = library_onChange_dyn(); return true; } break; case 17: if (HX_FIELD_EQ(inName,"__libraryNotFound") ) { outValue = _hx___libraryNotFound_dyn(); return true; } } return false; } bool Assets_obj::__SetStatic(const ::String &inName,Dynamic &ioValue,hx::PropertyAccess inCallProp) { switch(inName.length) { case 5: if (HX_FIELD_EQ(inName,"cache") ) { cache=ioValue.Cast< ::lime::utils::AssetCache >(); return true; } break; case 8: if (HX_FIELD_EQ(inName,"onChange") ) { onChange=ioValue.Cast< ::lime::app::_Event_Void_Void >(); return true; } break; case 9: if (HX_FIELD_EQ(inName,"libraries") ) { libraries=ioValue.Cast< ::haxe::ds::StringMap >(); return true; } break; case 12: if (HX_FIELD_EQ(inName,"libraryPaths") ) { libraryPaths=ioValue.Cast< ::haxe::ds::StringMap >(); return true; } break; case 15: if (HX_FIELD_EQ(inName,"defaultRootPath") ) { defaultRootPath=ioValue.Cast< ::String >(); return true; } } return false; } #ifdef HXCPP_SCRIPTABLE static hx::StorageInfo *Assets_obj_sMemberStorageInfo = 0; static hx::StaticInfo Assets_obj_sStaticStorageInfo[] = { {hx::fsObject /* ::lime::utils::AssetCache */ ,(void *) &Assets_obj::cache,HX_("cache",42,9a,14,41)}, {hx::fsObject /* ::lime::app::_Event_Void_Void */ ,(void *) &Assets_obj::onChange,HX_("onChange",ef,87,1f,97)}, {hx::fsString,(void *) &Assets_obj::defaultRootPath,HX_("defaultRootPath",c8,76,96,0a)}, {hx::fsObject /* ::haxe::ds::StringMap */ ,(void *) &Assets_obj::libraries,HX_("libraries",19,50,f8,18)}, {hx::fsObject /* ::haxe::ds::StringMap */ ,(void *) &Assets_obj::libraryPaths,HX_("libraryPaths",33,26,5e,06)}, { hx::fsUnknown, 0, null()} }; #endif static void Assets_obj_sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(Assets_obj::cache,"cache"); HX_MARK_MEMBER_NAME(Assets_obj::onChange,"onChange"); HX_MARK_MEMBER_NAME(Assets_obj::defaultRootPath,"defaultRootPath"); HX_MARK_MEMBER_NAME(Assets_obj::libraries,"libraries"); HX_MARK_MEMBER_NAME(Assets_obj::libraryPaths,"libraryPaths"); }; #ifdef HXCPP_VISIT_ALLOCS static void Assets_obj_sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(Assets_obj::cache,"cache"); HX_VISIT_MEMBER_NAME(Assets_obj::onChange,"onChange"); HX_VISIT_MEMBER_NAME(Assets_obj::defaultRootPath,"defaultRootPath"); HX_VISIT_MEMBER_NAME(Assets_obj::libraries,"libraries"); HX_VISIT_MEMBER_NAME(Assets_obj::libraryPaths,"libraryPaths"); }; #endif hx::Class Assets_obj::__mClass; static ::String Assets_obj_sStaticFields[] = { HX_("cache",42,9a,14,41), HX_("onChange",ef,87,1f,97), HX_("defaultRootPath",c8,76,96,0a), HX_("libraries",19,50,f8,18), HX_("libraryPaths",33,26,5e,06), HX_("exists",dc,1d,e0,bf), HX_("getAsset",7a,79,10,86), HX_("getAudioBuffer",80,41,e3,26), HX_("getBytes",f5,17,6f,1d), HX_("getFont",85,0d,43,16), HX_("getImage",e5,2e,40,1d), HX_("getLibrary",05,ad,d1,8e), HX_("getPath",5b,95,d4,1c), HX_("getText",63,7c,7c,1f), HX_("hasLibrary",c1,0e,24,ca), HX_("isLocal",21,6d,76,15), HX_("isValidAudio",c4,0a,df,47), HX_("isValidImage",49,b1,c7,dd), HX_("list",5e,1c,b3,47), HX_("loadAsset",ea,b5,70,41), HX_("loadAudioBuffer",f0,71,7c,e3), HX_("loadBytes",65,54,cf,d8), HX_("loadFont",15,2f,60,b4), HX_("loadImage",55,6b,a0,d8), HX_("loadLibrary",75,e5,0d,10), HX_("loadText",f3,9d,99,bd), HX_("registerLibrary",d8,8a,84,f2), HX_("unloadLibrary",bc,5b,48,31), HX_("__cacheBreak",3d,06,38,34), HX_("__libraryNotFound",2a,db,69,c9), HX_("library_onChange",f3,20,14,c8), ::String(null()) }; void Assets_obj::__register() { Assets_obj _hx_dummy; Assets_obj::_hx_vtable = *(void **)&_hx_dummy; hx::Static(__mClass) = new hx::Class_obj(); __mClass->mName = HX_("lime.utils.Assets",39,6e,7e,b0); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &Assets_obj::__GetStatic; __mClass->mSetStaticField = &Assets_obj::__SetStatic; __mClass->mMarkFunc = Assets_obj_sMarkStatics; __mClass->mStatics = hx::Class_obj::dupFunctions(Assets_obj_sStaticFields); __mClass->mMembers = hx::Class_obj::dupFunctions(0 /* sMemberFields */); __mClass->mCanCast = hx::TCanCast< Assets_obj >; #ifdef HXCPP_VISIT_ALLOCS __mClass->mVisitFunc = Assets_obj_sVisitStatics; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = Assets_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = Assets_obj_sStaticStorageInfo; #endif hx::_hx_RegisterClass(__mClass->mName, __mClass); } void Assets_obj::__boot() { { HX_GC_STACKFRAME(&_hx_pos_df5754140b017d9f_39_boot) HXDLIN( 39) cache = ::lime::utils::AssetCache_obj::__alloc( HX_CTX ); } { HX_GC_STACKFRAME(&_hx_pos_df5754140b017d9f_40_boot) HXDLIN( 40) onChange = ::lime::app::_Event_Void_Void_obj::__alloc( HX_CTX ); } { HX_GC_STACKFRAME(&_hx_pos_df5754140b017d9f_42_boot) HXDLIN( 42) libraries = ::haxe::ds::StringMap_obj::__alloc( HX_CTX ); } { HX_GC_STACKFRAME(&_hx_pos_df5754140b017d9f_43_boot) HXDLIN( 43) libraryPaths = ::haxe::ds::StringMap_obj::__alloc( HX_CTX ); } } } // end namespace lime } // end namespace utils
46.162712
293
0.683458
arturspon
a0d65a62bac666dc32545eb97211a79dfdb76e4e
120
cpp
C++
basic/assig_array.cpp
RohanKittu/CPP_practice_repo
4dd642cf2b3ba880f40f8dbd2cb5ae062fe6f089
[ "MIT" ]
null
null
null
basic/assig_array.cpp
RohanKittu/CPP_practice_repo
4dd642cf2b3ba880f40f8dbd2cb5ae062fe6f089
[ "MIT" ]
null
null
null
basic/assig_array.cpp
RohanKittu/CPP_practice_repo
4dd642cf2b3ba880f40f8dbd2cb5ae062fe6f089
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { int arr[10] = {0}; cout<< arr[9]<<"\n"; return 0; }
10.909091
24
0.533333
RohanKittu
a0d77c396a1199ac137d1980f1a61e1ebec1f188
9,372
cxx
C++
STEER/ESD/AliESDMuonGlobalTrack.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
STEER/ESD/AliESDMuonGlobalTrack.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
STEER/ESD/AliESDMuonGlobalTrack.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ //==================================================================================================================================================== // // ESD description of an ALICE muon forward track, combining the information of the Muon Spectrometer and the Muon Forward Tracker // // Contact author: antonio.uras@cern.ch // //==================================================================================================================================================== #include "AliESDMuonGlobalTrack.h" #include "AliESDEvent.h" #include "TClonesArray.h" #include "TLorentzVector.h" #include "TMath.h" #include "TDatabasePDG.h" ClassImp(AliESDMuonGlobalTrack) //==================================================================================================================================================== AliESDMuonGlobalTrack::AliESDMuonGlobalTrack(): AliVParticle(), fCharge(0), fMatchTrigger(0), fNMFTClusters(0), fNWrongMFTClustersMC(-1), fMFTClusterPattern(0), fPx(0), fPy(0), fPz(0), fPt(0), fP(0), fEta(0), fRapidity(0), fFirstTrackingPointX(0), fFirstTrackingPointY(0), fFirstTrackingPointZ(0), fXAtVertex(0), fYAtVertex(0), fRAtAbsorberEnd(0), fCovariances(0), fChi2OverNdf(0), fChi2MatchTrigger(0), fLabel(-1), fMuonClusterMap(0), fHitsPatternInTrigCh(0), fHitsPatternInTrigChTrk(0), fLoCircuit(0), fIsConnected(kFALSE), fESDEvent(0) { // Default constructor fProdVertexXYZ[0]=0; fProdVertexXYZ[1]=0; fProdVertexXYZ[2]=0; } //==================================================================================================================================================== AliESDMuonGlobalTrack::AliESDMuonGlobalTrack(Double_t px, Double_t py, Double_t pz): AliVParticle(), fCharge(0), fMatchTrigger(0), fNMFTClusters(0), fNWrongMFTClustersMC(-1), fMFTClusterPattern(0), fPx(0), fPy(0), fPz(0), fPt(0), fP(0), fEta(0), fRapidity(0), fFirstTrackingPointX(0), fFirstTrackingPointY(0), fFirstTrackingPointZ(0), fXAtVertex(0), fYAtVertex(0), fRAtAbsorberEnd(0), fCovariances(0), fChi2OverNdf(0), fChi2MatchTrigger(0), fLabel(-1), fMuonClusterMap(0), fHitsPatternInTrigCh(0), fHitsPatternInTrigChTrk(0), fLoCircuit(0), fIsConnected(kFALSE), fESDEvent(0) { // Constructor with kinematics SetPxPyPz(px, py, pz); fProdVertexXYZ[0]=0; fProdVertexXYZ[1]=0; fProdVertexXYZ[2]=0; } //==================================================================================================================================================== AliESDMuonGlobalTrack::AliESDMuonGlobalTrack(const AliESDMuonGlobalTrack& muonTrack): AliVParticle(muonTrack), fCharge(muonTrack.fCharge), fMatchTrigger(muonTrack.fMatchTrigger), fNMFTClusters(muonTrack.fNMFTClusters), fNWrongMFTClustersMC(muonTrack.fNWrongMFTClustersMC), fMFTClusterPattern(muonTrack.fMFTClusterPattern), fPx(muonTrack.fPx), fPy(muonTrack.fPy), fPz(muonTrack.fPz), fPt(muonTrack.fPt), fP(muonTrack.fP), fEta(muonTrack.fEta), fRapidity(muonTrack.fRapidity), fFirstTrackingPointX(muonTrack.fFirstTrackingPointX), fFirstTrackingPointY(muonTrack.fFirstTrackingPointY), fFirstTrackingPointZ(muonTrack.fFirstTrackingPointZ), fXAtVertex(muonTrack.fXAtVertex), fYAtVertex(muonTrack.fYAtVertex), fRAtAbsorberEnd(muonTrack.fRAtAbsorberEnd), fCovariances(0), fChi2OverNdf(muonTrack.fChi2OverNdf), fChi2MatchTrigger(muonTrack.fChi2MatchTrigger), fLabel(muonTrack.fLabel), fMuonClusterMap(muonTrack.fMuonClusterMap), fHitsPatternInTrigCh(muonTrack.fHitsPatternInTrigCh), fHitsPatternInTrigChTrk(muonTrack.fHitsPatternInTrigChTrk), fLoCircuit(muonTrack.fLoCircuit), fIsConnected(muonTrack.fIsConnected), fESDEvent(muonTrack.fESDEvent) { // Copy constructor fProdVertexXYZ[0]=muonTrack.fProdVertexXYZ[0]; fProdVertexXYZ[1]=muonTrack.fProdVertexXYZ[1]; fProdVertexXYZ[2]=muonTrack.fProdVertexXYZ[2]; if (muonTrack.fCovariances) fCovariances = new TMatrixD(*(muonTrack.fCovariances)); } //==================================================================================================================================================== AliESDMuonGlobalTrack& AliESDMuonGlobalTrack::operator=(const AliESDMuonGlobalTrack& muonTrack) { // Assignment operator if (this == &muonTrack) return *this; // Base class assignement AliVParticle::operator=(muonTrack); fCharge = muonTrack.fCharge; fMatchTrigger = muonTrack.fMatchTrigger; fNMFTClusters = muonTrack.fNMFTClusters; fNWrongMFTClustersMC = muonTrack.fNWrongMFTClustersMC; fMFTClusterPattern = muonTrack.fMFTClusterPattern; fPx = muonTrack.fPx; fPy = muonTrack.fPy; fPz = muonTrack.fPz; fPt = muonTrack.fPt; fP = muonTrack.fP; fEta = muonTrack.fEta; fRapidity = muonTrack.fRapidity; fFirstTrackingPointX = muonTrack.fFirstTrackingPointX; fFirstTrackingPointY = muonTrack.fFirstTrackingPointY; fFirstTrackingPointZ = muonTrack.fFirstTrackingPointZ; fXAtVertex = muonTrack.fXAtVertex; fYAtVertex = muonTrack.fYAtVertex; fRAtAbsorberEnd = muonTrack.fRAtAbsorberEnd; fChi2OverNdf = muonTrack.fChi2OverNdf; fChi2MatchTrigger = muonTrack.fChi2MatchTrigger; fLabel = muonTrack.fLabel; fMuonClusterMap = muonTrack.fMuonClusterMap; fHitsPatternInTrigCh = muonTrack.fHitsPatternInTrigCh; fHitsPatternInTrigChTrk = muonTrack.fHitsPatternInTrigChTrk; fLoCircuit = muonTrack.fLoCircuit; fIsConnected = muonTrack.fIsConnected; fESDEvent = muonTrack.fESDEvent; fProdVertexXYZ[0]=muonTrack.fProdVertexXYZ[0]; fProdVertexXYZ[1]=muonTrack.fProdVertexXYZ[1]; fProdVertexXYZ[2]=muonTrack.fProdVertexXYZ[2]; if (muonTrack.fCovariances) { if (fCovariances) *fCovariances = *(muonTrack.fCovariances); else fCovariances = new TMatrixD(*(muonTrack.fCovariances)); } else { delete fCovariances; fCovariances = 0x0; } return *this; } //==================================================================================================================================================== void AliESDMuonGlobalTrack::Copy(TObject &obj) const { // This overwrites the virtual TObject::Copy() // to allow run time copying without casting // in AliESDEvent if (this==&obj) return; AliESDMuonGlobalTrack *robj = dynamic_cast<AliESDMuonGlobalTrack*>(&obj); if (!robj) return; // not an AliESDMuonGlobalTrack *robj = *this; } //==================================================================================================================================================== void AliESDMuonGlobalTrack::SetPxPyPz(Double_t px, Double_t py, Double_t pz) { Double_t mMu = TDatabasePDG::Instance()->GetParticle("mu-")->Mass(); Double_t eMu = TMath::Sqrt(mMu*mMu + px*px + py*py + pz*pz); TLorentzVector kinem(px, py, pz, eMu); fPx = kinem.Px(); fPy = kinem.Py(); fPz = kinem.Pz(); fP = kinem.P(); fPt = kinem.Pt(); fEta = kinem.Eta(); fRapidity = kinem.Rapidity(); } //==================================================================================================================================================== const TMatrixD& AliESDMuonGlobalTrack::GetCovariances() const { // Return the covariance matrix (create it before if needed) if (!fCovariances) { fCovariances = new TMatrixD(5,5); fCovariances->Zero(); } return *fCovariances; } //==================================================================================================================================================== void AliESDMuonGlobalTrack::SetCovariances(const TMatrixD& covariances) { // Set the covariance matrix if (fCovariances) *fCovariances = covariances; else fCovariances = new TMatrixD(covariances); } //====================================================================================================================================================
33.471429
150
0.55303
AllaMaevskaya
a0d8f38580b717c44c24b17cf5b2010a482272bb
2,267
cpp
C++
src/events/PusherEventListener.cpp
BlockChain-Station/enjin-cpp-sdk
3af1cd001d7e660787bbfb2e2414a96f5a95a228
[ "Apache-2.0" ]
12
2021-09-28T14:37:22.000Z
2022-03-04T17:54:11.000Z
src/events/PusherEventListener.cpp
BlockChain-Station/enjin-cpp-sdk
3af1cd001d7e660787bbfb2e2414a96f5a95a228
[ "Apache-2.0" ]
null
null
null
src/events/PusherEventListener.cpp
BlockChain-Station/enjin-cpp-sdk
3af1cd001d7e660787bbfb2e2414a96f5a95a228
[ "Apache-2.0" ]
8
2021-11-05T18:56:55.000Z
2022-01-10T11:14:24.000Z
/* Copyright 2021 Enjin Pte. Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "PusherEventListener.hpp" #include "EventTypeDef.hpp" #include <sstream> namespace enjin::sdk::events { PusherEventListener::PusherEventListener(PusherEventService* service) : service(service) { } void PusherEventListener::on_event(const pusher::PusherEvent& event) { const std::string& key = event.get_event_name().value_or(""); const std::string& channel = event.get_channel_name().value_or(""); const std::string& message = event.get_data().value_or(""); auto listeners = service->get_listeners(); auto logger = service->get_logger_provider(); // Log event received if (logger != nullptr) { std::stringstream ss; ss << "Received event " << key << " on channel " << channel << " with results " << message; logger->log(utils::LogLevel::INFO, ss.str()); } if (listeners.empty()) { if (logger != nullptr) { logger->log(utils::LogLevel::INFO, "No registered listener when event was received"); } return; } EventTypeDef def = EventTypeDef::get_from_key(key); if (def.get_type() == models::EventType::UNKNOWN) { if (logger != nullptr) { std::stringstream ss; ss << "Unknown event type for key " << def.get_key(); logger->log(utils::LogLevel::WARN, ss.str()); } return; } models::NotificationEvent notification_event(def.get_type(), channel, message); for (const auto& registration : listeners) { if (registration.get_matcher()(notification_event.get_type())) { registration.get_listener().notification_received(notification_event); } } } }
32.385714
99
0.659462
BlockChain-Station
a0da67996eacef201090cf59e4c6ac93ace5b7c4
7,297
cpp
C++
code/edmond_blossom.cpp
raynoldng/icpc_notebook
aef047bb441998411a1f89078634c93a6fa5b5c1
[ "MIT" ]
1
2021-08-10T15:08:35.000Z
2021-08-10T15:08:35.000Z
code/edmond_blossom.cpp
raynoldng/icpc_notebook
aef047bb441998411a1f89078634c93a6fa5b5c1
[ "MIT" ]
null
null
null
code/edmond_blossom.cpp
raynoldng/icpc_notebook
aef047bb441998411a1f89078634c93a6fa5b5c1
[ "MIT" ]
1
2020-10-29T01:38:59.000Z
2020-10-29T01:38:59.000Z
#include <algorithm> #include <iostream> #include <queue> #include <vector> class edmond_blossom { private: std::vector<std::vector<int>> adj_list; std::vector<int> match; std::vector<int> parent; std::vector<int> blossom_root; std::vector<bool> in_queue; std::vector<bool> in_blossom; std::queue<int> process_queue; int num_v; /// Find the lowest common ancestor between u and v. /// The specified root represents an upper bound. int get_lca(int root, int u, int v) { std::vector<bool> in_path(num_v, false); for (u = blossom_root[u]; ; u = blossom_root[parent[match[u]]]) { in_path[u] = true; if (u == root) { break; } } for (v = blossom_root[v]; ; v = blossom_root[parent[match[v]]]) { if (in_path[v]) { return v; } } } /// Mark the vertices between u and the specified lowest /// common ancestor for contraction where necessary. void mark_blossom(int lca, int u) { while (blossom_root[u] != lca) { int v = match[u]; in_blossom[blossom_root[u]] = true; in_blossom[blossom_root[v]] = true; u = parent[v]; if (blossom_root[u] != lca) { parent[u] = v; } } } /// Contract the blossom that is formed after processing /// the edge u-v. void contract_blossom(int source, int u, int v) { int lca = get_lca(source, u, v); std::fill(in_blossom.begin(), in_blossom.end(), false); mark_blossom(lca, u); mark_blossom(lca, v); if (blossom_root[u] != lca) { parent[u] = v; } if (blossom_root[v] != lca) { parent[v] = u; } for (int i = 0; i < num_v; ++i) { if (in_blossom[blossom_root[i]]) { blossom_root[i] = lca; if (!in_queue[i]) { process_queue.push(i); in_queue[i] = true; } } } } /// Return the vertex at the end of an augmenting path /// starting at the specified source, or -1 if none exist. int find_augmenting_path(int source) { for (int i = 0; i < num_v; ++i) { in_queue[i] = false; parent[i] = -1; blossom_root[i] = i; } // Empty the queue process_queue = std::queue<int>(); process_queue.push(source); in_queue[source] = true; while (!process_queue.empty()) { int u = process_queue.front(); process_queue.pop(); for (int v : adj_list[u]) { if (blossom_root[u] != blossom_root[v] && match[u] != v) { // Process if // + u-v is not an edge in the matching // && u and v are not in the same blossom (yet) if (v == source || (match[v] != -1 && parent[match[v]] != -1)) { // Contract a blossom if // + v is the source // || v is matched and v's match has a parent. // // The fact that parents are assigned to vertices // with odd distances from the source is used to // check if a cycle is odd or even. u is always an // even distance away from the source, so if v's // match is assigned a parent, you have an odd cycle. contract_blossom(source, u, v); } else if (parent[v] == -1) { parent[v] = u; if (match[v] == -1) { // v is unmatched; augmenting path found return v; } else { // Enqueue v's match. int w = match[v]; if (!in_queue[w]) { process_queue.push(w); in_queue[w] = true; } } } } } } return -1; } /// Augment the path that ends with the specified vertex /// using the parent and match fields. Returns the increase /// in the number of matchings. (i.e. 1 if the path is valid, /// 0 otherwise) int augment_path(int end) { int u = end; while (u != -1) { // Currently w===v----u int v = parent[u]; int w = match[v]; // Change to w---v===u match[v] = u; match[u] = v; u = w; } // Return 1 if the augmenting path is valid return end == -1 ? 0 : 1; } public: edmond_blossom(int v) : adj_list(v), match(v, -1), parent(v), blossom_root(v), in_queue(v), in_blossom(v), num_v(v) {} /// Add a bidirectional edge from u to v. void add_edge(int u, int v) { adj_list[u].push_back(v); adj_list[v].push_back(u); } /// Returns the maximum cardinality matching int get_max_matching() { int ans = 0; // Reset std::fill(match.begin(), match.end(), -1); for (int u = 0; u < num_v; ++u) { if (match[u] == -1) { int v = find_augmenting_path(u); if (v != -1) { // An augmenting path exists ans += augment_path(v); } } } return ans; } /// Constructs the maximum cardinality matching std::vector<std::pair<int, int>> construct_matching() { std::vector<std::pair<int, int>> output; std::vector<bool> is_processed(num_v, false); for (int u = 0; u < num_v; ++u) { if (!is_processed[u] && match[u] != -1) { output.emplace_back(u, match[u]); is_processed[u] = true; is_processed[match[u]] = true; } } return output; } }; int main() { /* 10 18 0 1 0 2 1 2 1 3 1 4 3 4 2 4 2 5 4 5 3 6 3 7 4 7 4 8 5 8 5 9 6 7 7 8 8 9 */ std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); int num_vertices; int num_edges; std::cin >> num_vertices >> num_edges; edmond_blossom eb(num_vertices); for (int i = 0; i < num_edges; ++i) { int u, v; std::cin >> u >> v; eb.add_edge(u, v); } std::cout << "Maximum Cardinality: " << eb.get_max_matching() << "\n"; std::vector<std::pair<int, int>> matching = eb.construct_matching(); for (auto& match : matching) { std::cout << match.first << " " << match.second << "\n"; } }
28.282946
85
0.438262
raynoldng
a0dbccc4e62ee5869886e15bc78814c6aa37882b
4,904
cpp
C++
editor/src/formula_editor_window.cpp
huangfeidian/formula_tree
fdb0db2c3e4503055630381e499934118d4a6036
[ "BSD-3-Clause" ]
5
2020-04-10T07:31:11.000Z
2021-11-19T04:41:58.000Z
editor/src/formula_editor_window.cpp
huangfeidian/formula_tree
fdb0db2c3e4503055630381e499934118d4a6036
[ "BSD-3-Clause" ]
null
null
null
editor/src/formula_editor_window.cpp
huangfeidian/formula_tree
fdb0db2c3e4503055630381e499934118d4a6036
[ "BSD-3-Clause" ]
null
null
null
#include <fstream> #include <streambuf> #include <qfiledialog.h> #include <tree_editor/common/dialogs/path_config_dialog.h> #include <tree_editor/common/choice_manager.h> #include <tree_editor/common/graph/tree_instance.h> #include <any_container/decode.h> #include "formula_editor_window.h" #include "formula_nodes.h" using namespace spiritsaway::tree_editor; using namespace spiritsaway::formula_tree::editor; using namespace std; std::string formula_editor_window::new_file_name() { std::string temp = fmt::format("new_formula_tree_{}.json", get_seq()); std::filesystem::path temp_path = data_folder / temp; while (already_open(temp) || std::filesystem::exists(temp_path)) { temp = fmt::format("new_formula_tree_{}.json", get_seq()); temp_path = data_folder / temp; } return temp; } bool formula_editor_window::load_config() { auto config_file_name = "formula_node_config.json"; std::string notify_info; std::string node_desc_path; std::string choice_desc_path; std::string save_path; if (!std::filesystem::exists(std::filesystem::path(config_file_name))) { path_req_desc node_req; node_req.name = "formula node types"; node_req.tips = "file to provide all formula nodes"; node_req.extension = ".json"; path_req_desc choice_req; choice_req.name = "formula named attr"; choice_req.tips = "file to provide named attr"; choice_req.extension = ".json"; path_req_desc save_path_req; save_path_req.name = "data save dir"; save_path_req.tips = "directory to save data files"; save_path_req.extension = ""; std::vector<path_req_desc> path_reqs; path_reqs.push_back(node_req); path_reqs.push_back(choice_req); path_reqs.push_back(save_path_req); auto cur_dialog = new path_config_dialog(path_reqs, config_file_name, this); auto temp_result = cur_dialog->run(); if (!cur_dialog->valid) { QMessageBox::about(this, QString("Error"), QString::fromStdString("invalid formula node config")); return false; } node_desc_path = temp_result[0]; choice_desc_path = temp_result[1]; save_path = temp_result[2]; } else { auto config_json_variant = load_json_file(config_file_name); if (std::holds_alternative<std::string>(config_json_variant)) { auto notify_info = "config file: " + std::get<std::string>(config_json_variant); QMessageBox::about(this, QString("Error"), QString::fromStdString(notify_info)); return false; } auto json_content = std::get<json::object_t>(config_json_variant); std::vector<std::string> temp_result; std::vector<std::string> path_keys = { "formula node types", "formula named attr" , "data save dir" }; for (auto one_key : path_keys) { auto cur_value_iter = json_content.find(one_key); if (cur_value_iter == json_content.end()) { notify_info = "config content should be should has key " + one_key; QMessageBox::about(this, QString("Error"), QString::fromStdString(notify_info)); return false; } if (!cur_value_iter->second.is_string()) { notify_info = "config content should for key " + one_key + " should be str"; QMessageBox::about(this, QString("Error"), QString::fromStdString(notify_info)); return false; } temp_result.push_back(cur_value_iter->second.get<std::string>()); } node_desc_path = temp_result[0]; choice_desc_path = temp_result[1]; save_path = temp_result[2]; } // choice first auto choice_json_variant = load_json_file(choice_desc_path); if (std::holds_alternative<std::string>(choice_json_variant)) { auto notify_info = "chocie file: " + std::get<std::string>(choice_json_variant); QMessageBox::about(this, QString("Error"), QString::fromStdString(notify_info)); return false; } else { choice_manager::instance().load_from_json(std::get<json::object_t>(choice_json_variant)); } //nodes depends on choice auto node_json_variant = load_json_file(node_desc_path); if (std::holds_alternative<std::string>(node_json_variant)) { auto notify_info = "nodes file: " + std::get<std::string>(node_json_variant); QMessageBox::about(this, QString("Error"), QString::fromStdString(notify_info)); return false; } else { node_config_repo::instance().load_config(std::get<json::object_t>(node_json_variant)); } data_folder = save_path; return true; } basic_node* formula_editor_window::create_node_from_desc(const basic_node_desc& cur_desc, basic_node* parent) { auto cur_config = node_config_repo::instance().get_config(cur_desc.type); if (!cur_config) { return nullptr; } auto cur_node = new formula_node(cur_config.value(), dynamic_cast<formula_node*>(parent), cur_desc.idx); if (parent) { parent->add_child(cur_node); } cur_node->color = cur_desc.color; cur_node->_is_collapsed = cur_desc.is_collpased; cur_node->comment = cur_desc.comment; cur_node->refresh_editable_items(); cur_node->set_extra(json(cur_desc.extra)); return cur_node; }
31.235669
109
0.734095
huangfeidian
a0dbdb6f017542cc0b1646fda3086ac8535f1cd3
1,608
cxx
C++
inetsrv/query/cindex/prtiflst.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetsrv/query/cindex/prtiflst.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetsrv/query/cindex/prtiflst.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+--------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1991 - 1992. // // File: PRTIFLST.CXX // // Contents: Partition Information List // // Classes: // // History: 16-Feb-94 SrikantS Created. // //---------------------------------------------------------------------------- #include <pch.cxx> #pragma hdrstop #include "prtiflst.hxx" //+--------------------------------------------------------------------------- //---------------------------------------------------------------------------- CPartInfo::CPartInfo( PARTITIONID partId ) : _partId(partId) { _widChangeLog = widInvalid ; _widCurrMasterIndex = widInvalid ; _widNewMasterIndex = widInvalid ; _widMMergeLog = widInvalid ; } //+--------------------------------------------------------------------------- //---------------------------------------------------------------------------- CPartInfoList::~CPartInfoList() { CPartInfo * pNode = NULL; while ( (pNode = RemoveFirst()) != NULL ) { delete pNode; } } //+--------------------------------------------------------------------------- //---------------------------------------------------------------------------- CPartInfo* CPartInfoList::GetPartInfo( PARTITIONID partId ) { for ( CForPartInfoIter it(*this); !AtEnd(it); Advance(it) ) { if ( it->GetPartId() == partId ) { return it.GetPartInfo(); } } return NULL; }
27.254237
79
0.342662
npocmaka
a0dc0fd8aa4d9131132ebfc7d480bfa0d82fa5ac
2,802
hpp
C++
kernel/include/kernel/kallocators.hpp
F4doraOfDoom/juos
cdec685701c406defc9204dcadf154df9eefc879
[ "MIT" ]
3
2020-12-22T01:24:56.000Z
2021-01-06T11:44:50.000Z
kernel/include/kernel/kallocators.hpp
F4doraOfDoom/juos
cdec685701c406defc9204dcadf154df9eefc879
[ "MIT" ]
null
null
null
kernel/include/kernel/kallocators.hpp
F4doraOfDoom/juos
cdec685701c406defc9204dcadf154df9eefc879
[ "MIT" ]
null
null
null
#ifndef KERNEL_NEW_H_ #define KERNEL_NEW_H_ #include "kdef.h" #include "kuseful.h" #include "klog.h" #include <kernel/mem_operators.hpp> NAMESPACE_BEGIN(kernel) /** * @brief Custome memory allocator, that uses __primitive_heap * as an allocation space. Has no ability to deconstruct an object, * since you cannot deallocate on __primitive heap * More documentation inside of IAllocator (libstdcxx/allocator.hpp) * * @tparam Type - Allocator will alocate this type */ template <typename Type> struct PrimitiveAllocator { static constexpr uint32_t object_size = sizeof(Type); typedef Type value_type; typedef Type& reference; typedef const Type& const_reference; typedef Type* pointer; static pointer allocate(uint32_t n) { return (pointer)kernel::heap::Allocate(n * object_size); } static void construct(pointer p, const_reference v) { *p = Type(v); } static void destroy(pointer p) { p->~Type(); } }; /** * @brief Custome memory allocator, that uses __mapped_heap * as an allocation space. Has the ability to deallocate memory. * More documentation inside of IAllocator (libstdcxx/allocator.hpp) * * @tparam Type - Allocator will alocate this type */ template <typename Type> struct AdvancedAllocator { static constexpr uint32_t object_size = sizeof(Type); typedef Type value_type; typedef Type& reference; typedef const Type& const_reference; typedef Type* pointer; /** * @brief Allocate _n_ objects of size Type * * @param n * @return pointer */ static pointer allocate(uint32_t n) { return new Type[n]; } /** * @brief Deallocate a pointer pointing to _n_ objects of type Type * * @param p * @param n */ static void deallocate(pointer p, size_t n) { delete p; } /** * @brief construct an object of type Type in pointer _p_ with args _v_ * * @param p * @param v */ static void construct(pointer p, const_reference v) { *p = Type(v); } /** * @brief Destroy an object of type Type in pointer _p_ * * @param p */ static void destroy(pointer p) { p->~Type(); } }; NAMESPACE_END(kernel) #endif // KERNEL_NEW_H_
25.243243
79
0.534618
F4doraOfDoom
a0de34f02722046917ea77f2101c32b615e66db2
146
cpp
C++
Prova II/Aula XVIII/Teste.cpp
EhODavi/INF112
fe1b465a55b255dac4918f357a6e537b2893531e
[ "MIT" ]
null
null
null
Prova II/Aula XVIII/Teste.cpp
EhODavi/INF112
fe1b465a55b255dac4918f357a6e537b2893531e
[ "MIT" ]
null
null
null
Prova II/Aula XVIII/Teste.cpp
EhODavi/INF112
fe1b465a55b255dac4918f357a6e537b2893531e
[ "MIT" ]
null
null
null
#include "Teste.h" int Teste::ct =0; int Teste::getNumInstancias() { return ct; } Teste::Teste() { ct++; } Teste::~Teste() { ct--; }
8.588235
31
0.547945
EhODavi
a0df361c8cca36d2629df1a6e850ae30f244b7b7
1,207
cpp
C++
Piscines/CPP/rush01/srcs/TimeModule.cpp
SpeedFireSho/42-1
5d7ce17910794a28ca44d937651b961feadcff11
[ "MIT" ]
84
2020-10-13T14:50:11.000Z
2022-01-11T11:19:36.000Z
Piscines/CPP/rush01/srcs/TimeModule.cpp
SpeedFireSho/42-1
5d7ce17910794a28ca44d937651b961feadcff11
[ "MIT" ]
null
null
null
Piscines/CPP/rush01/srcs/TimeModule.cpp
SpeedFireSho/42-1
5d7ce17910794a28ca44d937651b961feadcff11
[ "MIT" ]
43
2020-09-10T19:26:37.000Z
2021-12-28T13:53:55.000Z
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* TimeModule.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jaleman <jaleman@student.42.us.org> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/07/15 18:52:47 by jaleman #+# #+# */ /* Updated: 2017/07/15 18:52:48 by jaleman ### ########.fr */ /* */ /* ************************************************************************** */ #include "TimeModule.hpp" TimeModule::TimeModule(void) { return ; } TimeModule::TimeModule(const TimeModule &src) { *this = src; return ; } TimeModule::~TimeModule(void) { return ; } TimeModule &TimeModule::operator= (const TimeModule &rhs) { static_cast <void> (rhs); return (*this); }
32.621622
80
0.256835
SpeedFireSho
a0e344ab6d420ded2e24d5db2a21d00614491eb0
124
cpp
C++
cmake/checks/test-cxx_memory_make_unique.cpp
moorwen91/plasma-potd-spotlight
c16417485fb62a1c8854935b8ce73b4cba9e24b4
[ "BSD-2-Clause" ]
104
2019-02-12T20:41:07.000Z
2022-03-07T16:58:47.000Z
cmake/checks/test-cxx_memory_make_unique.cpp
moorwen91/plasma-potd-spotlight
c16417485fb62a1c8854935b8ce73b4cba9e24b4
[ "BSD-2-Clause" ]
9
2019-08-24T03:23:21.000Z
2021-06-06T17:59:07.000Z
{{cookiecutter.project_slug}}/cmake/checks/test-cxx_memory_make_unique.cpp
Aetf/cc-modern-cmake
4421755acf85a30a42f3f48b6d2e1a5130fd3f46
[ "BSD-2-Clause" ]
18
2019-03-04T07:45:41.000Z
2021-09-15T22:13:07.000Z
#include <memory> int main() { std::unique_ptr<int> foo = std::make_unique<int>(42); return ((*foo) == 42) ? 0 : 1; }
13.777778
55
0.572581
moorwen91
a0e47c413d155c3b47c5100527e7e055d399d522
13,881
cpp
C++
math/LAPACKInterface.cpp
smeng9/KrisLibrary
4bd1aa4d9a2d5e40954f5d0b8e3e8a9f19c32add
[ "BSD-3-Clause" ]
57
2015-05-07T18:07:11.000Z
2022-03-18T18:44:39.000Z
math/LAPACKInterface.cpp
smeng9/KrisLibrary
4bd1aa4d9a2d5e40954f5d0b8e3e8a9f19c32add
[ "BSD-3-Clause" ]
7
2018-12-10T21:46:52.000Z
2022-01-20T19:49:11.000Z
math/LAPACKInterface.cpp
smeng9/KrisLibrary
4bd1aa4d9a2d5e40954f5d0b8e3e8a9f19c32add
[ "BSD-3-Clause" ]
36
2015-01-10T18:36:45.000Z
2022-01-20T19:49:24.000Z
#include <KrisLibrary/Logger.h> #include "LAPACKInterface.h" #include "complex.h" #include "errors.h" using namespace Math; bool LAPACKInterface::IsCompliant(const fVector& x) { return (x.stride == 1); } bool LAPACKInterface::IsCompliant(const dVector& x) { return (x.stride == 1); } bool LAPACKInterface::IsCompliant(const cVector& x) { return (x.stride == 1); } bool LAPACKInterface::IsCompliant(const fMatrix& A) { if(A.isRowMajor()) return false; return (A.istride == 1); } bool LAPACKInterface::IsCompliant(const dMatrix& A) { if(A.isRowMajor()) return false; return (A.istride == 1); } bool LAPACKInterface::IsCompliant(const cMatrix& A) { if(A.isRowMajor()) return false; return (A.istride == 1); } void LAPACKInterface::MakeCompliant(const fVector& x,fVector& res) { Assert(res.empty()); res.resize(x.n); res.copy(x); Assert(IsCompliant(res)); } void LAPACKInterface::MakeCompliant(const dVector& x,dVector& res) { Assert(res.empty()); res.resize(x.n); res.copy(x); Assert(IsCompliant(res)); } void LAPACKInterface::MakeCompliant(const cVector& x,cVector& res) { Assert(res.empty()); res.resize(x.n); res.copy(x); Assert(IsCompliant(res)); } void LAPACKInterface::MakeCompliant(const fMatrix& A,fMatrix& res) { Assert(res.isEmpty()); res.resize(A.m,A.n); std::swap(res.istride,res.jstride); //make column major Assert(res.isValid()); Assert(IsCompliant(res)); res.copy(A); } void LAPACKInterface::MakeCompliant(const dMatrix& A,dMatrix& res) { Assert(res.isEmpty()); res.resize(A.m,A.n); std::swap(res.istride,res.jstride); //make column major Assert(res.isValid()); Assert(IsCompliant(res)); res.copy(A); } void LAPACKInterface::MakeCompliant(const cMatrix& A,cMatrix& res) { Assert(res.isEmpty()); res.resize(A.m,A.n); std::swap(res.istride,res.jstride); //make column major Assert(res.isValid()); Assert(IsCompliant(res)); res.copy(A); } #if HAVE_CLAPACK extern "C" { #include "f2c.h" #include "clapack.h" } bool LAPACKInterface::Solve(const fMatrix& A,const fVector& b,fVector& x) { Assert(A.isSquare()); Assert(A.n == b.n); Assert(x.isEmpty() || !x.isReference()); fMatrix LU; MakeCompliant(A,LU); //copy b into x x.resize(0); MakeCompliant(b,x); //solve it integer n = A.m; integer nrhs = 1; //nrhs is 1, because only one vector solved for integer ldb = x.n; //ignored, because only one vector solved for integer info=0; integer* ipiv = new integer[n]; integer lda = LU.jstride; sgesv_(&n,&nrhs,LU.getStart(),&lda,ipiv,x.getStart(),&ldb,&info); delete [] ipiv; if(info != 0) { //failed somehow if(info < 0) //input error FatalError("Uh... info=%d\n",info); FatalError("Error... info=%d\n",info); return false; } return true; } bool LAPACKInterface::Solve(const dMatrix& A,const dVector& b,dVector& x) { Assert(A.isSquare()); Assert(A.n == b.n); Assert(x.isEmpty() || !x.isReference()); dMatrix LU; MakeCompliant(A,LU); //copy b into x x.resize(0); MakeCompliant(b,x); //solve it integer n = A.m; integer nrhs = 1; //nrhs is 1, because only one vector solved for integer ldb = x.n; //ignored, because only one vector solved for integer info=0; integer* ipiv = new integer[n]; integer lda = LU.jstride; dgesv_(&n,&nrhs,LU.getStart(),&lda,ipiv,x.getStart(),&ldb,&info); delete [] ipiv; if(info != 0) { //failed somehow if(info < 0) //input error FatalError("Uh... info=%d\n",info); FatalError("Error... info=%d\n",info); return false; } return true; } bool LAPACKInterface::LeastSquares(const fMatrix& A,const fVector& b,fVector& x) { Assert(A.m == b.n); Assert(x.isEmpty() || !x.isReference()); fMatrix QR; MakeCompliant(A,QR); //copy b into x x.resize(0); MakeCompliant(b,x); if(A.m < A.n) { //minimum norm solution x.resize(A.m); x.copySubVector(0,b); } //solve it char trans='N'; integer m = A.m; integer n = A.n; integer nrhs = 1; //nrhs is 1, because only one vector solved for integer lda = QR.jstride; integer ldb = x.n; //ignored, because only one vector solved for integer info=0; real worktemp; integer lwork = -1; //query workspace size sgels_(&trans,&m,&n,&nrhs,QR.getStart(),&lda,x.getStart(),&ldb,&worktemp,&lwork,&info); //do the LS lwork = (int)worktemp; real* work = new real[lwork]; sgels_(&trans,&m,&n,&nrhs,QR.getStart(),&lda,x.getStart(),&ldb,&worktemp,&lwork,&info); delete [] work; x.n = A.n; if(info != 0) { //failed somehow if(info < 0) //input error FatalError("Uh... info=%d\n",info); FatalError("Error... info=%d\n",info); return false; } return true; } bool LAPACKInterface::LeastSquares(const dMatrix& A,const dVector& b,dVector& x) { Assert(A.m == b.n); Assert(x.isEmpty() || !x.isReference()); dMatrix QR; MakeCompliant(A,QR); //copy b into x x.resize(0); MakeCompliant(b,x); if(A.m < A.n) { //minimum norm solution x.resize(A.m); x.copySubVector(0,b); } //solve it char trans='N'; integer m = A.m; integer n = A.n; integer nrhs = 1; //nrhs is 1, because only one vector solved for integer lda = QR.jstride; integer ldb = x.n; //ignored, because only one vector solved for integer info=0; doublereal worktemp; integer lwork = -1; //query workspace size dgels_(&trans,&m,&n,&nrhs,QR.getStart(),&lda,x.getStart(),&ldb,&worktemp,&lwork,&info); //do the LS lwork = (int)worktemp; doublereal* work = new doublereal[lwork]; dgels_(&trans,&m,&n,&nrhs,QR.getStart(),&lda,x.getStart(),&ldb,&worktemp,&lwork,&info); delete [] work; x.n = A.n; if(info != 0) { //failed somehow if(info < 0) //input error FatalError("Uh... info=%d\n",info); FatalError("Error... info=%d\n",info); return false; } return true; } bool LAPACKInterface::Eigenvalues_Symmetric(const fMatrix& A,fVector& lambda) { Assert(A.isSquare()); fMatrix Atemp; MakeCompliant(A,Atemp); fVector wtemp; wtemp.resize(A.n); Assert(IsCompliant(wtemp)); //solve it char job='N'; //only eigenvalues char uplo='U'; integer n = Atemp.n; integer lda = Atemp.jstride; integer info=0; real worktemp; integer lwork = -1; //query workspace size ssyev_(&job,&uplo,&n,Atemp.getStart(),&lda,wtemp.getStart(),&worktemp,&lwork,&info); //do the LS lwork = (int)worktemp; real* work = new real[lwork]; ssyev_(&job,&uplo,&n,Atemp.getStart(),&lda,wtemp.getStart(),work,&lwork,&info); delete [] work; lambda = wtemp; if(info != 0) { //failed somehow if(info < 0) //input error FatalError("Uh... info=%d\n",info); FatalError("Error... info=%d\n",info); return false; } return true; } bool LAPACKInterface::Eigenvalues_Symmetric(const dMatrix& A,dVector& lambda) { Assert(A.isSquare()); dMatrix Atemp; MakeCompliant(A,Atemp); dVector wtemp; wtemp.resize(A.n); Assert(IsCompliant(wtemp)); //solve it char job='N'; //only eigenvalues char uplo='U'; integer n = Atemp.n; integer lda = Atemp.jstride; integer info=0; doublereal worktemp; integer lwork = -1; //query workspace size dsyev_(&job,&uplo,&n,Atemp.getStart(),&lda,wtemp.getStart(),&worktemp,&lwork,&info); //do the LS lwork = (int)worktemp; doublereal* work = new doublereal[lwork]; dsyev_(&job,&uplo,&n,Atemp.getStart(),&lda,wtemp.getStart(),work,&lwork,&info); delete [] work; lambda = wtemp; if(info != 0) { //failed somehow if(info < 0) //input error FatalError("Uh... info=%d\n",info); FatalError("Error... info=%d\n",info); return false; } return true; } bool LAPACKInterface::Eigenvectors_Symmetric(const fMatrix& A,fVector& lambda,fMatrix& Q) { Assert(A.isSquare()); Assert(Q.isEmpty() || !Q.isRef()); MakeCompliant(A,Q); fVector wtemp; wtemp.resize(A.n); Assert(IsCompliant(wtemp)); //solve it char job='V'; //eigenvectors+eigenvalues char uplo='U'; integer n = Q.n; integer lda = Q.jstride; integer info=0; real worktemp; integer lwork = -1; //query workspace size ssyev_(&job,&uplo,&n,Q.getStart(),&lda,wtemp.getStart(),&worktemp,&lwork,&info); //do the LS lwork = (int)worktemp; real* work = new real[lwork]; ssyev_(&job,&uplo,&n,Q.getStart(),&lda,wtemp.getStart(),work,&lwork,&info); delete [] work; if(info != 0) { //failed somehow if(info < 0) //input error FatalError("Uh... info=%d\n",info); FatalError("Error... info=%d\n",info); return false; } lambda = wtemp; return true; } bool LAPACKInterface::Eigenvectors_Symmetric(const dMatrix& A,dVector& lambda,dMatrix& Q) { Assert(A.isSquare()); Assert(Q.isEmpty() || !Q.isRef()); MakeCompliant(A,Q); dVector wtemp; wtemp.resize(A.n); Assert(IsCompliant(wtemp)); //solve it char job='V'; //eigenvectors+eigenvalues char uplo='U'; integer n = Q.n; integer lda = Q.jstride; integer info=0; doublereal worktemp; integer lwork = -1; //query workspace size dsyev_(&job,&uplo,&n,Q.getStart(),&lda,wtemp.getStart(),&worktemp,&lwork,&info); Assert(info == 0); //do the LS lwork = (int)worktemp; Assert(lwork > 0); doublereal* work = new doublereal[lwork]; dsyev_(&job,&uplo,&n,Q.getStart(),&lda,wtemp.getStart(),work,&lwork,&info); delete [] work; if(info != 0) { //failed somehow if(info < 0) //input error FatalError("Uh... info=%d\n",info); FatalError("Error... info=%d\n",info); return false; } lambda = wtemp; return true; } bool LAPACKInterface::SVD(const fMatrix& A,fMatrix& U,fVector& W,fMatrix& Vt) { fMatrix Atemp; MakeCompliant(A,Atemp); Assert(U.isEmpty() || !U.isRef()); Assert(Vt.isEmpty() || !Vt.isRef()); Assert(W.isEmpty() || !W.isReference()); U.resize(A.m,A.m); std::swap(U.jstride,U.istride); Vt.resize(A.n,A.n); std::swap(Vt.jstride,Vt.istride); W.resize(Min(A.m,A.n)); Assert(W.stride == 1); //solve it char jobu='A'; //all left SV's in U char jobvt='A'; //all right SV's in Vt integer m = A.m; integer n = A.n; integer lda = Atemp.jstride; integer ldu = U.jstride; integer ldvt = Vt.jstride; integer info=0; real worktemp; integer lwork = -1; //query workspace size sgesvd_(&jobu,&jobvt,&m,&n,Atemp.getStart(),&lda,W.getStart(),U.getStart(),&ldu,Vt.getStart(),&ldvt,&worktemp,&lwork,&info); Assert(info == 0); //do the SVD lwork = (int)worktemp; Assert(lwork > 0); real* work = new real[lwork]; sgesvd_(&jobu,&jobvt,&m,&n,Atemp.getStart(),&lda,W.getStart(),U.getStart(),&ldu,Vt.getStart(),&ldvt,work,&lwork,&info); delete [] work; if(info != 0) { //failed somehow if(info < 0) //input error FatalError("Uh... info=%d\n",info); FatalError("Error... info=%d\n",info); return false; } return true; } bool LAPACKInterface::SVD(const dMatrix& A,dMatrix& U,dVector& W,dMatrix& Vt) { dMatrix Atemp; MakeCompliant(A,Atemp); Assert(U.isEmpty() || !U.isRef()); Assert(Vt.isEmpty() || !Vt.isRef()); Assert(W.isEmpty() || !W.isReference()); U.resize(A.m,A.m); std::swap(U.jstride,U.istride); Vt.resize(A.n,A.n); std::swap(Vt.jstride,Vt.istride); W.resize(Min(A.m,A.n)); Assert(W.stride == 1); //solve it char jobu='A'; //all left SV's in U char jobvt='A'; //all right SV's in Vt integer m = A.m; integer n = A.n; integer lda = Atemp.jstride; integer ldu = U.jstride; integer ldvt = Vt.jstride; integer info=0; doublereal worktemp; integer lwork = -1; //query workspace size dgesvd_(&jobu,&jobvt,&m,&n,Atemp.getStart(),&lda,W.getStart(),U.getStart(),&ldu,Vt.getStart(),&ldvt,&worktemp,&lwork,&info); Assert(info == 0); //do the LS lwork = (int)worktemp; Assert(lwork > 0); doublereal* work = new doublereal[lwork]; dgesvd_(&jobu,&jobvt,&m,&n,Atemp.getStart(),&lda,W.getStart(),U.getStart(),&ldu,Vt.getStart(),&ldvt,work,&lwork,&info); delete [] work; if(info != 0) { //failed somehow if(info < 0) //input error FatalError("Uh... info=%d\n",info); FatalError("Error... info=%d\n",info); return false; } return true; } #else #include <iostream> using namespace std; bool LAPACKInterface::Solve(const fMatrix& A,const fVector& b,fVector& x) { LOG4CXX_ERROR(KrisLibrary::logger(),"Warning, LAPACK not defined"); return false; } bool LAPACKInterface::Solve(const dMatrix& A,const dVector& b,dVector& x) { LOG4CXX_ERROR(KrisLibrary::logger(),"Warning, LAPACK not defined"); return false; } bool LAPACKInterface::LeastSquares(const fMatrix& A,const fVector& b,fVector& x) { LOG4CXX_ERROR(KrisLibrary::logger(),"Warning, LAPACK not defined"); return false; } bool LAPACKInterface::LeastSquares(const dMatrix& A,const dVector& b,dVector& x) { LOG4CXX_ERROR(KrisLibrary::logger(),"Warning, LAPACK not defined"); return false; } bool LAPACKInterface::Eigenvalues_Symmetric(const fMatrix& A,fVector& lambda) { LOG4CXX_ERROR(KrisLibrary::logger(),"Warning, LAPACK not defined"); return false; } bool LAPACKInterface::Eigenvalues_Symmetric(const dMatrix& A,dVector& lambda) { LOG4CXX_ERROR(KrisLibrary::logger(),"Warning, LAPACK not defined"); return false; } bool LAPACKInterface::Eigenvectors_Symmetric(const fMatrix& A,fVector& lambda,fMatrix& Q) { LOG4CXX_ERROR(KrisLibrary::logger(),"Warning, LAPACK not defined"); return false; } bool LAPACKInterface::Eigenvectors_Symmetric(const dMatrix& A,dVector& lambda,dMatrix& Q) { LOG4CXX_ERROR(KrisLibrary::logger(),"Warning, LAPACK not defined"); return false; } bool LAPACKInterface::SVD(const fMatrix& A,fMatrix& U,fVector& W,fMatrix& Vt) { LOG4CXX_ERROR(KrisLibrary::logger(),"Warning, LAPACK not defined"); return false; } bool LAPACKInterface::SVD(const dMatrix& A,dMatrix& U,dVector& W,dMatrix& Vt) { LOG4CXX_ERROR(KrisLibrary::logger(),"Warning, LAPACK not defined"); return false; } #endif
25.705556
126
0.654996
smeng9
a0e520d05a377d17ee332f8422515757b341ecf2
3,198
cpp
C++
src/caffe/layers/cross_perturbation_layer.cpp
chenbinghui1/Hybrid-Attention-based-Decoupled-Metric-Learning
7b1bda334efe0c98c6876548b35a728c3c35676d
[ "MIT" ]
44
2019-04-03T16:51:30.000Z
2022-02-02T15:19:48.000Z
src/caffe/layers/cross_perturbation_layer.cpp
chenbinghui1/Decoupled-Metric-Learning
7b1bda334efe0c98c6876548b35a728c3c35676d
[ "MIT" ]
1
2021-06-01T10:00:00.000Z
2021-06-23T01:46:43.000Z
src/caffe/layers/cross_perturbation_layer.cpp
chenbinghui1/Decoupled-Metric-Learning
7b1bda334efe0c98c6876548b35a728c3c35676d
[ "MIT" ]
8
2019-05-16T05:44:41.000Z
2020-08-19T17:16:28.000Z
//需要设置solver里面iter_size=2 ,第一次前向反向传播为正常输入和正常梯度,并记录反传回来的梯度,第二次前向为原输入+梯度干扰,输入list需要在第一次和第二次的时候保持一样。且根据ICLR18cross gradients 相应的loss也要做修改,此时只修改了BIER loss. #include <vector> #include "caffe/filler.hpp" #include "caffe/layers/cross_perturbation_layer.hpp" #include "caffe/util/math_functions.hpp" namespace caffe { template <typename Dtype> void CrossPerturbationLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { CHECK_EQ(bottom.size(), 2); CHECK_EQ(bottom[0]->count(), bottom[1]->count()); F_iter_size_ = 0; B_iter_size_ = 0; } template <typename Dtype> void CrossPerturbationLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { top[0]->ReshapeLike(*bottom[0]); top[1]->ReshapeLike(*bottom[1]); temp0_.ReshapeLike(*bottom[0]); temp1_.ReshapeLike(*bottom[1]); } template <typename Dtype> void CrossPerturbationLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { //load cross weights //static int iter_size = 0; vector<Dtype> ems; for(int i = 0; i < this->layer_param_.cross_perturbation_param().ems_size(); i++) { ems.push_back(this->layer_param_.cross_perturbation_param().ems(i)); } //forward propagation if(F_iter_size_ == 0) { for(int i = 0; i < bottom.size(); i++) caffe_copy(bottom[i]->count(), bottom[i]->cpu_data(), top[i]->mutable_cpu_data()); F_iter_size_ = 1; } else {//fi + ems[i]*gradient(fj) caffe_cpu_axpby(bottom[0]->count(), Dtype(1), bottom[0]->cpu_data(), Dtype(0), top[0]->mutable_cpu_data()); caffe_cpu_axpby(bottom[1]->count(), Dtype(ems[0]), temp1_.cpu_data(), Dtype(1), top[0]->mutable_cpu_data()); caffe_cpu_axpby(bottom[1]->count(), Dtype(1), bottom[1]->cpu_data(), Dtype(0), top[1]->mutable_cpu_data()); caffe_cpu_axpby(bottom[0]->count(), Dtype(ems[1]), temp0_.cpu_data(), Dtype(1), top[1]->mutable_cpu_data()); F_iter_size_ = 0; } } template <typename Dtype> void CrossPerturbationLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { //static int iter_size = 0; if(B_iter_size_ == 0) { for(int i = 0; i < bottom.size(); i++) { //propagate gradients caffe_copy(bottom[i]->count(), top[i]->cpu_diff(), bottom[i]->mutable_cpu_diff()); } //store gradients caffe_copy(bottom[0]->count(), top[0]->cpu_diff(), temp0_.mutable_cpu_data()); caffe_copy(bottom[1]->count(), top[1]->cpu_diff(), temp1_.mutable_cpu_data()); B_iter_size_ = 1; } else { for(int i = 0; i < bottom.size(); i++) { //propagate gradients caffe_set(bottom[i]->count(), Dtype(0), bottom[i]->mutable_cpu_diff()); } B_iter_size_ = 0; } } #ifdef CPU_ONLY STUB_GPU(CrossPerturbationLayer); #endif INSTANTIATE_CLASS(CrossPerturbationLayer); REGISTER_LAYER_CLASS(CrossPerturbation); } // namespace caffe
34.387097
151
0.636023
chenbinghui1
a0e63ac905122c14183c8f42d24490ea113f3e5f
2,573
cpp
C++
src/editors/LevelEditor/Edit/SceneUtil.cpp
acidicMercury8/xray-1.6
52fba7348a93a52ff9694f2c9dd40c0d090e791e
[ "Linux-OpenIB" ]
10
2021-05-04T06:40:27.000Z
2022-01-20T20:24:28.000Z
src/editors/LevelEditor/Edit/SceneUtil.cpp
Samsuper12/ixray-1.5
8070f833f8216d4ead294a9f19b7cd123bb76ba3
[ "Linux-OpenIB" ]
null
null
null
src/editors/LevelEditor/Edit/SceneUtil.cpp
Samsuper12/ixray-1.5
8070f833f8216d4ead294a9f19b7cd123bb76ba3
[ "Linux-OpenIB" ]
2
2021-11-07T16:57:19.000Z
2021-12-05T13:17:12.000Z
//---------------------------------------------------- // file: SceneUtil.cpp //---------------------------------------------------- #include "stdafx.h" #pragma hdrstop #include "Scene.h" #include "ELight.h" #include "SceneObject.h" #include "ui_leveltools.h" //---------------------------------------------------- CCustomObject* EScene::FindObjectByName( LPCSTR name, ObjClassID classfilter ) { if(!name) return NULL; CCustomObject* object = 0; if (classfilter==OBJCLASS_DUMMY) { SceneToolsMapPairIt _I = m_SceneTools.begin(); SceneToolsMapPairIt _E = m_SceneTools.end(); for (; _I!=_E; ++_I) { ESceneCustomOTool* mt = dynamic_cast<ESceneCustomOTool*>(_I->second); if (mt&&(0!=(object=mt->FindObjectByName(name)))) return object; } }else{ ESceneCustomOTool* mt = GetOTool(classfilter); VERIFY(mt); if (mt&&(0!=(object=mt->FindObjectByName(name)))) return object; } return object; } CCustomObject* EScene::FindObjectByName( LPCSTR name, CCustomObject* pass_object ) { CCustomObject* object = 0; SceneToolsMapPairIt _I = m_SceneTools.begin(); SceneToolsMapPairIt _E = m_SceneTools.end(); for (; _I!=_E; _I++){ ESceneCustomOTool* mt = dynamic_cast<ESceneCustomOTool*>(_I->second); if (mt&&(0!=(object=mt->FindObjectByName(name,pass_object)))) return object; } return 0; } bool EScene::FindDuplicateName() { // find duplicate name SceneToolsMapPairIt _I = m_SceneTools.begin(); SceneToolsMapPairIt _E = m_SceneTools.end(); for (; _I!=_E; _I++){ ESceneCustomOTool* mt = dynamic_cast<ESceneCustomOTool*>(_I->second); if (mt){ ObjectList& lst = mt->GetObjects(); for(ObjectIt _F = lst.begin();_F!=lst.end();_F++) if (FindObjectByName((*_F)->Name, *_F)){ ELog.DlgMsg(mtError,"Duplicate object name already exists: '%s'",(*_F)->Name); return true; } } } return false; } void EScene::GenObjectName( ObjClassID cls_id, char *buffer, const char* pref ) { ESceneCustomOTool* ot = GetOTool(cls_id); VERIFY(ot); AnsiString result = FHelper.GenerateName(pref&&pref[0]?pref:ot->ClassName(),4,fastdelegate::bind<TFindObjectByName>(this,&EScene::FindObjectByNameCB),true,true); strcpy (buffer,result.c_str()); } //------------------------------------------------------------------------------
32.987179
166
0.552662
acidicMercury8
a0e8b87316eb686bb2997d40a1066a92e5746a5f
1,308
hpp
C++
libs/boost_1_72_0/boost/fusion/view/nview/detail/value_of_impl.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
libs/boost_1_72_0/boost/fusion/view/nview/detail/value_of_impl.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
libs/boost_1_72_0/boost/fusion/view/nview/detail/value_of_impl.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
/*============================================================================= Copyright (c) 2009 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) ==============================================================================*/ #if !defined(BOOST_FUSION_VALUE_OF_PRIOR_IMPL_SEP_24_2009_0158PM) #define BOOST_FUSION_VALUE_OF_PRIOR_IMPL_SEP_24_2009_0158PM #include <boost/fusion/container/vector.hpp> #include <boost/fusion/iterator/deref.hpp> #include <boost/fusion/support/config.hpp> namespace boost { namespace fusion { struct nview_iterator_tag; template <typename Sequence, typename Pos> struct nview_iterator; namespace extension { template <typename Tag> struct value_of_impl; template <> struct value_of_impl<nview_iterator_tag> { template <typename Iterator> struct apply { typedef typename Iterator::first_type first_type; typedef typename Iterator::sequence_type sequence_type; typedef typename result_of::deref<first_type>::type index; typedef typename result_of::at<typename sequence_type::sequence_type, index>::type type; }; }; } // namespace extension } // namespace fusion } // namespace boost #endif
32.7
80
0.66896
henrywarhurst
a0ee0ba5749c2a6b6cbb9535419c1331fc71f08d
1,350
cpp
C++
sharing_data_new/src/main5.cpp
hadleyhzy34/distributed-deep-learning-framework-for-robotics
38f5e5b26403048ddd4b5beb381c58262580d5f7
[ "Apache-2.0" ]
null
null
null
sharing_data_new/src/main5.cpp
hadleyhzy34/distributed-deep-learning-framework-for-robotics
38f5e5b26403048ddd4b5beb381c58262580d5f7
[ "Apache-2.0" ]
null
null
null
sharing_data_new/src/main5.cpp
hadleyhzy34/distributed-deep-learning-framework-for-robotics
38f5e5b26403048ddd4b5beb381c58262580d5f7
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <thread> #include <map> #include <string> #include <mutex> #include <shared_mutex> #include <string> //void myprint(const int &i, const std::string &mybuf) void myprint(const int &i, char* mybuf) { //below print shows that address of i is not the same as one in the main function //which later proves that reference variable `i` is copied when calling std::thread std::cout<<"address of i inside function is: "<<&i<<"\n"; std::cout<<"char array address in function is: "<<&mybuf<<"\n"; std::cout<<i<<std::endl; std::cout<<mybuf<<std::endl; } int main() { int myvar = 1; std::cout<<"address of myvar inside main is: "<<&myvar<<"\n"; int &var = myvar; std::cout<<"reference of myvar address is: "<<&var<<"\n"; char mybuf[] = "this is a test!"; //char* mybuf = (char*)"this is a test!"; std::cout<<"char array address in main is: "<<&mybuf<<"\n"; std::thread myobj(myprint, myvar, mybuf); //if args in function is `const std::string`, there could be possible chance that //main thread is finished while mybuf is not converted yet //adding std::string() could prevent this case //std::thread myobj(myprint, myvar, std::string(mybuf)); myobj.join(); //myobj.detach(); std::cout<<"this is thread basic testing"<<std::endl; return 0; }
32.926829
87
0.640741
hadleyhzy34
a0f0c8e40c3982bdc323228e9603e3da357f8ad7
612
cpp
C++
ianlmk/cs161b/zybooks/11.4.3.cpp
ianlmk/cs161
7a50740d1642ca0111a6d0d076b600744552a066
[ "MIT" ]
null
null
null
ianlmk/cs161b/zybooks/11.4.3.cpp
ianlmk/cs161
7a50740d1642ca0111a6d0d076b600744552a066
[ "MIT" ]
1
2022-03-25T18:34:47.000Z
2022-03-25T18:35:23.000Z
ianlmk/cs161b/zybooks/11.4.3.cpp
ianlmk/cs161
7a50740d1642ca0111a6d0d076b600744552a066
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { const int SCORES_SIZE = 4; int bonusScores[SCORES_SIZE]; int i; for (i = 0; i < SCORES_SIZE; ++i) { cin >> bonusScores[i]; } // Set all indexed values to itself plus the next value except for the last element for (i = 0; i < SCORES_SIZE; ++i) { if (i == SCORES_SIZE - 1) { bonusScores[i] = bonusScores[i]; } else { bonusScores[i] = bonusScores[i] + bonusScores[i + 1]; } } for (i = 0; i < SCORES_SIZE; ++i) { cout << bonusScores[i] << " "; } cout << endl; return 0; }
20.4
88
0.545752
ianlmk
a0f12cf3aa1939bf73da706bf2ef14fdeb22c67e
411
cpp
C++
codeforces/gym/2018 IME Tryouts/b.cpp
tysm/cpsols
262212646203e516d1706edf962290de93762611
[ "MIT" ]
4
2020-10-05T19:24:10.000Z
2021-07-15T00:45:43.000Z
codeforces/gym/2018 IME Tryouts/b.cpp
tysm/cpsols
262212646203e516d1706edf962290de93762611
[ "MIT" ]
null
null
null
codeforces/gym/2018 IME Tryouts/b.cpp
tysm/cpsols
262212646203e516d1706edf962290de93762611
[ "MIT" ]
null
null
null
#include <cpplib/stdinc.hpp> int32_t main(){ desync(); int acc = 0; char last = 0; string s; cin >> s; for(char c:s){ if(c != last) acc = 0; acc++; if(acc == 3){ cout << (c == 'C'? 'P' : 'T'); acc = 0; } else cout << (c == 'C'? 'B' : 'D'); last = c; } cout << endl; return 0; }
17.125
42
0.3382
tysm
a0f3ed03f501666b3f05e094978fa1abd8f19733
6,486
cc
C++
components/offline_pages/core/background/request_queue.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
components/offline_pages/core/background/request_queue.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
components/offline_pages/core/background/request_queue.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/offline_pages/core/background/request_queue.h" #include <utility> #include "base/bind.h" #include "base/location.h" #include "base/threading/thread_task_runner_handle.h" #include "components/offline_pages/core/background/add_request_task.h" #include "components/offline_pages/core/background/change_requests_state_task.h" #include "components/offline_pages/core/background/get_requests_task.h" #include "components/offline_pages/core/background/initialize_store_task.h" #include "components/offline_pages/core/background/mark_attempt_aborted_task.h" #include "components/offline_pages/core/background/mark_attempt_completed_task.h" #include "components/offline_pages/core/background/mark_attempt_started_task.h" #include "components/offline_pages/core/background/pick_request_task.h" #include "components/offline_pages/core/background/reconcile_task.h" #include "components/offline_pages/core/background/remove_requests_task.h" #include "components/offline_pages/core/background/request_queue_store.h" #include "components/offline_pages/core/background/save_page_request.h" namespace offline_pages { namespace { // Completes the get requests call. void GetRequestsDone(RequestQueue::GetRequestsCallback callback, bool success, std::vector<std::unique_ptr<SavePageRequest>> requests) { GetRequestsResult result = success ? GetRequestsResult::SUCCESS : GetRequestsResult::STORE_FAILURE; std::move(callback).Run(result, std::move(requests)); } // Completes the add request call. void AddRequestDone(RequestQueue::AddRequestCallback callback, const SavePageRequest& request, ItemActionStatus status) { AddRequestResult result; switch (status) { case ItemActionStatus::SUCCESS: result = AddRequestResult::SUCCESS; break; case ItemActionStatus::ALREADY_EXISTS: result = AddRequestResult::ALREADY_EXISTS; break; case ItemActionStatus::STORE_ERROR: result = AddRequestResult::STORE_FAILURE; break; case ItemActionStatus::NOT_FOUND: default: NOTREACHED(); return; } std::move(callback).Run(result, request); } } // namespace RequestQueue::RequestQueue(std::unique_ptr<RequestQueueStore> store) : store_(std::move(store)), task_queue_(this), weak_ptr_factory_(this) { Initialize(); } RequestQueue::~RequestQueue() {} void RequestQueue::OnTaskQueueIsIdle() {} void RequestQueue::GetRequests(GetRequestsCallback callback) { std::unique_ptr<Task> task(new GetRequestsTask( store_.get(), base::BindOnce(&GetRequestsDone, std::move(callback)))); task_queue_.AddTask(std::move(task)); } void RequestQueue::AddRequest(const SavePageRequest& request, AddRequestCallback callback) { std::unique_ptr<AddRequestTask> task(new AddRequestTask( store_.get(), request, base::BindOnce(&AddRequestDone, std::move(callback), request))); task_queue_.AddTask(std::move(task)); } void RequestQueue::RemoveRequests(const std::vector<int64_t>& request_ids, UpdateCallback callback) { std::unique_ptr<Task> task( new RemoveRequestsTask(store_.get(), request_ids, std::move(callback))); task_queue_.AddTask(std::move(task)); } void RequestQueue::ChangeRequestsState( const std::vector<int64_t>& request_ids, const SavePageRequest::RequestState new_state, UpdateCallback callback) { std::unique_ptr<Task> task(new ChangeRequestsStateTask( store_.get(), request_ids, new_state, std::move(callback))); task_queue_.AddTask(std::move(task)); } void RequestQueue::MarkAttemptStarted(int64_t request_id, UpdateCallback callback) { std::unique_ptr<Task> task(new MarkAttemptStartedTask( store_.get(), request_id, std::move(callback))); task_queue_.AddTask(std::move(task)); } void RequestQueue::MarkAttemptAborted(int64_t request_id, UpdateCallback callback) { std::unique_ptr<Task> task(new MarkAttemptAbortedTask( store_.get(), request_id, std::move(callback))); task_queue_.AddTask(std::move(task)); } void RequestQueue::MarkAttemptCompleted(int64_t request_id, FailState fail_state, UpdateCallback callback) { std::unique_ptr<Task> task(new MarkAttemptCompletedTask( store_.get(), request_id, fail_state, std::move(callback))); task_queue_.AddTask(std::move(task)); } void RequestQueue::PickNextRequest( OfflinerPolicy* policy, PickRequestTask::RequestPickedCallback picked_callback, PickRequestTask::RequestNotPickedCallback not_picked_callback, PickRequestTask::RequestCountCallback request_count_callback, DeviceConditions& conditions, std::set<int64_t>& disabled_requests, base::circular_deque<int64_t>& prioritized_requests) { // Using the PickerContext, create a picker task. std::unique_ptr<Task> task(new PickRequestTask( store_.get(), policy, std::move(picked_callback), std::move(not_picked_callback), std::move(request_count_callback), conditions, disabled_requests, prioritized_requests)); // Queue up the picking task, it will call one of the callbacks when it // completes. task_queue_.AddTask(std::move(task)); } void RequestQueue::ReconcileRequests(UpdateCallback callback) { std::unique_ptr<Task> task( new ReconcileTask(store_.get(), std::move(callback))); // Queue up the reconcile task. task_queue_.AddTask(std::move(task)); } void RequestQueue::CleanupRequestQueue() { // Create a cleanup task. std::unique_ptr<Task> task(cleanup_factory_->CreateCleanupTask(store_.get())); // Queue up the cleanup task. task_queue_.AddTask(std::move(task)); } void RequestQueue::Initialize() { std::unique_ptr<Task> task(new InitializeStoreTask( store_.get(), base::BindOnce(&RequestQueue::InitializeStoreDone, weak_ptr_factory_.GetWeakPtr()))); task_queue_.AddTask(std::move(task)); } void RequestQueue::InitializeStoreDone(bool success) { // TODO(fgorski): Result can be ignored for now. Report UMA in future. // No need to pass the result up to RequestCoordinator. } } // namespace offline_pages
37.929825
81
0.726796
zipated
a0f3f3b75f368223a128d49a347759e4e33df816
1,438
cpp
C++
Chapter_04/Source/Chapter_04/BarricksUnit.cpp
CoolHandNick80/Unreal-Engine-4.x-Scripting-with-C-Cookbook---Second-edition
4ceb7a6f61cb9e1301def08a4a0aa1759c0659be
[ "MIT" ]
1
2020-10-26T10:11:26.000Z
2020-10-26T10:11:26.000Z
Chapter_04/Source/Chapter_04/BarricksUnit.cpp
CoolHandNick80/Unreal-Engine-4.x-Scripting-with-C-Cookbook---Second-edition
4ceb7a6f61cb9e1301def08a4a0aa1759c0659be
[ "MIT" ]
null
null
null
Chapter_04/Source/Chapter_04/BarricksUnit.cpp
CoolHandNick80/Unreal-Engine-4.x-Scripting-with-C-Cookbook---Second-edition
4ceb7a6f61cb9e1301def08a4a0aa1759c0659be
[ "MIT" ]
1
2020-10-26T10:11:36.000Z
2020-10-26T10:11:36.000Z
// Fill out your copyright notice in the Description page of Project Settings. #include "BarricksUnit.h" #include "Particles/ParticleSystemComponent.h" // Sets default values ABarricksUnit::ABarricksUnit() { // Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; SpawnPoint = CreateDefaultSubobject<UParticleSystemComponent>("SpawnPoint"); auto ParticleSystem = ConstructorHelpers::FObjectFinder<UParticleSystem>(TEXT("ParticleSystem'/Engine/Tutorial/SubEditors/TutorialAssets/TutorialParticleSystem.TutorialParticleSystem'")); if (ParticleSystem.Object != nullptr) { SpawnPoint->SetTemplate(ParticleSystem.Object); } SpawnPoint->SetRelativeScale3D(FVector(0.5, 0.5, 0.5)); SpawnCollisionHandlingMethod = ESpawnActorCollisionHandlingMethod::AlwaysSpawn; } // Called when the game starts or when spawned void ABarricksUnit::BeginPlay() { Super::BeginPlay(); SpawnPoint->AttachTo(RootComponent); } // Called every frame void ABarricksUnit::Tick(float DeltaTime) { Super::Tick(DeltaTime); SetActorLocation(GetActorLocation() + FVector(10, 0, 0)); } // Called to bind functionality to input void ABarricksUnit::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); }
27.653846
192
0.749652
CoolHandNick80
a0f4e25382743a924359a066604f26bc2d114b41
158
cpp
C++
examples/access-via-this-under-construction.cpp
dawidpilarski/LifetimePresentation
56d59295b5ace86015072e65bccb3310cc5a435e
[ "BSD-3-Clause" ]
null
null
null
examples/access-via-this-under-construction.cpp
dawidpilarski/LifetimePresentation
56d59295b5ace86015072e65bccb3310cc5a435e
[ "BSD-3-Clause" ]
null
null
null
examples/access-via-this-under-construction.cpp
dawidpilarski/LifetimePresentation
56d59295b5ace86015072e65bccb3310cc5a435e
[ "BSD-3-Clause" ]
null
null
null
struct C { int c; C() : c(0) { no_opt(); } }; const C cobj; void no_opt() { int i = cobj.c * 100; //unspecified value std::cout << i << std::endl; }
15.8
43
0.525316
dawidpilarski
a0f5a62ecf0c44be91f23e92204d834d6c8bfae8
5,122
cpp
C++
src/saiga/vision/camera/KittiDataset.cpp
SimonMederer/saiga
ff167e60c50b1cead4d19eb5ab2e93acce8c42a3
[ "MIT" ]
null
null
null
src/saiga/vision/camera/KittiDataset.cpp
SimonMederer/saiga
ff167e60c50b1cead4d19eb5ab2e93acce8c42a3
[ "MIT" ]
null
null
null
src/saiga/vision/camera/KittiDataset.cpp
SimonMederer/saiga
ff167e60c50b1cead4d19eb5ab2e93acce8c42a3
[ "MIT" ]
null
null
null
/** * Copyright (c) 2017 Darius Rückert * Licensed under the MIT License. * See LICENSE file for more information. */ #include "KittiDataset.h" #include "saiga/core/util/ProgressBar.h" #include "saiga/core/util/easylogging++.h" #include "saiga/core/util/file.h" #include "saiga/core/util/fileChecker.h" #include "saiga/core/util/tostring.h" #include "saiga/vision/camera/TimestampMatcher.h" #include <filesystem> namespace Saiga { KittiDataset::KittiDataset(const DatasetParameters& params_) : DatasetCameraBase<StereoFrameData>(params_) { // Kitti was recorded with 10 fps intrinsics.fps = 10; VLOG(1) << "Loading KittiDataset Stereo Dataset: " << params.dir; auto leftImageDir = params.dir + "/image_0"; auto rightImageDir = params.dir + "/image_1"; auto calibFile = params.dir + "/calib.txt"; auto timesFile = params.dir + "/times.txt"; auto groundtruthFile = params.groundTruth; SAIGA_ASSERT(std::filesystem::exists(leftImageDir)); SAIGA_ASSERT(std::filesystem::exists(rightImageDir)); SAIGA_ASSERT(std::filesystem::exists(calibFile)); SAIGA_ASSERT(std::filesystem::exists(timesFile)); { // load calibration matrices // They are stored like this: // P0: a00, a01, a02, ... auto lines = File::loadFileStringArray(calibFile); std::vector<Eigen::Matrix<double, 3, 4>> matrices; StringViewParser parser(" "); for (auto l : lines) { if (l.empty()) continue; parser.set(l); // parse the "P0" parser.next(); Eigen::Matrix<double, 3, 4> m; for (int i = 0; i < 12; ++i) { auto sv = parser.next(); SAIGA_ASSERT(!sv.empty()); m(i / 4, i % 4) = to_double(sv); } // std::cout << m << std::endl << std::endl; matrices.push_back(m); } SAIGA_ASSERT(matrices.size() == 4); // Extract K and bf // Distortion is 0 Mat3 K1 = matrices[0].block<3, 3>(0, 0); Mat3 K2 = matrices[1].block<3, 3>(0, 0); double bf = -matrices[1](0, 3); intrinsics.model.K = K1; intrinsics.rightModel.K = K2; intrinsics.bf = bf; } std::cout << intrinsics << std::endl; std::vector<double> timestamps; { // load timestamps auto lines = File::loadFileStringArray(timesFile); for (auto l : lines) { if (l.empty()) continue; timestamps.push_back(Saiga::to_double(l)); } std::cout << "got " << timestamps.size() << " timestamps" << std::endl; } std::vector<SE3> groundTruth; if (std::filesystem::exists(params.groundTruth)) { // load ground truth std::cout << "loading ground truth " << std::endl; auto lines = File::loadFileStringArray(params.groundTruth); StringViewParser parser(" "); for (auto l : lines) { if (l.empty()) continue; parser.set(l); Eigen::Matrix<double, 3, 4> m; for (int i = 0; i < 12; ++i) { auto sv = parser.next(); SAIGA_ASSERT(!sv.empty()); m(i / 4, i % 4) = to_double(sv); } // std::cout << m << std::endl << std::endl; // matrices.push_back(m); Mat4 m4 = Mat4::Identity(); m4.block<3, 4>(0, 0) = m; groundTruth.push_back(SE3::fitToSE3(m4)); } SAIGA_ASSERT(groundTruth.size() == timestamps.size()); } { // load left and right images // frames.resize(N); int N = timestamps.size(); if (params.maxFrames == -1) { params.maxFrames = N; } params.maxFrames = std::min(N - params.startFrame, params.maxFrames); frames.resize(params.maxFrames); N = params.maxFrames; SyncedConsoleProgressBar loadingBar(std::cout, "Loading " + to_string(N) + " images ", N); #pragma omp parallel for if (params.multiThreadedLoad) for (int id = 0; id < params.maxFrames; ++id) { auto& frame = frames[id]; int i = id + params.startFrame; std::string leftFile = leftImageDir + "/" + leadingZeroString(i, 6) + ".png"; std::string rightFile = rightImageDir + "/" + leadingZeroString(i, 6) + ".png"; frame.grayImg.load(leftFile); frame.grayImg2.load(rightFile); SAIGA_ASSERT(frame.grayImg); SAIGA_ASSERT(frame.grayImg2); if (!groundTruth.empty()) frame.groundTruth = groundTruth[i]; frame.timeStamp = timestamps[i]; loadingBar.addProgress(1); } auto firstFrame = frames.front(); intrinsics.imageSize = firstFrame.grayImg.dimensions(); intrinsics.rightImageSize = firstFrame.grayImg2.dimensions(); } } } // namespace Saiga
28.614525
106
0.544319
SimonMederer
a0f628edf7995e28becf70ba07b68df379b0cb34
1,427
cpp
C++
4. Алгоритмы на графах/3.1. Максимальное число маршрутов (не пересекающихся по рёбрам) #747/[OK]234197.cpp
godnoTA/acm.bsu.by
3e1cf1c545c691de82b5e1d2e0768b41ea581734
[ "Unlicense" ]
19
2018-05-19T16:37:14.000Z
2022-03-23T20:13:43.000Z
4. Алгоритмы на графах/3.1. Максимальное число маршрутов (не пересекающихся по рёбрам) #747/[OK]234197.cpp
godnoTA/acm.bsu.by
3e1cf1c545c691de82b5e1d2e0768b41ea581734
[ "Unlicense" ]
6
2020-05-07T21:06:48.000Z
2020-06-05T17:52:57.000Z
4. Алгоритмы на графах/3.1. Максимальное число маршрутов (не пересекающихся по рёбрам) #747/[OK]234197.cpp
godnoTA/acm.bsu.by
3e1cf1c545c691de82b5e1d2e0768b41ea581734
[ "Unlicense" ]
31
2019-03-01T21:41:38.000Z
2022-03-27T17:56:39.000Z
#include <iostream> #include <string.h> #include <queue> #include <fstream> using namespace std; int N, s,t; const int MAXN=100; int matrix[MAXN][MAXN]; bool bfs(int parent[]) { bool visit[N]; memset(visit, 0, sizeof(visit)); queue <int> q; q.push(s); visit[s] = true; parent[s] = -1; while (!q.empty()) { int i = q.front(); q.pop(); for (int j=0; j<N; j++) { if (visit[j]!= true&& matrix[i][j]!=0) { q.push(j); parent[j] = i; visit[j] = true; } } } if(visit[t] == true) return true; else return false; } int Ford_Fulkerson() { int parent[N]; int max_flow = 0; while (bfs(parent)== true) { for (int v=t; v != s; v=parent[v]) { int u = parent[v]; matrix[u][v] -= 1; matrix[v][u] += 1; } max_flow++; } return max_flow; } int main() { ofstream fout("output.out"); ifstream fin("input.in"); int n, m; fin>>n>>m; N=n; int buf; for(int i=0; i<n; i++) { fin>>buf; while (buf!=0) { matrix[i][buf-1]=1; fin>>buf; } } fin>>s>>t; --s; --t; fout<<Ford_Fulkerson(); return 0; }
17.8375
51
0.403644
godnoTA
a0f6a90104d0eea3dff399517fc88b84b3914b4c
9,116
cpp
C++
WebKit2-7606.2.104.1.1/WebKit2-7606.2.104.1.1/WebProcess/InjectedBundle/API/gtk/DOM/WebKitDOMUIEvent.cpp
mlcldh/appleWebKit2
39cc42a4710c9319c8da269621844493ab2ccdd6
[ "MIT" ]
1
2021-05-27T07:29:31.000Z
2021-05-27T07:29:31.000Z
WebKit2-7606.2.104.1.1/WebKit2-7606.2.104.1.1/WebProcess/InjectedBundle/API/gtk/DOM/WebKitDOMUIEvent.cpp
mlcldh/appleWebKit2
39cc42a4710c9319c8da269621844493ab2ccdd6
[ "MIT" ]
null
null
null
WebKit2-7606.2.104.1.1/WebKit2-7606.2.104.1.1/WebProcess/InjectedBundle/API/gtk/DOM/WebKitDOMUIEvent.cpp
mlcldh/appleWebKit2
39cc42a4710c9319c8da269621844493ab2ccdd6
[ "MIT" ]
null
null
null
/* * This file is part of the WebKit open source project. * * 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; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #include "WebKitDOMUIEvent.h" #include <WebCore/CSSImportRule.h> #include "DOMObjectCache.h" #include <WebCore/Document.h> #include <WebCore/ExceptionCode.h> #include <WebCore/JSMainThreadExecState.h> #include <WebCore/KeyboardEvent.h> #include "WebKitDOMDOMWindowPrivate.h" #include "WebKitDOMEventPrivate.h" #include "WebKitDOMPrivate.h" #include "WebKitDOMUIEventPrivate.h" #include "ConvertToUTF8String.h" #include <wtf/GetPtr.h> #include <wtf/RefPtr.h> G_GNUC_BEGIN_IGNORE_DEPRECATIONS; namespace WebKit { WebKitDOMUIEvent* kit(WebCore::UIEvent* obj) { return WEBKIT_DOM_UI_EVENT(kit(static_cast<WebCore::Event*>(obj))); } WebCore::UIEvent* core(WebKitDOMUIEvent* request) { return request ? static_cast<WebCore::UIEvent*>(WEBKIT_DOM_OBJECT(request)->coreObject) : 0; } WebKitDOMUIEvent* wrapUIEvent(WebCore::UIEvent* coreObject) { ASSERT(coreObject); return WEBKIT_DOM_UI_EVENT(g_object_new(WEBKIT_DOM_TYPE_UI_EVENT, "core-object", coreObject, nullptr)); } } // namespace WebKit G_DEFINE_TYPE(WebKitDOMUIEvent, webkit_dom_ui_event, WEBKIT_DOM_TYPE_EVENT) enum { DOM_UI_EVENT_PROP_0, DOM_UI_EVENT_PROP_VIEW, DOM_UI_EVENT_PROP_DETAIL, DOM_UI_EVENT_PROP_KEY_CODE, DOM_UI_EVENT_PROP_CHAR_CODE, DOM_UI_EVENT_PROP_LAYER_X, DOM_UI_EVENT_PROP_LAYER_Y, DOM_UI_EVENT_PROP_PAGE_X, DOM_UI_EVENT_PROP_PAGE_Y, }; static void webkit_dom_ui_event_get_property(GObject* object, guint propertyId, GValue* value, GParamSpec* pspec) { WebKitDOMUIEvent* self = WEBKIT_DOM_UI_EVENT(object); switch (propertyId) { case DOM_UI_EVENT_PROP_VIEW: g_value_set_object(value, webkit_dom_ui_event_get_view(self)); break; case DOM_UI_EVENT_PROP_DETAIL: g_value_set_long(value, webkit_dom_ui_event_get_detail(self)); break; case DOM_UI_EVENT_PROP_KEY_CODE: g_value_set_long(value, webkit_dom_ui_event_get_key_code(self)); break; case DOM_UI_EVENT_PROP_CHAR_CODE: g_value_set_long(value, webkit_dom_ui_event_get_char_code(self)); break; case DOM_UI_EVENT_PROP_LAYER_X: g_value_set_long(value, webkit_dom_ui_event_get_layer_x(self)); break; case DOM_UI_EVENT_PROP_LAYER_Y: g_value_set_long(value, webkit_dom_ui_event_get_layer_y(self)); break; case DOM_UI_EVENT_PROP_PAGE_X: g_value_set_long(value, webkit_dom_ui_event_get_page_x(self)); break; case DOM_UI_EVENT_PROP_PAGE_Y: g_value_set_long(value, webkit_dom_ui_event_get_page_y(self)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propertyId, pspec); break; } } static void webkit_dom_ui_event_class_init(WebKitDOMUIEventClass* requestClass) { GObjectClass* gobjectClass = G_OBJECT_CLASS(requestClass); gobjectClass->get_property = webkit_dom_ui_event_get_property; g_object_class_install_property( gobjectClass, DOM_UI_EVENT_PROP_VIEW, g_param_spec_object( "view", "UIEvent:view", "read-only WebKitDOMDOMWindow* UIEvent:view", WEBKIT_DOM_TYPE_DOM_WINDOW, WEBKIT_PARAM_READABLE)); g_object_class_install_property( gobjectClass, DOM_UI_EVENT_PROP_DETAIL, g_param_spec_long( "detail", "UIEvent:detail", "read-only glong UIEvent:detail", G_MINLONG, G_MAXLONG, 0, WEBKIT_PARAM_READABLE)); g_object_class_install_property( gobjectClass, DOM_UI_EVENT_PROP_KEY_CODE, g_param_spec_long( "key-code", "UIEvent:key-code", "read-only glong UIEvent:key-code", G_MINLONG, G_MAXLONG, 0, WEBKIT_PARAM_READABLE)); g_object_class_install_property( gobjectClass, DOM_UI_EVENT_PROP_CHAR_CODE, g_param_spec_long( "char-code", "UIEvent:char-code", "read-only glong UIEvent:char-code", G_MINLONG, G_MAXLONG, 0, WEBKIT_PARAM_READABLE)); g_object_class_install_property( gobjectClass, DOM_UI_EVENT_PROP_LAYER_X, g_param_spec_long( "layer-x", "UIEvent:layer-x", "read-only glong UIEvent:layer-x", G_MINLONG, G_MAXLONG, 0, WEBKIT_PARAM_READABLE)); g_object_class_install_property( gobjectClass, DOM_UI_EVENT_PROP_LAYER_Y, g_param_spec_long( "layer-y", "UIEvent:layer-y", "read-only glong UIEvent:layer-y", G_MINLONG, G_MAXLONG, 0, WEBKIT_PARAM_READABLE)); g_object_class_install_property( gobjectClass, DOM_UI_EVENT_PROP_PAGE_X, g_param_spec_long( "page-x", "UIEvent:page-x", "read-only glong UIEvent:page-x", G_MINLONG, G_MAXLONG, 0, WEBKIT_PARAM_READABLE)); g_object_class_install_property( gobjectClass, DOM_UI_EVENT_PROP_PAGE_Y, g_param_spec_long( "page-y", "UIEvent:page-y", "read-only glong UIEvent:page-y", G_MINLONG, G_MAXLONG, 0, WEBKIT_PARAM_READABLE)); } static void webkit_dom_ui_event_init(WebKitDOMUIEvent* request) { UNUSED_PARAM(request); } void webkit_dom_ui_event_init_ui_event(WebKitDOMUIEvent* self, const gchar* type, gboolean canBubble, gboolean cancelable, WebKitDOMDOMWindow* view, glong detail) { WebCore::JSMainThreadNullState state; g_return_if_fail(WEBKIT_DOM_IS_UI_EVENT(self)); g_return_if_fail(type); g_return_if_fail(WEBKIT_DOM_IS_DOM_WINDOW(view)); WebCore::UIEvent* item = WebKit::core(self); WTF::String convertedType = WTF::String::fromUTF8(type); item->initUIEvent(convertedType, canBubble, cancelable, WebKit::toWindowProxy(view), detail); } WebKitDOMDOMWindow* webkit_dom_ui_event_get_view(WebKitDOMUIEvent* self) { WebCore::JSMainThreadNullState state; g_return_val_if_fail(WEBKIT_DOM_IS_UI_EVENT(self), 0); WebCore::UIEvent* item = WebKit::core(self); return WebKit::kit(item->view()); } glong webkit_dom_ui_event_get_detail(WebKitDOMUIEvent* self) { WebCore::JSMainThreadNullState state; g_return_val_if_fail(WEBKIT_DOM_IS_UI_EVENT(self), 0); WebCore::UIEvent* item = WebKit::core(self); glong result = item->detail(); return result; } glong webkit_dom_ui_event_get_key_code(WebKitDOMUIEvent* self) { WebCore::JSMainThreadNullState state; g_return_val_if_fail(WEBKIT_DOM_IS_UI_EVENT(self), 0); WebCore::UIEvent* item = WebKit::core(self); glong result = is<WebCore::KeyboardEvent>(*item) ? downcast<WebCore::KeyboardEvent>(*item).keyCode() : 0; return result; } glong webkit_dom_ui_event_get_char_code(WebKitDOMUIEvent* self) { WebCore::JSMainThreadNullState state; g_return_val_if_fail(WEBKIT_DOM_IS_UI_EVENT(self), 0); WebCore::UIEvent* item = WebKit::core(self); glong result = is<WebCore::KeyboardEvent>(*item) ? downcast<WebCore::KeyboardEvent>(*item).charCode() : 0; return result; } glong webkit_dom_ui_event_get_layer_x(WebKitDOMUIEvent* self) { WebCore::JSMainThreadNullState state; g_return_val_if_fail(WEBKIT_DOM_IS_UI_EVENT(self), 0); WebCore::UIEvent* item = WebKit::core(self); glong result = item->layerX(); return result; } glong webkit_dom_ui_event_get_layer_y(WebKitDOMUIEvent* self) { WebCore::JSMainThreadNullState state; g_return_val_if_fail(WEBKIT_DOM_IS_UI_EVENT(self), 0); WebCore::UIEvent* item = WebKit::core(self); glong result = item->layerY(); return result; } glong webkit_dom_ui_event_get_page_x(WebKitDOMUIEvent* self) { WebCore::JSMainThreadNullState state; g_return_val_if_fail(WEBKIT_DOM_IS_UI_EVENT(self), 0); WebCore::UIEvent* item = WebKit::core(self); glong result = item->pageX(); return result; } glong webkit_dom_ui_event_get_page_y(WebKitDOMUIEvent* self) { WebCore::JSMainThreadNullState state; g_return_val_if_fail(WEBKIT_DOM_IS_UI_EVENT(self), 0); WebCore::UIEvent* item = WebKit::core(self); glong result = item->pageY(); return result; } G_GNUC_END_IGNORE_DEPRECATIONS;
32.441281
162
0.709193
mlcldh
a0f935ea1b19f2035a51876111e7b2d8b81018d0
2,112
hpp
C++
include/linear_algebra/addition_traits_impl.hpp
shogun-toolbox/linger
953628ef636b7f87f5cdcbc6dd7367a1476ebc39
[ "BSD-3-Clause" ]
1
2020-04-26T09:45:32.000Z
2020-04-26T09:45:32.000Z
include/linear_algebra/addition_traits_impl.hpp
shogun-toolbox/linger
953628ef636b7f87f5cdcbc6dd7367a1476ebc39
[ "BSD-3-Clause" ]
2
2019-11-12T16:09:31.000Z
2020-09-09T18:52:43.000Z
include/linear_algebra/addition_traits_impl.hpp
shogun-toolbox/linger
953628ef636b7f87f5cdcbc6dd7367a1476ebc39
[ "BSD-3-Clause" ]
3
2019-11-11T15:55:48.000Z
2020-06-02T20:33:48.000Z
//================================================================================================== // File: addition_traits_impl.hpp // // Summary: This header defines the static member functions of matrix_addition_traits that // perform the actual arithmetic. //================================================================================================== // #ifndef LINEAR_ALGEBRA_ADDITION_TRAITS_IMPL_HPP_DEFINED #define LINEAR_ALGEBRA_ADDITION_TRAITS_IMPL_HPP_DEFINED namespace STD_LA { //================================================================================================= // **** ADDITION TRAITS FUNCTION IMPLEMENTATION **** //================================================================================================== // template<class OT, class ET1, class OT1, class ET2, class OT2> inline auto matrix_addition_traits<OT, vector<ET1, OT1>, vector<ET2, OT2>>::add (vector<ET1, OT1> const& v1, vector<ET2, OT2> const& v2) -> result_type { PrintOperandTypes<result_type>("addition_traits", v1, v2); result_type vr; if constexpr (result_requires_resize(vr)) { vr.resize(v1.elements()); } transform(v1.begin(), v1.end(), v2.begin(), vr.begin(), [](auto lhs, auto rhs) { return lhs + rhs; }); return vr; } //------ // template<class OT, class ET1, class OT1, class ET2, class OT2> inline auto matrix_addition_traits<OT, matrix<ET1, OT1>, matrix<ET2, OT2>>::add (matrix<ET1, OT1> const& m1, matrix<ET2, OT2> const& m2) -> result_type { PrintOperandTypes<result_type>("addition_traits", m1, m2); result_type mr{}; //- Braces here to avoid C4701 from MSVC auto const rows = m1.rows(); auto const columns = m1.columns(); if constexpr (result_requires_resize(mr)) { mr.resize(rows, columns); } for (auto i = 0; i < rows; ++i) { for (auto j = 0; j < columns; ++j) { mr(i, j) = m1(i, j) + m2(i, j); } } return mr; } } //- STD_LA namespace #endif //- LINEAR_ALGEBRA_ADDITION_TRAITS_IMPL_HPP_DEFINED
32
106
0.516098
shogun-toolbox
a0f9cce195257aaf52a404852335cf7a0f4f2306
6,696
cpp
C++
legacy/src/camera/COrbitCamera.cpp
wpumacay/tiny_renderer
9d59be49086822860654afddaf94ce1cec374ea8
[ "MIT" ]
1
2018-07-05T15:54:51.000Z
2018-07-05T15:54:51.000Z
legacy/src/camera/COrbitCamera.cpp
wpumacay/cat1
9d59be49086822860654afddaf94ce1cec374ea8
[ "MIT" ]
null
null
null
legacy/src/camera/COrbitCamera.cpp
wpumacay/cat1
9d59be49086822860654afddaf94ce1cec374ea8
[ "MIT" ]
null
null
null
#include <camera/COrbitCamera.h> namespace engine { std::string ToString( const eOrbitCameraState& state ) { /**/ if ( state == eOrbitCameraState::IDLE ) return "idle"; else if ( state == eOrbitCameraState::DRAGGING ) return "dragging"; else if ( state == eOrbitCameraState::MOVING_TARGET ) return "moving_target"; ENGINE_CORE_CRITICAL( "Invalid orbit-camera state" ); return "undefined"; } COrbitCamera::COrbitCamera( const std::string& name, const CVec3& position, const CVec3& target_point, const eAxis& up_axis, const CCameraProjData& proj_data, float move_sensitivity, float zoom_sensitivity ) : CICamera( name, position, target_point, up_axis, proj_data ) { m_Type = eCameraType::ORBIT; m_TargetPoint0 = m_TargetPoint; m_MoveSensitivity = move_sensitivity; m_ZoomSensitivity = zoom_sensitivity; _ComputeSphericalsFromPosition(); _UpdateCameraVectors(); _BuildViewMatrix(); } void COrbitCamera::_PositionChangedInternal() { _ComputeSphericalsFromPosition(); _UpdateCameraVectors(); _BuildViewMatrix(); } void COrbitCamera::_TargetPointChangedInternal() { _ComputeSphericalsFromPosition(); _UpdateCameraVectors(); _BuildViewMatrix(); } void COrbitCamera::_UpdateInternal() { if ( !m_Active ) return; if ( m_State == eOrbitCameraState::IDLE ) { if ( CInputManager::IsMouseDown( Mouse::BUTTON_LEFT ) ) { m_State = eOrbitCameraState::DRAGGING; m_Cursor0 = CInputManager::GetCursorPosition(); m_Cursor = CInputManager::GetCursorPosition(); m_Phi0 = m_Phi; m_Theta0 = m_Theta; } else if ( CInputManager::IsMouseDown( Mouse::BUTTON_RIGHT ) ) { m_State = eOrbitCameraState::MOVING_TARGET; m_Cursor0 = CInputManager::GetCursorPosition(); m_Cursor = CInputManager::GetCursorPosition(); m_TargetPoint0 = m_TargetPoint; } } else if ( m_State == eOrbitCameraState::DRAGGING ) { m_Cursor = CInputManager::GetCursorPosition(); float _dx = m_Cursor.x() - m_Cursor0.x(); float _dy = m_Cursor.y() - m_Cursor0.y(); float _dtheta = ( -_dx / m_ProjData.viewportWidth ) * 2.0f * engine::PI; float _dphi = ( -_dy / m_ProjData.viewportHeight ) * engine::PI; m_Theta = m_Theta0 + _dtheta; m_Phi = m_Phi0 + _dphi; if ( !CInputManager::IsMouseDown( Mouse::BUTTON_LEFT ) ) m_State = eOrbitCameraState::IDLE; } else if ( m_State == eOrbitCameraState::MOVING_TARGET ) { m_Cursor = CInputManager::GetCursorPosition(); float _dx = -( m_Cursor.x() - m_Cursor0.x() ); float _dy = m_Cursor.y() - m_Cursor0.y(); m_TargetPoint.x() = m_TargetPoint0.x() + ( m_Right.x() * _dx + m_Up.x() * _dy ) * m_MoveSensitivity; m_TargetPoint.y() = m_TargetPoint0.y() + ( m_Right.y() * _dx + m_Up.y() * _dy ) * m_MoveSensitivity; m_TargetPoint.z() = m_TargetPoint0.z(); if ( !CInputManager::IsMouseDown( Mouse::BUTTON_RIGHT ) ) m_State = eOrbitCameraState::IDLE; } m_Rho = m_Rho0 + ( m_ZoomSensitivity * CInputManager::GetScrollAccumValueY() ) * 0.25f; _ComputePositionFromSphericals(); _UpdateCameraVectors(); _BuildViewMatrix(); } std::string COrbitCamera::_ToStringInternal() const { std::string strrep; strrep += "state : " + engine::ToString( m_State ) + "\n\r"; strrep += "front : " + engine::toString( m_Front ) + "\n\r"; strrep += "right : " + engine::toString( m_Right ) + "\n\r"; strrep += "up : " + engine::toString( m_Up ) + "\n\r"; strrep += "rho : " + std::to_string( m_Rho ) + "\n\r"; strrep += "rho0 : " + std::to_string( m_Rho0 ) + "\n\r"; strrep += "phi : " + std::to_string( m_Phi ) + "\n\r"; strrep += "phi0 : " + std::to_string( m_Phi ) + "\n\r"; strrep += "theta : " + std::to_string( m_Theta ) + "\n\r"; strrep += "theta0 : " + std::to_string( m_Theta0 ) + "\n\r"; strrep += "r : " + engine::toString( m_Radial ) + "\n\r"; return strrep; } void COrbitCamera::_ComputeSphericalsFromPosition() { m_Radial = m_Position - m_TargetPoint; m_Rho0 = m_Rho = m_Radial.length(); if ( m_UpAxis == eAxis::X ) { m_Phi0 = m_Phi = std::acos( m_Radial.x() / m_Rho0 ); m_Theta0 = m_Theta = std::atan2( m_Radial.z(), m_Radial.y() ); } else if ( m_UpAxis == eAxis::Y ) { m_Phi0 = m_Phi = std::acos( m_Radial.y() / m_Rho0 ); m_Theta0 = m_Theta = std::atan2( m_Radial.x(), m_Radial.z() ); } else if ( m_UpAxis == eAxis::Z ) { m_Phi0 = m_Phi = std::acos( m_Radial.z() / m_Rho0 ); m_Theta0 = m_Theta = std::atan2( m_Radial.y(), m_Radial.x() ); } } void COrbitCamera::_ComputePositionFromSphericals() { const float _sphi = std::sin( m_Phi ); const float _cphi = std::cos( m_Phi ); const float _stheta = std::sin( m_Theta ); const float _ctheta = std::cos( m_Theta ); if ( m_UpAxis == eAxis::X ) { m_Radial.x() = m_Rho * _cphi; m_Radial.y() = m_Rho * _sphi * _ctheta; m_Radial.z() = m_Rho * _sphi * _stheta; } else if ( m_UpAxis == eAxis::Y ) { m_Radial.x() = m_Rho * _sphi * _stheta; m_Radial.y() = m_Rho * _cphi; m_Radial.z() = m_Rho * _sphi * _ctheta; } else if ( m_UpAxis == eAxis::Z ) { m_Radial.x() = m_Rho * _sphi * _ctheta; m_Radial.y() = m_Rho * _sphi * _stheta; m_Radial.z() = m_Rho * _cphi; } m_Position = m_TargetPoint + m_Radial; } void COrbitCamera::_UpdateCameraVectors() { m_Front = ( m_TargetPoint - m_Position ).normalized(); m_Right = tinymath::cross( m_Front, m_WorldUp ).normalized(); m_Up = tinymath::cross( m_Right, m_Front ).normalized(); } }
35.428571
112
0.535842
wpumacay
a0fc472e9841a08da115d317e030776f7ade7508
28,805
cpp
C++
src/libishlang/parser.cpp
jrtabash/ishlang
7e1d5dcfbb3383854ac9bff643d9f5820a63091e
[ "MIT" ]
2
2019-09-11T17:49:29.000Z
2021-09-03T21:13:17.000Z
src/libishlang/parser.cpp
jrtabash/ishlang
7e1d5dcfbb3383854ac9bff643d9f5820a63091e
[ "MIT" ]
null
null
null
src/libishlang/parser.cpp
jrtabash/ishlang
7e1d5dcfbb3383854ac9bff643d9f5820a63091e
[ "MIT" ]
null
null
null
#include "parser.h" #include "exception.h" #include "struct.h" #include "util.h" #include <algorithm> #include <cctype> #include <cstdlib> #include <fstream> using namespace Ishlang; // ------------------------------------------------------------- Parser::Parser() : lexer_() { initAppFtns(); } // ------------------------------------------------------------- CodeNode::SharedPtr Parser::read(const std::string &expr) { lexer_.read(expr); return readExpr(); } // ------------------------------------------------------------- CodeNode::SharedPtr Parser::readLiteral(const std::string &expr) { const auto tokTyp = Lexer::tokenType(expr); switch (tokTyp) { case Lexer::Char: case Lexer::String: case Lexer::Int: case Lexer::Real: case Lexer::Bool: case Lexer::Null: return makeLiteral(tokTyp, expr); default: break; } return std::make_shared<Literal>(Value(expr)); } // ------------------------------------------------------------- void Parser::readMulti(const std::string &expr, CallBack callback) { lexer_.read(expr); while (!lexer_.empty()) { if (!haveSExpression()) { return; } auto code = readExpr(); if (code.get()) { callback(code); } } } // ------------------------------------------------------------- void Parser::readFile(const std::string &filename, CallBack callback) { std::ifstream ifs(filename.c_str()); if (!ifs.is_open()) { throw UnknownFile(filename); } unsigned lineNo = 0; try { std::string line; while (std::getline(ifs, line)) { ++lineNo; readMulti(line, callback); } if (hasIncompleteExpr()) { clearIncompleteExpr(); throw IncompleteExpression("Incomplete code at end of file " + filename); } ifs.close(); } catch (Exception &ex) { ifs.close(); ex.setFileContext(filename, lineNo); throw; } catch (...) { ifs.close(); throw; } } // ------------------------------------------------------------- CodeNode::SharedPtr Parser::readExpr() { while (!lexer_.empty()) { if (!haveSExpression()) { return CodeNode::SharedPtr(); } auto token = lexer_.next(); if (!token.text.empty()) { switch (token.type) { case Lexer::LeftP: return readApp(); case Lexer::RightP: return CodeNode::SharedPtr(); case Lexer::Char: case Lexer::String: case Lexer::Int: case Lexer::Real: case Lexer::Bool: case Lexer::Null: return makeLiteral(token.type, token.text); case Lexer::Symbol: return std::make_shared<Variable>(token.text); case Lexer::Unknown: throw UnknownTokenType(token.text, static_cast<char>(token.type)); break; } } } return std::make_shared<Literal>(Value::Null); } // ------------------------------------------------------------- CodeNode::SharedPtr Parser::makeLiteral(Lexer::TokenType type, const std::string &text) { switch (type) { case Lexer::Char: return std::make_shared<Literal>(Value(text[1])); case Lexer::String: return std::make_shared<Literal>(Value(std::string(text.c_str() + 1, text.size() - 2))); case Lexer::Int: return std::make_shared<Literal>(Value(Value::Long(std::stoll(text, 0, 10)))); case Lexer::Real: return std::make_shared<Literal>(Value(std::stod(text, 0))); case Lexer::Bool: return std::make_shared<Literal>((Value(Value::Bool(text == "true")))); default: break; } return std::make_shared<Literal>(Value::Null); } // ------------------------------------------------------------- CodeNode::SharedPtr Parser::readApp(const std::string &expected) { if (!lexer_.empty()) { auto token = lexer_.next(); if (!token.text.empty()) { if (!expected.empty() && token.text != expected) { throw UnexpectedExpression("lambda", token.text); } auto iter = appFtns_.find(token.text); if (iter != appFtns_.end()) { return iter->second(); } else { if (token.type == Lexer::Symbol) { const auto & name(token.text); auto args(readExprList()); return std::make_shared<FunctionApp>(name, args); } else { throw UnknownSymbol(token.text); } } } } return std::make_shared<Literal>(Value::Null); } // ------------------------------------------------------------- CodeNode::SharedPtrList Parser::readExprList() { CodeNode::SharedPtrList forms; auto form = readExpr(); while (form.get()) { forms.push_back(form); form = readExpr(); } return forms; } // ------------------------------------------------------------- CodeNode::SharedPtrList Parser::readAndCheckExprList(const char *name, std::size_t expectedSize) { auto exprs(readExprList()); if (exprs.size() != expectedSize) { throw TooManyOrFewForms(name); } return exprs; } // ------------------------------------------------------------- CodeNode::SharedPtrList Parser::readAndCheckRangeExprList(const char *name, std::size_t minExpectedSize, std::size_t maxExpectedSize) { auto exprs(readExprList()); if (exprs.size() < minExpectedSize || exprs.size() > maxExpectedSize) { throw TooManyOrFewForms(name); } return exprs; } // ------------------------------------------------------------- CodeNode::SharedPtrPairs Parser::readExprPairs() { CodeNode::SharedPtrPairs pairs; CodeNode::SharedPtrPair cons; ignoreLeftP(false); cons.first = readExpr(); cons.second = readExpr(); ignoreRightP(); while (cons.first.get() && cons.second.get()) { pairs.push_back(cons); if (ignoreLeftP(true)) { break; } cons.first = readExpr(); cons.second = readExpr(); ignoreRightP(); } return pairs; } // ------------------------------------------------------------- CodeNode::NameSharedPtrs Parser::readNameExprPairs() { CodeNode::NameSharedPtrs nameExprs; std::pair<std::string, CodeNode::SharedPtr> cons; bool rpseen = false; if (lexer_.peek().type == Lexer::LeftP) { ignoreLeftP(false); cons.first = readName(); cons.second = readExpr(); ignoreRightP(); while (cons.second.get()) { nameExprs.push_back(cons); if (ignoreLeftP(true)) { rpseen = true; break; } cons.first = readName(); cons.second = readExpr(); ignoreRightP(); } } if (!rpseen && lexer_.peek().type == Lexer::RightP) { ignoreRightP(); } return nameExprs; } // ------------------------------------------------------------- std::string Parser::readName() { auto nameToken = lexer_.next(); if (nameToken.type != Lexer::Symbol) { throw UnexpectedExpression("name", nameToken.text); } return nameToken.text; } // ------------------------------------------------------------- CodeNode::NameAndAsList Parser::readNameAndAsList() { // Parse following format: "name [as asName] [name [as asName]]*" // Examples: // 1) foo // 2) foo as bar // 3) one two // 4) one as single two as double // 5) one two foo as bar CodeNode::NameAndAsList nameAndAsList; auto getNext = [this]() { auto token = lexer_.next(); if (token.type != Lexer::Symbol) { throw UnexpectedTokenType(token.text, token.type, "name/as list"); } return token; }; auto name = getNext(); while (name.type != Lexer::RightP) { if (name.text == "as") { throw InvalidExpression("Misformed name/as list"); } auto maybeAs = lexer_.next(); if (maybeAs.text == "as") { auto asName = getNext(); nameAndAsList.emplace_back(name.text, asName.text); name = lexer_.next(); } else { nameAndAsList.emplace_back(name.text, std::nullopt); name = maybeAs; } } return nameAndAsList; } // ------------------------------------------------------------- CodeNode::ParamList Parser::readParams() { CodeNode::ParamList params; auto token = lexer_.next(); if (token.type != Lexer::LeftP) { throw InvalidExpression("Expecting ( beginning of param list"); } token = lexer_.next(); while (token.type != Lexer::RightP) { if (token.type != Lexer::Symbol) { throw UnexpectedTokenType(token.text, token.type, "paramList"); } params.push_back(std::move(token.text)); token = lexer_.next(); } return params; } // ------------------------------------------------------------- bool Parser::ignoreLeftP(bool allowRightP) { auto token = lexer_.next(); if (token.type == Lexer::RightP && allowRightP) { return true; } if (token.type != Lexer::LeftP) { throw ExpectedParenthesis('('); } return false; } // ------------------------------------------------------------- void Parser::ignoreRightP() { if (lexer_.next().type != Lexer::RightP) { throw ExpectedParenthesis(')'); } } // ------------------------------------------------------------- bool Parser::haveSExpression() const { size_t openParenthesis = 0; for (auto iter = lexer_.cbegin(); iter != lexer_.cend(); ++iter) { const auto & token = *iter; if (token.type == Lexer::LeftP) { ++openParenthesis; } else if (token.type == Lexer::RightP) { if (openParenthesis > 0) { --openParenthesis; } } if (openParenthesis == 0) { return true; } } return openParenthesis == 0; } // ------------------------------------------------------------- void Parser::initAppFtns() { appFtns_ = { { "import", [this]() { const auto nameAndAsList = readNameAndAsList(); if (nameAndAsList.size() == 1) { return std::make_shared<ImportModule>(nameAndAsList[0].first, nameAndAsList[0].second ? *nameAndAsList[0].second : ""); } else { throw InvalidExpression("Misformed import"); } } }, { "from", [this]() { const auto name = readName(); const auto import = readName(); if (import != "import") { throw InvalidExpression("Misformed from/import"); } const auto nameAndAsList = readNameAndAsList(); if (nameAndAsList.size() > 0) { return std::make_shared<FromModuleImport>(name, nameAndAsList); } else { throw InvalidExpression("Misformed from/import"); } } }, { "var", [this]() { const auto name(readName()); auto expr(readAndCheckExprList("var", 1)); return std::make_shared<Define>(name, expr[0]); } }, { "=", [this]() { const auto name(readName()); auto expr(readAndCheckExprList("=", 1)); return std::make_shared<Assign>(name, expr[0]); } }, { "?", [this]() { const auto name(readName()); ignoreRightP(); return std::make_shared<Exists>(name); } }, { "clone", [this]() { auto expr(readAndCheckExprList("clone", 1)); return std::make_shared<Clone>(expr[0]); } }, { "+", MakeBinaryExpression<ArithOp, ArithOp::Type>("+", *this, ArithOp::Add) }, { "-", MakeBinaryExpression<ArithOp, ArithOp::Type>("-", *this, ArithOp::Sub) }, { "*", MakeBinaryExpression<ArithOp, ArithOp::Type>("*", *this, ArithOp::Mul) }, { "/", MakeBinaryExpression<ArithOp, ArithOp::Type>("/", *this, ArithOp::Div) }, { "%", MakeBinaryExpression<ArithOp, ArithOp::Type>("%", *this, ArithOp::Mod) }, { "^", MakeBinaryExpression<ArithOp, ArithOp::Type>("^", *this, ArithOp::Pow) }, { "==", MakeBinaryExpression<CompOp, CompOp::Type>("==", *this, CompOp::EQ) }, { "!=", MakeBinaryExpression<CompOp, CompOp::Type>("!=", *this, CompOp::NE) }, { "<", MakeBinaryExpression<CompOp, CompOp::Type>("<", *this, CompOp::LT) }, { ">", MakeBinaryExpression<CompOp, CompOp::Type>("<", *this, CompOp::GT) }, { "<=", MakeBinaryExpression<CompOp, CompOp::Type>("<=", *this, CompOp::LE) }, { ">=", MakeBinaryExpression<CompOp, CompOp::Type>(">=", *this, CompOp::GE) }, { "and", MakeBinaryExpression<LogicOp, LogicOp::Type>("and", *this, LogicOp::Conjunction) }, { "or", MakeBinaryExpression<LogicOp, LogicOp::Type>("or", *this, LogicOp::Disjunction) }, { "not", [this]() { auto expr(readAndCheckExprList("not", 1)); return std::make_shared<Not>(expr[0]); } }, { "neg", [this]() { auto expr(readAndCheckExprList("neg", 1)); return std::make_shared<NegativeOf>(expr[0]); } }, { "progn", [this]() { auto exprs(readExprList()); return std::make_shared<ProgN>(exprs); } }, { "block", [this]() { auto exprs(readExprList()); return std::make_shared<Block>(exprs); } }, { "if", [this]() { auto exprs(readExprList()); if (exprs.size() == 2) { return std::make_shared<If>(exprs[0], exprs[1]); } else if (exprs.size() == 3) { return std::make_shared<If>(exprs[0], exprs[1], exprs[2]); } else { throw TooManyOrFewForms("if"); } } }, { "when", [this]() { auto exprs(readAndCheckExprList("when", 2)); return std::make_shared<If>(exprs[0], exprs[1]); } }, { "unless", [this]() { auto exprs(readAndCheckExprList("unless", 2)); return std::make_shared<If>(std::make_shared<Not>(exprs[0]), exprs[1]); } }, { "cond", [this]() { auto pairs(readExprPairs()); return std::make_shared<Cond>(pairs); } }, { "break", [this]() { ignoreRightP(); return std::make_shared<Break>(); } }, { "loop", [this]() { auto forms(readExprList()); if (forms.size() == 4) { auto iter = forms.begin(); auto decl(*iter++); auto cond(*iter++); auto next(*iter++); auto body(*iter++); return std::make_shared<Loop>(decl, cond, next, body); } else if (forms.size() == 2) { auto iter = forms.begin(); auto cond(*iter++); auto body(*iter++); return std::make_shared<Loop>(cond, body); } else { throw TooManyOrFewForms("loop"); } } }, { "lambda", [this]() { auto params(readParams()); auto exprs(readExprList()); auto body(exprs.size() == 1 ? exprs[0] : std::make_shared<ProgN>(exprs)); return std::make_shared<LambdaExpr>(params, body); } }, { "defun", [this]() { const auto name(readName()); auto params(readParams()); auto exprs(readExprList()); auto body(exprs.size() == 1 ? exprs[0] : std::make_shared<ProgN>(exprs)); return std::make_shared<FunctionExpr>(name, params, body); } }, { "(", [this]() { auto lambda(readApp("lambda")); auto args(readExprList()); return std::make_shared<LambdaApp>(lambda, args); } }, { "istypeof", [this]() { auto form(readExpr()); auto type(Value::stringToType(readName())); ignoreRightP(); return std::make_shared<IsType>(form, type); } }, { "typename", [this]() { auto exprs(readAndCheckExprList("typename", 1)); return std::make_shared<TypeName>(exprs[0]); } }, { "astype", [this]() { auto form(readExpr()); auto type(Value::stringToType(readName())); ignoreRightP(); return std::make_shared<AsType>(form, type); } }, { "print", [this]() { auto exprs(readAndCheckExprList("print", 1)); return std::make_shared<Print>(false, exprs[0]); } }, { "println", [this]() { auto exprs(readAndCheckExprList("println", 1)); return std::make_shared<Print>(true, exprs[0]); } }, { "read", [this]() { ignoreRightP(); return std::make_shared<Read>(); } }, { "struct", [this]() { const auto name(readName()); const auto members(readParams()); ignoreRightP(); return std::make_shared<StructExpr>(name, members); } }, { "isstructname", [this]() { auto snExpr(readExpr()); const auto name(readName()); ignoreRightP(); return std::make_shared<IsStructName>(snExpr, name); } }, { "structname", [this]() { auto exprs(readAndCheckExprList("structname", 1)); return std::make_shared<StructName>(exprs[0]); } }, { "makeinstance", [this]() { const auto name(readName()); const auto initArgs = readNameExprPairs(); return std::make_shared<MakeInstance>(name, initArgs); } }, { "isinstanceof", [this]() { auto ioExpr(readExpr()); const auto name(readName()); ignoreRightP(); return std::make_shared<IsInstanceOf>(ioExpr, name); } }, { "memget", [this]() { auto instExpr(readExpr()); const auto name(readName()); ignoreRightP(); return std::make_shared<GetMember>(instExpr, name); } }, { "memset", [this]() { auto instExpr(readExpr()); const auto name(readName()); auto valueExpr(readExpr()); ignoreRightP(); return std::make_shared<SetMember>(instExpr, name, valueExpr); } }, { "strlen", [this]() { auto exprs(readAndCheckExprList("strlen", 1)); return std::make_shared<StringLen>(exprs[0]); } }, { "strget", [this]() { auto exprs(readAndCheckExprList("strget", 2)); return std::make_shared<StringGet>(exprs[0], exprs[1]); } }, { "strset", [this]() { auto exprs(readAndCheckExprList("strset", 3)); return std::make_shared<StringSet>(exprs[0], exprs[1], exprs[2]); } }, { "strcat", [this]() { auto exprs(readAndCheckExprList("strcat", 2)); return std::make_shared<StringCat>(exprs[0], exprs[1]); } }, { "substr", [this]() { auto exprs(readExprList()); if (exprs.size() == 2) { return std::make_shared<SubString>(exprs[0], exprs[1]); } else if (exprs.size() == 3) { return std::make_shared<SubString>(exprs[0], exprs[1], exprs[2]); } else { throw TooManyOrFewForms("substr"); } } }, { "strfind", [this]() { auto exprs(readExprList()); if (exprs.size() == 2) { return std::make_shared<StringFind>(exprs[0], exprs[1]); } else if (exprs.size() == 3) { return std::make_shared<StringFind>(exprs[0], exprs[1], exprs[2]); } else { throw TooManyOrFewForms("strfind"); } } }, { "strcount", [this]() { auto exprs(readAndCheckExprList("strcount", 2)); return std::make_shared<StringCount>(exprs[0], exprs[1]); } }, { "array", [this]() { auto valueExprs(readExprList()); if (valueExprs.size() == 0) { return std::make_shared<MakeArray>(); } else { return std::make_shared<MakeArray>(valueExprs); } } }, { "arraysv", [this]() { auto exprs(readExprList()); if (exprs.size() == 1) { return std::make_shared<MakeArraySV>(exprs[0]); } else if (exprs.size() == 2) { return std::make_shared<MakeArraySV>(exprs[0], exprs[1]); } else { throw TooManyOrFewForms("arraysv"); } } }, { "arrlen", [this]() { auto exprs(readAndCheckExprList("arrlen", 1)); return std::make_shared<ArrayLen>(exprs[0]); } }, { "arrget", [this]() { auto exprs(readAndCheckExprList("arrget", 2)); return std::make_shared<ArrayGet>(exprs[0], exprs[1]); } }, { "arrset", [this]() { auto exprs(readAndCheckExprList("arrset", 3)); return std::make_shared<ArraySet>(exprs[0], exprs[1], exprs[2]); } }, { "arradd", [this]() { auto exprs(readAndCheckExprList("arradd", 2)); return std::make_shared<ArrayAdd>(exprs[0], exprs[1]); } }, { "arrfind", [this]() { auto exprs(readExprList()); if (exprs.size() == 2) { return std::make_shared<ArrayFind>(exprs[0], exprs[1]); } else if (exprs.size() == 3) { return std::make_shared<ArrayFind>(exprs[0], exprs[1], exprs[2]); } else { throw TooManyOrFewForms("arrfind"); } } }, { "arrcount", [this]() { auto exprs(readAndCheckExprList("arrcount", 2)); return std::make_shared<ArrayCount>(exprs[0], exprs[1]); } }, { "isupper", MakeStrCharOp<StrCharCheck>("isupper", *this, StrCharCheck::Upper) }, { "islower", MakeStrCharOp<StrCharCheck>("islower", *this, StrCharCheck::Lower) }, { "isalpha", MakeStrCharOp<StrCharCheck>("isalpha", *this, StrCharCheck::Alpha) }, { "isnumer", MakeStrCharOp<StrCharCheck>("isnumer", *this, StrCharCheck::Numer) }, { "isalnum", MakeStrCharOp<StrCharCheck>("isalnum", *this, StrCharCheck::Alnum) }, { "ispunct", MakeStrCharOp<StrCharCheck>("ispunct", *this, StrCharCheck::Punct) }, { "isspace", MakeStrCharOp<StrCharCheck>("isspace", *this, StrCharCheck::Space) }, { "toupper", MakeStrCharOp<StrCharTransform>("toupper", *this, StrCharTransform::ToUpper) }, { "tolower", MakeStrCharOp<StrCharTransform>("tolower", *this, StrCharTransform::ToLower) }, { "rand", [this]() { auto exprs(readExprList()); if (exprs.size() > 1) { throw TooManyOrFewForms("rand"); } return std::make_shared<Random>(exprs.size() == 1 ? exprs[0] : CodeNode::SharedPtr()); } }, { "hash", [this]() { auto exprs(readAndCheckExprList("hash", 1)); return std::make_shared<Hash>(exprs[0]); } }, { "hashmap", [this]() { return std::make_shared<MakeHashMap>(readExprList()); } }, { "hmlen", [this]() { auto exprs(readAndCheckExprList("hmlen", 1)); return std::make_shared<HashMapLen>(exprs[0]); } }, { "hmhas", [this]() { auto exprs(readAndCheckExprList("hmhas", 2)); return std::make_shared<HashMapContains>(exprs[0], exprs[1]); } }, { "hmget", [this]() { auto exprs(readAndCheckRangeExprList("hmget", 2, 3)); return std::make_shared<HashMapGet>(exprs[0], exprs[1], exprs.size() == 3 ? exprs[2] : CodeNode::SharedPtr()); } }, { "hmset", [this]() { auto exprs(readAndCheckExprList("hmget", 3)); return std::make_shared<HashMapSet>(exprs[0], exprs[1], exprs[2]); } }, { "hmrem", [this]() { auto exprs(readAndCheckExprList("hmrem", 2)); return std::make_shared<HashMapRemove>(exprs[0], exprs[1]); } }, { "hmclr", [this]() { auto exprs(readAndCheckExprList("hmclr", 1)); return std::make_shared<HashMapClear>(exprs[0]); } }, { "hmfind", [this]() { auto exprs(readAndCheckExprList("hmfind", 2)); return std::make_shared<HashMapFind>(exprs[0], exprs[1]); } }, { "hmcount", [this]() { auto exprs(readAndCheckExprList("hmcount", 2)); return std::make_shared<HashMapCount>(exprs[0], exprs[1]); } }, { "hmkeys", [this]() { auto exprs(readAndCheckExprList("hmkeys", 1)); return std::make_shared<HashMapKeys>(exprs[0]); } }, { "hmvals", [this]() { auto exprs(readAndCheckExprList("hmvals", 1)); return std::make_shared<HashMapValues>(exprs[0]); } }, { "hmitems", [this]() { auto exprs(readAndCheckExprList("hmitems", 1)); return std::make_shared<HashMapItems>(exprs[0]); } }, { "pair", [this]() { auto exprs(readAndCheckExprList("pair", 2)); return std::make_shared<MakePair>(exprs[0], exprs[1]); } }, { "first", [this]() { auto exprs(readAndCheckExprList("first", 1)); return std::make_shared<PairFirst>(exprs[0]); } }, { "second", [this]() { auto exprs(readAndCheckExprList("second", 1)); return std::make_shared<PairSecond>(exprs[0]); } } }; }
30.06785
135
0.451172
jrtabash
a0fd710ff66ab669b39c812004b64b79f5832e2f
388
cpp
C++
contest/May_Challenge_2021/LKDNGOLF.cpp
Akash671/Codechef
8de5cab864e011952d7428303f8b4e6951ee57cb
[ "MIT" ]
2
2020-09-26T07:17:19.000Z
2021-04-25T10:07:19.000Z
contest/May_Challenge_2021/LKDNGOLF.cpp
Akash671/Codechef
8de5cab864e011952d7428303f8b4e6951ee57cb
[ "MIT" ]
null
null
null
contest/May_Challenge_2021/LKDNGOLF.cpp
Akash671/Codechef
8de5cab864e011952d7428303f8b4e6951ee57cb
[ "MIT" ]
1
2021-08-18T20:04:53.000Z
2021-08-18T20:04:53.000Z
/* author : @akashsaini */ #include<bits/stdc++.h> using namespace std; #define ll long long int string solve(ll n,ll x,ll k) { if(x%k==0) { return "YES"; } else { if(((n+1)-x)%k==0) { return "YES"; } else { return "NO"; } } } int main() { long int t; cin>>t; while(t--) { ll n,x,k; cin>>n>>x>>k; cout<<solve(n,x,k)<<"\n"; } return 0; }
9.948718
30
0.489691
Akash671
9d004959d230e75a3d9873e82a91e64d7afad464
3,158
cpp
C++
test/lib/quickjs/quickjshelper.test.cpp
tmehnert/complate-cpp
8780cff967e25279584d0e1619666783f7ff6b40
[ "Apache-2.0" ]
5
2021-12-18T09:12:51.000Z
2022-01-28T17:43:13.000Z
test/lib/quickjs/quickjshelper.test.cpp
tmehnert/complate-cpp
8780cff967e25279584d0e1619666783f7ff6b40
[ "Apache-2.0" ]
10
2021-10-18T05:45:18.000Z
2021-12-12T11:09:20.000Z
test/lib/quickjs/quickjshelper.test.cpp
tmehnert/complate-cpp
8780cff967e25279584d0e1619666783f7ff6b40
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2021 Torsten Mehnert * * 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 "../../../lib/quickjs/quickjshelper.h" #include <complate/core/exception.h> #include "catch2/catch.hpp" #include "quickjs.h" #include "resources.h" using namespace Catch::Matchers; using namespace std; TEST_CASE("QuickJsHelper", "[quickjs]") { JSRuntime *runtime = JS_NewRuntime(); JSContext *context = JS_NewContext(runtime); JSValue v = JS_UNINITIALIZED; SECTION("evaluate") { SECTION("can evaluate the views.js bundle") { const string bundle = Resources::read("views.js"); QuickJsHelper::evaluate(context, bundle); v = QuickJsHelper::getFunction(context, "render"); REQUIRE(JS_IsFunction(context, v)); } SECTION("throws complate::Exception when source is malformed") { const string malformed = Resources::read("views.js.malformed"); REQUIRE_THROWS_AS(QuickJsHelper::evaluate(context, malformed), complate::Exception); REQUIRE_THROWS_WITH(QuickJsHelper::evaluate(context, malformed), Contains("SyntaxError")); } } SECTION("getFunction") { SECTION("return the function") { QuickJsHelper::evaluate(context, "function foo() {};"); v = QuickJsHelper::getFunction(context, "foo"); REQUIRE(JS_IsFunction(context, v)); } SECTION("throws complate::Exception when error occured in eval") { const string malformed = "foo /&=/!{D<"; QuickJsHelper::evaluate(context, "function foo() {};"); REQUIRE_THROWS_AS(QuickJsHelper::getFunction(context, malformed), complate::Exception); REQUIRE_THROWS_WITH(QuickJsHelper::getFunction(context, malformed), Contains("SyntaxError")); } SECTION("throws complate::Exception when name is not a function") { QuickJsHelper::evaluate(context, "const foo = 3;"); REQUIRE_THROWS_AS(QuickJsHelper::getFunction(context, "foo"), complate::Exception); REQUIRE_THROWS_WITH(QuickJsHelper::getFunction(context, "foo"), Contains("Is not a function")); } SECTION("throws complate::Exception when name is undefined") { REQUIRE_THROWS_AS(QuickJsHelper::getFunction(context, "foo"), complate::Exception); REQUIRE_THROWS_WITH(QuickJsHelper::getFunction(context, "foo"), Contains("ReferenceError: 'foo' is not defined")); } } if (!JS_IsUninitialized(v)) { JS_FreeValue(context, v); } JS_FreeContext(context); JS_FreeRuntime(runtime); }
36.72093
76
0.659595
tmehnert
9d0486e86314187d85d328afb72c6cddbed79843
4,663
cpp
C++
solid/frame/aio/src/aioerror.cpp
vipalade/solidframe
cff130652127ca9607019b4db508bc67f8bbecff
[ "BSL-1.0" ]
26
2015-08-25T16:07:58.000Z
2019-07-05T15:21:22.000Z
solid/frame/aio/src/aioerror.cpp
vipalade/solidframe
cff130652127ca9607019b4db508bc67f8bbecff
[ "BSL-1.0" ]
5
2016-10-15T22:55:15.000Z
2017-09-19T12:41:10.000Z
solid/frame/aio/src/aioerror.cpp
vipalade/solidframe
cff130652127ca9607019b4db508bc67f8bbecff
[ "BSL-1.0" ]
5
2016-09-15T10:34:52.000Z
2018-10-30T11:46:46.000Z
// solid/frame/aio/src/aioerror.cpp // // Copyright (c) 2016 Valentin Palade (vipalade @ gmail . com) // // This file is part of SolidFrame framework. // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt. // #include "solid/frame/aio/aioerror.hpp" #include <sstream> namespace solid { namespace frame { namespace aio { namespace { enum { ErrorResolverDirectE = 1, ErrorResolverReverseE, ErrorDatagramShutdownE, ErrorDatagramSystemE, ErrorDatagramCreateE, ErrorDatagramSocketE, ErrorStreamSystemE, ErrorStreamSocketE, ErrorStreamShutdownE, ErrorTimerCancelE, ErrorListenerSystemE, ErrorListenerHangupE, ErrorSecureContextE, ErrorSecureSocketE, ErrorSecureRecvE, ErrorSecureSendE, ErrorSecureAcceptE, ErrorSecureConnectE, ErrorSecureShutdownE, }; class ErrorCategory : public ErrorCategoryT { public: ErrorCategory() {} const char* name() const noexcept override { return "solid::frame::aio"; } std::string message(int _ev) const override; }; const ErrorCategory category; std::string ErrorCategory::message(int _ev) const { std::ostringstream oss; oss << "(" << name() << ":" << _ev << "): "; switch (_ev) { case 0: oss << "Success"; break; case ErrorResolverDirectE: oss << "Resolver: direct"; break; case ErrorResolverReverseE: oss << "Resolver: reverse"; break; case ErrorDatagramShutdownE: oss << "Datagram: peer shutdown"; break; case ErrorDatagramSystemE: oss << "Datagram: system"; break; case ErrorDatagramCreateE: oss << "Datagram: socket create"; break; case ErrorDatagramSocketE: oss << "Datagram: socket"; break; case ErrorStreamSystemE: oss << "Stream: system"; break; case ErrorStreamSocketE: oss << "Stream: socket"; break; case ErrorStreamShutdownE: oss << "Stream: peer shutdown"; break; case ErrorTimerCancelE: oss << "Timer: canceled"; break; case ErrorListenerSystemE: oss << "Listener: system"; break; case ErrorListenerHangupE: oss << "Listener: Hangup"; break; case ErrorSecureContextE: oss << "Secure: context"; break; case ErrorSecureSocketE: oss << "Secure: socket"; break; case ErrorSecureRecvE: oss << "Secure: recv"; break; case ErrorSecureSendE: oss << "Secure: send"; break; case ErrorSecureAcceptE: oss << "Secure: accept"; break; case ErrorSecureConnectE: oss << "Secure: connect"; break; case ErrorSecureShutdownE: oss << "Secure: shutdown"; break; default: oss << "Unknown"; break; } return oss.str(); } } //namespace /*extern*/ const ErrorCodeT error_resolver_direct(ErrorResolverDirectE, category); /*extern*/ const ErrorCodeT error_resolver_reverse(ErrorResolverReverseE, category); /*extern*/ const ErrorConditionT error_datagram_shutdown(ErrorDatagramShutdownE, category); /*extern*/ const ErrorConditionT error_datagram_system(ErrorDatagramSystemE, category); /*extern*/ const ErrorConditionT error_datagram_create(ErrorDatagramCreateE, category); /*extern*/ const ErrorConditionT error_datagram_socket(ErrorDatagramSocketE, category); /*extern*/ const ErrorConditionT error_stream_system(ErrorStreamSystemE, category); /*extern*/ const ErrorConditionT error_stream_socket(ErrorStreamSocketE, category); /*extern*/ const ErrorConditionT error_stream_shutdown(ErrorStreamShutdownE, category); /*extern*/ const ErrorConditionT error_timer_cancel(ErrorTimerCancelE, category); /*extern*/ const ErrorConditionT error_listener_system(ErrorListenerSystemE, category); /*extern*/ const ErrorConditionT error_listener_hangup(ErrorListenerHangupE, category); /*extern*/ const ErrorCodeT error_secure_context(ErrorSecureContextE, category); /*extern*/ const ErrorCodeT error_secure_socket(ErrorSecureSocketE, category); /*extern*/ const ErrorCodeT error_secure_recv(ErrorSecureRecvE, category); /*extern*/ const ErrorCodeT error_secure_send(ErrorSecureSendE, category); /*extern*/ const ErrorCodeT error_secure_accept(ErrorSecureAcceptE, category); /*extern*/ const ErrorCodeT error_secure_connect(ErrorSecureConnectE, category); /*extern*/ const ErrorCodeT error_secure_shutdown(ErrorSecureShutdownE, category); } //namespace aio } //namespace frame } //namespace solid
29.512658
91
0.693759
vipalade
9d07f99ee1e5dfbb512cbd22f470000495a773f3
131
hpp
C++
75th_RR/cfgFactionClasses.hpp
cptbassbeard/Valhalla
56868a4567898750526e1d7a66731f23c1b7d18e
[ "CC0-1.0" ]
null
null
null
75th_RR/cfgFactionClasses.hpp
cptbassbeard/Valhalla
56868a4567898750526e1d7a66731f23c1b7d18e
[ "CC0-1.0" ]
null
null
null
75th_RR/cfgFactionClasses.hpp
cptbassbeard/Valhalla
56868a4567898750526e1d7a66731f23c1b7d18e
[ "CC0-1.0" ]
null
null
null
class CfgFactionClasses { class 75th_RR { displayName = "75th Ranger Regiment"; priority = 5; side = 1; icon = ""; }; };
13.1
39
0.618321
cptbassbeard
9d09ab5479200b17fcdfacb91a37167835f67963
49,418
cpp
C++
Causality/Foregrounds.cpp
ArcEarth/SrInspection
63c540d1736e323a0f409914e413cb237f03c5c9
[ "MIT" ]
3
2016-07-13T18:30:33.000Z
2020-03-31T22:20:34.000Z
Causality/Foregrounds.cpp
ArcEarth/SrInspection
63c540d1736e323a0f409914e413cb237f03c5c9
[ "MIT" ]
null
null
null
Causality/Foregrounds.cpp
ArcEarth/SrInspection
63c540d1736e323a0f409914e413cb237f03c5c9
[ "MIT" ]
5
2016-01-16T14:25:28.000Z
2017-06-12T16:15:18.000Z
#include "pch_bullet.h" #include <iostream> #include <numeric> #include "Foregrounds.h" #include "CausalityApplication.h" #include "Common\PrimitiveVisualizer.h" #include "Common\Extern\cpplinq.hpp" #include <boost\format.hpp> using namespace Causality; using namespace DirectX; using namespace DirectX::Scene; using namespace std; using namespace Platform; using namespace Eigen; using namespace concurrency; using namespace DirectX::Visualizers; extern wstring ResourcesDirectory; //std::unique_ptr<DirectX::GeometricPrimitive> HandPhysicalModel::s_pCylinder; //std::unique_ptr<DirectX::GeometricPrimitive> HandPhysicalModel::s_pSphere; const static wstring SkyBoxTextures[6] = { ResourcesDirectory + wstring(L"Textures\\SkyBox\\GrimmNight\\Right.dds"), ResourcesDirectory + wstring(L"Textures\\SkyBox\\GrimmNight\\Left.dds"), ResourcesDirectory + wstring(L"Textures\\SkyBox\\GrimmNight\\Top.dds"), ResourcesDirectory + wstring(L"Textures\\SkyBox\\GrimmNight\\Bottom.dds"), ResourcesDirectory + wstring(L"Textures\\SkyBox\\GrimmNight\\Front.dds"), ResourcesDirectory + wstring(L"Textures\\SkyBox\\GrimmNight\\Back.dds"), }; //std::unique_ptr<btBroadphaseInterface> pBroadphase = nullptr; //// Set up the collision configuration and dispatcher //std::unique_ptr<btDefaultCollisionConfiguration> pCollisionConfiguration = nullptr; //std::unique_ptr<btCollisionDispatcher> pDispatcher = nullptr; //// The actual physics solver //std::unique_ptr<btSequentialImpulseConstraintSolver> pSolver = nullptr; std::queue<std::unique_ptr<WorldBranch>> WorldBranch::BranchPool; float ShapeSimiliarity(const Eigen::VectorXf& v1, const Eigen::VectorXf& v2) { auto v = v1 - v2; //dis = sqrt(v.dot(v); //1.414 - dis; auto theta = XMScalarACosEst(v1.dot(v2) * XMScalarReciprocalSqrtEst(v1.dot(v1) * v2.dot(v2))); // Difference in angular [0,pi/4] auto rhlo = abs(sqrt(v1.dot(v1)) - sqrtf(v2.dot(v2))); // Difference in length [0,sqrt(2)] return 1.0f - 0.5f * (0.3f * rhlo / sqrtf(2.0f) + 0.7f * theta / (XM_PIDIV4)); } Causality::WorldScene::WorldScene(const std::shared_ptr<DirectX::DeviceResources>& pResouce, const DirectX::ILocatable* pCamera) : States(pResouce->GetD3DDevice()) , m_pCameraLocation(pCamera) { m_HaveHands = false; m_showTrace = true; LoadAsync(pResouce->GetD3DDevice()); } WorldScene::~WorldScene() { } const float fingerRadius = 0.006f; const float fingerLength = 0.02f; class XmlModelLoader { }; WorldBranch::WorldBranch() { pBroadphase.reset(new btDbvtBroadphase()); // Set up the collision configuration and dispatcher pCollisionConfiguration.reset(new btDefaultCollisionConfiguration()); pDispatcher.reset(new btCollisionDispatcher(pCollisionConfiguration.get())); // The actual physics solver pSolver.reset(new btSequentialImpulseConstraintSolver()); // The world. pDynamicsWorld.reset(new btDiscreteDynamicsWorld(pDispatcher.get(), pBroadphase.get(), pSolver.get(), pCollisionConfiguration.get())); pDynamicsWorld->setGravity(btVector3(0, -1.0f, 0)); IsEnabled = false; } void Causality::WorldScene::LoadAsync(ID3D11Device* pDevice) { m_loadingComplete = false; pBackground = nullptr; //CD3D11_DEFAULT d; //CD3D11_RASTERIZER_DESC Desc(d); //Desc.MultisampleEnable = TRUE; //ThrowIfFailed(pDevice->CreateRasterizerState(&Desc, &pRSState)); concurrency::task<void> load_models([this, pDevice]() { { lock_guard<mutex> guard(m_RenderLock); WorldBranch::InitializeBranchPool(1); WorldTree = WorldBranch::DemandCreate("Root"); //std::vector<AffineTransform> subjectTrans(30); //subjectTrans.resize(20); //for (size_t i = 0; i < 20; i++) //{ // subjectTrans[i].Scale = XMVectorReplicate(1.1f + 0.15f * i);// XMMatrixTranslation(0, 0, i*(-150.f)); //} //WorldTree->Fork(subjectTrans); WorldTree->Enable(DirectX::AffineTransform::Identity()); } //m_pFramesPool.reset(new WorldBranchPool); //m_pFramesPool->Initialize(30); //{ // lock_guard<mutex> guard(m_RenderLock); // for (size_t i = 0; i < 30; i++) // { // m_StateFrames.push_back(m_pFramesPool->DemandCreate()); // auto pFrame = m_StateFrames.back(); // //pFrame->Initialize(); // pFrame->SubjectTransform.Scale = XMVectorReplicate(1.0f + 0.1f * i);// XMMatrixTranslation(0, 0, i*(-150.f)); // } // m_StateFrames.front()->Enable(DirectX::AffineTransform::Identity()); //} auto Directory = App::Current()->GetResourcesDirectory(); auto ModelDirectory = Directory / "Models"; auto TextureDirectory = Directory / "Textures"; auto texDir = TextureDirectory.wstring(); pEffect = std::make_shared<BasicEffect>(pDevice); pEffect->SetVertexColorEnabled(false); pEffect->SetTextureEnabled(true); //pEffect->SetLightingEnabled(true); pEffect->EnableDefaultLighting(); { void const* shaderByteCode; size_t byteCodeLength; pEffect->GetVertexShaderBytecode(&shaderByteCode, &byteCodeLength); pInputLayout = CreateInputLayout<VertexPositionNormalTexture>(pDevice, shaderByteCode, byteCodeLength); } //pBackground = std::make_unique<SkyDome>(pDevice, SkyBoxTextures); auto sceneFile = Directory / "Foregrounds.xml"; tinyxml2::XMLDocument sceneDoc; sceneDoc.LoadFile(sceneFile.string().c_str()); auto scene = sceneDoc.FirstChildElement("scene"); auto node = scene->FirstChildElement(); while (node) { if (!strcmp(node->Name(), "obj")) { auto path = node->Attribute("src"); if (path != nullptr && strlen(path) != 0) { auto pModel = std::make_shared<ShapedGeomrtricModel>(); GeometryModel::CreateFromObjFile(pModel.get(), pDevice, (ModelDirectory / path).wstring(), texDir); XMFLOAT3 v = pModel->BoundOrientedBox.Extents; v.y /= v.x; v.z /= v.x; m_ModelFeatures[pModel->Name] = Eigen::Vector2f(v.y, v.z); std::cout << "[Model] f(" << pModel->Name << ") = " << m_ModelFeatures[pModel->Name] << std::endl; float scale = 1.0f; float mass = 1.0f; Vector3 pos; auto attr = node->Attribute("scale"); if (attr != nullptr) { stringstream ss(attr); ss >> scale; //model->SetScale(XMVectorReplicate(scale)); } attr = node->Attribute("position"); if (attr != nullptr) { stringstream ss(attr); char ch; ss >> pos.x >> ch >> pos.y >> ch >> pos.z; //model->SetPosition(pos); } attr = node->Attribute("mass"); if (attr) mass = (float) atof(attr); AddObject(pModel, mass, pos, DirectX::Quaternion::Identity, DirectX::Vector3(scale)); //auto pShape = model->CreateCollisionShape(); //pShape->setLocalScaling(btVector3(scale, scale, scale)); //btVector3 minb, maxb; //model->InitializePhysics(pDynamicsWorld, pShape, mass, pos, XMQuaternionIdentity()); //model->GetBulletRigid()->setFriction(1.0f); //{ // std::lock_guard<mutex> guard(m_RenderLock); // Models.push_back(model); //} } } else if (!strcmp(node->Name(), "cube")) { Vector3 extent(1.0f); Vector3 pos; Color color(255, 255, 255, 255); string name("cube"); float mass = 1.0f; auto attr = node->Attribute("extent"); if (attr != nullptr) { stringstream ss(attr); char ch; ss >> extent.x >> ch >> extent.y >> ch >> extent.z; } attr = node->Attribute("position"); if (attr != nullptr) { stringstream ss(attr); char ch; ss >> pos.x >> ch >> pos.y >> ch >> pos.z; } attr = node->Attribute("color"); if (attr != nullptr) { stringstream ss(attr); char ch; ss >> color.x >> ch >> color.y >> ch >> color.z; if (!ss.eof()) ss >> ch >> color.w; color = color.ToVector4() / 255; color.Saturate(); } attr = node->Attribute("name"); if (attr) name = attr; attr = node->Attribute("mass"); if (attr) mass = (float) atof(attr); auto pModel = make_shared<CubeModel>(name, extent, (XMVECTOR) color); XMFLOAT3 v = pModel->BoundOrientedBox.Extents; v.y /= v.x; v.z /= v.x; m_ModelFeatures[pModel->Name] = Eigen::Vector2f(v.y, v.z); AddObject(pModel, mass, pos, DirectX::Quaternion::Identity, DirectX::Vector3::One); //auto pShape = pModel->CreateCollisionShape(); //pModel->InitializePhysics(nullptr, pShape, mass, pos); //pModel->Enable(pDynamicsWorld); //pModel->GetBulletRigid()->setFriction(1.0f); //{ // std::lock_guard<mutex> guard(m_RenderLock); // Models.push_back(pModel); //} } node = node->NextSiblingElement(); } m_loadingComplete = true; }); } void Causality::WorldScene::SetViewIdenpendntCameraPosition(const DirectX::ILocatable * pCamera) { m_pCameraLocation = pCamera; } void Causality::WorldScene::Render(ID3D11DeviceContext * pContext) { if (pBackground) pBackground->Render(pContext); { pContext->IASetInputLayout(pInputLayout.Get()); auto pAWrap = States.AnisotropicWrap(); pContext->PSSetSamplers(0, 1, &pAWrap); pContext->RSSetState(pRSState.Get()); std::lock_guard<mutex> guard(m_RenderLock); BoundingOrientedBox modelBox; using namespace cpplinq; // Render models for (const auto& model : Models) { auto superposition = ModelStates[model->Name]; for (const auto& state : superposition) { auto mat = state.TransformMatrix(); model->LocalMatrix = state.TransformMatrix(); //.first->GetRigidTransformMatrix(); model->Opticity = state.Probability; //state.second; model->BoundOrientedBox.Transform(modelBox, mat); // Render if in the view frustum if (ViewFrutum.Contains(modelBox) != ContainmentType::DISJOINT) model->Render(pContext, pEffect.get()); } } for (const auto& branch : WorldTree->leaves()) { //Subjects for (const auto& item : branch.Subjects) { if (item.second) { item.second->Opticity = branch.Liklyhood(); item.second->Render(pContext, nullptr); } } } } g_PrimitiveDrawer.Begin(); Vector3 conners[8]; ViewFrutum.GetCorners(conners); DrawBox(conners, Colors::Pink); BoundingOrientedBox obox; BoundingBox box; { //Draw axias DrawAxis(); //g_PrimitiveDrawer.DrawQuad({ 1.0f,0,1.0f }, { -1.0f,0,1.0f }, { -1.0f,0,-1.0f }, { 1.0f,0,-1.0f }, Colors::Pink); auto& fh = m_HandDescriptionFeature; { std::lock_guard<mutex> guard(m_RenderLock); auto s = Models.size(); if (m_HaveHands) std::cout << "Detail Similarity = {"; for (size_t i = 0; i < s; i++) { const auto& model = Models[i]; obox = model->GetOrientedBoundingBox(); if (ViewFrutum.Contains(obox) != ContainmentType::DISJOINT) { obox.GetCorners(conners); DrawBox(conners, DirectX::Colors::DarkGreen); } if (m_HaveHands) { auto fm = m_ModelFeatures[model->Name]; auto similarity = ShapeSimiliarity(fm, fh); m_ModelDetailSimilarity[model->Name] = similarity; std::cout << model->Name << ':' << similarity << " , "; Color c = Color::Lerp({ 1,0,0 }, { 0,1,0 }, similarity); for (size_t i = 0; i < 8; i++) { g_PrimitiveDrawer.DrawSphere(conners[i], 0.005f * similarity, c); } } auto pModel = dynamic_cast<CompositeModel*>(model.get()); XMMATRIX transform = model->GetWorldMatrix(); if (pModel) { for (const auto& part : pModel->Parts) { part->BoundOrientedBox.Transform(obox, transform); if (ViewFrutum.Intersects(obox)) { obox.GetCorners(conners); DrawBox(conners, DirectX::Colors::Orange); } } } } } if (m_HaveHands) std::cout << '}' << std::endl; } if (m_HaveHands) { //for (auto& pRigid : m_HandRigids) //{ // g_PrimitiveDrawer.DrawSphere(pRigid->GetPosition(), 0.01f, Colors::Pink); //} auto pCamera = App::Current()->GetPrimaryCamera(); XMMATRIX leap2world = m_FrameTransform;// XMMatrixScalingFromVector(XMVectorReplicate(0.001f)) * XMMatrixTranslation(0,0,-1.0) * XMMatrixRotationQuaternion(pCamera->GetOrientation()) * XMMatrixTranslationFromVector((XMVECTOR)pCamera->GetPosition()); std::lock_guard<mutex> guard(m_HandFrameMutex); for (const auto& hand : m_Frame.hands()) { auto palmPosition = XMVector3Transform(hand.palmPosition().toVector3<Vector3>(), leap2world); g_PrimitiveDrawer.DrawSphere(palmPosition, 0.02f, Colors::YellowGreen); //for (const auto& finger : hand.fingers()) //{ // for (size_t i = 0; i < 4; i++) // { // const auto & bone = finger.bone((Leap::Bone::Type)i); // XMVECTOR bJ = XMVector3Transform(bone.prevJoint().toVector3<Vector3>(), leap2world); // XMVECTOR eJ = XMVector3Transform(bone.nextJoint().toVector3<Vector3>(), leap2world); // //if (i == 0) // // g_PrimitiveDrawer.DrawSphere(bJ, 0.01f, DirectX::Colors::Lime); // //// The unit of leap is millimeter // //g_PrimitiveDrawer.DrawSphere(eJ, 0.01f, DirectX::Colors::Lime); // g_PrimitiveDrawer.DrawLine(bJ, eJ, DirectX::Colors::White); // } //} } // NOT VALIAD!~!!!!! //if (m_HandTrace.size() > 0 && m_showTrace) //{ // std::lock_guard<mutex> guard(m_RenderLock); // //auto pJoints = m_HandTrace.linearize(); // m_CurrentHandBoundingBox.GetCorners(conners); // DrawBox(conners, Colors::LimeGreen); // m_HandTraceBoundingBox.GetCorners(conners); // DrawBox(conners, Colors::YellowGreen); // m_HandTraceModel.Primitives.clear(); // for (int i = m_HandTrace.size() - 1; i >= std::max<int>(0, (int) m_HandTrace.size() - TraceLength); i--) // { // const auto& h = m_HandTrace[i]; // float radius = (i + 1 - std::max<int>(0, m_HandTrace.size() - TraceLength)) / (std::min<float>(m_HandTrace.size(), TraceLength)); // for (size_t j = 0; j < h.size(); j++) // { // //m_HandTraceModel.Primitives.emplace_back(h[j], 0.02f); // g_PrimitiveDrawer.DrawSphere(h[j], 0.005f * radius, Colors::LimeGreen); // } // } //} } g_PrimitiveDrawer.End(); //if (m_HandTrace.size() > 0) //{ // if (!pBatch) // { // pBatch = std::make_unique<PrimitiveBatch<VertexPositionNormal>>(pContext, 204800,40960); // } // m_HandTraceModel.SetISO(0.33333f); // m_HandTraceModel.Update(); // m_HandTraceModel.Tessellate(m_HandTraceVertices, m_HandTraceIndices, 0.005f); // pBatch->Begin(); // pEffect->SetDiffuseColor(Colors::LimeGreen); // //pEffect->SetEmissiveColor(Colors::LimeGreen); // pEffect->SetTextureEnabled(false); // pEffect->SetWorld(XMMatrixIdentity()); // pEffect->Apply(pContext); // pBatch->DrawIndexed(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST, m_HandTraceIndices.data(), m_HandTraceIndices.size(), m_HandTraceVertices.data(), m_HandTraceVertices.size()); // pBatch->End(); //} } void Causality::WorldScene::DrawAxis() { g_PrimitiveDrawer.DrawSphere({ 0,0,0,0.02 }, Colors::Red); g_PrimitiveDrawer.DrawLine({ -5,0,0 }, { 5,0,0 }, Colors::Red); g_PrimitiveDrawer.DrawLine({ 0,-5,0 }, { 0,5,0 }, Colors::Green); g_PrimitiveDrawer.DrawLine({ 0,0,-5 }, { 0,0,5 }, Colors::Blue); g_PrimitiveDrawer.DrawTriangle({ 5.05f,0,0 }, { 4.95,0.05,0 }, { 4.95,-0.05,0 }, Colors::Red); g_PrimitiveDrawer.DrawTriangle({ 5.05f,0,0 }, { 4.95,-0.05,0 }, { 4.95,0.05,0 }, Colors::Red); g_PrimitiveDrawer.DrawTriangle({ 5.05f,0,0 }, { 4.95,0,0.05 }, { 4.95,0,-0.05 }, Colors::Red); g_PrimitiveDrawer.DrawTriangle({ 5.05f,0,0 }, { 4.95,0,-0.05 }, { 4.95,0,0.05 }, Colors::Red); g_PrimitiveDrawer.DrawTriangle({ 0,5.05f,0 }, { -0.05,4.95,0 }, { 0.05,4.95,0 }, Colors::Green); g_PrimitiveDrawer.DrawTriangle({ 0,5.05f,0 }, { 0.05,4.95,0 }, { -0.05,4.95,0 }, Colors::Green); g_PrimitiveDrawer.DrawTriangle({ 0,5.05f,0 }, { 0.0,4.95,-0.05 }, { 0,4.95,0.05 }, Colors::Green); g_PrimitiveDrawer.DrawTriangle({ 0,5.05f,0 }, { 0.0,4.95,0.05 }, { 0,4.95,-0.05 }, Colors::Green); g_PrimitiveDrawer.DrawTriangle({ 0,0,5.05f }, { 0.05,0,4.95 }, { -0.05,0,4.95 }, Colors::Blue); g_PrimitiveDrawer.DrawTriangle({ 0,0,5.05f }, { -0.05,0,4.95 }, { 0.05,0,4.95 }, Colors::Blue); g_PrimitiveDrawer.DrawTriangle({ 0,0,5.05f }, { 0,0.05,4.95 }, { 0,-0.05,4.95 }, Colors::Blue); g_PrimitiveDrawer.DrawTriangle({ 0,0,5.05f }, { 0,-0.05,4.95 }, { 0,0.05,4.95 }, Colors::Blue); } void Causality::WorldScene::DrawBox(DirectX::SimpleMath::Vector3 conners [], DirectX::CXMVECTOR color) { g_PrimitiveDrawer.DrawLine(conners[0], conners[1], color); g_PrimitiveDrawer.DrawLine(conners[1], conners[2], color); g_PrimitiveDrawer.DrawLine(conners[2], conners[3], color); g_PrimitiveDrawer.DrawLine(conners[3], conners[0], color); g_PrimitiveDrawer.DrawLine(conners[3], conners[7], color); g_PrimitiveDrawer.DrawLine(conners[2], conners[6], color); g_PrimitiveDrawer.DrawLine(conners[1], conners[5], color); g_PrimitiveDrawer.DrawLine(conners[0], conners[4], color); g_PrimitiveDrawer.DrawLine(conners[4], conners[5], color); g_PrimitiveDrawer.DrawLine(conners[5], conners[6], color); g_PrimitiveDrawer.DrawLine(conners[6], conners[7], color); g_PrimitiveDrawer.DrawLine(conners[7], conners[4], color); } void XM_CALLCONV Causality::WorldScene::UpdateViewMatrix(DirectX::FXMMATRIX view, DirectX::CXMMATRIX projection) { if (pEffect) { pEffect->SetView(view); pEffect->SetProjection(projection); } if (pBackground) { pBackground->UpdateViewMatrix(view,projection); } g_PrimitiveDrawer.SetView(view); g_PrimitiveDrawer.SetProjection( projection); // BoundingFrustum is assumpt Left-Handed BoundingFrustumExtension::CreateFromMatrixRH(ViewFrutum, projection); //BoundingFrustum::CreateFromMatrix(ViewFrutum, projection); // Fix the RH-projection matrix //XMStoreFloat4((XMFLOAT4*) &ViewFrutum.RightSlope, -XMLoadFloat4((XMFLOAT4*) &ViewFrutum.RightSlope)); //XMStoreFloat2((XMFLOAT2*) &ViewFrutum.Near, -XMLoadFloat2((XMFLOAT2*) &ViewFrutum.Near)); //ViewFrutum.LeftSlope = -ViewFrutum.LeftSlope; //ViewFrutum.RightSlope = -ViewFrutum.RightSlope; //ViewFrutum.TopSlope = -ViewFrutum.TopSlope; //ViewFrutum.BottomSlope = -ViewFrutum.BottomSlope; //ViewFrutum.Near = -ViewFrutum.Near; //ViewFrutum.Far = -ViewFrutum.Far; XMVECTOR det; auto invView = view; //invView.r[2] = -invView.r[2]; invView = XMMatrixInverse(&det, invView); //invView.r[2] = -invView.r[2]; //XMVECTOR temp = invView.r[2]; //invView.r[2] = invView.r[1]; //invView.r[1] = temp; ViewFrutum.Transform(ViewFrutum,invView); // Fix the RH-inv-view-matrix to LH-equalulent by swap row-y with row-z //XMStoreFloat3(&ViewFrutum.Origin, invView.r[3]); //XMStoreFloat4(&ViewFrutum.Orientation, XMQuaternionRotationMatrix(invView));; //for (const auto& item : m_HandModels) //{ // if (item.second) // item.second->UpdateViewMatrix(view); //} } //void XM_CALLCONV Causality::WorldScene::UpdateProjectionMatrix(DirectX::FXMMATRIX projection) //{ // if (pEffect) // pEffect->SetProjection(projection); // if (pBackground) // pBackground->UpdateProjectionMatrix(projection); // // g_PrimitiveDrawer.SetProjection(projection); //} void Causality::WorldScene::UpdateAnimation(StepTimer const & timer) { { lock_guard<mutex> guard(m_RenderLock); using namespace cpplinq; using namespace std::placeholders; float stepTime = (float) timer.GetElapsedSeconds(); WorldTree->Evolution(stepTime, m_Frame, m_FrameTransform); ModelStates = WorldTree->CaculateSuperposition(); } if (m_HandTrace.size() > 0) { { // Critia section std::lock_guard<mutex> guard(m_HandFrameMutex); const int plotSize = 45; BoundingOrientedBox::CreateFromPoints(m_CurrentHandBoundingBox, m_HandTrace.back().size(), m_HandTrace.back().data(), sizeof(Vector3)); m_TracePoints.clear(); Color color = Colors::LimeGreen; for (int i = m_HandTrace.size() - 1; i >= std::max(0, (int) m_HandTrace.size() - plotSize); i--) { const auto& h = m_HandTrace[i]; //float radius = (i + 1 - std::max(0U, m_HandTrace.size() - plotSize)) / (std::min<float>(m_HandTrace.size(), plotSize)); for (size_t j = 0; j < h.size(); j++) { //g_PrimitiveDrawer.DrawSphere(h[j], 0.005 * radius, color); m_TracePoints.push_back(h[j]); } } //for (const auto& pModel : Children) //{ // //btCollisionWorld::RayResultCallback // auto pRigid = dynamic_cast<PhysicalGeometryModel*>(pModel.get()); // pRigid->GetBulletRigid()->checkCollideWith() //} //auto pBat = dynamic_cast<PhysicalGeometryModel*>(Children[0].get()); //pBat->SetPosition(vector_cast<Vector3>(m_Frame.hands().frontmost().palmPosition())); } CreateBoundingOrientedBoxFromPoints(m_HandTraceBoundingBox, m_TracePoints.size(), m_TracePoints.data(), sizeof(Vector3)); XMFLOAT3 v = m_HandTraceBoundingBox.Extents; m_HandDescriptionFeature = Eigen::Vector2f(v.y / v.x, v.z / v.x); // ASSUMPTION: Extends is sorted from! //XMMATRIX invTrans = XMMatrixAffineTransformation(g_XMOne / XMVectorReplicate(m_HandTraceBoundingBox.Extents.x), XMVectorZero(), XMQuaternionInverse(XMLoadFloat4(&m_HandTraceBoundingBox.Orientation)), -XMLoadFloat3(&m_HandTraceBoundingBox.Center)); //int sampleCount = std::min<int>(m_TraceSamples.size(), TraceLength)*m_TraceSamples[0].size(); //for (const auto& model : Children) //{ // auto pModel = dynamic_cast<Model*>(model.get()); // auto inCount = 0; // if (pModel) // { // auto obox = model->GetOrientedBoundingBox(); // XMMATRIX fowTrans = XMMatrixAffineTransformation(XMVectorReplicate(obox.Extents.x), XMVectorZero(), XMQuaternionIdentity(), XMVectorZero()); // fowTrans = invTrans * fowTrans; // auto pSample = m_TraceSamples.back().data() + m_TraceSamples.back().size()-1; // for (size_t i = 0; i < sampleCount; i++) // { // const auto& point = pSample[-i]; // XMVECTOR p = XMVector3Transform(point, fowTrans); // int j; // for ( j = 0; j < pModel->Parts.size(); j++) // { // if (pModel->Parts[j].BoundOrientedBox.Contains(p)) // break; // } // if (j >= pModel->Parts.size()) // inCount++; // } // } // m_ModelDetailSimilarity[model->Name] = (float) inCount / (float)sampleCount; //} } //if (pGroundRigid) // pGroundRigid->setLinearVelocity({ 0,-1.0f,0 }); //pDynamicsWorld->stepSimulation(timer.GetElapsedSeconds(), 10); //for (auto& obj : Children) //{ // auto s = (rand() % 1000) / 1000.0; // obj->Rotate(XMQuaternionRotationRollPitchYaw(0, 0.5f * timer.GetElapsedSeconds(), 0)); //} } void Causality::WorldScene::OnHandsTracked(const UserHandsEventArgs & e) { m_HaveHands = true; //const auto& hand = e.sender.frame().hands().frontmost(); //size_t i = 0; // //XMMATRIX leap2world = e.toWorldTransform; //for (const auto& finger : hand.fingers()) //{ // XMVECTOR bJ = XMVector3Transform(finger.bone((Leap::Bone::Type)0).prevJoint().toVector3<Vector3>(), leap2world); // auto pState = m_HandRigids[i]->GetBulletRigid()->getMotionState(); // auto transform = btTransform::getIdentity(); // transform.setOrigin(vector_cast<btVector3>(bJ)); // if (!pState) // { // pState = new btDefaultMotionState(transform); // m_HandRigids[i]->GetBulletRigid()->setMotionState(pState); // } // else // pState->setWorldTransform(transform); // // i++; // for (size_t boneIdx = 0; boneIdx < 4; boneIdx++) // bone idx // { // const auto & bone = finger.bone((Leap::Bone::Type)boneIdx); // XMVECTOR eJ = XMVector3Transform(bone.nextJoint().toVector3<Vector3>(), leap2world); // auto pState = m_HandRigids[i]->GetBulletRigid()->getMotionState(); // auto transform = btTransform::getIdentity(); // transform.setOrigin(vector_cast<btVector3>(eJ)); // if (!pState) // { // pState = new btDefaultMotionState(transform); // m_HandRigids[i]->GetBulletRigid()->setMotionState(pState); // } // else // pState->setWorldTransform(transform); // i++; // } //} m_Frame = e.sender.frame(); for (auto& branch : WorldTree->leaves()) { for (const auto& hand : m_Frame.hands()) { auto & subjects = branch.Subjects; branch.AddSubjectiveObject(hand,e.toWorldTransform); //if (!subjects[hand.id()]) //{ // subjects[hand.id()].reset( // new HandPhysicalModel( // pFrame->pDynamicsWorld, // hand, e.toWorldTransform, // pFrame->SubjectTransform) // ); // //for (const auto& itm : pFrame->Objects) // //{ // // const auto& pObj = itm.second; // // if (!pObj->GetBulletRigid()->isStaticOrKinematicObject()) // // { // // for (const auto& bone : subjects[hand.id()]->Rigids()) // // pObj->GetBulletRigid()->setIgnoreCollisionCheck(bone.get(), false); // // } // //} //} } } //for (size_t j = 0; j < i; j++) //{ // pDynamicsWorld->addRigidBody(m_HandRigids[j]->GetBulletRigid()); // m_HandRigids[j]->GetBulletRigid()->setGravity({ 0,0,0 }); //} } void Causality::WorldScene::OnHandsTrackLost(const UserHandsEventArgs & e) { m_Frame = e.sender.frame(); m_FrameTransform = e.toWorldTransform; if (m_Frame.hands().count() == 0) { m_HaveHands = false; std::lock_guard<mutex> guard(m_HandFrameMutex); m_HandTrace.clear(); m_TraceSamples.clear(); WorldTree->Collapse(); //for (const auto &pRigid : m_HandRigids) //{ // pDynamicsWorld->removeRigidBody(pRigid->GetBulletRigid()); //} } } void Causality::WorldScene::OnHandsMove(const UserHandsEventArgs & e) { std::lock_guard<mutex> guard(m_HandFrameMutex); m_Frame = e.sender.frame(); m_FrameTransform = e.toWorldTransform; XMMATRIX leap2world = m_FrameTransform; //std::array<DirectX::Vector3, 25> joints; std::vector<DirectX::BoundingOrientedBox> handBoxes; float fingerStdev = 0.02f; std::random_device rd; std::mt19937 gen(rd()); std::normal_distribution<float> normalDist(0, fingerStdev); std::uniform_real<float> uniformDist; // Caculate moving trace int handIdx = 0; for (const auto& hand : m_Frame.hands()) { int fingerIdx = 0; // hand idx m_HandTrace.emplace_back(); m_TraceSamples.emplace_back(); auto& samples = m_TraceSamples.back(); auto& joints = m_HandTrace.back(); for (const auto& finger : hand.fingers()) { XMVECTOR bJ = XMVector3Transform(finger.bone((Leap::Bone::Type)0).prevJoint().toVector3<Vector3>(), leap2world); joints[fingerIdx * 5] = bJ; for (size_t boneIdx = 0; boneIdx < 4; boneIdx++) // bone idx { const auto & bone = finger.bone((Leap::Bone::Type)boneIdx); XMVECTOR eJ = XMVector3Transform(bone.nextJoint().toVector3<Vector3>(), leap2world); joints[fingerIdx * 5 + boneIdx + 1] = eJ; //auto dir = eJ - bJ; //float dis = XMVectorGetX(XMVector3Length(dir)); //if (abs(dis) < 0.001) // continue; //XMVECTOR rot = XMQuaternionRotationVectorToVector(g_XMIdentityR1, dir); //bJ = eJ; //for (size_t k = 0; k < 100; k++) // bone idx //{ // float x = normalDist(gen); // float h = uniformDist(gen); // float z = normalDist(gen); // XMVECTOR disp = XMVectorSet(x, h*dis, z, 1); // disp = XMVector3Rotate(disp, rot); // disp += bJ; // samples[(fingerIdx * 4 + boneIdx) * 100 + k] = disp; //} } fingerIdx++; } handIdx++; while (m_HandTrace.size() > 60) { m_HandTrace.pop_front(); //m_TraceSamples.pop_front(); } // Cone intersection test section //Vector3 rayEnd = XMVector3Transform(hand.palmPosition().toVector3<Vector3>(), leap2world); //Vector3 rayBegin = m_pCameraLocation->GetPosition(); //auto pConeShape = new btConeShape(100, XM_PI / 16 * 100); //auto pCollisionCone = new btCollisionObject(); //pCollisionCone->setCollisionShape(pConeShape); //btTransform trans( // vector_cast<btQuaternion>(XMQuaternionRotationVectorToVector(g_XMIdentityR1, rayEnd - rayBegin)), // vector_cast<btVector3>(rayBegin)); //pCollisionCone->setWorldTransform(trans); //class Callback : public btDynamicsWorld::ContactResultCallback //{ //public: // const IModelNode* pModel; // Callback() {} // void SetModel(const IModelNode* pModel) // { // this->pModel = pModel; // } // Callback(const IModelNode* pModel) // : pModel(pModel) // { // } // virtual btScalar addSingleResult(btManifoldPoint& cp, const btCollisionObjectWrapper* colObj0Wrap, int partId0, int index0, const btCollisionObjectWrapper* colObj1Wrap, int partId1, int index1) // { // cout << "point frustrum contact with "<< pModel->Name << endl; // return 0; // } //}; //static map<string, Callback> callbackTable; //for (const auto& model : Children) //{ // auto pRigid = dynamic_cast<PhysicalRigid*>(model.get()); // callbackTable[model->Name].SetModel(model.get()); // pDynamicsWorld->contactPairTest(pRigid->GetBulletRigid(), pCollisionCone, callbackTable[model->Name]); //} } //int i = 0; //const auto& hand = m_Frame.hands().frontmost(); //for (const auto& finger : hand.fingers()) //{ // XMVECTOR bJ = XMVector3Transform(finger.bone((Leap::Bone::Type)0).prevJoint().toVector3<Vector3>(), leap2world); // auto pState = m_HandRigids[i]->GetBulletRigid()->getMotionState(); // auto transform = btTransform::getIdentity(); // transform.setOrigin(vector_cast<btVector3>(bJ)); // m_HandRigids[i]->GetBulletRigid()->proceedToTransform(transform); // i++; // for (size_t boneIdx = 0; boneIdx < 4; boneIdx++) // bone idx // { // const auto & bone = finger.bone((Leap::Bone::Type)boneIdx); // XMVECTOR eJ = XMVector3Transform(bone.nextJoint().toVector3<Vector3>(), leap2world); // auto pState = m_HandRigids[i]->GetBulletRigid()->getMotionState(); // auto transform = btTransform::getIdentity(); // transform.setOrigin(vector_cast<btVector3>(eJ)); // m_HandRigids[i]->GetBulletRigid()->proceedToTransform(transform); // i++; // } //} std::cout << "[Leap] Hands Move." << std::endl; } void Causality::WorldScene::OnKeyDown(const KeyboardEventArgs & e) { } void Causality::WorldScene::OnKeyUp(const KeyboardEventArgs & e) { if (e.Key == 'T') m_showTrace = !m_showTrace; } void Causality::WorldScene::AddObject(const std::shared_ptr<IModelNode>& pModel, float mass, const DirectX::Vector3 & Position, const DirectX::Quaternion & Orientation, const Vector3 & Scale) { lock_guard<mutex> guard(m_RenderLock); Models.push_back(pModel); auto pShaped = dynamic_cast<IShaped*>(pModel.get()); auto pShape = pShaped->CreateCollisionShape(); pShape->setLocalScaling(vector_cast<btVector3>(Scale)); WorldTree->AddDynamicObject(pModel->Name, pShape, mass, Position, Orientation); //for (const auto& pFrame : m_StateFrames) //{ // auto pObject = std::shared_ptr<PhysicalRigid>(new PhysicalRigid()); // pObject->InitializePhysics(pFrame->pDynamicsWorld, pShape, mass, Position, Orientation); // pObject->GetBulletRigid()->setFriction(1.0f); // pObject->GetBulletRigid()->setDamping(0.8, 0.9); // pObject->GetBulletRigid()->setRestitution(0.0); // pFrame->Objects[pModel->Name] = pObject; //} } std::pair<DirectX::Vector3, DirectX::Quaternion> XM_CALLCONV CaculateCylinderTransform(FXMVECTOR P1, FXMVECTOR P2) { std::pair<DirectX::Vector3, DirectX::Quaternion> trans; auto center = XMVectorAdd(P1, P2); center = XMVectorMultiply(center, g_XMOneHalf); auto dir = XMVectorSubtract(P1, P2); auto scale = XMVector3Length(dir); XMVECTOR rot; if (XMVector4Equal(dir, g_XMZero)) rot = XMQuaternionIdentity(); else rot = XMQuaternionRotationVectorToVector(g_XMIdentityR1.v, dir); trans.first = center; trans.second = rot; return trans; } XMMATRIX Causality::HandPhysicalModel::CaculateLocalMatrix(const Leap::Hand & hand, const DirectX::Matrix4x4 & leapTransform) { XMVECTOR palmCenter = hand.palmPosition().toVector3<Vector3>(); return XMMatrixScalingFromCenter(m_InheritTransform.Scale, palmCenter) * ((RigidTransform&) m_InheritTransform).TransformMatrix() * (XMMATRIX) leapTransform; } Causality::HandPhysicalModel::HandPhysicalModel (const std::shared_ptr<btDynamicsWorld> &pWorld, const Leap::Hand & hand, const DirectX::Matrix4x4 & leapTransform, const DirectX::AffineTransform &inheritTransform) : m_Hand(hand) { Color.G(0.5f); Color.B(0.5f); Id = hand.id(); m_InheritTransform = inheritTransform; LocalMatrix = CaculateLocalMatrix(hand, leapTransform); XMMATRIX leap2world = LocalMatrix; int j = 0; for (const auto& finger : m_Hand.fingers()) { for (size_t i = 0; i < 4; i++) { const auto & bone = finger.bone((Leap::Bone::Type)i); XMVECTOR bJ = XMVector3Transform(bone.prevJoint().toVector3<Vector3>(), leap2world); XMVECTOR eJ = XMVector3Transform(bone.nextJoint().toVector3<Vector3>(), leap2world); m_Bones[i + j * 4].first = bJ; m_Bones[i + j * 4].second = eJ; // Initalize rigid hand model auto center = 0.5f * XMVectorAdd(bJ, eJ); auto dir = XMVectorSubtract(eJ, bJ); auto height = std::max(XMVectorGetX(XMVector3Length(dir)), fingerLength); XMVECTOR rot; if (XMVector4Equal(dir, g_XMZero)) rot = XMQuaternionIdentity(); else rot = XMQuaternionRotationVectorToVector(g_XMIdentityR1, dir); shared_ptr<btCapsuleShape> pShape(new btCapsuleShape(fingerRadius, height)); // Scaling in Y axis is encapsled in bJ and eJ btVector3 scl = vector_cast<btVector3>(m_InheritTransform.Scale); scl.setY(1.0f); pShape->setLocalScaling(scl); m_HandRigids.emplace_back(new PhysicalRigid()); const auto & pRigid = m_HandRigids.back(); //pRigid->GetBulletRigid()->setGravity({ 0,0,0 }); pRigid->InitializePhysics(nullptr, pShape, 0, center, rot); const auto& body = pRigid->GetBulletRigid(); body->setFriction(1.0f); body->setRestitution(0.0f); body->setCollisionFlags(body->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT); body->setActivationState(DISABLE_DEACTIVATION); //body->setAngularFactor(0.0f); // Rotation Along Y not affact pRigid->Enable(pWorld); } } //for (size_t i = 0; i < m_HandRigids.size(); i++) //{ // for (size_t j = 0; j < m_HandRigids.size(); j++) // { // if (i != j) // m_HandRigids[i]->GetBulletRigid()->setIgnoreCollisionCheck(m_HandRigids[j]->GetBulletRigid(), true); // } //} } bool Causality::HandPhysicalModel::Update(const Leap::Frame & frame, const DirectX::Matrix4x4 & leapTransform) { m_Hand = frame.hand(Id); if (m_Hand.isValid()) { XMMATRIX transform = CaculateLocalMatrix(m_Hand, leapTransform); LocalMatrix = transform; Color.R(m_Hand.grabStrength()); LostFrames = 0; int j = 0; for (const auto& finger : m_Hand.fingers()) { for (size_t i = 0; i < 4; i++) { const auto & bone = finger.bone((Leap::Bone::Type)i); XMVECTOR bJ = XMVector3Transform(bone.prevJoint().toVector3<Vector3>(), transform); XMVECTOR eJ = XMVector3Transform(bone.nextJoint().toVector3<Vector3>(), transform); m_Bones[i + j * 4].first = bJ; m_Bones[i + j * 4].second = eJ; // Rigid hand model auto & pRigid = m_HandRigids[i + j * 4]; if (!pRigid->IsEnabled()) pRigid->Enable(); auto center = 0.5f * XMVectorAdd(bJ, eJ); auto dir = XMVectorSubtract(eJ, bJ); XMVECTOR rot; if (XMVector4Equal(dir, g_XMZero)) rot = XMQuaternionIdentity(); else rot = XMQuaternionRotationVectorToVector(g_XMIdentityR1, dir); auto trans = btTransform(vector_cast<btQuaternion>(rot), vector_cast<btVector3>(center)); pRigid->GetBulletRigid()->getMotionState()->setWorldTransform(trans); } j++; } return true; } else { for (auto& pRigid : m_HandRigids) { pRigid->Disable(); } LostFrames++; return false; } } // Inherited via IModelNode void Causality::HandPhysicalModel::Render(ID3D11DeviceContext * pContext, DirectX::IEffect * pEffect) { XMMATRIX leap2world = LocalMatrix; //auto palmPosition = XMVector3Transform(m_Hand.palmPosition().toVector3<Vector3>(), leap2world); //g_PrimitiveDrawer.DrawSphere(palmPosition, 0.02f, Colors::YellowGreen); Color.A(Opticity); XMVECTOR color = Color; //color = XMVectorSetW(color, Opticity); //g_PrimitiveDrawer.Begin(); //for (const auto& bone : m_Bones) //{ // //g_PrimitiveDrawer.DrawSphere(bone.second, fingerRadius, jC); // g_PrimitiveDrawer.DrawCylinder(bone.first, bone.second, fingerRadius * m_InheritTransform.Scale.x, color); //} //g_PrimitiveDrawer.End(); for (const auto& pRigid : m_HandRigids) { g_PrimitiveDrawer.DrawCylinder( pRigid->GetPosition(), XMVector3Rotate(g_XMIdentityR1, pRigid->GetOrientation()), dynamic_cast<btCapsuleShape*>(pRigid->GetBulletShape())->getHalfHeight() * 2, fingerRadius * m_InheritTransform.Scale.x, color); } //for (const auto& finger : m_Hand.fingers()) //{ // for (size_t i = 0; i < 4; i++) // { // const auto & bone = finger.bone((Leap::Bone::Type)i); // XMVECTOR bJ = XMVector3Transform(bone.prevJoint().toVector3<Vector3>(), leap2world); // XMVECTOR eJ = XMVector3Transform(bone.nextJoint().toVector3<Vector3>(), leap2world); // //g_PrimitiveDrawer.DrawLine(bJ, eJ, Colors::LimeGreen); // //g_PrimitiveDrawer.DrawCube(bJ, g_XMOne * 0.03, g_XMIdentityR3, Colors::Red); // g_PrimitiveDrawer.DrawCylinder(bJ, eJ,0.015f,Colors::LimeGreen); // //auto center = 0.5f * XMVectorAdd(bJ, eJ); // //auto dir = XMVectorSubtract(eJ, bJ); // //auto scale = XMVector3Length(dir); // //XMVECTOR rot; // //if (XMVector4LessOrEqual(XMVector3LengthSq(dir), XMVectorReplicate(0.01f))) // // rot = XMQuaternionIdentity(); // //else // // rot = XMQuaternionRotationVectorToVector(g_XMIdentityR1, dir); // //XMMATRIX world = XMMatrixAffineTransformation(scale, g_XMZero, rot, center); // //s_pCylinder->Draw(world, ViewMatrix, ProjectionMatrix,Colors::LimeGreen); // } //} } inline void debug_assert(bool condition) { #ifdef DEBUG if (!condition) { _CrtDbgBreak(); //std::cout << "assert failed." << std::endl; } #endif } // normalized feild intensity equalent charge XMVECTOR XM_CALLCONV FieldSegmentToPoint(FXMVECTOR P, FXMVECTOR L0, FXMVECTOR L1) { if (XMVector4NearEqual(L0, L1, XMVectorReplicate(0.001f))) { XMVECTOR v = XMVectorAdd(L0, L1); v = XMVectorMultiply(v, g_XMOneHalf); v = XMVectorSubtract(v, P); XMVECTOR d = XMVector3LengthSq(v); v = XMVector3Normalize(v); v /= d; return v; } XMVECTOR s = XMVectorSubtract(L1, L0); XMVECTOR v0 = XMVectorSubtract(L0, P); XMVECTOR v1 = XMVectorSubtract(L1, P); XMMATRIX Rot; Rot.r[1] = XMVector3Normalize(s); Rot.r[2] = XMVector3Cross(v0, v1); Rot.r[2] = XMVector3Normalize(Rot.r[2]); Rot.r[0] = XMVector3Cross(Rot.r[1], Rot.r[2]); Rot.r[3] = g_XMIdentityR3; // Rotated to standard question: // Y // ^ *y1 // | | //--o-----|x0----->X // | | // | | // *y0 // Close form solution of the intergral : f(y0,y1) = <-y/(x0*sqrt(x0^2+y^2)),1/sqrt(x0^2+y^2),0> | (y0,y1) XMVECTOR Ds = XMVector3ReciprocalLength(s); XMVECTOR Ps = XMVector3Dot(v0, s); XMVECTOR Y0 = XMVectorMultiply(Ps, Ds); Ps = XMVector3Dot(v1, s); XMVECTOR Y1 = XMVectorMultiply(Ps, Ds); XMVECTOR X0 = XMVector3LengthSq(v1); Ps = XMVectorMultiply(Y1, Y1); X0 = XMVectorSubtract(X0, Ps); //debug_assert(XMVector4GreaterOrEqual(X0, XMVectorZero())); XMVECTOR R0 = XMVectorMultiplyAdd(Y0, Y0, X0); XMVECTOR R1 = XMVectorMultiplyAdd(Y1, Y1, X0); R0 = XMVectorReciprocalSqrt(R0); R1 = XMVectorReciprocalSqrt(R1); XMVECTOR Ry = XMVectorSubtract(R1, R0); R0 = XMVectorMultiply(R0, Y0); R1 = XMVectorMultiply(R1, Y1); XMVECTOR Rx = XMVectorSubtract(R0, R1); X0 = XMVectorReciprocalSqrt(X0); //debug_assert(!XMVectorGetIntX(XMVectorIsNaN(X0))); Rx = XMVectorMultiply(Rx, X0); Rx = XMVectorSelect(Rx, Ry, g_XMSelect0101); // Field intensity in P centered coordinate Rx = XMVectorAndInt(Rx, g_XMSelect1100); Rx = XMVectorMultiply(Rx, Ds); Rx = XMVector3Transform(Rx, Rot); //debug_assert(!XMVectorGetIntX(XMVectorIsNaN(Rx))); return Rx; } DirectX::XMVECTOR XM_CALLCONV Causality::HandPhysicalModel::FieldAtPoint(DirectX::FXMVECTOR P) { // Palm push force //XMVECTOR palmP = m_Hand.palmPosition().toVector3<Vector3>(); //XMVECTOR palmN = m_Hand.palmNormal().toVector3<Vector3>(); //auto dis = XMVectorSubtract(P,palmP); //auto mag = XMVectorReciprocal(XMVector3LengthSq(dis)); //dis = XMVector3Normalize(dis); //auto fac = XMVector3Dot(dis, palmN); //mag = XMVectorMultiply(fac, mag); //return XMVectorMultiply(dis, mag); XMVECTOR field = XMVectorZero(); for (const auto& bone : m_Bones) { XMVECTOR v0 = bone.first; XMVECTOR v1 = bone.second; XMVECTOR f = FieldSegmentToPoint(P, v0, v1); field += f; //XMVECTOR l = XMVector3LengthSq(XMVectorSubtract(v1,v0)); } return field; } inline Causality::CubeModel::CubeModel(const std::string & name, DirectX::FXMVECTOR extend, DirectX::FXMVECTOR color) { Name = name; m_Color = color; XMStoreFloat3(&BoundBox.Extents, extend); XMStoreFloat3(&BoundOrientedBox.Extents, extend); } std::shared_ptr<btCollisionShape> Causality::CubeModel::CreateCollisionShape() { std::shared_ptr<btCollisionShape> pShape; pShape.reset(new btBoxShape(vector_cast<btVector3>(BoundBox.Extents))); return pShape; } void Causality::CubeModel::Render(ID3D11DeviceContext * pContext, DirectX::IEffect * pEffect) { XMVECTOR extent = XMLoadFloat3(&BoundBox.Extents); XMMATRIX world = GetWorldMatrix(); //XMVECTOR scale, pos, rot; XMVECTOR color = m_Color; color = XMVectorSetW(color, Opticity); g_PrimitiveDrawer.DrawCube(extent, world, color); } // !!!Current don't support dynamic scaling for each state now!!! inline std::shared_ptr<btCollisionShape> Causality::ShapedGeomrtricModel::CreateCollisionShape() { if (!m_pShape) { btTransform trans; std::shared_ptr<btCompoundShape> pShape(new btCompoundShape()); //trans.setOrigin(vector_cast<btVector3>(model->BoundOrientedBox.Center)); //trans.setRotation(vector_cast<btQuaternion>(model->BoundOrientedBox.Orientation)); //pShape->addChildShape(trans, new btBoxShape(vector_cast<btVector3>(model->BoundOrientedBox.Extents))); for (const auto& part : Parts) { trans.setOrigin(vector_cast<btVector3>(part->BoundOrientedBox.Center)); trans.setRotation(vector_cast<btQuaternion>(part->BoundOrientedBox.Orientation)); pShape->addChildShape(trans, new btBoxShape(vector_cast<btVector3>(part->BoundOrientedBox.Extents))); } m_pShape = pShape; return m_pShape; } else { return m_pShape; } } void Causality::WorldBranch::InitializeBranchPool(int size, bool autoExpandation) { for (size_t i = 0; i < 30; i++) { BranchPool.emplace(new WorldBranch()); } } void Causality::WorldBranch::Reset() { for (const auto& pair : Items) { pair.second->Disable(); } Items.clear(); } void Causality::WorldBranch::Collapse() { //using namespace cpplinq; //using cref = decltype(m_StateFrames)::const_reference; //auto mlh = from(m_StateFrames) // >> where([](cref pFrame) {return pFrame->IsEnabled; }) // >> max([](cref pFrame)->float {return pFrame->Liklyhood(); }); //WordBranch master_frame; ////for (auto & pFrame : m_StateFrames) ////{ //// if (pFrame->Liklyhood() < mlh) //// { //// pFrame->Disable(); //// m_pFramesPool->Recycle(std::move(pFrame)); //// } //// else //// { //// master_frame = std::move(pFrame); //// } ////} //m_StateFrames.clear(); //m_StateFrames.push_back(std::move(master_frame)); } SuperpositionMap Causality::WorldBranch::CaculateSuperposition() { using namespace cpplinq; SuperpositionMap SuperStates; auto itr = this->begin(); auto eitr = this->end(); NormalizeLiklyhood(CaculateLiklyhood()); auto pItem = Items.begin(); for (size_t i = 0; i < Items.size(); i++,++pItem) { const auto& pModel = pItem->second; auto& distribution = SuperStates[pItem->first]; //auto& = state.StatesDistribution; int j = 0; for (const auto& branch : leaves()) { if (!branch.IsEnabled) continue; auto itrObj = branch.Items.find(pItem->first); if (itrObj == branch.Items.end()) continue; auto pNew = itrObj->second; ProblistiscAffineTransform tNew; tNew.Translation = pNew->GetPosition(); tNew.Rotation = pNew->GetOrientation(); tNew.Scale = pNew->GetScale(); tNew.Probability = branch.Liklyhood(); auto itr = std::find_if(distribution.begin(), distribution.end(), [&tNew](std::remove_reference_t<decltype(distribution)>::const_reference trans) -> bool { return trans.NearEqual(tNew); }); if (itr == distribution.end()) { distribution.push_back(tNew); } else { itr->Probability += tNew.Probability; } j++; } } return SuperStates; } void Causality::WorldBranch::InternalEvolution(float timeStep, const Leap::Frame & frame, const DirectX::Matrix4x4 & leapTransform) { auto& subjects = Subjects; BoundingSphere sphere; //if (!is_leaf()) return; for (auto itr = subjects.begin(); itr != subjects.end(); ) { bool result = itr->second->Update(frame, leapTransform); // Remove hands lost track for 60+ frames if (!result) { if (itr->second->LostFramesCount() > 60) itr = subjects.erase(itr); } else { //std::vector<PhysicalRigid*> collideObjects; //for (auto& item : Items) //{ // btVector3 c; // item.second->GetBulletShape()->getBoundingSphere(c, sphere.Radius); // sphere.Center = vector_cast<Vector3>(sphere.Center); // if (itr->second->OperatingFrustum().Contains(sphere) != ContainmentType::DISJOINT) // { // collideObjects.push_back(item.second.get()); // } //} //if (collideObjects.size() > 0) //{ // Fork(collideObjects); //} //const auto &pHand = itr->second; //for (auto& item : pFrame->Objects) //{ // const auto& pObj = item.second; // if (pObj->GetBulletRigid()->isStaticObject()) // continue; // //pObj->GetBulletShape()-> // auto force = pHand->FieldAtPoint(pObj->GetPosition()) * 0.00001f; // pObj->GetBulletRigid()->clearForces(); // //vector_cast<btVector3>(force) * 0.01f // std::cout << item.first << " : " << Vector3(force) << std::endl; // pObj->GetBulletRigid()->applyCentralForce(vector_cast<btVector3>(force)); // pObj->GetBulletRigid()->activate(); //} ++itr; } } pDynamicsWorld->stepSimulation(timeStep, 10); } float Causality::WorldBranch::CaculateLiklyhood() { if (is_leaf()) { if (IsEnabled) _Liklyhood = 1; else _Liklyhood = 0; return _Liklyhood; } else { _Liklyhood = 0; for (auto& branch : children()) { _Liklyhood += branch.CaculateLiklyhood(); } return _Liklyhood; } } void Causality::WorldBranch::NormalizeLiklyhood(float total) { for (auto& branch : nodes_in_tree()) { branch._Liklyhood /= total; } } void Causality::WorldBranch::AddSubjectiveObject(const Leap::Hand & hand, const DirectX::Matrix4x4& leapTransform) { if (!Subjects[hand.id()]) { Subjects[hand.id()].reset( new HandPhysicalModel( pDynamicsWorld, hand, leapTransform, SubjectTransform) ); //for (const auto& itm : pFrame->Objects) //{ // const auto& pObj = itm.second; // if (!pObj->GetBulletRigid()->isStaticOrKinematicObject()) // { // for (const auto& bone : subjects[hand.id()]->Rigids()) // pObj->GetBulletRigid()->setIgnoreCollisionCheck(bone.get(), false); // } //} } } void Causality::WorldBranch::AddDynamicObject(const std::string &name, const std::shared_ptr<btCollisionShape> &pShape, float mass, const DirectX::Vector3 & Position, const DirectX::Quaternion & Orientation) { for (auto& branch : nodes_in_tree()) { auto pObject = std::shared_ptr<PhysicalRigid>(new PhysicalRigid()); pObject->InitializePhysics(branch.pDynamicsWorld, pShape, mass, Position, Orientation); pObject->GetBulletRigid()->setFriction(1.0f); pObject->GetBulletRigid()->setDamping(0.8f, 0.9f); pObject->GetBulletRigid()->setRestitution(0.0); branch.Items[name] = pObject; } } void Causality::WorldBranch::Evolution(float timeStep, const Leap::Frame & frame, const DirectX::Matrix4x4 & leapTransform) { using namespace cpplinq; vector<reference_wrapper<WorldBranch>> leaves; //auto levr = this->leaves(); copy(this->leaves_begin(), leaves_end(), back_inserter(leaves)); auto branchEvolution = [timeStep, &frame, &leapTransform](WorldBranch& branch) { branch.InternalEvolution(timeStep,frame, leapTransform); }; //auto branchEvolution = std::bind(&WorldBranch::InternalEvolution, placeholders::_1, frame, leapTransform); if (leaves.size() >= 10) concurrency::parallel_for_each(leaves.begin(), leaves.end(), branchEvolution); else for_each(leaves.begin(), leaves.end(), branchEvolution); } void Causality::WorldBranch::Fork(const std::vector<PhysicalRigid*>& focusObjects) { //int i = 0; //for (const auto& obj : focusObjects) //{ // auto branch = DemandCreate((boost::format("%s/%d") % this->Name % i++).str()); //} } void Causality::WorldBranch::Fork(const std::vector<DirectX::AffineTransform>& subjectTransforms) { for (int i = subjectTransforms.size() - 1; i >= 0; --i) { const auto& trans = subjectTransforms[i]; auto branch = DemandCreate((boost::format("%s/%d") % this->Name % i).str()); branch->Enable(trans); append_children_front(branch.release()); //branch->SubjectTransform = trans; } } std::unique_ptr<WorldBranch> Causality::WorldBranch::DemandCreate(const string& branchName) { if (!BranchPool.empty()) { auto frame = std::move(BranchPool.front()); BranchPool.pop(); frame->Name = branchName; return frame; } else return nullptr; } void Causality::WorldBranch::Recycle(std::unique_ptr<WorldBranch>&& pFrame) { pFrame->Reset(); BranchPool.push(std::move(pFrame)); } //inline void Causality::SkeletonModel::Render(ID3D11DeviceContext * pContext, DirectX::IEffect * pEffect) //{ // g_PrimitiveDrawer.DrawCylinder(Joints[0],Joints[1].Position) //}
31.903163
251
0.68123
ArcEarth
9d0a0426a96bc1410fbc389a08ae818d5a5e3071
3,796
cpp
C++
modules/stitching/perf/perf_estimators.cpp
yo1990/opencv
aef4fab1c8632940d53c694f09466dcd3e72eae2
[ "BSD-3-Clause" ]
1
2020-05-11T22:26:54.000Z
2020-05-11T22:26:54.000Z
modules/stitching/perf/perf_estimators.cpp
yo1990/opencv
aef4fab1c8632940d53c694f09466dcd3e72eae2
[ "BSD-3-Clause" ]
3
2019-08-21T07:13:41.000Z
2020-06-23T12:35:17.000Z
modules/stitching/perf/perf_estimators.cpp
yo1990/opencv
aef4fab1c8632940d53c694f09466dcd3e72eae2
[ "BSD-3-Clause" ]
null
null
null
#include "perf_precomp.hpp" #include "opencv2/imgcodecs.hpp" #include "opencv2/opencv_modules.hpp" namespace opencv_test { using namespace perf; typedef TestBaseWithParam<tuple<string, string> > bundleAdjuster; #if defined(HAVE_OPENCV_XFEATURES2D) && defined(OPENCV_ENABLE_NONFREE) #define TEST_DETECTORS testing::Values("surf", "orb") #else #define TEST_DETECTORS testing::Values<string>("orb") #endif #define WORK_MEGAPIX 0.6 #define AFFINE_FUNCTIONS testing::Values("affinePartial", "affine") PERF_TEST_P(bundleAdjuster, affine, testing::Combine(TEST_DETECTORS, AFFINE_FUNCTIONS)) { Mat img1, img1_full = imread(getDataPath("stitching/s1.jpg")); Mat img2, img2_full = imread(getDataPath("stitching/s2.jpg")); float scale1 = (float)std::min(1.0, sqrt(WORK_MEGAPIX * 1e6 / img1_full.total())); float scale2 = (float)std::min(1.0, sqrt(WORK_MEGAPIX * 1e6 / img2_full.total())); resize(img1_full, img1, Size(), scale1, scale1, INTER_LINEAR_EXACT); resize(img2_full, img2, Size(), scale2, scale2, INTER_LINEAR_EXACT); string detector = get<0>(GetParam()); string affine_fun = get<1>(GetParam()); Ptr<detail::FeaturesFinder> finder; Ptr<detail::FeaturesMatcher> matcher; Ptr<detail::BundleAdjusterBase> bundle_adjuster; if (detector == "surf") finder = makePtr<detail::SurfFeaturesFinder>(); else if (detector == "orb") finder = makePtr<detail::OrbFeaturesFinder>(); if (affine_fun == "affinePartial") { matcher = makePtr<detail::AffineBestOf2NearestMatcher>(false); bundle_adjuster = makePtr<detail::BundleAdjusterAffinePartial>(); } else if (affine_fun == "affine") { matcher = makePtr<detail::AffineBestOf2NearestMatcher>(true); bundle_adjuster = makePtr<detail::BundleAdjusterAffine>(); } Ptr<detail::Estimator> estimator = makePtr<detail::AffineBasedEstimator>(); std::vector<Mat> images; images.push_back(img1), images.push_back(img2); std::vector<detail::ImageFeatures> features; std::vector<detail::MatchesInfo> pairwise_matches; std::vector<detail::CameraParams> cameras; std::vector<detail::CameraParams> cameras2; (*finder)(images, features); (*matcher)(features, pairwise_matches); if (!(*estimator)(features, pairwise_matches, cameras)) FAIL() << "estimation failed. this should never happen."; // this is currently required for (size_t i = 0; i < cameras.size(); ++i) { Mat R; cameras[i].R.convertTo(R, CV_32F); cameras[i].R = R; } cameras2 = cameras; bool success = true; while(next()) { cameras = cameras2; // revert cameras back to original initial guess startTimer(); success = (*bundle_adjuster)(features, pairwise_matches, cameras); stopTimer(); } EXPECT_TRUE(success); EXPECT_TRUE(cameras.size() == 2); // fist camera should be just identity Mat &first = cameras[0].R; SANITY_CHECK(first, 1e-3, ERROR_ABSOLUTE); // second camera should be the estimated transform between images // separate rotation and translation in transform matrix Mat T_second (cameras[1].R, Range(0, 2), Range(2, 3)); Mat R_second (cameras[1].R, Range(0, 2), Range(0, 2)); Mat h (cameras[1].R, Range(2, 3), Range::all()); SANITY_CHECK(T_second, 5, ERROR_ABSOLUTE); // allow 5 pixels diff in translations SANITY_CHECK(R_second, .01, ERROR_ABSOLUTE); // rotations must be more precise // last row should be precisely (0, 0, 1) as it is just added for representation in homogeneous // coordinates EXPECT_TRUE(h.type() == CV_32F); EXPECT_FLOAT_EQ(h.at<float>(0), 0.f); EXPECT_FLOAT_EQ(h.at<float>(1), 0.f); EXPECT_FLOAT_EQ(h.at<float>(2), 1.f); } } // namespace
37.584158
99
0.68098
yo1990
9d0b0c274542dcd1e6103378377dd038e647afab
7,035
cpp
C++
adapters-stk/test/stk_interface_test/tScatterSpeed_Epetra.cpp
hillyuan/Panzer
13ece3ea4c145c4d7b6339e3ad6332a501932ea8
[ "BSD-3-Clause" ]
1
2022-03-22T03:49:50.000Z
2022-03-22T03:49:50.000Z
adapters-stk/test/stk_interface_test/tScatterSpeed_Epetra.cpp
hillyuan/Panzer
13ece3ea4c145c4d7b6339e3ad6332a501932ea8
[ "BSD-3-Clause" ]
null
null
null
adapters-stk/test/stk_interface_test/tScatterSpeed_Epetra.cpp
hillyuan/Panzer
13ece3ea4c145c4d7b6339e3ad6332a501932ea8
[ "BSD-3-Clause" ]
null
null
null
// STL includes #include <iostream> #include <vector> #include <set> // Teuchos includes #include "Teuchos_GlobalMPISession.hpp" #include "Teuchos_RCP.hpp" #include "Teuchos_ParameterList.hpp" #include "Teuchos_FancyOStream.hpp" #include "Teuchos_TimeMonitor.hpp" #include <Teuchos_oblackholestream.hpp> // Intrepid2 includes #include "Intrepid2_HGRAD_QUAD_C1_FEM.hpp" #include "Intrepid2_HGRAD_QUAD_C2_FEM.hpp" #include "Intrepid2_HGRAD_HEX_C1_FEM.hpp" #include "Intrepid2_HGRAD_HEX_C2_FEM.hpp" // Panzer includes #include "Panzer_ConnManager.hpp" #include "Panzer_FieldPattern.hpp" #include "Panzer_IntrepidFieldPattern.hpp" #include "Panzer_DOFManager.hpp" // Panzer_STK includes #include "Panzer_STK_SquareQuadMeshFactory.hpp" #include "Panzer_STK_CubeHexMeshFactory.hpp" #include "Panzer_STKConnManager.hpp" #include "Epetra_Map.h" #include "Epetra_CrsMatrix.h" #include "Epetra_CrsGraph.h" #include "Epetra_MpiComm.h" #ifdef HAVE_MPI #include "mpi.h" #endif using Teuchos::RCP; using Teuchos::rcp; using Teuchos::ArrayRCP; using Teuchos::Array; using Teuchos::ArrayView; using Teuchos::TimeMonitor; using Teuchos::Time; typedef Kokkos::DynRankView<double,PHX::Device> FieldContainer; typedef Epetra_Map Map; typedef Epetra_CrsMatrix CrsMatrix; typedef Epetra_CrsGraph CrsGraph; //****************************Function Definitions****************************** void newAssembly(Teuchos::FancyOStream &out); //Will run the generic setup of the DOFManager through the buildGlobalUnknowns size_t setUp1(RCP<Map> &rowmap, RCP<Map> &colmap, RCP<panzer::DOFManager> &my_dofM, RCP<panzer::ConnManager> &conn); //I'm not entirely sure on this yet. void fillMeUp1(std::vector<std::vector<int> > &gids, std::vector<std::vector<int> > &lids, std::vector< std::vector<std::vector<double> > > &miniMat, RCP<panzer::DOFManager> &dofM, const std::vector<int> &mElem, const RCP<const Map> &mcmap); RCP<Time> New_Time = TimeMonitor::getNewCounter("New Assembly Time"); RCP<Time> Old_Time = TimeMonitor::getNewCounter("Old Assembly Time"); int xelem=10; int yelem=10; int zelem=10; int xblocks=1; int yblocks=1; int zblocks=1; //****************************************************************************** int main(int argc,char * argv[]) { Teuchos::oblackholestream blackhole; #ifdef HAVE_MPI Teuchos::GlobalMPISession mpiSession(&argc,&argv, &blackhole); //Teuchos::GlobalMPISession mpiSession(&argc,&argv, &std::cout); #else EPIC_FAIL // Panzer is an MPI only code. #endif Teuchos::FancyOStream out(Teuchos::rcpFromRef(std::cout)); out.setOutputToRootOnly(-1); out.setShowProcRank(true); newAssembly(out); TimeMonitor::summarize(); return 0; } //****************************************************************************** // Standard Usage Functions //****************************************************************************** void newAssembly(Teuchos::FancyOStream& /* out */) { RCP<panzer::DOFManager> my_dofM; RCP<Map> rowmap; RCP<Map> colmap; RCP<panzer::ConnManager> conn; const std::vector<int> & myElements=conn->getElementBlock("eblock-0_0_0"); std::vector<std::vector<int> > gids; std::vector<std::vector<int> > lids; std::vector< std::vector<std::vector<double> > >miniMat; fillMeUp1(gids,lids,miniMat,my_dofM,myElements,colmap); RCP<CrsGraph> crsgraph = rcp(new CrsGraph(Copy,*rowmap,*colmap,-1)); //Tell the graph where elements will be. for(size_t e=0;e<myElements.size();++e){ for (size_t i = 0; i < gids[e].size(); ++i) { crsgraph->InsertGlobalIndices(gids[e][i],gids[e].size(), &gids[e][0]); } } { crsgraph->FillComplete(); } RCP<CrsMatrix> crsmat = rcp(new CrsMatrix(Copy,*crsgraph)); //Where the data transfer takes place. for(std::size_t i=0;i<20;i++) { Teuchos::TimeMonitor LocalTimer(*New_Time); for ( size_t e = 0; e < myElements.size(); ++e) { for (size_t j = 0; j < gids[e].size(); ++j) { int accid=lids[e][j]; crsmat->SumIntoMyValues(accid,lids[e].size(),&miniMat[e][j][0],&lids[e][0]); } } } return; } size_t setUp1(RCP<Map> &rowmap, RCP<Map> &colmap, RCP<panzer::DOFManager> &my_dofM, RCP<panzer::ConnManager> &conn) { RCP<Teuchos::ParameterList> pl = rcp(new Teuchos::ParameterList); pl->set("X Blocks",xblocks); pl->set("Y Blocks",yblocks); pl->set("Z Blocks",zblocks); pl->set("X Elements",xelem); pl->set("Y Elements",yelem); pl->set("Z Elements",zelem); panzer_stk::CubeHexMeshFactory factory; factory.setParameterList(pl); RCP<panzer_stk::STK_Interface> mesh = factory.buildMesh(MPI_COMM_WORLD); conn = rcp(new panzer_stk::STKConnManager(mesh)); RCP<Intrepid2::Basis<PHX::exec_space,double,double> > basis1 = rcp(new Intrepid2::Basis_HGRAD_HEX_C1_FEM<PHX::exec_space,double,double>); RCP<const panzer::FieldPattern> pressure_pattern = Teuchos::rcp(new panzer::Intrepid2FieldPattern(basis1)); my_dofM = Teuchos::rcp(new panzer::DOFManager()); my_dofM->setConnManager(conn,MPI_COMM_WORLD); my_dofM->addField("u", pressure_pattern); my_dofM->addField("v", pressure_pattern); my_dofM->addField("w", pressure_pattern); my_dofM->addField("p", pressure_pattern); my_dofM->buildGlobalUnknowns(); std::vector<int> owned; std::vector<int> ownedAndGhosted; my_dofM->getOwnedIndicesAsInt(owned); my_dofM->getOwnedAndGhostedIndicesAsInt(ownedAndGhosted); size_t sz = ownedAndGhosted.size(); Epetra_MpiComm mpiComm(MPI_COMM_WORLD); //This is taken from Tpetra_Map_def.hpp //I could probably use a non-member constructor. rowmap = rcp(new Map(-1,ownedAndGhosted.size(),&ownedAndGhosted[0],0,mpiComm)); colmap = rcp(new Map(-1,ownedAndGhosted.size(),&ownedAndGhosted[0],0,mpiComm)); return sz; } void fillMeUp1(std::vector<std::vector<int> > &gids, std::vector<std::vector<int> > &lids, std::vector< std::vector<std::vector<double> > > &miniMat, RCP<panzer::DOFManager> &dofM, const std::vector<int> &mElem, const RCP<const Map> &mcmap) { for (std::size_t e = 0; e < mElem.size(); ++e) { std::vector<int> tgids; dofM->getElementGIDsAsInt(mElem[e], tgids); std::vector<int> tlids; for (size_t i = 0; i < tgids.size(); ++i) { tlids.push_back(mcmap->LID(tgids[i])); } std::vector<std::vector<double> > tminiMat; for (size_t i = 0; i < tgids.size(); ++i) { std::vector<double> temp(tgids.size()); for (size_t j = 0; j < tgids.size(); ++j) { //Right now everything is a one. That was just to make sure that the overlapping worked //correctly. This can literally be set to anything. double newval=1; temp[j]=newval; } tminiMat.push_back(temp); temp.clear(); } gids.push_back(tgids); lids.push_back(tlids); miniMat.push_back(tminiMat); } }
30.855263
139
0.653021
hillyuan
9d0b0e0c15ce51f590e9174537a4122d71fb630a
6,710
hpp
C++
boost/spirit/home/qi/nonterminal/nonterminal_director.hpp
mike-code/boost_1_38_0
7ff8b2069344ea6b0b757aa1f0778dfb8526df3c
[ "BSL-1.0" ]
30
2016-04-23T04:55:52.000Z
2021-05-19T10:26:27.000Z
boost/spirit/home/qi/nonterminal/nonterminal_director.hpp
xin3liang/platform_external_boost
ac861f8c0f33538060790a8e50701464ca9982d3
[ "BSL-1.0" ]
11
2016-11-22T13:14:55.000Z
2021-12-14T00:56:51.000Z
boost/spirit/home/qi/nonterminal/nonterminal_director.hpp
xin3liang/platform_external_boost
ac861f8c0f33538060790a8e50701464ca9982d3
[ "BSL-1.0" ]
15
2016-04-26T13:16:38.000Z
2022-03-08T06:13:14.000Z
/*============================================================================= Copyright (c) 2001-2007 Joel de Guzman 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) ==============================================================================*/ #if !defined(BOOST_SPIRIT_NONTERMINAL_DIRECTOR_FEB_19_2007_0259PM) #define BOOST_SPIRIT_NONTERMINAL_DIRECTOR_FEB_19_2007_0259PM #include <boost/spirit/home/support/nonterminal/nonterminal.hpp> #include <boost/spirit/home/support/nonterminal/detail/expand_arg.hpp> #include <boost/spirit/home/qi/domain.hpp> #include <boost/spirit/home/support/component.hpp> #include <boost/spirit/home/support/detail/values.hpp> #include <boost/fusion/include/transform.hpp> #include <boost/fusion/include/join.hpp> #include <boost/fusion/include/single_view.hpp> #include <boost/intrusive_ptr.hpp> #include <boost/mpl/at.hpp> #include <boost/type_traits/is_same.hpp> #include <boost/type_traits/remove_const.hpp> namespace boost { namespace spirit { namespace qi { struct nonterminal_director { template <typename Component, typename Context, typename Iterator> struct attribute { typedef typename result_of::subject<Component>::type nonterminal_holder; typedef typename nonterminal_holder::nonterminal_type::attr_type type; }; template < typename NonterminalContext, typename Nonterminal , typename Iterator, typename Context , typename Skipper, typename Attribute> static bool parse_nonterminal( nonterminal_object<Nonterminal> const& x , Iterator& first, Iterator const& last , Context& /*caller_context*/, Skipper const& skipper , Attribute& attr) { // the nonterminal_holder holds an actual nonterminal_object typedef typename Nonterminal::locals_type locals_type; fusion::single_view<Attribute&> front(attr); NonterminalContext context(front, locals_type()); return x.obj.parse(first, last, context, skipper); } template < typename NonterminalContext, typename Nonterminal , typename Iterator, typename Context , typename Skipper, typename Attribute> static bool parse_nonterminal( Nonterminal const* ptr , Iterator& first, Iterator const& last , Context& /*caller_context*/, Skipper const& skipper , Attribute& attr) { // the nonterminal_holder holds a pointer to a nonterminal typedef typename Nonterminal::locals_type locals_type; fusion::single_view<Attribute&> front(attr); NonterminalContext context(front, locals_type()); return ptr->parse(first, last, context, skipper); } template < typename NonterminalContext, typename Nonterminal, typename FSequence , typename Iterator, typename Context , typename Skipper, typename Attribute> static bool parse_nonterminal( parameterized_nonterminal<Nonterminal, FSequence> const& x , Iterator& first, Iterator const& last , Context& caller_context, Skipper const& skipper , Attribute& attr) { // the nonterminal_holder holds a parameterized_nonterminal typedef typename Nonterminal::locals_type locals_type; fusion::single_view<Attribute&> front(attr); NonterminalContext context( fusion::join( front , fusion::transform( x.fseq , spirit::detail::expand_arg<Context>(caller_context) ) ) , locals_type() ); return x.ptr->parse(first, last, context, skipper); } template < typename Component , typename Iterator, typename Context , typename Skipper, typename Attribute> static bool parse( Component const& component , Iterator& first, Iterator const& last , Context& context, Skipper const& skipper , Attribute& attr_) { // main entry point typedef typename result_of::subject<Component>::type nonterminal_holder; // The overall context_type consist of a tuple with: // 1) a tuple of the return value and parameters // 2) the locals // if no signature is specified the first tuple contains // an unused_type element at position zero only. typedef typename nonterminal_holder::nonterminal_type::context_type context_type; // attr_type is the return type as specified by the associated // nonterminal signature, if no signature is specified this is // the unused_type typedef typename nonterminal_holder::nonterminal_type::attr_type attr_type; // create an attribute if one is not supplied typename mpl::if_< is_same<typename remove_const<Attribute>::type, unused_type> , attr_type , Attribute&>::type attr = spirit::detail::make_value<attr_type>::call(attr_); return parse_nonterminal<context_type>( subject(component).held , first, last, context, skipper, attr ); } template <typename Nonterminal> static std::string what_nonterminal(nonterminal_object<Nonterminal> const& x) { // the nonterminal_holder holds an actual nonterminal_object return x.obj.what(); } template <typename Nonterminal> static std::string what_nonterminal(Nonterminal const* ptr) { // the nonterminal_holder holds a pointer to a nonterminal return ptr->what(); } template <typename Nonterminal, typename FSequence> static std::string what_nonterminal( parameterized_nonterminal<Nonterminal, FSequence> const& x) { // the nonterminal_holder holds a parameterized_nonterminal return x.ptr->what(); } template <typename Component, typename Context> static std::string what(Component const& component, Context const& ctx) { return what_nonterminal(subject(component).held); } }; }}} #endif
39.239766
85
0.608048
mike-code