blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
f3a90e0b57f26aa7759f9156e09fd0d8a7de70a1
282f567373766261ef56e3b8824b58e107584f94
/OJ/OpenJudge/1.9 编程基础之顺序查找/1.9-03.cpp
19fa6a1257b0a6caf1a3a71057de4ab2ce84efbd
[]
no_license
yhzhm/Practice
27aff56652122d64d7879f15aa41e2550240bb06
9114447ed3346614a7c633f51917069da6aa17f7
refs/heads/master
2022-10-19T01:15:10.517149
2022-09-29T09:04:38
2022-09-29T09:04:38
121,328,943
0
0
null
null
null
null
UTF-8
C++
false
false
243
cpp
#include<bits/stdc++.h> using namespace std; int main() { int max = 0, n1, n2, d = 0; for (int i = 1; i <= 7; ++i) { cin >> n1 >> n2; if (n1 + n2 > 8 && max < n1 + n2) { max = n1 + n2; d = i; } } cout << d << endl; return 0; }
[ "yhzhm@qq.com" ]
yhzhm@qq.com
2baed85eca21934ec8b91d5f8b4c7866e5809ae9
16044e3f6f48f33a270867eef13d41b6a0617186
/boost/library/boost/thread/detail/lock.hpp
d2974ea0de2d139a6d3fc0dd93db8b1264688bea
[]
no_license
esoobservatory/fitsliberator
47350be9b99ff7ba3c16bae9766621d1f324d2ef
02e11d9bd718dfb68b3d729cafc49915c8962b8e
refs/heads/master
2021-01-18T16:30:10.922487
2015-08-19T15:14:58
2015-08-19T15:14:58
41,041,169
38
11
null
null
null
null
UTF-8
C++
false
false
4,621
hpp
// Copyright (C) 2001-2003 // William E. Kempf // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_XLOCK_WEK070601_HPP #define BOOST_XLOCK_WEK070601_HPP #include <boost/thread/detail/config.hpp> #include <boost/utility.hpp> #include <boost/thread/exceptions.hpp> namespace boost { class condition; struct xtime; namespace detail { namespace thread { template <typename Mutex> class lock_ops : private noncopyable { private: lock_ops() { } public: typedef typename Mutex::cv_state lock_state; static void lock(Mutex& m) { m.do_lock(); } static bool trylock(Mutex& m) { return m.do_trylock(); } static bool timedlock(Mutex& m, const xtime& xt) { return m.do_timedlock(xt); } static void unlock(Mutex& m) { m.do_unlock(); } static void lock(Mutex& m, lock_state& state) { m.do_lock(state); } static void unlock(Mutex& m, lock_state& state) { m.do_unlock(state); } }; template <typename Mutex> class scoped_lock : private noncopyable { public: typedef Mutex mutex_type; explicit scoped_lock(Mutex& mx, bool initially_locked=true) : m_mutex(mx), m_locked(false) { if (initially_locked) lock(); } ~scoped_lock() { if (m_locked) unlock(); } void lock() { if (m_locked) throw lock_error(); lock_ops<Mutex>::lock(m_mutex); m_locked = true; } void unlock() { if (!m_locked) throw lock_error(); lock_ops<Mutex>::unlock(m_mutex); m_locked = false; } bool locked() const { return m_locked; } operator const void*() const { return m_locked ? this : 0; } private: friend class boost::condition; Mutex& m_mutex; bool m_locked; }; template <typename TryMutex> class scoped_try_lock : private noncopyable { public: typedef TryMutex mutex_type; explicit scoped_try_lock(TryMutex& mx) : m_mutex(mx), m_locked(false) { try_lock(); } scoped_try_lock(TryMutex& mx, bool initially_locked) : m_mutex(mx), m_locked(false) { if (initially_locked) lock(); } ~scoped_try_lock() { if (m_locked) unlock(); } void lock() { if (m_locked) throw lock_error(); lock_ops<TryMutex>::lock(m_mutex); m_locked = true; } bool try_lock() { if (m_locked) throw lock_error(); return (m_locked = lock_ops<TryMutex>::trylock(m_mutex)); } void unlock() { if (!m_locked) throw lock_error(); lock_ops<TryMutex>::unlock(m_mutex); m_locked = false; } bool locked() const { return m_locked; } operator const void*() const { return m_locked ? this : 0; } private: friend class boost::condition; TryMutex& m_mutex; bool m_locked; }; template <typename TimedMutex> class scoped_timed_lock : private noncopyable { public: typedef TimedMutex mutex_type; scoped_timed_lock(TimedMutex& mx, const xtime& xt) : m_mutex(mx), m_locked(false) { timed_lock(xt); } scoped_timed_lock(TimedMutex& mx, bool initially_locked) : m_mutex(mx), m_locked(false) { if (initially_locked) lock(); } ~scoped_timed_lock() { if (m_locked) unlock(); } void lock() { if (m_locked) throw lock_error(); lock_ops<TimedMutex>::lock(m_mutex); m_locked = true; } bool try_lock() { if (m_locked) throw lock_error(); return (m_locked = lock_ops<TimedMutex>::trylock(m_mutex)); } bool timed_lock(const xtime& xt) { if (m_locked) throw lock_error(); return (m_locked = lock_ops<TimedMutex>::timedlock(m_mutex, xt)); } void unlock() { if (!m_locked) throw lock_error(); lock_ops<TimedMutex>::unlock(m_mutex); m_locked = false; } bool locked() const { return m_locked; } operator const void*() const { return m_locked ? this : 0; } private: friend class boost::condition; TimedMutex& m_mutex; bool m_locked; }; } // namespace thread } // namespace detail } // namespace boost #endif // BOOST_XLOCK_WEK070601_HPP // Change Log: // 8 Feb 01 WEKEMPF Initial version. // 22 May 01 WEKEMPF Modified to use xtime for time outs. // 30 Jul 01 WEKEMPF Moved lock types into boost::detail::thread. Renamed // some types. Added locked() methods.
[ "kaspar@localhost" ]
kaspar@localhost
73fe1961d66789e1c2691cd2a400574424ccd116
af886cff5033e866c2208f2d179b88ff74d33794
/PCSamples/Graphics/VideoTexturePC12/DeviceResources.h
21b2cc7e8f72d53b4a1eca235b98d4a9eb947700
[]
permissive
tunip3/Xbox-ATG-Samples
c1d1d6c0b9f93c453733a1dada074b357bd6577a
27e30925a46ae5777703361409b8395fed0394d3
refs/heads/master
2020-04-14T08:37:00.614182
2018-12-14T02:38:01
2018-12-14T02:38:01
163,739,353
3
0
MIT
2019-01-01T13:38:37
2019-01-01T13:38:37
null
UTF-8
C++
false
false
6,572
h
// // DeviceResources.h - A wrapper for the Direct3D 12 device and swapchain // #pragma once namespace DX { // Provides an interface for an application that owns DeviceResources to be notified of the device being lost or created. interface IDeviceNotify { virtual void OnDeviceLost() = 0; virtual void OnDeviceRestored() = 0; }; // Controls all the DirectX device resources. class DeviceResources { public: static const unsigned int c_AllowTearing = 0x1; static const unsigned int c_EnableHDR = 0x2; DeviceResources(DXGI_FORMAT backBufferFormat = DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT depthBufferFormat = DXGI_FORMAT_D32_FLOAT, UINT backBufferCount = 2, D3D_FEATURE_LEVEL minFeatureLevel = D3D_FEATURE_LEVEL_11_0, unsigned int flags = 0) noexcept(false); ~DeviceResources(); void CreateDeviceResources(); void CreateWindowSizeDependentResources(); void SetWindow(HWND window, int width, int height); bool WindowSizeChanged(int width, int height); void HandleDeviceLost(); void RegisterDeviceNotify(IDeviceNotify* deviceNotify) { m_deviceNotify = deviceNotify; } void Prepare(D3D12_RESOURCE_STATES beforeState = D3D12_RESOURCE_STATE_PRESENT); void Present(D3D12_RESOURCE_STATES beforeState = D3D12_RESOURCE_STATE_RENDER_TARGET); void WaitForGpu() noexcept; // Device Accessors. RECT GetOutputSize() const { return m_outputSize; } // Direct3D Accessors. ID3D12Device* GetD3DDevice() const { return m_d3dDevice.Get(); } IDXGISwapChain3* GetSwapChain() const { return m_swapChain.Get(); } IDXGIFactory4* GetDXGIFactory() const { return m_dxgiFactory.Get(); } D3D_FEATURE_LEVEL GetDeviceFeatureLevel() const { return m_d3dFeatureLevel; } ID3D12Resource* GetRenderTarget() const { return m_renderTargets[m_backBufferIndex].Get(); } ID3D12Resource* GetDepthStencil() const { return m_depthStencil.Get(); } ID3D12CommandQueue* GetCommandQueue() const { return m_commandQueue.Get(); } ID3D12CommandAllocator* GetCommandAllocator() const { return m_commandAllocators[m_backBufferIndex].Get(); } ID3D12GraphicsCommandList* GetCommandList() const { return m_commandList.Get(); } DXGI_FORMAT GetBackBufferFormat() const { return m_backBufferFormat; } DXGI_FORMAT GetDepthBufferFormat() const { return m_depthBufferFormat; } D3D12_VIEWPORT GetScreenViewport() const { return m_screenViewport; } D3D12_RECT GetScissorRect() const { return m_scissorRect; } UINT GetCurrentFrameIndex() const { return m_backBufferIndex; } UINT GetBackBufferCount() const { return m_backBufferCount; } DXGI_COLOR_SPACE_TYPE GetColorSpace() const { return m_colorSpace; } unsigned int GetDeviceOptions() const { return m_options; } CD3DX12_CPU_DESCRIPTOR_HANDLE GetRenderTargetView() const { return CD3DX12_CPU_DESCRIPTOR_HANDLE(m_rtvDescriptorHeap->GetCPUDescriptorHandleForHeapStart(), m_backBufferIndex, m_rtvDescriptorSize); } CD3DX12_CPU_DESCRIPTOR_HANDLE GetDepthStencilView() const { return CD3DX12_CPU_DESCRIPTOR_HANDLE(m_dsvDescriptorHeap->GetCPUDescriptorHandleForHeapStart()); } private: void MoveToNextFrame(); void GetAdapter(IDXGIAdapter1** ppAdapter); void UpdateColorSpace(); static const size_t MAX_BACK_BUFFER_COUNT = 3; UINT m_backBufferIndex; // Direct3D objects. Microsoft::WRL::ComPtr<ID3D12Device> m_d3dDevice; Microsoft::WRL::ComPtr<ID3D12CommandQueue> m_commandQueue; Microsoft::WRL::ComPtr<ID3D12GraphicsCommandList> m_commandList; Microsoft::WRL::ComPtr<ID3D12CommandAllocator> m_commandAllocators[MAX_BACK_BUFFER_COUNT]; // Swap chain objects. Microsoft::WRL::ComPtr<IDXGIFactory4> m_dxgiFactory; Microsoft::WRL::ComPtr<IDXGISwapChain3> m_swapChain; Microsoft::WRL::ComPtr<ID3D12Resource> m_renderTargets[MAX_BACK_BUFFER_COUNT]; Microsoft::WRL::ComPtr<ID3D12Resource> m_depthStencil; // Presentation fence objects. Microsoft::WRL::ComPtr<ID3D12Fence> m_fence; UINT64 m_fenceValues[MAX_BACK_BUFFER_COUNT]; Microsoft::WRL::Wrappers::Event m_fenceEvent; // Direct3D rendering objects. Microsoft::WRL::ComPtr<ID3D12DescriptorHeap> m_rtvDescriptorHeap; Microsoft::WRL::ComPtr<ID3D12DescriptorHeap> m_dsvDescriptorHeap; UINT m_rtvDescriptorSize; D3D12_VIEWPORT m_screenViewport; D3D12_RECT m_scissorRect; // Direct3D properties. DXGI_FORMAT m_backBufferFormat; DXGI_FORMAT m_depthBufferFormat; UINT m_backBufferCount; D3D_FEATURE_LEVEL m_d3dMinFeatureLevel; // Cached device properties. HWND m_window; D3D_FEATURE_LEVEL m_d3dFeatureLevel; DWORD m_dxgiFactoryFlags; RECT m_outputSize; // HDR Support DXGI_COLOR_SPACE_TYPE m_colorSpace; // DeviceResources options (see flags above) unsigned int m_options; // The IDeviceNotify can be held directly as it owns the DeviceResources. IDeviceNotify* m_deviceNotify; }; }
[ "chuckw@windows.microsoft.com" ]
chuckw@windows.microsoft.com
4d8a7d81f657c9d3e964834e42b018354bb4fd3e
9b8591c5f2a54cc74c73a30472f97909e35f2ecf
/codegen/QtCharts/QVPieModelMapperSlots.h
80cdd51380059a564216b25016c1cb346d4f1f83
[ "MIT" ]
permissive
tnsr1/Qt5xHb
d3a9396a6ad5047010acd5d8459688e6e07e49c2
04b6bd5d8fb08903621003fa5e9b61b831c36fb3
refs/heads/master
2021-05-17T11:15:52.567808
2020-03-26T06:52:17
2020-03-26T06:52:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
477
h
%% %% Qt5xHb - Bindings libraries for Harbour/xHarbour and Qt Framework 5 %% %% Copyright (C) 2020 Marcos Antonio Gambeta <marcosgambeta AT outlook DOT com> %% $project=Qt5xHb $module=QtCharts $header $includes=5,7,0 using namespace QtCharts; $beginSlotsClass $signal=5,7,0|firstRowChanged() $signal=5,7,0|labelsColumnChanged() $signal=5,7,0|modelReplaced() $signal=5,7,0|rowCountChanged() $signal=5,7,0|seriesReplaced() $signal=5,7,0|valuesColumnChanged() $endSlotsClass
[ "5998677+marcosgambeta@users.noreply.github.com" ]
5998677+marcosgambeta@users.noreply.github.com
259880e592a6f7194dc69f7b054227460ebc06c3
1c83aef38de4e27f54d4664886a431b4fd2caea3
/Engine/Rendering/VertexArray.h
38946e75f40796b05d442f3f7b9e32d28a95b6ee
[]
no_license
quinsmpang/StormBrewerEngine
7a84494debe415c9216586ccfb7d1faf5e0e016f
73f0f3874874909fdf97977737133f5996668410
refs/heads/master
2021-06-21T05:42:34.051588
2017-08-09T08:51:42
2017-08-09T08:51:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
807
h
#pragma once #include "Engine/EngineCommon.h" #include "Engine/Rendering/VertexDefinition.h" #include "Engine/Rendering/ShaderProgram.h" #include "Engine/Rendering/VertexBuffer.h" #ifndef _WEB class ENGINE_EXPORT VertexArray { public: VertexArray(); VertexArray(const VertexArray & rhs) = delete; VertexArray(VertexArray && rhs) noexcept; ~VertexArray(); VertexArray & operator = (VertexArray & rhs) = delete; VertexArray & operator = (VertexArray && rhs) noexcept; void Move(VertexArray && rhs) noexcept; void Destroy(); void CreateDefaultBinding(const ShaderProgram & program, const VertexBuffer & buffer); int GetLoadError() const { return m_LoadError; } void Bind() const; void Unbind() const; private: unsigned int m_VertexArrayName; int m_LoadError; }; #endif
[ "nick.weihs@gmail.com" ]
nick.weihs@gmail.com
b7799b124336aa3cee9e3ab585b6afcc2e705c63
aa238e9d4f0b7ff0e86469b88bd877fde3f2c37f
/be/src/http/http_status.h
44779a2d65acfc2120c10bfc80ae484c93f1835a
[ "Apache-2.0", "BSD-3-Clause", "dtoa", "bzip2-1.0.6", "BSL-1.0", "PSF-2.0" ]
permissive
tengxunshigou/palo
42474a5bcb3933443830c0ea6a1c56dd8f608c45
fb64a1a8e8ed612cd95d1ea0c67bf70804a1d2da
refs/heads/master
2021-01-16T21:13:50.190451
2017-08-11T14:09:07
2017-08-11T14:09:07
100,223,889
1
0
null
2017-08-14T03:18:55
2017-08-14T03:18:55
null
UTF-8
C++
false
false
2,201
h
// Copyright (c) 2017, Baidu.com, Inc. All Rights Reserved // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #ifndef BDG_PALO_BE_SRC_COMMON_UTIL_HTTP_STATUS_H #define BDG_PALO_BE_SRC_COMMON_UTIL_HTTP_STATUS_H #include <string> namespace palo { enum HttpStatus { CONTINUE = 100, SWITCHING_PROTOCOLS = 101, OK = 200, CREATED = 201, ACCEPTED = 202, NON_AUTHORITATIVE_INFORMATION = 203, NO_CONTENT = 204, RESET_CONTENT = 205, PARTIAL_CONTENT = 206, MULTIPLE_CHOICES = 300, MOVED_PERMANENTLY = 301, FOUND = 302, SEE_OTHER = 303, NOT_MODIFIED = 304, USE_PROXY = 305, TEMPORARY_REDIRECT = 307, BAD_REQUEST = 400, UNAUTHORIZED = 401, PAYMENT_REQUIRED = 402, FORBIDDEN = 403, NOT_FOUND = 404, METHOD_NOT_ALLOWED = 405, NOT_ACCEPTABLE = 406, PROXY_AUTHENTICATION = 407, REQUEST_TIMEOUT = 408, CONFLICT = 409, GONE = 410, LENGTH_REQUIRED = 411, PRECONDITION_FAILED = 412, REQUEST_ENTITY_TOO_LARGE = 413, REQUEST_URI_TOO_LONG = 414, UNSUPPORTED_MEDIA_TYPE = 415, REQUESTED_RANGE_NOT_SATISFIED = 416, EXPECTATION_FAILED = 417, INTERNAL_SERVER_ERROR = 500, NOT_IMPLEMENTED = 501, BAD_GATEWAY = 502, SERVICE_UNAVAILABLE = 503, GATEWAY_TIMEOUT = 504, HTTP_VERSION_NOT_SUPPORTED = 505 }; std::string to_code(const HttpStatus& status); std::string defalut_reason(const HttpStatus& status); } #endif
[ "lichaoyong121@qq.com" ]
lichaoyong121@qq.com
2465ef4b26b60aa47797c16e5d5c9ee85b13433f
2442e2798dd379a5adeebfa392728720e6d14015
/Promise.h
67e5dcc1248b893f5d793fb22eb154563c688879
[]
no_license
Amoniy/cpp-second-year-hometasks
38e9c5c54ff0c02106c99c84cedb63d266fcc2d6
03a3615edcdd8221d0fc944eacdffb61c0623740
refs/heads/master
2021-09-28T08:12:03.654931
2018-11-15T20:54:49
2018-11-15T20:54:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,161
h
#pragma once #include <functional> #include "Future.h" template<typename T> class Promise { void ensureInitialized() const { if (!state) { throw std::runtime_error("Promise does not have state"); } } public: void setPool(ThreadPool *threadPool) { state->threadPool = threadPool; } Promise() : state(std::make_shared<FutureState<T> >()), futureExists(false) { state->hasPromise = true; } Promise(Promise<T> &&promise) noexcept : state(std::move(promise.state)), futureExists(promise.futureExists.load()) { futureExists = promise.futureExists ? true : false; } ~Promise() { if (state) { state->hasPromise = false; state->conditionVariable.notify_one(); } } Promise &operator=(Promise<T> &&promise) noexcept { futureExists = promise.futureExists.load(); state = std::move(promise.state); return *this; }; Promise(Promise<T> const &) = delete; Promise &operator=(Promise<T> const &) = delete; Future<T> getFuture() { if (futureExists) { throw std::runtime_error("Future already set"); } futureExists = true; return Future<T>(state); } void set(const T &value) { ensureInitialized(); std::unique_lock<std::mutex> lock(state->mutex); if (state->isReady) { throw std::runtime_error("value already set"); } state->value = value; state->isReady = true; state->conditionVariable.notify_one(); } void set(T &&v) { ensureInitialized(); std::unique_lock<std::mutex> lock(state->mutex); if (state->isReady) { throw std::runtime_error("value already set"); } state->value = std::move(v); state->isReady = true; state->conditionVariable.notify_one(); } void setException(const std::exception_ptr &exceptionPtr) { ensureInitialized(); std::unique_lock<std::mutex> lock(state->mutex); if (state->exceptionPtr) { throw std::runtime_error("error already set"); } state->exceptionPtr = exceptionPtr; state->isReady = true; state->conditionVariable.notify_one(); } private: std::shared_ptr<FutureState<T> > state; std::atomic<bool> futureExists; }; template<> class Promise<void> { void ensureInitialized() const { if (!state) { throw std::runtime_error("Promise does not have state"); } } public: Promise() : state(std::make_shared<FutureState<void> >()), futureExists(false) { state->hasPromise = true; } ~Promise() { if (state) { state->hasPromise = false; state->conditionVariable.notify_one(); } } Promise(Promise<void> &&promise) noexcept : state(std::move(promise.state)), futureExists(promise.futureExists.load()) { } Promise &operator=(Promise<void> &&promise) noexcept { futureExists = promise.futureExists.load(); state = std::move(promise.state); return *this; }; Promise(Promise<void> const &) = delete; Promise &operator=(Promise<void> const &) = delete; Future<void> getFuture() { if (futureExists) { throw std::runtime_error("Future already set"); } futureExists = true; return Future<void>(state); } void set() { ensureInitialized(); if (state->isReady) { throw std::runtime_error("value already set"); } state->isReady = true; state->conditionVariable.notify_one(); } void setException(const std::exception_ptr &exceptionPtr) { ensureInitialized(); std::unique_lock<std::mutex> lock(state->mutex); if (state->exceptionPtr) { throw std::runtime_error("error already set"); } state->exceptionPtr = exceptionPtr; state->isReady = true; state->conditionVariable.notify_one(); }; private: std::shared_ptr<FutureState<void> > state; std::atomic<bool> futureExists; }; template<typename T> class Promise<T &> { void ensureInitialized() const { if (!state) { throw std::runtime_error("Promise does not have state"); } } public: Promise() : state(std::make_shared<FutureState<T &> >()), futureExists(false) { state->hasPromise = true; } ~Promise() { if (state) { state->hasPromise = false; state->conditionVariable.notify_one(); } } Promise(Promise &&promise) noexcept : state(std::move(promise.state)), futureExists(promise.futureExists.load()) { } Promise &operator=(Promise &&promise) noexcept { futureExists = promise.futureExists.load(); state = std::move(promise.state); return *this; }; Promise(const Promise &) = delete; Promise &operator=(const Promise &) = delete; Future<T &> getFuture() { if (futureExists) { throw std::runtime_error("Future already set"); } futureExists = true; return Future<T &>(state); } void set(T &v) { ensureInitialized(); std::unique_lock<std::mutex> lock(state->mutex); if (state->isReady) { throw std::runtime_error("value already set"); } state->value = &v; state->isReady = true; state->conditionVariable.notify_one(); } void setException(const std::exception_ptr &exceptionPtr) { ensureInitialized(); std::unique_lock<std::mutex> lock(state->mutex); if (state->exceptionPtr) { throw std::runtime_error("error already set"); } state->exceptionPtr = exceptionPtr; state->isReady = true; state->conditionVariable.notify_one(); } private: std::shared_ptr<FutureState<T &> > state; std::atomic<bool> futureExists; };
[ "anton17.04.1998@gmail.com" ]
anton17.04.1998@gmail.com
56cac07d3f808598c1e1a2d7354bd594586e84fb
10ee620f5e4473e11fb821d5944a6b06bf4ca493
/UPPayAppDemo1/inc/BrCtlSampleAppContainer.h
43f3da2633cd1714296830d0ceaeb30ad898f630
[]
no_license
zhonghualee/TestSymbian
a4bc7401964da9a47ea4f80c68386e834613eb24
014ef7ef759a3dca419daf787eca2e5b8b8e4d6b
refs/heads/master
2016-09-05T11:28:51.442611
2012-08-06T07:31:02
2012-08-06T07:31:02
5,311,232
0
1
null
null
null
null
MacCentralEurope
C++
false
false
8,795
h
/* * Copyright (c) 2005-2006 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of the License "Symbian Foundation License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.symbianfoundation.org/legal/sfl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: Declares container control for Browser Control Sample application. * */ #ifndef BRCTLSAMPLEAPPCONTAINER_H #define BRCTLSAMPLEAPPCONTAINER_H // INCLUDES #include <coecntrl.h> #include "BrCtlInterface.h" #include "WebClientEngine.h" // FORWARD DECLARATIONS class CBrCtlSampleAppSpecialLoadObserver; class CBrCtlSampleAppLayoutObserver; class CBrCtlSampleAppSoftkeysObserver; class CBrCtlSampleAppLoadEventObserver; class CBrCtlSampleAppCommandObserver; class CBrCtlSampleAppLinkResolver; class CBrCtlSampleAppStateChangeObserver; class CBrCtlSampleAppDialogsProvider; class CBrCtlSampleAppWidgetHandler; class CBrowserContentView; class MWebClientObserver; class CUPPayAppDemo1AppView; // CLASS DECLARATION /** * CBrCtlSampleAppContainer class. * This is the container control class. */ class CBrCtlSampleAppContainer : public CCoeControl, public MWebClientObserver, MCoeControlObserver, MBrCtlDataLoadSupplier { public: // Constructors and destructor /** * EPOC default constructor. * @param aRect Frame rectangle for container. */ void ConstructL(CUPPayAppDemo1AppView* aContainer, const TRect& aRect); /** * Two-phased constructor. */ static CBrCtlSampleAppContainer* NewL(const TRect& aRect); /** * Destructor. */ ~CBrCtlSampleAppContainer(); public: // New functions /** * Pass a command to the Browser Control * @since 2.8 * @param aCommand The command that the Browser Control should process * @return void */ void HandleCommandL(TInt aCommand); /** * Dynamically initialises a menu pane. The Uikon framework calls this * function, if it is implemented in a menuís observer, immediately before * the menu pane is activated. * @since 2.8 * @param aResourceId Resource ID identifying the menu pane to initialise * @param aMenuPane The in-memory representation of the menu pane. * @return void */ void DynInitMenuPaneL(TInt aResourceId, CEikMenuPane* aMenuPane); /** * Handles key events * @since 2.8 * @param aKeyEvent The key event that occurred. * @param aType The window server event type that is being handled * @return TKeyResponse Value indicates whether or not the key event was consumed by the control. The default implementation simply returns EKeyWasNotConsumed. */ TKeyResponse HandleKeyEventL(const TKeyEvent& aKeyEvent,TEventCode aType); /** * Accessor method for iText * @since 2.8 * @param void * @return TDesc& The descriptor of the text */ inline const TDesC& Text() const {return iText;} /** * Setter method for iText * @since 2.8 * @param aText The descriptor for the text you wish to display * @return void */ void SetText( const TDesC& aText ); /** * Setter method for iPoint * @since 2.8 * @param aPoint The point at which you want to display the text * @return void */ void SetPoint( const TPoint& aPoint ); /** * Accessor method iBrCtlInterface * @since 2.8 * @param void * @return CBrCtlInterface* A pointer to the browser control interface as a convenience to the observers */ inline CBrCtlInterface* BrCtlInterface() const {return iBrCtlInterface;} void ProcessIcon(); /** * Check if this is an GetBitmapData test * @param void * @return */ TBool isIconTest(); void setIconTest(); void BasicBrowserControlL(); void SpecialLoadRequestsL(); /** * From MWebClientObserver (see WebClientEngine.h) */ void ClientEvent( const TDesC& aEventDescription ); void ClientHeaderReceived( const TDesC& aHeaderData ); void ClientBodyReceived( const TDesC8& aBodyData ); // const TDesC& CreateOrders(const TDesC& sum, const TDesC& SPId, const TDesC& SPName, int UserId); CUPPayAppDemo1AppView* GetView() {return iAppView;}; void NotifyUser(const TDesC& aData); private: // Functions from base classes /** * From CoeControl,SizeChanged. */ void SizeChanged(); /** * From CoeControl,CountComponentControls. */ TInt CountComponentControls() const; /** * From CCoeControl,ComponentControl. */ CCoeControl* ComponentControl(TInt aIndex) const; /** * From CCoeControl,Draw. */ void Draw(const TRect& aRect) const; /** * Handle key events. */ TKeyResponse OfferKeyEventL(const TKeyEvent& aKeyEvent,TEventCode aType); /** * From MBrCtlDataLoadSupplier, Cancel an on-going load */ void CancelLoad(); /** * Create a Basic Browser Control that does not have observers with scrolling * and HTTP framework capabilities */ void CreateBasicBrowserControlL(); /** * Create Browser Control with observers with the given capabilities */ void CreateBrowserControlWithObserversL(TUint aCapabilities); /** * Read the file. */ HBufC8* ReadFileLC(const TDesC& aFileName); /** * Handles an event from an observed control. */ void HandleControlEventL(CCoeControl* aControl,TCoeEvent aEventType); /** * The following methods are used to demonstrate the functionality of * the browser control API */ // void BasicBrowserControlL(); void BrowserControlWithObserversL(); void BrowserControlPostWithObserversL(); void LoadingContentWithFileHandleL(); void LoadingContentWithBufferL(); void IncrementalLoadingL(); // void SpecialLoadRequestsL(); void CustomizedDialogsL(); void CustomizedSoftKeysL(); void ResolvingEmbeddedLinksL(); void CustomizedScrollBarsL(); void HandleStateChangedL(); void ChangeSizeExtentsL(); void PageInfoL(); void ContentSizeImageCountL(); void GetBitmapDataL(); void CommandObserverL(); void WidgetHandlerL(); void LoadurlL(); private: //data // Pointer to the browser control interface CBrCtlInterface* iBrCtlInterface; // Desired capabilities of the browser control TUint iBrCtlCapabilities; // Command Base TInt iCommandBase; // Special Load Observer CBrCtlSampleAppSpecialLoadObserver* iBrCtlSampleAppSpecialLoadObserver; // Layout Observer CBrCtlSampleAppLayoutObserver* iBrCtlSampleAppLayoutObserver; // Softkeys Observer CBrCtlSampleAppSoftkeysObserver* iBrCtlSampleAppSoftkeysObserver; // Load Event Observer CBrCtlSampleAppLoadEventObserver* iBrCtlSampleAppLoadEventObserver; // Command Observer CBrCtlSampleAppCommandObserver* iBrCtlSampleAppCommandObserver; // Link Resolver CBrCtlSampleAppLinkResolver* iBrCtlSampleAppLinkResolver; // State Change Observer CBrCtlSampleAppStateChangeObserver* iBrCtlSampleAppStateChangeObserver; // // Dialogs Provider // CBrCtlSampleAppDialogsProvider* iBrCtlSampleAppDialogsProvider; // //Widget Handler // CBrCtlSampleAppWidgetHandler* iBrCtlSampleAppWidgetHandler; // // Informs whether or not CancelLoad has been called TBool iCancelInitDataLoad; // Abstract font interface CFont* iFont; // Text to display to the screen if desired TPtrC iText; // Point at which to display text TPoint iPoint; //icon: favicon or thumbnail CGulIcon* icon; TBool iconFlag; TRect iRect; TBool iRectChanged; CUPPayAppDemo1AppView* iAppView; }; #endif // End of File
[ "zhonghua.lee@gmail.com" ]
zhonghua.lee@gmail.com
817395801d2ef98d2a8fc9abaedd094fc60a9632
8c46efa71edb8413bb46deb36b347627834a0c77
/Common/math/triangle.cpp
2bb95e19975d28924fbaaa8701266a76408f0f92
[ "MIT" ]
permissive
azhugg/Common
4f5b08d3f8dc66936b7eb243a5db2b3379fba06a
239caba7912454a239e2162cad479fb1dd4ced7e
refs/heads/master
2021-08-18T18:58:12.723498
2017-11-23T15:41:11
2017-11-23T15:41:11
null
0
0
null
null
null
null
UHC
C++
false
false
1,992
cpp
#include "stdafx.h" #include "triangle.h" using namespace common; Triangle::Triangle() { } Triangle::Triangle( const Vector3& v1, const Vector3& v2, const Vector3 &v3 ): a(v1), b(v2), c( v3 ) { } // Init void Triangle::Create( const Vector3& v1, const Vector3& v2, const Vector3& v3 ) { a = v1; b = v2; c = v3; } // Triangle::Intersect //pfT, pfU, pfV : out BOOL Triangle::Intersect( const Vector3& vOrig, const Vector3& vDir, float *pfT, float *pfU, float *pfV ) const { static float u, v; // Find vectors for two edges sharing vert0 static Vector3 vEdge1; static Vector3 vEdge2; vEdge1 = b - a; vEdge2 = c - a; // Begin calculating determinant - also used to calculate U parameter static Vector3 vP; vP = vDir.CrossProduct( vEdge2 ); // If determinant is near zero, ray lies in plane of triangle float fDet = vEdge1.DotProduct( vP ); if( fDet < 0.0001F ) { return FALSE; } //if // Calculate distance from vert0 to ray origin static Vector3 vT; vT = vOrig - a; // Calculate U parameter and test bounds u = vT.DotProduct( vP ); if( u < 0.0F || u > fDet ) { return FALSE; } //if // Prepare to test V parameter static Vector3 vQ; vQ = vT.CrossProduct( vEdge1 ); // Calculate V parameter and test bounds v = vDir.DotProduct( vQ ); if( v < 0.0F || u + v > fDet ) { return FALSE; } //if // Calculate t, scale parameters, ray intersects triangle float fInvDet = 1.0F / fDet; if (pfT) *pfT = vEdge2.DotProduct( vQ ) * fInvDet; if (pfU) *pfU = u * fInvDet; if (pfV) *pfV = v * fInvDet; return TRUE; } // vPos와 Triangle의 거리를 리턴한다. float Triangle::Distance( const Vector3& vPos ) const { Vector3 center; center.x = (a.x + b.x + c.x) / 3.f; center.y = (a.y + b.y + c.y) / 3.f; center.z = (a.z + b.z + c.z) / 3.f; return (vPos - center).Length(); } Vector3 Triangle::Normal() const { const Vector3 v0 = (b - a).Normal(); const Vector3 v1 = (c - a).Normal(); return v0.CrossProduct(v1).Normal(); }
[ "jjuiddong@gmail.com" ]
jjuiddong@gmail.com
5a5bafc37a73a009d6777f95038161f03ede3feb
c32829b434b3527a9545fa5db37af62fba818508
/WinSTDyn/GUI/CIWidget.cpp
5df78e24c9f2412bda933da224f5b1fe8a6a4668
[ "MIT" ]
permissive
chen0040/ogre-war-game-simulator
63dabfbf9e4bbfe4d1489cf7e67e2f93215af1c9
58eee268eae0612d206e7eb0b8e495708db1ef27
refs/heads/master
2021-01-20T06:14:31.772192
2017-09-06T00:27:39
2017-09-06T00:27:39
101,493,196
0
0
null
null
null
null
UTF-8
C++
false
false
1,186
cpp
#include "stdafx.h" #include "CIWidget.h" #include "GUIManager.h" #include <Ogre.h> #include <sstream> CIWidget::CIWidget(CIWidget* parentWidget, CEGUI::Window* parentWindow) { mParentWidget=parentWidget; mParentWindow=parentWindow; if(mParentWindow == NULL) { mParentWindow=CEGUI::System::getSingletonPtr()->getGUISheet(); } } void CIWidget::initializeComponents(const std::string& rootId) { mRootId=rootId; CEGUI::WindowManager* wm=CEGUI::WindowManager::getSingletonPtr(); if(wm->isWindowPresent(mRootId)) { std::ostringstream oss; oss << "wm->isWindowPresent(" << mRootId << ")==true"; throw Ogre::Exception(42, oss.str().c_str(), "CIWidget::initializeComponents(const std::string& rootId)"); } else { this->create(); } this->subscribeEvents(); } CIWidget::~CIWidget() { this->unsubscribeEvents(); } void CIWidget::showWindow() { mRootWindow->show(); } void CIWidget::hideWindow() { mRootWindow->hide(); } std::string CIWidget::getUIId(const std::string& localUIId) const { return mRootId+std::string("/")+localUIId; } void CIWidget::setPosition(float x, float y) { mRootWindow->setPosition(CEGUI::UVector2(cegui_reldim(x), cegui_reldim(y))); }
[ "xs0040@gmail.com" ]
xs0040@gmail.com
704b4b36a6a3a06861ee4e77c40d0513f0b4c338
f34d62dbcc664385823c0f273c3e6aef66037f58
/SimpleManager/RoleManagerItem.h
dbd259cd8b82c0b6c7178d2789d922433b6bec65
[]
no_license
MetalPizzaCat/SimpleManager
4a1455555aaf6cb8b83fe08ddb007b1fb88d848a
fb42350ce9061e2c7c5e97cc0f7e3424f6af7748
refs/heads/master
2023-03-12T23:10:34.635008
2021-02-26T12:14:04
2021-02-26T12:14:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
479
h
#pragma once #include <QWidget> #include "ui_RoleManagerItem.h" #include "Info.h" #include <QSqlDatabase> class RoleManagerItem : public QWidget { Q_OBJECT public: RoleManagerItem(ManagerInfo::SUserInfo currentUserInfo, QSqlDatabase dataBase, QWidget *parent = Q_NULLPTR); ~RoleManagerItem(); private: void GenerateList(); Ui::RoleManagerItem ui; QWidget* scrollWidget; QVBoxLayout* scrollBox; ManagerInfo::SUserInfo CurrentUserInfo; QSqlDatabase DataBase; };
[ "catguy228@gmail.com" ]
catguy228@gmail.com
5cd51f2eefe35c079bf0a6b95fd417d0fa910f53
e672c441b7cb2fbfc5af72b18a6c7cd1621efc7d
/general/base/ChatParsing.cpp
4ab2925295aa715b532ad5c8997bbe65bc99cf15
[]
no_license
tgjklmda/CatchChallenger
f7b16da8ebcd3ef61e08c6e51015d49c4e8cbefb
beea053f581ecf9732aa887c6b6e5e4ff8769e9e
refs/heads/master
2020-12-25T12:28:10.163407
2013-02-14T13:23:46
2013-02-14T13:23:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,411
cpp
#include "ChatParsing.h" using namespace CatchChallenger; QString ChatParsing::new_chat_message(QString pseudo,Player_type player_type,Chat_type chat_type,QString text) { QString returned_html; returned_html+="<div style=\""; switch(chat_type) { case Chat_type_local://local break; case Chat_type_all://all break; case Chat_type_clan://clan returned_html+="color:#FFBF00;"; break; case Chat_type_aliance://aliance returned_html+="color:#60BF20;"; break; case Chat_type_pm://to player returned_html+="color:#5C255F;"; break; case Chat_type_system://system returned_html+="color:#707070;font-style:italic;font-size:small;"; break; case Chat_type_system_important://system importance: hight returned_html+="color:#60BF20;"; break; default: break; } switch(player_type) { case Player_type_normal://normal player break; case Player_type_premium://premium player break; case Player_type_gm://gm returned_html+="font-weight:bold;"; break; case Player_type_dev://dev returned_html+="font-weight:bold;"; break; default: break; } returned_html+="\">"; switch(player_type) { case Player_type_normal://normal player break; case Player_type_premium://premium player returned_html+="<img src=\":/images/chat/premium.png\" alt\"\" />"; break; case Player_type_gm://gm returned_html+="<img src=\":/images/chat/admin.png\" alt\"\" />"; break; case Player_type_dev://dev returned_html+="<img src=\":/images/chat/developer.png\" alt\"\" />"; break; default: break; } if(chat_type==Chat_type_system || chat_type==Chat_type_system_important) returned_html+=QString("%1").arg(text); else returned_html+=QString("%1: %2").arg(pseudo).arg(toSmilies(toHtmlEntities(text))); returned_html+="</div>"; return returned_html; } QString ChatParsing::toHtmlEntities(QString text) { text.replace("&","&amp;"); text.replace("\"","&quot;"); text.replace("'","&#039;"); text.replace("<","&lt;"); text.replace(">","&gt;"); return text; } QString ChatParsing::toSmilies(QString text) { text.replace(":)","<img src=\":/images/smiles/face-smile.png\" alt=\"\" style=\"vertical-align:middle;\" />"); text.replace(":|","<img src=\":/images/smiles/face-plain.png\" alt=\"\" style=\"vertical-align:middle;\" />"); text.replace(":(","<img src=\":/images/smiles/face-sad.png\" alt=\"\" style=\"vertical-align:middle;\" />"); text.replace(":P","<img src=\":/images/smiles/face-raspberry.png\" alt=\"\" style=\"vertical-align:middle;\" />"); text.replace(":p","<img src=\":/images/smiles/face-raspberry.png\" alt=\"\" style=\"vertical-align:middle;\" />"); text.replace(":D","<img src=\":/images/smiles/face-laugh.png\" alt=\"\" style=\"vertical-align:middle;\" />"); text.replace(":o","<img src=\":/images/smiles/face-surprise.png\" alt=\"\" style=\"vertical-align:middle;\" />"); text.replace(";)","<img src=\":/images/smiles/face-wink.png\" alt=\"\" style=\"vertical-align:middle;\" />"); return text; }
[ "alpha_one_x86@first-world.info" ]
alpha_one_x86@first-world.info
c99cf373b34b49b8374c2f78850e8c97fc665ff0
ee61f27df1463ebe0e77c2184cced2b587d6f61c
/app/src/main/cpp/include/seeta/QualityOfPoseEx.h
1e9e4d0430be08b0f307a591aade044dac272a28
[]
no_license
crisgol/SeetafaceJni
1e42179326aa163bcead0acc61c030a90a1386e9
1efbf765f765e7c5d78480fb1fd1f627f1d3e591
refs/heads/master
2023-06-26T15:12:40.175594
2021-07-21T14:45:49
2021-07-21T14:45:49
388,300,550
3
0
null
null
null
null
UTF-8
C++
false
false
1,699
h
// // Created by kier on 2019-07-24. // #ifndef SEETA_QUALITYEVALUATOR_QUALITYOFPOSEEX_H #define SEETA_QUALITYEVALUATOR_QUALITYOFPOSEEX_H #include "QualityStructure.h" namespace seeta { namespace v3 { class QualityOfPoseEx : public QualityRule { public: enum PROPERTY { YAW_LOW_THRESHOLD = 0, YAW_HIGH_THRESHOLD = 1, PITCH_LOW_THRESHOLD = 2, PITCH_HIGH_THRESHOLD = 3, ROLL_LOW_THRESHOLD = 4, ROLL_HIGH_THRESHOLD = 5 }; using self = QualityOfPoseEx; using supper = QualityRule; /** * Construct with recommend parameters */ SEETA_API QualityOfPoseEx(const SeetaModelSetting &setting); SEETA_API ~QualityOfPoseEx() override; SEETA_API QualityResult check( const SeetaImageData &image, const SeetaRect &face, const SeetaPointF *points, const int32_t N) override; SEETA_API float get(PROPERTY property); SEETA_API void set(PROPERTY property, float value); private: QualityOfPoseEx(const QualityOfPoseEx &) = delete; QualityOfPoseEx &operator=(const QualityOfPoseEx &) = delete; private: void *m_data; float m_yaw_low; float m_pitch_low; float m_roll_low; float m_yaw_high; float m_pitch_high; float m_roll_high; }; } using namespace v3; } #endif //SEETA_QUALITYEVALUATOR_QUALITYOFPOSEEX_H
[ "1299204885@qq.com" ]
1299204885@qq.com
bc0006ece8659384ba0105766b9be8c649a19fb9
80526767a31791306fb8ebd3969a53c59c5c55c3
/Torretta.cpp
6a24df39141886381c807f63e0e43b75fb3de1ce
[]
no_license
SeppiaBrilla/Non-Gravitar
6de3338d998f9bf5c1dd5faf613724a5ccbe8156
0c542084d6e7d2b71383f3198f4d10d357df814a
refs/heads/master
2020-09-25T08:26:49.572065
2019-12-04T21:42:01
2019-12-04T21:42:01
225,962,078
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,069
cpp
#include "Torretta.hpp" Torretta::Torretta() {} Torretta::~Torretta() {} Torretta::Torretta(float x, float y, float Angle) :objGame(x, y, 2) { angle = Angle; TimeToShoot = 200; pro = false; Color = 3; } void Torretta::Update(float fElapsedTime, float Px, float Py) { //Viene modificato l'angolo di puntamento tra la torretta ed il giocatore e inoltre viene azzerato il vettore proiettili relativo a questa torretta float anglep = atan2f(Px - X, Y - Py); TorreProiettili.clear(); /*Viene fatto un conto alla rovescia, se il valore è pari o minore di 0 vengono inseriti all'interno del vettore proiettili, i proiettili appena sparati dalla torretta, e resetta il timer al suo valore originale altrimenta decrementa il timer ed esce dalla funzione*/ if (TimeToShoot <= 0) { TorreProiettili.push_back({ false, X + sinf(angle)*4.0f, Y - cosf(angle)*4.0f, anglep - 0.08f }); TorreProiettili.push_back({ false, X + sinf(angle)*4.0f, Y - cosf(angle)*4.0f, anglep + 0.08f }); TimeToShoot = 200; } else TimeToShoot = TimeToShoot - 1 * fElapsedTime; }
[ "noreply@github.com" ]
SeppiaBrilla.noreply@github.com
8b32a8635834168d57c311d5b8419347f8e3f639
cd004ef6ad32218c7153bd8c06cc83818975154a
/FDK/LrpCommon/Server_Server.hpp
f086164d79722a0e9a51d1a3fc33f5d05429982d
[ "MIT" ]
permissive
marmysh/FDK
11b7890c26f7aa024af8ea82fcb7c141326d2e6f
cc6696a8eded9355e4789b0193872332f46cb792
refs/heads/master
2020-12-14T18:56:28.229987
2016-07-13T13:50:42
2016-07-13T13:50:42
63,467,798
1
0
null
2016-07-16T05:51:14
2016-07-16T05:51:14
null
UTF-8
C++
false
false
10,000
hpp
// This is always generated file. Do not change anything. // handlers of Server component namespace { const unsigned short LrpComponent_Server_Id = 0; const unsigned short LrpMethod_Server_OnHeartBeatRequest_Id = 0; const unsigned short LrpMethod_Server_OnHeartBeatResponse_Id = 1; const unsigned short LrpMethod_Server_OnCurrenciesInfoRequest_Id = 2; const unsigned short LrpMethod_Server_OnSymbolsInfoRequest_Id = 3; const unsigned short LrpMethod_Server_OnSessionInfoRequest_Id = 4; const unsigned short LrpMethod_Server_OnSubscribeToQuotesRequest_Id = 5; const unsigned short LrpMethod_Server_OnUnsubscribeQuotesRequest_Id = 6; const unsigned short LrpMethod_Server_OnComponentsInfoRequest_Id = 7; const unsigned short LrpMethod_Server_OnDataHistoryRequest_Id = 8; const unsigned short LrpMethod_Server_OnFileChunkRequest_Id = 9; const unsigned short LrpMethod_Server_OnBarsHistoryMetaInfoFileRequest_Id = 10; const unsigned short LrpMethod_Server_OnQuotesHistoryMetaInfoFileRequest_Id = 11; typedef void (*LrpInvoke_Server_Method_Handler)(size_t offset, MemoryBuffer& buffer, LrpChannel* pChannel); void LrpInvoke_Server_OnHeartBeatRequest(size_t offset, MemoryBuffer& buffer, LrpChannel* pChannel) { pChannel;// if all methods of LrpChannel are static then the next line generates warning #4100 auto& component = pChannel->GetServer(); component; // if all methods of component are static then the next line generates warning #4189 component.OnHeartBeatRequest(); buffer.Reset(offset); } void LrpInvoke_Server_OnHeartBeatResponse(size_t offset, MemoryBuffer& buffer, LrpChannel* pChannel) { pChannel;// if all methods of LrpChannel are static then the next line generates warning #4100 auto& component = pChannel->GetServer(); component; // if all methods of component are static then the next line generates warning #4189 component.OnHeartBeatResponse(); buffer.Reset(offset); } void LrpInvoke_Server_OnCurrenciesInfoRequest(size_t offset, MemoryBuffer& buffer, LrpChannel* pChannel) { pChannel;// if all methods of LrpChannel are static then the next line generates warning #4100 auto& component = pChannel->GetServer(); component; // if all methods of component are static then the next line generates warning #4189 auto arg0 = ReadAString(buffer); component.OnCurrenciesInfoRequest(arg0); buffer.Reset(offset); } void LrpInvoke_Server_OnSymbolsInfoRequest(size_t offset, MemoryBuffer& buffer, LrpChannel* pChannel) { pChannel;// if all methods of LrpChannel are static then the next line generates warning #4100 auto& component = pChannel->GetServer(); component; // if all methods of component are static then the next line generates warning #4189 auto arg0 = ReadAString(buffer); component.OnSymbolsInfoRequest(arg0); buffer.Reset(offset); } void LrpInvoke_Server_OnSessionInfoRequest(size_t offset, MemoryBuffer& buffer, LrpChannel* pChannel) { pChannel;// if all methods of LrpChannel are static then the next line generates warning #4100 auto& component = pChannel->GetServer(); component; // if all methods of component are static then the next line generates warning #4189 auto arg0 = ReadAString(buffer); component.OnSessionInfoRequest(arg0); buffer.Reset(offset); } void LrpInvoke_Server_OnSubscribeToQuotesRequest(size_t offset, MemoryBuffer& buffer, LrpChannel* pChannel) { pChannel;// if all methods of LrpChannel are static then the next line generates warning #4100 auto& component = pChannel->GetServer(); component; // if all methods of component are static then the next line generates warning #4189 auto arg0 = ReadAString(buffer); auto arg1 = ReadAStringArray(buffer); auto arg2 = ReadInt32(buffer); component.OnSubscribeToQuotesRequest(arg0, arg1, arg2); buffer.Reset(offset); } void LrpInvoke_Server_OnUnsubscribeQuotesRequest(size_t offset, MemoryBuffer& buffer, LrpChannel* pChannel) { pChannel;// if all methods of LrpChannel are static then the next line generates warning #4100 auto& component = pChannel->GetServer(); component; // if all methods of component are static then the next line generates warning #4189 auto arg0 = ReadAString(buffer); auto arg1 = ReadAStringArray(buffer); component.OnUnsubscribeQuotesRequest(arg0, arg1); buffer.Reset(offset); } void LrpInvoke_Server_OnComponentsInfoRequest(size_t offset, MemoryBuffer& buffer, LrpChannel* pChannel) { pChannel;// if all methods of LrpChannel are static then the next line generates warning #4100 auto& component = pChannel->GetServer(); component; // if all methods of component are static then the next line generates warning #4189 auto arg0 = ReadAString(buffer); auto arg1 = ReadInt32(buffer); component.OnComponentsInfoRequest(arg0, arg1); buffer.Reset(offset); } void LrpInvoke_Server_OnDataHistoryRequest(size_t offset, MemoryBuffer& buffer, LrpChannel* pChannel) { pChannel;// if all methods of LrpChannel are static then the next line generates warning #4100 auto& component = pChannel->GetServer(); component; // if all methods of component are static then the next line generates warning #4189 auto arg0 = ReadAString(buffer); auto arg1 = ReadDataHistoryRequest(buffer); component.OnDataHistoryRequest(arg0, arg1); buffer.Reset(offset); } void LrpInvoke_Server_OnFileChunkRequest(size_t offset, MemoryBuffer& buffer, LrpChannel* pChannel) { pChannel;// if all methods of LrpChannel are static then the next line generates warning #4100 auto& component = pChannel->GetServer(); component; // if all methods of component are static then the next line generates warning #4189 auto arg0 = ReadAString(buffer); auto arg1 = ReadAString(buffer); auto arg2 = ReadUInt32(buffer); component.OnFileChunkRequest(arg0, arg1, arg2); buffer.Reset(offset); } void LrpInvoke_Server_OnBarsHistoryMetaInfoFileRequest(size_t offset, MemoryBuffer& buffer, LrpChannel* pChannel) { pChannel;// if all methods of LrpChannel are static then the next line generates warning #4100 auto& component = pChannel->GetServer(); component; // if all methods of component are static then the next line generates warning #4189 auto arg0 = ReadAString(buffer); auto arg1 = ReadAString(buffer); auto arg2 = ReadInt32(buffer); auto arg3 = ReadAString(buffer); component.OnBarsHistoryMetaInfoFileRequest(arg0, arg1, arg2, arg3); buffer.Reset(offset); } void LrpInvoke_Server_OnQuotesHistoryMetaInfoFileRequest(size_t offset, MemoryBuffer& buffer, LrpChannel* pChannel) { pChannel;// if all methods of LrpChannel are static then the next line generates warning #4100 auto& component = pChannel->GetServer(); component; // if all methods of component are static then the next line generates warning #4189 auto arg0 = ReadAString(buffer); auto arg1 = ReadAString(buffer); auto arg2 = ReadBoolean(buffer); component.OnQuotesHistoryMetaInfoFileRequest(arg0, arg1, arg2); buffer.Reset(offset); } LrpInvoke_Server_Method_Handler gServerHandlers[] = { LrpInvoke_Server_OnHeartBeatRequest, LrpInvoke_Server_OnHeartBeatResponse, LrpInvoke_Server_OnCurrenciesInfoRequest, LrpInvoke_Server_OnSymbolsInfoRequest, LrpInvoke_Server_OnSessionInfoRequest, LrpInvoke_Server_OnSubscribeToQuotesRequest, LrpInvoke_Server_OnUnsubscribeQuotesRequest, LrpInvoke_Server_OnComponentsInfoRequest, LrpInvoke_Server_OnDataHistoryRequest, LrpInvoke_Server_OnFileChunkRequest, LrpInvoke_Server_OnBarsHistoryMetaInfoFileRequest, LrpInvoke_Server_OnQuotesHistoryMetaInfoFileRequest, }; HRESULT LrpInvoke_Server(size_t offset, size_t methodId, MemoryBuffer& buffer, LrpChannel* pChannel) { if(methodId >= 12) { return LRP_INVALID_METHOD_ID; } gServerHandlers[methodId](offset, buffer, pChannel); return S_OK; } } // components handler namespace { typedef HRESULT (*LrpInvoke_Component_Handler)(size_t offset, size_t methodId, MemoryBuffer& buffer, LrpChannel* pChannel); LrpInvoke_Component_Handler gHandlers[] = { LrpInvoke_Server, }; } namespace { HRESULT LrpInvokeEx(size_t offset, size_t componentId, size_t methodId, MemoryBuffer& buffer, LrpChannel* pChannel) { if(componentId >= 1) { return LRP_INVALID_COMPONENT_ID; } HRESULT result = LRP_EXCEPTION; try { try { result = gHandlers[componentId](offset, methodId, buffer, pChannel); return result; } catch(const std::exception& e) { buffer.Reset(offset); WriteInt32(-1, buffer); WriteAString(e.what(), buffer); } catch(...) { result = E_FAIL; } } catch(...) { result = E_FAIL; } return result; } } extern "C" HRESULT __stdcall LrpInvoke(unsigned __int16 componentId, unsigned __int16 methodId, void* heap, unsigned __int32* pSize, void** ppData, unsigned __int32* pCapacity) { MemoryBuffer buffer(heap, *ppData, *pSize, *pCapacity); HRESULT result = LrpInvokeEx(0, componentId, methodId, buffer, nullptr); *pSize = static_cast<unsigned __int32>(buffer.GetSize()); *ppData = buffer.GetData(); *pCapacity = static_cast<unsigned __int32>(buffer.GetCapacity()); buffer = MemoryBuffer(); return result; } extern "C" const char* __stdcall LrpSignature() { return "$Exceptions;" "$Server;" "OnHeartBeatRequest@649F60FAC31A75EF0179222C5C27655D;" "OnHeartBeatResponse@53584CC68A5EF9F98311B4D86431576D;" "OnCurrenciesInfoRequest@E6F0091DB9E7B73AE0CEA7CD77318241;" "OnSymbolsInfoRequest@83BCDF2EEBC55F2EF1AEFBCE150E9FCF;" "OnSessionInfoRequest@A941B0F5C96CF054661A0F6925751F99;" "OnSubscribeToQuotesRequest@48BD3703EA5F3D3D116930EC0F7D6E5B;" "OnUnsubscribeQuotesRequest@65D0C196E1F746602C717772463A9910;" "OnComponentsInfoRequest@80705679A4CE1A94C0A95C109D91661A;" "OnDataHistoryRequest@A51124B279EE15597282498B005B2ACF;" "OnFileChunkRequest@EFEF9C78B68ED7950A413964030A0149;" "OnBarsHistoryMetaInfoFileRequest@C9559DB271D8ACDD57378A460FB87FED;" "OnQuotesHistoryMetaInfoFileRequest@84B7650F68B7EE82E499673405B98DA0;" ""; }
[ "chronoxor@gmail.com" ]
chronoxor@gmail.com
5729fab1fbc3c2302e7ea7999c80fafe556a29d5
03d625a9296d7820d5ae64bdbf934c8a822af568
/Node.cpp
0a61d2d49f13b5761c81a85907b106907839181c
[]
no_license
kutycoi123/BpTree
0906b049d6fc70e0bea4cdb2e3b3a2b6569ac23b
dbfb56d629766afa3ad21a677442a628c279184f
refs/heads/main
2023-04-19T04:58:53.042650
2021-04-21T21:09:41
2021-04-21T21:09:41
360,306,843
0
0
null
null
null
null
UTF-8
C++
false
false
14,250
cpp
#include "Node.h" /*======== NODE class implementation ========*/ Node::Node(int limit) : keysLimit(limit), parent(nullptr){ } bool Node::hasKey(int k) const noexcept{ auto it = std::find(keys.begin(), keys.end(), k); return it != keys.end(); } int Node::getIndexOfKey(int k) const noexcept{ auto it = std::find(keys.begin(), keys.end(), k); if(it != keys.end()){ return std::distance(keys.begin(), it); } return -1; } bool Node::isLimitExceeded() const noexcept{ return keys.size() > keysLimit; } std::string Node::keysToString() const noexcept{ if(keys.size() == 0) return "[]"; std::string res = "["; std::for_each(keys.begin(), keys.end(), [&res](int key){ res += std::to_string(key) + ","; }); res.pop_back(); //pop the last ',' res += "]"; return res; } Node* Node::getLeftSibling() const noexcept{ if(!parent){ return nullptr; } auto par = static_cast<InteriorNode*>(parent); auto keyAssociatedWithThisNode = std::upper_bound(par->keys.begin(), par->keys.end(), keys.front()); int idxOfNextPtr = std::distance(par->keys.begin(), keyAssociatedWithThisNode); if(idxOfNextPtr > 0){ return par->next[idxOfNextPtr-1].get(); } return nullptr; } Node* Node::getRightSibling() const noexcept{ if(!parent){ return nullptr; } auto par = static_cast<InteriorNode*>(parent); auto keyAssociatedWithThisNode = std::upper_bound(par->keys.begin(), par->keys.end(), keys.front()); int idxOfNextPtr = std::distance(par->keys.begin(), keyAssociatedWithThisNode); if(idxOfNextPtr+1 < par->next.size()){ return par->next[idxOfNextPtr+1].get(); } return nullptr; } bool Node::coalescible(int k) const noexcept{ return keys.size() + k <= keysLimit ; } /*===================== END OF NODE =======================================*/ /*==================== InteriorNode class implementation ==========================*/ InteriorNode::InteriorNode(int keysLimit) : Node(keysLimit){ next.reserve(keysLimit+1); } InteriorNode::InteriorNode(int keysLimit, std::unique_ptr<Node> n) : Node(keysLimit){ next.push_back(std::move(n)); } bool InteriorNode::isLeafNode() const noexcept{ return false; } bool InteriorNode::isFullEnough() const noexcept{ return next.size() >= ((keysLimit + 1) / 2); } bool InteriorNode::isRedistributable() const noexcept{ return next.size() - 1 >= ((keysLimit + 1) / 2); } void InteriorNode::cleanNode() noexcept{ keys.clear(); next.clear(); } void InteriorNode::insertKey(int k, std::unique_ptr<Node> newNode) noexcept{ auto keyPos = std::upper_bound(keys.begin(), keys.end(), k); auto nextPos = next.begin() + std::distance(keys.begin(), keyPos) + 1; keys.insert(keyPos, k); newNode->parent = this; next.insert(nextPos, std::move(newNode)); } Node* InteriorNode::getNextNode(int k) const noexcept{ auto upperBoundOfK = std::upper_bound(keys.begin(), keys.end(), k); auto nextNodeIndex = std::distance(keys.begin(), upperBoundOfK); return next[nextNodeIndex].get(); } int InteriorNode::split(InteriorNode* newSplitNode) noexcept{ //Split keys in original interior node to new split node int numOfRemainingKeys = ceil(keysLimit/2.0); int numOfSplitKeys = floor(keysLimit/2.0); auto keysBegin = keys.begin(); auto keysEnd = keys.end(); newSplitNode->keys.resize(numOfSplitKeys); //Allocate memories for split keys std::copy(keysBegin + numOfRemainingKeys + 1, keysEnd, newSplitNode->keys.begin()); //Spit keys to new node keys.erase(keysBegin + numOfRemainingKeys + 1, keysEnd); //Erase split keys and keep remaining keys in original node //Last key is now to be removed and inserted into node's parent //The rest keys are kept in original node auto removedKey = keys.back(); keys.pop_back(); //Split next node pointers auto nextNodesBegin = next.begin(); auto nextNodesEnd = next.end(); int numOfNextNodesInOriginalNode = ceil((keysLimit+2)/2.0); auto nextNodesInSplitNodeBegin = nextNodesBegin + numOfNextNodesInOriginalNode; for(auto it = nextNodesInSplitNodeBegin; it != nextNodesEnd ; ++it){ if((*it) != nullptr) (*it)->parent = newSplitNode; newSplitNode->next.push_back(std::move(*it)); } next.erase(nextNodesInSplitNodeBegin, nextNodesEnd); return removedKey; } InteriorNode* InteriorNode::getLeftSibling() const noexcept{ return static_cast<InteriorNode*>(Node::getLeftSibling()); } InteriorNode* InteriorNode::getRightSibling() const noexcept{ return static_cast<InteriorNode*>(Node::getRightSibling()); } Node* InteriorNode::removeKey(int k, int keyOfNextNodeToBeRemoved) noexcept{ auto keyPos = getIndexOfKey(k); if(keyPos == -1) return this; auto nextPos = keyPos; if(keyOfNextNodeToBeRemoved >= keys[keyPos]) nextPos = keyPos + 1; keys.erase(keys.begin() + keyPos); next.erase(next.begin() + nextPos); if(isFullEnough()) return this; InteriorNode* leftSibling = getLeftSibling(); InteriorNode* rightSibling = getRightSibling(); if(leftSibling && leftSibling->isRedistributable()){ return redistributeLeftInterior(leftSibling); }else if(rightSibling && rightSibling->isRedistributable()){ return redistributeRightInterior(rightSibling); }else if(leftSibling && leftSibling->coalescible(keys.size())){ return coalescLeftInterior(leftSibling, k); }else if(rightSibling && rightSibling->coalescible(keys.size())){ return coalescRightInterior(rightSibling, k); } return this; } Node* InteriorNode::redistributeLeftInterior(InteriorNode* sibling) noexcept{ Node* par = sibling->parent; auto upperBoundOfRedistributedKey = std::upper_bound(par->keys.begin(), par->keys.end(), sibling->keys.front()); auto parentKey = upperBoundOfRedistributedKey - 1; keys.insert(keys.begin(), *parentKey); *parentKey = sibling->keys.back(); sibling->keys.pop_back(); std::unique_ptr<Node> newNext = std::move(sibling->next.back()); sibling->next.pop_back(); newNext->parent = this; next.insert(next.begin(), std::move(newNext)); return this; } Node* InteriorNode::redistributeRightInterior(InteriorNode* sibling) noexcept{ Node* par = sibling->parent; auto parentKey = std::upper_bound(par->keys.begin(), par->keys.end(), keys.front()); keys.insert(keys.end(), *parentKey); *parentKey = sibling->keys.front(); sibling->keys.erase(sibling->keys.begin()); std::unique_ptr<Node> newNext = std::move(sibling->next.front()); newNext->parent = this; sibling->next.erase(sibling->next.begin()); next.insert(next.end(), std::move(newNext)); return this; } Node* InteriorNode::coalescLeftInterior(InteriorNode* sibling, int firstKeyAlreadyRemoved) noexcept{ if(!sibling->coalescible(keys.size())) return this; auto keyBetween2Coalesced = std::upper_bound(parent->keys.begin(), parent->keys.end(), sibling->keys.front()); sibling->keys.insert(sibling->keys.end(), *keyBetween2Coalesced); sibling->keys.insert(sibling->keys.end(), keys.begin(), keys.end()); //Update parent pointer of each next node before coalescing with sibling for(auto& nextNode : next){ nextNode->parent = static_cast<Node*>(sibling); } sibling->next.insert(sibling->next.end(), std::make_move_iterator(next.begin()), std::make_move_iterator(next.end())); int keyToBeRemoved = firstKeyAlreadyRemoved; if(keys.size() > 0) keyToBeRemoved = keys.front(); cleanNode(); return static_cast<InteriorNode*>(parent)->removeKey(*keyBetween2Coalesced, keyToBeRemoved); } Node* InteriorNode::coalescRightInterior(InteriorNode* sibling, int firstKeyAlreadyRemoved) noexcept{ if(!sibling->coalescible(keys.size())) return this; auto keyBetween2Coalesced = std::upper_bound(parent->keys.begin(), parent->keys.end(), keys.front()); sibling->keys.insert(sibling->keys.begin(), *keyBetween2Coalesced); sibling->keys.insert(sibling->keys.begin(), keys.begin(), keys.end()); //Update parent pointer of each next node before coalescing with sibling for(auto& nextNode : next){ nextNode->parent = static_cast<Node*>(sibling); } sibling->next.insert(sibling->next.begin(), std::make_move_iterator(next.begin()), std::make_move_iterator(next.end())); int keyToBeRemoved = firstKeyAlreadyRemoved; if(keys.size() > 0) keyToBeRemoved = keys.front(); cleanNode(); return static_cast<InteriorNode*>(parent)->removeKey(*keyBetween2Coalesced, keyToBeRemoved); } /*===================== End of InteriorNode =========================================*/ /*==================== LeafNode class implementation =================================*/ LeafNode::LeafNode(int keysLimit) : Node(keysLimit), nextLeaf(nullptr), prevLeaf(nullptr){ vals.reserve(keysLimit); } void LeafNode::cleanNode() noexcept{ keys.clear(); vals.clear(); } bool LeafNode::isFullEnough() const noexcept{ return vals.size() >= ((keysLimit + 1) / 2); } bool LeafNode::isRedistributable() const noexcept{ return vals.size() - 1 >= ((keysLimit + 1) / 2); } std::string LeafNode::getVal(int k) const noexcept{ int keyIndex = getIndexOfKey(k); if(keyIndex == -1) return ""; return vals[keyIndex]; } std::string LeafNode::valsToString() const noexcept{ std::string res = ""; std::for_each(vals.begin(), vals.end(), [&res](const std::string& val){ res += val + "\n"; }); res.pop_back(); return res; } bool LeafNode::isLeafNode() const noexcept{ return true; } Node* LeafNode::getNextNode(int i) const noexcept{ return nextLeaf; } void LeafNode::insertKey(int k, const std::string& v) noexcept{ auto keyPos = std::upper_bound(keys.begin(), keys.end(), k); auto valPos = vals.begin() + std::distance(keys.begin(), keyPos); keys.insert(keyPos, k); vals.insert(valPos, v); } int LeafNode::split(LeafNode* newSplitNode) noexcept{ //Split keys auto keysBegin= keys.begin(); auto keysEnd = keys.end(); int numOfRemainingKeys = ceil((keysLimit + 1)/2.0); int numOfSplitKeys = keys.size() - numOfRemainingKeys; newSplitNode->keys.resize(numOfSplitKeys); //Allocate memories for new node's keys std::copy(keysBegin + numOfRemainingKeys, keysEnd, (newSplitNode->keys).begin()); //Split keys to new node keys.erase(keysBegin + numOfRemainingKeys, keysEnd); //Erase split keys and keep remaining keys in original node //Split values auto valsBegin = vals.begin(); auto valsEnd = vals.end(); auto numOfRemainingVals = numOfRemainingKeys; newSplitNode->vals.resize(numOfSplitKeys); //Allocate memories for new node's vals std::copy(valsBegin + numOfRemainingVals, valsEnd, newSplitNode->vals.begin()); //Split vals to new node vals.erase(valsBegin + numOfRemainingVals, valsEnd); //Erase split vals and keep remaining vals in original node newSplitNode->nextLeaf = nextLeaf; newSplitNode->prevLeaf = this; nextLeaf = newSplitNode; if(newSplitNode->nextLeaf) newSplitNode->nextLeaf->prevLeaf = newSplitNode; return newSplitNode->keys.front(); } LeafNode* LeafNode::getLeftSibling() const noexcept{ return static_cast<LeafNode*>(Node::getLeftSibling()); } LeafNode* LeafNode::getRightSibling() const noexcept{ return static_cast<LeafNode*>(Node::getRightSibling()); } Node* LeafNode::removeKey(int k) noexcept{ auto keyPos = getIndexOfKey(k); if(keyPos == -1) return this; auto valPos = keyPos; keys.erase(keys.begin() + keyPos); vals.erase(vals.begin() + valPos); if(isFullEnough()) return this; LeafNode* leftSibling = getLeftSibling(); LeafNode* rightSibling = getRightSibling(); if(leftSibling && leftSibling->isRedistributable()){ return redistributeLeftLeaf(leftSibling); }else if(rightSibling && rightSibling->isRedistributable()){ return redistributeRightLeaf(rightSibling); }else if(leftSibling && leftSibling->coalescible(keys.size())){ return coalescLeftLeaf(leftSibling, k); }else if(rightSibling && rightSibling->coalescible(keys.size())){ return coalescRightLeaf(rightSibling, k); } return this; } Node* LeafNode::redistributeLeftLeaf(LeafNode* sibling) noexcept{ int distributedKey = sibling->keys.back(); sibling->keys.pop_back(); std::string distributedVal = sibling->vals.back(); sibling->vals.pop_back(); keys.insert(keys.begin(), distributedKey); vals.insert(vals.begin(), distributedVal); Node* par = parent; auto parentKey = std::upper_bound(par->keys.begin(), par->keys.end(), distributedKey); *parentKey = distributedKey; return this; } Node* LeafNode::redistributeRightLeaf(LeafNode* sibling) noexcept{ int distributedKey = sibling->keys.front(); sibling->keys.erase(sibling->keys.begin()); std::string distributedVal = sibling->vals.front(); sibling->vals.erase(sibling->vals.begin()); keys.push_back(distributedKey); vals.push_back(distributedVal); Node* par = parent; auto upperBoundOfDistributedKey = std::upper_bound(par->keys.begin(), par->keys.end(), distributedKey); auto parentKey = upperBoundOfDistributedKey - 1; *parentKey = sibling->keys.front(); return this; } Node* LeafNode::coalescLeftLeaf(LeafNode* sibling, int firstKeyAlreadyRemoved) noexcept{ if(!sibling->coalescible(keys.size())) return this; sibling->keys.insert(sibling->keys.end(), keys.begin(), keys.end()); sibling->vals.insert(sibling->vals.end(), vals.begin(), vals.end()); auto parentKey = std::upper_bound(sibling->parent->keys.begin(), sibling->parent->keys.end(),sibling->keys.front()); sibling->nextLeaf = nextLeaf; if(nextLeaf) nextLeaf->prevLeaf = sibling; int keyToBeRemoved = firstKeyAlreadyRemoved; if(keys.size() > 0) keyToBeRemoved = keys.front(); cleanNode(); return static_cast<InteriorNode*>(parent)->removeKey(*parentKey, keyToBeRemoved); } Node* LeafNode::coalescRightLeaf(LeafNode* sibling, int firstKeyAlreadyRemoved) noexcept{ if(!sibling->coalescible(keys.size())) return this; sibling->keys.insert(sibling->keys.begin(), keys.begin(), keys.end()); sibling->vals.insert(sibling->vals.begin(), vals.begin(), vals.end()); int keyToBeRemoved = firstKeyAlreadyRemoved; if(keys.size() > 0) keyToBeRemoved = keys.front(); auto parentKey = std::upper_bound(sibling->parent->keys.begin(), sibling->parent->keys.end(), keyToBeRemoved); sibling->prevLeaf = prevLeaf; if(prevLeaf) prevLeaf->nextLeaf = sibling; cleanNode(); return static_cast<InteriorNode*>(parent)->removeKey(*parentKey, keyToBeRemoved); } /*=======================End of LeafNode ============================================*/
[ "kutycoi123@gmail.com" ]
kutycoi123@gmail.com
b37c4be4aacb765dae92d77c993add50d6bd0dd0
e38c42dbf7de211b770898449b70313255085518
/template/template/class.cpp
e70cfb03ccc3599ab7a46559f2cefc5d8d7b4d61
[]
no_license
CycMei/cccccc
b59fc5ecdaab0e22b49f8419699b16a49bf8fa88
3b50ab3fe197acf0c37e46854d76c232eda252e8
refs/heads/master
2021-05-04T03:49:13.541088
2016-10-13T09:04:19
2016-10-13T09:04:19
70,788,670
0
0
null
null
null
null
UTF-8
C++
false
false
3,424
cpp
#include<iostream> #include<vector> #include<memory> #include<string> #include<initializer_list> #include<boost\bimap.hpp> template<typename T>class Blob { public: typedef T value_type; typedef typename std::vector<T>::size_type size_type; Blob(); Blob(std::initializer_list<T> il); size_type size() const { return data->size(); } bool empty() const { data->empty(); } void push_back(const T &t) { data->push_back(t); } void push_back(T &&t) { data->push_back(std::move(t)); } void pop_back(); T &back(); T &operator[](size_type i); private: std::shared_ptr<std::vector<T>> data; void check(size_type i, const std::string &msg) const; }; template<class T = int> class Numbes { private: T val; public: Numbes(T v = 0) :val(v) {}; }; Numbes<long double> lots_of_precision; Numbes<> average; class DebugDelete { public: DebugDelete(std::ostream &s = std::cout) :os(s) {} template<typename T> void operator()(T *p) const { delete p; } private: std::ostream &os; }; void test() { int *p = new int(0); DebugDelete()(p); std::unique_ptr<int, DebugDelete> pps(new int(), DebugDelete()); } template<typename T> class copyB { template<typename It> copyB(It b, It e); }; template<typename T> template<typename It> copyB<T>::copyB(It b, It e) { } extern template class copyB<std::string>; unsigned int myINT; template<typename T> class Stack{}; void fc(Stack<char>){} class Exercise { Stack<double> &rsd; Stack<int> si; }; void copyMain() { //Stack<char> *sc; int iObj = sizeof(Stack<std::string>); } namespace stdds { //std::vector<int&> vcs; template<typename T> void g(T&& val){} template<typename T> void gg(T val){} template<typename T> void ggg(const T &val){} template<typename T> void gc(T &&val){ std::vector<T> v; } template<typename T> typename std::remove_reference<T>::type &&move(T &&t) { return static_cast<typename std::remove_reference<T>::type&&>(t); } int i = 0; const int ci = i; void test() { g(i); g(ci); g(ci*i); g(i = ci); gg(i); gg(ci); gg(ci*i); gg(i = ci); ggg(i); ggg(ci); ggg(ci*i); ggg(i = ci); gc(42); // gc(i); } }; namespace trans { template<typename T1, typename T2> void flip1( T1 &&t1, T2 &&t2) { } template<typename T1, typename T2> void fss(const T1 &&t1, const T2 &&t2) { } void test() { int i = 0; int j = i; const int &c = i; flip1(i, j); //fss(i, j); } } namespace tracsws { template<typename T> void f(T t) { std::cout << 1 << std::endl; } template<typename T> void f(const T *t) { std::cout << 2 << std::endl; } template<typename T> void g(T t) { std::cout << 3 << std::endl; } template<typename T> void g(T *t) { std::cout << 4 << std::endl; } template<typename...Args> void g(Args...args) { std::cout << sizeof...(Args); std::cout << sizeof...(args); } template<typename T> std::ostream &print(std::ostream &os, const T &t) { return os << t; } template<typename T, typename...Args> std::ostream &print(std::ostream &os, const T &t, const Args... rest) { os << t << " ,"; return print(os, rest...); } template<class... Args> void emplace_back(Args&&...) { } template<typename T> int compare(const T&, const T&) {}; template<> int compare(const char *const &p1,const char *const &p2){} }; void main() { using namespace tracsws; int i = 42, *p = &i; const int ci = 0, *p2 = &ci; g(42); g(p); g(ci); g(p2); f(42); f(p); f(ci); f(p2); }
[ "chayalikemei@outlook.com" ]
chayalikemei@outlook.com
f4aa4dc33b66831298a5643799449bb5772a8cf9
ca57d57bec37faeb57899a80df5b4d267a536ac5
/src/sun_ray/main.cpp
173954ba0111b04b0d7d4e54c8529f44ac64a053
[ "BSD-3-Clause" ]
permissive
fuersten/sun_ray
ed875b2a5a2c0f9fd8bfb7321921b1b70c205a3a
b882d67cd9747f61b50def4c1414e7552ba917c0
refs/heads/main
2023-04-17T04:08:18.860499
2021-04-27T10:15:50
2021-04-27T10:15:50
335,270,596
2
0
BSD-3-Clause
2021-04-27T10:03:57
2021-02-02T11:46:17
C++
UTF-8
C++
false
false
450
cpp
// // main.cpp // sun_ray // // Created by Lars-Christian Fürstenberg on 21.12.19. // Copyright © 2019 Lars-Christian Fürstenberg. All rights reserved. // #include <sun_ray/init.h> #include <iostream> #include "application.h" int main(int argc, const char* argv[]) { std::vector<std::string> args; for (int n = 0; n < argc; ++n) { args.emplace_back(argv[n]); } return sunray::Application{std::cout, std::cerr, args}.run(); }
[ "lcf@miztli.de" ]
lcf@miztli.de
06368b96e5b0f45657b098ec3288f6fe7c864113
8b50e46c29b21a8c9c52091ddeb1856d17b9c570
/Chapter12/09/thread9/textdialog.h
88573c72ff4f8938fc7e57532fde2e5e3ae0554d
[]
no_license
anthonychl/Foundations-of-Qt-Development
ef6e7234263c51ca15c3cf4332dc0122367f45d7
34f5a84c65ca1da074f83345dd0d2431c911f36b
refs/heads/master
2020-07-03T05:53:04.035264
2019-08-11T19:56:18
2019-08-11T19:56:18
201,809,232
0
0
null
null
null
null
UTF-8
C++
false
false
542
h
#ifndef TEXTDIALOG_H #define TEXTDIALOG_H #include <QDialog> #include "textandnumber.h" #include <QAbstractButton> #include <QMutex> namespace Ui { class TextDialog; } class TextDialog : public QDialog { Q_OBJECT public: /* explicit TextDialog(QWidget *parent = 0); ~TextDialog();*/ TextDialog(); ~TextDialog(); public slots: void showText(TextAndNumber tan); private slots: void buttonClicked(QAbstractButton*); private: Ui::TextDialog *ui; int count; QMutex mutex; }; #endif // TEXTDIALOG_H
[ "anthonychl.dev@gmail.com" ]
anthonychl.dev@gmail.com
a1309ce9c0a05b1e19eee994d8b6fe25515474f2
fdaa5c780752bcd7b68b59e34b03f40ffe30613d
/image.cpp
16127f003e4f7a74766ae6ed3bd78f51e0d7d956
[]
no_license
JD-DA/BarjoKart
07d65f1609b519aabbd8dc6ab921c5d186c4024e
6a6469ac7026a032fc0c01dc14da4c5d1bc58f26
refs/heads/master
2023-08-10T22:51:26.677829
2021-03-31T05:03:04
2021-03-31T05:03:04
404,103,524
0
0
null
null
null
null
UTF-8
C++
false
false
9,044
cpp
#include <iostream> #include <cstdlib> #include <stdio.h> #include <png.h> #include <png++/png.hpp> #include <toml++/toml.h> #include "image.hpp" Image::Image(){ } Image::~Image(){ for (int i = 0; i < this->height; i++) { delete(matrice[i]); } delete(matrice); /*for (std::list<std::pair<int,int>>::iterator i = zoneArrive.begin(); i != zoneArrive.end(); ++i) { delete(i); }*/ } void Image::build_image(std::string fichier){ std::cout<<"Construction de l'image..."<<std::endl; std::cout<<fichier<<std::endl; png::image< png::rgba_pixel > image(fichier); int nbPixelArrive=0; this->width=image.get_width(); this->height=image.get_height(); std::cout<<"Largeur : "<<width<<" Hauteur : "<<height<<std::endl; int r; int g; int b; //int a; this->matrice = new char*[height]; //int size = 0; //bool test; for (unsigned int i = 0; i <(unsigned int) this->height; ++i) { this->matrice[i]= new char[width]; for(unsigned int j=0;j<(unsigned int) this->width;++j){ r = image.get_pixel(j,i).red; g = image.get_pixel(j,i).green; b = image.get_pixel(j,i).blue; //a=image.get_pixel(j,i).alpha; //std::cout<<r<<' '<<g<<' '<<b<<std::endl; if((r==255 and g==255 and b==255)){ this->matrice[i][j]='b'; //putchar(' '); }else if(r==arrivalColorR and g==arrivalColorG and b==arrivalColorB){ this->matrice[i][j]='a'; nbPixelArrive++; zoneArrive.push_back(std::pair<int,int>(i,j)); //putchar('a'); }else if(r==0 and g==0 and b==0){ this->matrice[i][j]='n'; //putchar('n'); }else{ this->matrice[i][j]='g'; //putchar('g'); } } //putchar('\n'); } std::cout<<"Image contruite !"<<std::endl; std::cout<<"Nb de pixel de la zone d'arrivée : "<<nbPixelArrive<<std::endl; std::cout<<"Taille de la liste : "<<zoneArrive.size()<<std::endl; } void Image::load_data(std::string fpng,std::string ftoml){ toml::table tbl; try{ tbl = toml::parse_file(ftoml); //std::cout<<tbl<<std::endl; std::cout<<"Lecture du .toml..."<<std::endl; maxAcceleration = tbl["acc_max"].value<int>().value(); arrivalColorR = (tbl["couleur_arrivee"][0].value<int>().value()); arrivalColorG = (tbl["couleur_arrivee"][1].value<int>().value()); arrivalColorB = (tbl["couleur_arrivee"][2].value<int>().value()); departureX= (tbl["depart"]["x"].value<int>().value()); departureY= (tbl["depart"]["y"].value<int>().value()); std::cout<<"Acceleration Max : "<<maxAcceleration<<std::endl; std::cout<<"Couleur d'arrivée :"<<arrivalColorR<<' '<<arrivalColorG<<' '<<arrivalColorB<<std::endl; std::cout<<"Position de départ : x->"<<departureX<<" y->"<<departureY<<std::endl; build_image(fpng); }catch(const toml::parse_error& err){ std::cerr<<"La lecture du toml a échouée :\n"<<err<<"\n"; } } /* Permet de verifier le bonne lecture du fichier png via la creation d'un fichier pgm copiant l'image et donnant aux differentes zones un niveau de gris different. */ void Image::affichage(char* fichierSortie){ FILE* fichier = fopen(fichierSortie,"w"); if(fichier!=NULL){ fputs("P2",fichier); fputs("\n",fichier); fprintf(fichier, "# image générée par Image::affichage\n"); fprintf(fichier, "%d\t", width); fprintf(fichier, "%d\n", height); fprintf(fichier, "%d\n", 255); std::cout<<"Écriture PGM..."<<std::endl; int num; for(int i=0; i<height;i++){ for(int j=0;j<width;j++){ char cara =matrice[i][j]; if(cara=='b'){ //utilisé pour afficher les directions /*if(i<2*(j)+(y-2*x)){ if(i>-0.5*j+(y+0.5*x)){ if(i>0.5*j+(y-0.5*x)){ num = 200; }else{ num = 150; } }else{ if(i>-2*j+(y+2*x)){ num = 100; }else{ num = 50; } } }else{ if(i>-0.5*j+(y+0.5*x)){ if(i>-2*j+(y+2*x)){ num = 250; }else{ num = 200; } }else{ if(i>0.5*j+(y-0.5*x)){ num = 150; }else{ num = 100; } } }*/ num = 255; }else if(cara=='n'){ num = 0; }else if (cara=='a'){ num = 50; }else{ //std::cout<<"Charactère bizarre : i="<<i<<" j="<<j<<std::endl; num = 100; } fprintf(fichier, "%d ", num); } //putchar('\n'); } fclose(fichier); std::cout<<"L'image a été écrite, allez voir :"<<fichierSortie<<std::endl; } else{ std::cout<<"Erreur d'ouverture du fichier"<<std::endl; } } void Image::affichageDirection(const char* fichierSortie, int x,int y){ FILE* fichier = fopen(fichierSortie,"w"); if(fichier!=NULL){ fputs("P2",fichier); fputs("\n",fichier); fprintf(fichier, "# image générée par Image::affichage\n"); fprintf(fichier, "%d\t", width); fprintf(fichier, "%d\n", height); fprintf(fichier, "%d\n", 255); std::cout<<"Écriture PGM..."<<std::endl; int num; for(int i=0; i<height;i++){ for(int j=0;j<width;j++){ char cara =matrice[i][j]; if(cara=='b'){ if(i<2*(j)+(y-2*x)){ if(i>-0.5*j+(y+0.5*x)){ if(i>0.5*j+(y-0.5*x)){ num = 200; }else{ num = 150; } }else{ if(i>-2*j+(y+2*x)){ num = 100; }else{ num = 50; } } }else{ if(i>-0.5*j+(y+0.5*x)){ if(i>-2*j+(y+2*x)){ num = 250; }else{ num = 200; } }else{ if(i>0.5*j+(y-0.5*x)){ num = 150; }else{ num = 100; } } } }else if(cara=='n'){ num = 0; }else if (cara=='a'){ num = 50; }else{ num = 100; } fprintf(fichier, "%d ", num); } } fclose(fichier); std::cout<<"L'image a été écrite, allez voir :"<<fichierSortie<<std::endl; } else{ std::cout<<"Erreur d'ouverture du fichier"<<std::endl; } } bool Image::verifierPixel(int x,int y){ return matrice[y-1][x-1]!='n'; } bool Image::verifierPixel2(int x,int y){ return matrice[y][x]!='n'; } bool Image::verifierPixel3(int x,int y){ bool test= matrice[y][x]!='n'; if(x-1>0){ test = test and matrice[y][x-1]!='n'; } if(y-1>0){ test = test and matrice[y-1][x]!='n'; } if(y+1<height){ test = test and matrice[y+1][x]!='n'; } if(x+1<width){ test = test and matrice[y][x+1]!='n'; } return test; } bool Image::verifierArrivee(int x,int y){ return matrice[y-1][x-1]=='a'; } bool Image::verifierArrivee2(int x,int y){ return matrice[y][x]=='a'; } /** * renvoi une paire de coordonnées de type y/x correspondant au centre de la zone d'arrivée(origine en haut à gauche) **/ std::pair<int,int> Image::centreZoneArrivee(){ std::list<std::pair<int,int>>::iterator i = zoneArrive.begin(); int res=0; while(res<zoneArrive.size()/2){ i++; res++; } return (*i); } /** * Pour un point donné, renvoie la direction vers laquelle se trouve le plus grand nombre de pixel qui composent la zone d'arrivée * **/ std::map<std::string,int> Image::direction(int x,int y){ std::map<std::string,int> map; int n = 0; map.insert(std::pair<std::string,int>("n",0)); map.insert(std::pair<std::string,int>("e",0)); map.insert(std::pair<std::string,int>("s",0)); map.insert(std::pair<std::string,int>("o",0)); map.insert(std::pair<std::string,int>("ne",0)); map.insert(std::pair<std::string,int>("no",0)); map.insert(std::pair<std::string,int>("so",0)); map.insert(std::pair<std::string,int>("se",0)); int e = 0; int s = 0; int o = 0; int ne = 0; int no = 0; int se = 0; int so = 0; //float diff = y-x; for (std::list<std::pair<int,int>>::iterator it = zoneArrive.begin(); it != zoneArrive.end(); ++it) { int xa=(*it).second; int ya=(*it).first; if(ya<2*xa+(y-2*x)){ if(ya>-0.5*xa+(y+0.5*x)){ if(ya>0.5*xa+(y-0.5*x)){ ++se; map["se"]++; }else{ ++e; map["e"]++; } }else{ if(ya>-2*xa+(y+2*x)){ ++ne; map["ne"]++; }else{ ++n; map["n"]++; } } }else{ if(ya>-0.5*xa+(y+0.5*x)){ if(ya>-2*xa+(y+2*x)){ ++s; map["s"]++; }else{ ++so; map["so"]++; } }else{ if(ya>0.5*xa+(y-0.5*x)){ ++o; map["o"]++; }else{ ++no; map["no"]++; } } } } std::cout<<"n "<<n<<" ne "<<ne<<" e "<<e<<" se "<<se<<" s "<<s<<" so "<<so<<" o "<<o<<" no "<<no<<std::endl; return map; } /** * Renvoi un int qui correpond au potentiel de ce point dans cette direction, c'est à dire la distance qui le sépare du prochain obstacle * **/ int Image::potentiel(std::string dir, int x,int y){ int pasX; int pasY; if(strcmp(dir.c_str(),"n")==0){ pasX=0; pasY=-1; }else if(strcmp(dir.c_str(),"no")==0){ pasX=-1; pasY=-1; }else if(strcmp(dir.c_str(),"o")==0){ pasX=-1; pasY=0; }else if(strcmp(dir.c_str(),"so")==0){ pasX=-1; pasY=1; }else if(strcmp(dir.c_str(),"s")==0){ pasX=0; pasY=1; }else if(strcmp(dir.c_str(),"se")==0){ pasX=1; pasY=-1; }else if(strcmp(dir.c_str(),"e")==0){ pasX=1; pasY=0; }else{ //ne pasX=1; pasY=-1; } int nbPasPotentiels = 0; x+=pasX; y+=pasY; while(verifierPixel2(x,y)){ nbPasPotentiels++; x+=pasX; y+=pasY; } return nbPasPotentiels; }
[ "jean-daniel.de-ambrogi@etu.univ-orleans.fr" ]
jean-daniel.de-ambrogi@etu.univ-orleans.fr
431fbd28ad5e4a08b800cd51c12b59ce88c90ecf
a179a141970ac96057643f09b97871709097c2a4
/GFG/BT_BST/delete_tree.cpp
cde75a8599906a3bcde578c6854728a67e941b8f
[]
no_license
rahulranjan96/Programming
7ce784b31300d0703149f2e60d8a2923247f6399
dbd4a0bef7dc667f6505d59b9ed5177927bb63c5
refs/heads/master
2021-03-24T10:18:41.811818
2016-10-25T04:45:49
2016-10-25T04:45:49
71,860,279
0
0
null
null
null
null
UTF-8
C++
false
false
1,304
cpp
#include <iostream> #include <cstdio> #include <cstdlib> #include <queue> #include <stack> using namespace std; typedef struct Node{ int key; struct Node *left; struct Node *right; }node; node* insert(node *root,int key) { if(root==NULL) { root=(node*)malloc(sizeof(node)); root->key=key; root->left=NULL; root->right=NULL; } else if(key>=root->key) root->right=insert(root->right,key); else if(key<root->key) root->left=insert(root->left,key); return root; } void deleteTree(node *root) { if(root!=NULL) { delete(root->left); delete(root->right); free(root); } } void inorder(node *root) { if(root!=NULL) { inorder(root->left); cout<<root->key<<" "; inorder(root->right); } } int main() { int c,key; node *root=NULL; while(1) { cout<<"1:Insert\n2:Print\n3:Delete\n4:Exit\nEnter Choice:"; cin>>c; switch(c) { case 1:cout<<"Enter key to be inserted:"; cin>>key; root=insert(root,key); break; case 2:inorder(root); cout<<endl; break; case 3:deleteTree(root); root=NULL; break; case 4:return 0; default:cout<<"Please enter a valid choice\n"; } } return 0; }
[ "rahulranjanyadav96@gmail.com" ]
rahulranjanyadav96@gmail.com
9c0a5f3c976d06cb5556be723819f89656f62200
0cd648478fbca2085d4be739caf9cbf0a57ab70c
/9-sequential_container/9.21-add_elements.cpp
51f2617cc740853ba9d9c0b5dc04a5f7aa6387a1
[]
no_license
icrelae/cpp_primer
f3fb497b96736f944701aecc25dd182f1e8cd73d
1ed1fef52356626440ca354fada0b673fce67465
refs/heads/master
2021-01-12T07:29:15.036680
2017-11-17T22:47:39
2017-11-17T22:47:39
76,966,712
0
0
null
null
null
null
UTF-8
C++
false
false
658
cpp
/* 2016.11.19 16:12 * P_309 * !!! * ??? * for deque, insert at head and tail costing constant time, at other site will be very time-consuming !!! * insert/eplace enlements into vector/string/deque will cause invalidation of iterators/references/pointers point to it !!! * * allocate new memory for every insert ??? */ #include <iostream> #include <string> #include <vector> #include <deque> #include <list> using namespace std; int main(int argc, char **argv) { vector<string> lst; string word; auto iter = lst.begin(); while (cin >> word) iter = lst.insert(iter, word); for (const auto itList : lst) cout << itList << ' '; return 0; }
[ "anadia@163.com" ]
anadia@163.com
e5c12b0574c3bf450189731b5f0757062d16aaa4
ba96d7f21540bd7504e61954f01a6d77f88dea6f
/build/Android/Debug/app/src/main/include/Uno.IO.CppXliStreamHandle.h
fc0a34d65b6761d1b238b90dcd284f38aa16ddf6
[]
no_license
GetSomefi/haslaamispaivakirja
096ff35fe55e3155293e0030c91b4bbeafd512c7
9ba6766987da4af3b662e33835231b5b88a452b3
refs/heads/master
2020-03-21T19:54:24.148074
2018-11-09T06:44:18
2018-11-09T06:44:18
138,976,977
0
0
null
null
null
null
UTF-8
C++
false
false
474
h
// This file was generated based on /usr/local/share/uno/Packages/UnoCore/1.6.1/Source/Uno/IO/CppXliStream.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <uBase/Stream.h> #include <Uno.Object.h> namespace uBase { class Stream; } namespace g{ namespace Uno{ namespace IO{ // internal extern struct CppXliStreamHandle :10 // { uStructType* CppXliStreamHandle_typeof(); struct CppXliStreamHandle { }; // } }}} // ::g::Uno::IO
[ "peyte.com@gmail.com" ]
peyte.com@gmail.com
f018c0b1e27af2148c95b021fb7548d198b3e06c
ddad5e9ee062d18c33b9192e3db95b58a4a67f77
/strings/strtoint.h
02f06465777432aa653bb97474872f3b478ddfe0
[ "BSD-2-Clause" ]
permissive
romange/gaia
c7115acf55e4b4939f8111f08e5331dff964fd02
8ef14627a4bf42eba83bb6df4d180beca305b307
refs/heads/master
2022-01-11T13:35:22.352252
2021-12-28T16:11:13
2021-12-28T16:11:13
114,404,005
84
17
BSD-2-Clause
2021-12-28T16:11:14
2017-12-15T19:20:34
C++
UTF-8
C++
false
false
3,287
h
// Copyright 2008 Google Inc. All Rights Reserved. // // Architecture-neutral plug compatible replacements for strtol() friends. // // Long's have different lengths on ILP-32 and LP-64 platforms, and so overflow // behavior across the two varies when strtol() and similar are used to parse // 32-bit integers. Similar problems exist with atoi(), because although it // has an all-integer interface, it uses strtol() internally, and so suffers // from the same narrowing problems on assignments to int. // // Examples: // errno = 0; // i = strtol("3147483647", NULL, 10); // printf("%d, errno %d\n", i, errno); // // 32-bit platform: 2147483647, errno 34 // // 64-bit platform: -1147483649, errno 0 // // printf("%d\n", atoi("3147483647")); // // 32-bit platform: 2147483647 // // 64-bit platform: -1147483649 // // A way round this is to define local replacements for these, and use them // instead of the standard libc functions. // // In most 32-bit cases the replacements can be inlined away to a call to the // libc function. In a couple of 64-bit cases, however, adapters are required, // to provide the right overflow and errno behavior. // #ifndef BASE_STRTOINT_H_ #define BASE_STRTOINT_H_ #include <stdlib.h> // For strtol* functions. #include <string> using std::string; #include "base/integral_types.h" #include "base/macros.h" #include "base/port.h" // Adapter functions for handling overflow and errno. int32 strto32_adapter(const char *nptr, char **endptr, int base); uint32 strtou32_adapter(const char *nptr, char **endptr, int base); // Conversions to a 32-bit integer can pass the call to strto[u]l on 32-bit // platforms, but need a little extra work on 64-bit platforms. inline int32 strto32(const char *nptr, char **endptr, int base) { if (sizeof(int32) == sizeof(long)) return static_cast<int32>(strtol(nptr, endptr, base)); else return strto32_adapter(nptr, endptr, base); } inline uint32 strtou32(const char *nptr, char **endptr, int base) { if (sizeof(uint32) == sizeof(unsigned long)) return static_cast<uint32>(strtoul(nptr, endptr, base)); else return strtou32_adapter(nptr, endptr, base); } // For now, long long is 64-bit on all the platforms we care about, so these // functions can simply pass the call to strto[u]ll. inline int64 strto64(const char *nptr, char **endptr, int base) { COMPILE_ASSERT(sizeof(int64) == sizeof(long long), sizeof_int64_is_not_sizeof_long_long); return strtoll(nptr, endptr, base); } inline uint64 strtou64(const char *nptr, char **endptr, int base) { COMPILE_ASSERT(sizeof(uint64) == sizeof(unsigned long long), sizeof_uint64_is_not_sizeof_long_long); return strtoull(nptr, endptr, base); } // Although it returns an int, atoi() is implemented in terms of strtol, and // so has differing overflow and underflow behavior. atol is the same. inline int32 atoi32(const char *nptr) { return strto32(nptr, NULL, 10); } inline int64 atoi64(const char *nptr) { return strto64(nptr, NULL, 10); } // Convenience versions of the above that take a string argument. inline int32 atoi32(const string &s) { return atoi32(s.c_str()); } inline int64 atoi64(const string &s) { return atoi64(s.c_str()); } #endif // BASE_STRTOINT_H_
[ "romange@gmail.com" ]
romange@gmail.com
93a605c1c4541fd59e4678178629e63009e17137
4fd87b5a8b7008822bdecf8346e4895257da4e38
/my_plugin/stringsearch_handle.cpp
f4b6920e4c7ad4b7c4c151c5968101f18b0265ac
[ "BSD-2-Clause" ]
permissive
zachturing/decaf-plugin
5dfcb5e9a7884a5bb4d8db9232abebe3f3f05c59
630b9e8781121ec211944f9f1470cf17c88b2a04
refs/heads/master
2020-03-19T08:06:05.837517
2018-06-05T09:50:30
2018-06-05T09:50:30
136,175,798
1
0
null
null
null
null
UTF-8
C++
false
false
8,291
cpp
#ifdef __cplusplus extern "C" { #endif #include <sys/time.h> #include "DECAF_main.h" #include "DECAF_callback.h" #include "DECAF_callback_common.h" #include "vmi_callback.h" #include "utils/Output.h" #include "DECAF_target.h" #include "hookapi.h" #include "shared/vmi_callback.h" #include "vmi_c_wrapper.h" #include "shared/tainting/taintcheck_opt.h" #include "function_map.h" #include "DECAF_types.h" #include "config.h" #ifdef __cplusplus } #endif #include "stringsearch_handle.h" #include <cstdio> #include <cstdlib> #include <ctype.h> #include <cmath> #include <map> #include <fstream> #include <sstream> #include <string> #include <iostream> using namespace std; extern DECAF_Handle mem_read_handle; extern DECAF_Handle mem_write_handle; extern FILE *stringsearch_log; uint8_t tofind[MAX_STRINGS][MAX_STRLEN]; uint32_t strlens[MAX_STRINGS]; char buf[MAX_SEARCH_LEN]; int num_strings = 0; int n_callers = 16; char target_file_name[512]; struct string_pos { uint32_t val[MAX_STRINGS]; string_pos() { bzero(val, sizeof(val)); } }; void stringsearch_cleanup() { DECAF_printf("stringsearch_cleanup.\n"); if(stringsearch_log != NULL) { fclose(stringsearch_log); stringsearch_log = NULL; DECAF_printf("close file stringsearch_log.\n"); } if(mem_read_handle != DECAF_NULL_HANDLE) { DECAF_unregister_callback(DECAF_MEM_READ_CB, mem_read_handle); mem_read_handle = NULL; } if(mem_write_handle != DECAF_NULL_HANDLE) { DECAF_unregister_callback(DECAF_MEM_WRITE_CB, mem_write_handle); mem_write_handle = NULL; } } int mem_callback(void *buf, int size, bool is_write, int *pMatchLen) { //DECAF_printf("mem_callback.\n"); string_pos sp; int offset = -1; for (unsigned int i = 0; i < size; i++) { uint8_t val = ((uint8_t *)buf)[i]; for(int str_idx = 0; str_idx < num_strings; str_idx++) { if (tofind[str_idx][sp.val[str_idx]] == val) { sp.val[str_idx]++; } else { sp.val[str_idx] = 0; } if (sp.val[str_idx] == strlens[str_idx]) //第str_idx个字符串匹配成功 { // Victory! //DECAF_printf("%s Match of str %s\n", (is_write ? "WRITE" : "READ"), tofind[str_idx]); fprintf(stringsearch_log, "%s Match of str %s\n", (is_write ? "WRITE" : "READ"), tofind[str_idx]); fprintf(stringsearch_log, "addr:0x%x\n", (uint8_t*)buf + i - strlens[str_idx]); *pMatchLen = strlens[str_idx]; //记录当前匹配的字符串的长度 fprintf(stringsearch_log, "match string len is %d.\n", *pMatchLen); int index = 1; for(; index <= strlens[str_idx]; ++index) { fprintf(stringsearch_log, "0x%x:%c\n", (char*)buf + i - strlens[str_idx] + index, *((char*)buf + i - strlens[str_idx] + index)); } //DECAF_printf("Victory\n"); fprintf(stringsearch_log, "%s\n\n", "Victory"); fflush(stringsearch_log); sp.val[str_idx] = 0; offset = i; break; } } } return offset; } /* * @function name:parse_file * @function:解析存放待搜索字符串的文件.字符串包括两种,同panda * @params: stringsfile:存放待搜索字符串的文件名 * @return:正确解析返回true,反之返回false */ bool parse_file(const char* stringsfile) { ifstream search_strings(stringsfile); if(!search_strings) { DECAF_printf("Couldn't open %s; no strings to search for. Exiting.\n", stringsfile); return false; } string line; while(getline(search_strings, line)) { DECAF_printf("line:%s\n", line.c_str()); istringstream iss(line); if(line[0] == '"') //解析 " xxx " 双引号括起来的字符串 { size_t len = line.size() - 2; //获取字符串的长度 memcpy(tofind[num_strings], line.substr(1, len).c_str(), len); strlens[num_strings] = len; } else //解析以":"分隔的十六进制字节序列 { string x; int i = 0; while(getline(iss, x, ':')) { tofind[num_strings][i++] = (uint8_t)strtoul(x.c_str(), NULL, 16); if(i >= MAX_STRLEN) { printf("WARN: Reached max number of characters (%d) on string %d, truncating.\n", MAX_STRLEN, num_strings); break; } } strlens[num_strings] = i; } DECAF_printf("stringsearch: added string of length %d to search set\n", strlens[num_strings]); if(++num_strings >= MAX_STRINGS) { //最多搜索MAX_STRINGS个字符序列,这里定义的是100 DECAF_printf("WARN: maximum number of strings (%d) reached, will not load any more.\n", MAX_STRINGS); break; } } search_strings.close(); return true; } void do_mem_read_cb(DECAF_Callback_Params *param) { //DECAF_printf("do_mem_read_cb.\n"); CPUState *env=param->be.env; if(env == NULL) { DECAF_printf("env is NULL\n"); return; } uint32_t eip = DECAF_getPC(cpu_single_env); uint32_t cr3 = DECAF_getPGD(cpu_single_env); char name[128]; tmodinfo_t dm; if(VMI_locate_module_c(eip, cr3, name, &dm) == -1) { strcpy(name, "<None>"); bzero(&dm, sizeof(dm)); } for(int i = 0; i < PROC_NUM; ++i) { if(strcmp(name, procname[i]) == 0) //说明触发此回调函数的进程是我们所关注的进程 { DECAF_read_mem_with_pgd(cpu_single_env, cr3, param->mr.vaddr, MAX_SEARCH_LEN, (void*)buf); int bytes_read = 0; int offset = mem_callback(buf, MAX_SEARCH_LEN, false, &bytes_read); //返回匹配的最后的一个字符的位置 if(offset != -1) { fprintf(stringsearch_log, "%s:\n", name); fprintf(stringsearch_log, "proc name :%s offset :%d tainted bytes :%d\n", name, offset + 1, bytes_read); //因为下标从0开始,所以表示位置时要加1 uint8_t* taint_flag= new uint8_t[bytes_read]; memset((void*)taint_flag, 0xff, bytes_read); //打上污点标签 taintcheck_taint_virtmem(param->mr.vaddr + offset - STRING_LEN + 1, bytes_read, taint_flag); fflush(stringsearch_log); //fprintf(stringsearch_log, "vaddr:0x%x\n", param->mr.vaddr + offset - STRING_LEN); //fprintf(stringsearch_log, "vaddr->paddr:%x\n", DECAF_get_phys_addr(cpu_single_env, param->mr.vaddr + offset - STRING_LEN)); //fprintf(stringsearch_log, "guest os virtual address:%x\n", cpu_single_env->regs[R_EBP]); delete[] taint_flag; break; } } } } void do_mem_write_cb(DECAF_Callback_Params *param) { //DECAF_printf("do_mem_write_cb.\n"); CPUState *env=param->be.env; if(env == NULL) { DECAF_printf("env is NULL\n"); return; } uint32_t eip = DECAF_getPC(cpu_single_env); uint32_t cr3 = DECAF_getPGD(cpu_single_env); char name[128]; tmodinfo_t dm; if(VMI_locate_module_c(eip, cr3, name, &dm) == -1) { strcpy(name, "<None>"); bzero(&dm, sizeof(dm)); } for(int i = 0; i < PROC_NUM; ++i) { if(strcmp(name, procname[i]) == 0) //说明触发此回调函数的进程是我们所关注的进程 { DECAF_read_mem_with_pgd(cpu_single_env, cr3, param->mr.vaddr, MAX_SEARCH_LEN, (void*)buf); int bytes_read = 0; int offset = mem_callback(buf, MAX_SEARCH_LEN, true, &bytes_read); if(offset != -1) { fprintf(stringsearch_log, "%s:\n", name); fprintf(stringsearch_log, "proc name :%s offset :%d tainted bytes :%d\n", name, offset + 1, bytes_read); int bytes_read = STRING_LEN; uint8_t* taint_flag= new uint8_t[bytes_read]; memset((void*)taint_flag, 0xff, bytes_read); taintcheck_taint_virtmem(param->mr.vaddr + offset - STRING_LEN + 1, bytes_read, taint_flag); //fprintf(stringsearch_log, "vaddr:0x%x\n", param->mr.vaddr); //fprintf(stringsearch_log, "paddr:0x%x\n", param->mr.paddr); fflush(stringsearch_log); delete[] taint_flag; break; } } } }
[ "zach_turing@outlook.com" ]
zach_turing@outlook.com
5e9eac77df529dbd5d2830f38390917723d95040
bc3a6cf1e9fb34f2fc597c4320cfddff01c2c474
/include/IntegerSetArray.h
fc60972d0a26f824d56b41d45c74c3ce4dca5769
[]
no_license
eschild2/test
c4df3c3c31d3bc8b80e0725b06abdf96c0078aa0
80cfc06671d9ba2b22c11366f2d28ae78299b12f
refs/heads/master
2020-04-09T05:35:15.445686
2018-12-02T18:08:35
2018-12-02T18:08:35
160,070,789
0
0
null
null
null
null
UTF-8
C++
false
false
513
h
namespace ece309{ class IntegerSet { protected: int size; public: IntegerSet(int htsize):size(htsize) {} virtual bool insert(int) = 0; virtual bool search(int) const = 0; virtual void remove(int) = 0; }; class IntegerSetArray: public IntegerSet { public: int size; int* a; int currentIndex; IntegerSetArray(int s); bool insert(int x); bool search(int x) const; void remove(int x); }; }
[ "noreply@github.com" ]
eschild2.noreply@github.com
90d8c12d1519358247f873732dac9855de848e35
a88124690a500e728229ae1c3646721b8f5a4c82
/two_sets_ii.cpp
c687936ad29daadd709a1a4377baf7c2ef815d39
[ "MIT" ]
permissive
ShinAKS/cses_solutions
237eedaaa2940d57b1b666a808ad93c9a9169a3c
e4ebcf80c010785f1b73df7aa8052da07ad549e0
refs/heads/master
2022-12-22T21:12:30.568416
2020-10-01T13:54:31
2020-10-01T13:54:31
300,294,172
0
0
null
null
null
null
UTF-8
C++
false
false
1,038
cpp
#include <bits/stdc++.h> #define ll long long #define int long long #define pb push_back #define pii pair<int,int> #define vi vector<int> #define vii vector<pii> #define mi map<int,int> #define mii map<pii,int> #define all(a) (a).begin(),(a).end() #define ff first #define ss second #define sz(x) (int)x.size() #define endl '\n' #define hell 1000000007 #define rep(i,a,b) for(int i=a;i<b;i++) using namespace std; const int P = (500*501)/2+1; ll dp[501][P]; int32_t main(){ cin.tie(NULL); ios::sync_with_stdio(false); //insert code int n; cin>>n; ll s = (n*(n+1))/2; if (s%2){ cout<<0<<endl; return 0; } memset(dp,0,sizeof(dp)); dp[0][0] = 1; rep(i,1,n+1){ rep(j,0,s/2+1){ if (j == 0)dp[i][j] = 1; else{ dp[i][j] = dp[i-1][j]; if (j>=i-1)dp[i][j] = (dp[i][j]+dp[i-1][j-i+1])%hell; } } } /* rep(i,0,n+1){ rep(j,0,s/2+1)cout<<dp[i][j]<<" "; cout<<endl; } */ cout<<dp[n][s/2]<<endl; }
[ "ayushsinha0@gmail.com" ]
ayushsinha0@gmail.com
6e92bed032c003268d3ae9e0f42e5d6655b865d4
e1ad82f32e73b0a9750eb1a3eaf23b46a531cf12
/lines/src/main.cpp
21e32ad758351f8c1f100b3b9387b909d234b6f7
[]
no_license
markbirss/PicoQVGA
fb7f6deef67a1bed88b568fdf71528e073463c9e
7d29c62ea1cda46bbec03f63b4d5fb8c8173700e
refs/heads/main
2023-08-08T01:56:43.813250
2021-09-16T20:30:53
2021-09-16T20:30:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,903
cpp
// **************************************************************************** // // Main code // // **************************************************************************** #include "include.h" #define LINENUM 50 // number of lines #define SPEEDMIN 2.0f // minimal speed #define SPEEDMAX 7.0f // maximal speed #define LENMIN 40 // minimal length of color #define LENMAX 200 // maximal length of color #define LEVMIN (3*80) // minimal bright level // coordinates enum { C_X1 = 0, C_Y1, C_X2, C_Y2, C_NUM // number of coordinates }; // current coordinate of the head float Coord[C_NUM]; // coordinate u16 CoordMax[C_NUM]; // max. coordinate float Delta[C_NUM]; // delta u8 R, G, B; // length of color segment int ColLen; // lines typedef struct { u8 r, g, b; // line color int coord[C_NUM]; // line coordinates } sLine; sLine Lines[LINENUM]; // list of lines int Head; // head index int main() { int i, j, k, rr, gg, bb; sLine* line; // initialize line head to random position and color CoordMax[C_X1] = WIDTH-1; CoordMax[C_Y1] = HEIGHT-1; CoordMax[C_X2] = WIDTH-1; CoordMax[C_Y2] = HEIGHT-1; for (i = 0; i < C_NUM; i++) { Coord[i] = RandU16Max(CoordMax[i]); Delta[i] = RandFloatMinMax(SPEEDMIN, SPEEDMAX); if ((RandU8() & 1) != 0) Delta[i] = -Delta[i]; } do { R = RandU8(); G = RandU8(); B = RandU8(); } while (R+G+B < LEVMIN); Head = 0; ColLen = RandU8MinMax(LENMIN,LENMAX); memset(Lines, 0, sizeof(Lines)); // main loop while (true) { // wait for VSync WaitVSync(); // draw lines j = Head; for (i = 0; i < LINENUM; i++) { // pointer to the line line = &Lines[j]; // calculate color components rr = (int)((float)line->r * i / (LINENUM-1) + 0.5f); if (rr > 255) rr = 255; gg = (int)((float)line->g * i / (LINENUM-1) + 0.5f); if (gg > 255) gg = 255; bb = (int)((float)line->b * i / (LINENUM-1) + 0.5f); if (bb > 255) bb = 255; // draw line DrawLine(line->coord[C_X1], line->coord[C_Y1], line->coord[C_X2], line->coord[C_Y2], COLRGB(rr,gg,bb)); // shift line index j++; if (j >= LINENUM) j = 0; } // generate new head line j = Head; line = &Lines[j]; for (i = 0; i < C_NUM; i++) line->coord[i] = (int)(Coord[i] + 0.5f); line->r = R; line->g = G; line->b = B; // shift header j++; if (j >= LINENUM) j = 0; Head = j; // shift coordinates for (i = 0; i < C_NUM; i++) { Coord[i] += Delta[i]; if (Coord[i] < 0) { Coord[i] = 0; Delta[i] = RandFloatMinMax(SPEEDMIN, SPEEDMAX); } if (Coord[i] > CoordMax[i]) { Coord[i] = CoordMax[i]; Delta[i] = -RandFloatMinMax(SPEEDMIN, SPEEDMAX); } } // generate new color ColLen--; if (ColLen <= 0) { ColLen = RandU8MinMax(LENMIN,LENMAX); do { R = RandU8(); G = RandU8(); B = RandU8(); } while (R+G+B < LEVMIN); } } }
[ "Panda38@seznam.cz" ]
Panda38@seznam.cz
3361eab1ae980ca6bb16921c589f76ffe41fdb88
c30a94fda11a05853c959cde74c302400298e46a
/Astronomy Solar System/LightManager.h
922ec4f16d44c8a269bce3d9aad3f3b093f9cb34
[]
no_license
cmilatinov/solar-system-sim
eb98f1eff213132683f8b49ea9f5837c9617e4d9
00502f19feb739a6b09ca2d589437dde0edcb466
refs/heads/master
2023-01-24T15:25:15.668799
2019-03-16T19:37:20
2019-03-16T19:37:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
229
h
#include <vector> #include "Light.h" #pragma once class LightManager { public: LightManager(Light * sun); ~LightManager(); const static int maxLights = 1; void addLight(Light * l); std::vector<Light*> getAllLights(); };
[ "milatinovcristian@gmail.com" ]
milatinovcristian@gmail.com
89b44afeba4883ff4343e20e32d6d6ffb9b19fbd
c09c94210c61918d7fe8a5782761c10ddfc3f002
/案例7_类的继承与派生/6-5 多重继承派生类构造函数.cpp
607bba413d4961a8ee908b7ce7ce3401f4f10f52
[]
no_license
SWQXDBA/Pintia_C-
b0c05476193e39669c45c7f949e528a21579d7d0
014b48ae12142117922f490a6b25f4f6227829c2
refs/heads/master
2023-05-02T08:19:51.145454
2021-05-26T05:18:12
2021-05-26T05:18:12
365,187,119
1
0
null
null
null
null
UTF-8
C++
false
false
1,228
cpp
#include <iostream> #include <cstdio> #include <string> using namespace std; //class Teacher //{public: // Teacher(string nam,int a,string t) // {name=nam; // age=a; // title=t;} // void display() // {cout<<"name:"<<name<<endl; // cout<<"age"<<age<<endl; // cout<<"title:"<<title<<endl; // } //protected: // string name; // int age; // string title; //}; // //class Student //{public: // Student(string nam,char s,float sco) // {name1=nam; // sex=s; // score=sco;} // void display1() // {cout<<"name:"<<name1<<endl; // cout<<"sex:"<<sex<<endl; // cout<<"score:"<<score<<endl; // } //protected: // string name1; // char sex; // float score; //}; class Graduate:public Teacher,public Student{ private: float wage; public: Graduate(const string &name,int age,char sex,const string &title,float score,float wages):Teacher(name,age,title), Student(name,sex,score),wage(wages){} void show(){ printf("name:%s\n" "age:%d\n" "sex:%c\n" "score:%g\n" "title:%s\n" "wages:%g\n",name.c_str(),age,sex,score,title.c_str(),wage); } };
[ "SWQXDBA2" ]
SWQXDBA2
0997b54258cc050cdcb22687bdad63bf5bcd9d20
39ad116dab0ba316a6e7f737a031a0f853685d41
/edu116/b.cpp
528adffd7126bd2a19109653b8afb43426661101
[]
no_license
Abunyawa/contests
e0f9d157ce93d3fc5fbff0e3e576f15286272c98
9923df8f167e8091e23f890b01368a3a8f61e452
refs/heads/master
2023-05-31T14:20:31.983437
2023-05-11T14:19:58
2023-05-11T14:19:58
251,015,695
10
0
null
null
null
null
UTF-8
C++
false
false
1,004
cpp
// chrono::system_clock::now().time_since_epoch().count() #include <bits/stdc++.h> #define pb push_back #define eb emplace_back #define mp make_pair #define fi first #define se second #define all(x) (x).begin(), (x).end() #define sz(x) (int)(x).size() #define rep(i, a, b) for (int i = (a); i < (b); ++i) #define debug(x) cerr << #x << " = " << x << endl using namespace std; typedef long long ll; typedef pair<int, int> pii; typedef vector<int> vi; typedef vector<ll> vl; void yes(){ cout<<"YES"<<'\n'; } void no(){ cout<<"NO"<<'\n'; } void solve() { ll n,k; cin>>n>>k; ll cur = 1; ll ans = 0; while(cur<n){ if(cur<=k){ cur*=2; ans++; }else{ break; } } if(cur<n){ ans += (n-cur+k-1)/k; } cout<<ans<<'\n'; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tt = 1; cin>>tt; while (tt--) { solve(); } return 0; }
[ "abusaid.manap@gmail.com" ]
abusaid.manap@gmail.com
aaf8eaba78ad385bcbd3754e23dcf79ae97f701c
cdb83d7f079d211a2b5493145ef9bdfef6b6e434
/include/logger.h
8845b7f669822ed9f043967fc2132034a0e50c77
[]
no_license
theDrsh/uComsImpl
a03a7077c98a898ad74af50c60a32f04cfcf8664
2f3ac7f8d1a9cc605e95c2c6ca9b0a59aaba945e
refs/heads/master
2023-02-04T05:38:48.738603
2020-12-09T00:43:08
2020-12-09T00:43:08
318,061,730
0
0
null
null
null
null
UTF-8
C++
false
false
506
h
// Author: Daniel Rush #pragma once #include <stdarg.h> #include <stdio.h> #include <string.h> #include "stm32f3xx_hal.h" enum LoggerLevel { kLogDebug = 0, kLogInfo = 1, kLogError = 2, kLogFatal = 3, kLogLevels, }; const int32_t MSG_SIZE = 256; class Logger { public: void Printf(LoggerLevel Level, const char* format, ...); private: void Write(const char* msg); void FormatMessage(LoggerLevel level, const char* format, va_list args); int foo; char msg_buffer_[MSG_SIZE]; };
[ "rush.daniel95@gmail.com" ]
rush.daniel95@gmail.com
6a96ac4a63a5dccdafa1bc8e1d73b11c8e829806
c831d5b1de47a062e1e25f3eb3087404b7680588
/webkit/Source/WebKit/Storage/StorageNamespaceImpl.h
ae161e1b58fb0623eebd4805769fad3e40639f27
[ "BSD-2-Clause" ]
permissive
naver/sling
705b09c6bba6a5322e6478c8dc58bfdb0bfb560e
5671cd445a2caae0b4dd0332299e4cfede05062c
refs/heads/master
2023-08-24T15:50:41.690027
2016-12-20T17:19:13
2016-12-20T17:27:47
75,152,972
126
6
null
2022-10-31T00:25:34
2016-11-30T04:59:07
C++
UTF-8
C++
false
false
3,138
h
/* * Copyright (C) 2008 Apple Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef StorageNamespaceImpl_h #define StorageNamespaceImpl_h #include <WebCore/SecurityOriginHash.h> #include <WebCore/StorageArea.h> #include <WebCore/StorageNamespace.h> #include <wtf/HashMap.h> #include <wtf/RefPtr.h> #include <wtf/text/WTFString.h> namespace WebCore { class StorageAreaImpl; class StorageNamespaceImpl : public StorageNamespace { public: WEBCORE_EXPORT static RefPtr<StorageNamespaceImpl> createSessionStorageNamespace(unsigned quota); WEBCORE_EXPORT static RefPtr<StorageNamespaceImpl> getOrCreateLocalStorageNamespace(const String& databasePath, unsigned quota); virtual ~StorageNamespaceImpl(); void close(); // Not removing the origin's StorageArea from m_storageAreaMap because // we're just deleting the underlying db file. If an item is added immediately // after file deletion, we want the same StorageArea to eventually trigger // a sync and for StorageAreaSync to recreate the backing db file. void clearOriginForDeletion(SecurityOrigin*); void clearAllOriginsForDeletion(); void sync(); void closeIdleLocalStorageDatabases(); private: StorageNamespaceImpl(StorageType, const String& path, unsigned quota); RefPtr<StorageArea> storageArea(RefPtr<SecurityOrigin>&&) override; RefPtr<StorageNamespace> copy(Page* newPage) override; typedef HashMap<RefPtr<SecurityOrigin>, RefPtr<StorageAreaImpl>> StorageAreaMap; StorageAreaMap m_storageAreaMap; StorageType m_storageType; // Only used if m_storageType == LocalStorage and the path was not "" in our constructor. String m_path; RefPtr<StorageSyncManager> m_syncManager; // The default quota for each new storage area. unsigned m_quota; bool m_isShutdown; }; } // namespace WebCore #endif // StorageNamespaceImpl_h
[ "daewoong.jang@navercorp.com" ]
daewoong.jang@navercorp.com
bca319cfd190afd4473cbff347a81eb1571ed5cf
e65a4dbfbfb0e54e59787ba7741efee12f7687f3
/devel/libphonenumber/files/patch-src_phonenumbers_base_synchronization_lock.h
6455ae783a95ca7b43526b694ad124c520ac0fef
[ "BSD-2-Clause" ]
permissive
freebsd/freebsd-ports
86f2e89d43913412c4f6b2be3e255bc0945eac12
605a2983f245ac63f5420e023e7dce56898ad801
refs/heads/main
2023-08-30T21:46:28.720924
2023-08-30T19:33:44
2023-08-30T19:33:44
1,803,961
916
918
NOASSERTION
2023-09-08T04:06:26
2011-05-26T11:15:35
null
UTF-8
C++
false
false
689
h
--- src/phonenumbers/base/synchronization/lock.h.orig 2020-06-18 13:06:40 UTC +++ src/phonenumbers/base/synchronization/lock.h @@ -22,7 +22,7 @@ #elif (__cplusplus >= 201103L) && defined(I18N_PHONENUMBERS_USE_STDMUTEX) // C++11 Lock implementation based on std::mutex. #include "phonenumbers/base/synchronization/lock_stdmutex.h" -#elif defined(__linux__) || defined(__APPLE__) || defined(I18N_PHONENUMBERS_HAVE_POSIX_THREAD) +#elif defined(__linux__) || defined(__APPLE__) || defined(I18N_PHONENUMBERS_HAVE_POSIX_THREAD) || defined(__FreeBSD__) #include "phonenumbers/base/synchronization/lock_posix.h" #elif defined(WIN32) #include "phonenumbers/base/synchronization/lock_win32.h"
[ "tcberner@FreeBSD.org" ]
tcberner@FreeBSD.org
bbf0bf528cdfbb06688515f9abbd6183a406f69c
76290c3f22ac436c52f29e9be5119d96cda551e7
/AESGUI/AlertDialog.h
f2da3e04189df3104f2a82a4a6cd319ce930aeb7
[]
no_license
CH-Chang/1091-AESGUI
8fbc912c06e7a3f6bd27b173f503be800764df18
57a839caec719310d45d4640b9213637fb230a78
refs/heads/main
2023-01-10T22:59:13.277015
2020-11-19T13:25:05
2020-11-19T13:25:05
309,672,086
1
0
null
null
null
null
BIG5
C++
false
false
713
h
#pragma once #include <QDialog> #include <QCursor> #include <QMouseEvent> #include "ui_AlertDialog.h" class AlertDialog : public QDialog { Q_OBJECT public: AlertDialog(QWidget *parent = Q_NULLPTR); ~AlertDialog(); void setTitle(QString); void setMessage(QString); private: // 變數 int moveFlag = false; Ui::AlertDialog ui; QPoint movePosition; void init(); void initView(); void initInteraction(); protected: // 重載方法 virtual void mousePressEvent(QMouseEvent *); virtual void mouseMoveEvent(QMouseEvent *); virtual void mouseReleaseEvent(QMouseEvent *); public slots: void onCloseClicked(); void onMaximizeClicked(); void onMinimizeClicked(); void onComfirmClicked(); };
[ "hew12233@gmail.com" ]
hew12233@gmail.com
6864b6600ba10911356faf694a673bf25956a21e
94a91b89f420e50a8ac827e3323b5e6ec588820e
/Engine/Core/Components/LightSource (Old).h
4bd70024184258fa40c52ebc4904373747e69aad
[]
no_license
cn1504/OrcRugby
6e5e2dffa795ea2873e60f2b383725068a80a656
af56a70c7aaffe26403a8085f9ea15166127646b
refs/heads/master
2020-03-29T12:55:52.937391
2015-06-29T21:19:30
2015-06-29T21:19:30
26,777,949
0
0
null
null
null
null
UTF-8
C++
false
false
929
h
#pragma once #include "Core.h" #include "Component.h" #include <Bullet/BulletCollision/CollisionDispatch/btGhostObject.h> #include <Renderers/RenderBuffer.h> #include <Renderers/Shader.h> namespace Core { namespace Components { class LightSource : public Component { protected: //Scene* scene; bool shadow; btSphereShape* shape; std::vector<Core::Entity*> litObjects; public: //RenderBuffer* ShadowRB; glm::mat4 Projection; glm::vec3 Color; float Radius; float Intensity; float CosInner; float CosOuter; //LightSource(Scene* scene, glm::vec3 color, float radius, float intensity, float cosInner, float cosOuter, bool castsShadow = false); virtual ~LightSource(); virtual void Load(); virtual void Update(); bool CastsShadow(); std::vector<Core::Entity*>* GetLitObjects(); GLuint GetShadowTexture(); //void WriteShaderUniforms(Shader* shader); }; } }
[ "cnielsenxt@gmail.com" ]
cnielsenxt@gmail.com
674d4888a0eb6ed551ccc634751f11f568a9ca61
d08d64d9cf83022a511aaa9f8e6d3cf162eef2af
/dev_ws/src/aimibot/src/message_callback.cpp
d47031859058f814fba1c0760efdac4d120c2644
[]
no_license
UnmannedVehicle/Vehcle
39900b28ccdfce8493d36621268ea71eae24d86b
dc9a6ab0a5365973b97b678d15ad6465ca447f30
refs/heads/main
2023-07-27T00:35:09.345638
2021-09-10T02:52:57
2021-09-10T02:52:57
404,932,262
0
0
null
null
null
null
UTF-8
C++
false
false
2,539
cpp
#include "iostream" #include "../include/aimibot/message_callback.hpp" #include "legacy/mavlink_interface.h" //51 #include "../include/aimibot/aimibot.hpp" #include "limits.h" using namespace std; void aimibot::subscribeGpsCommand(const geometry_msgs::msg::PoseStamped::SharedPtr msg) { geometry_msgs::msg::Quaternion orientation; orientation = msg->pose.orientation; tf2::Quaternion quat(orientation.x,orientation.y,orientation.w,orientation.z); double roll, pitch;//定义存储r\p\y的容器 tf2::Matrix3x3 m(quat); m.getRPY(roll, pitch, gps_yaw);//进行转换 //gps_yaw = yaw / 180.0 * pi; head_init = false; } void aimibot::subscribeVelocityCommand(const geometry_msgs::msg::Twist::SharedPtr msg) { int ret; float wz = (msg->angular.z) ; float vx = msg->linear.x ; // mavlink_interface->Mav_Set_Cmd_Long_Mode(0,AMB_MODE_FLAG_SPEED_MODE_ENABLED); // usleep(5000); // mavlink_interface->Mav_Set_Cmd_Long_Torque(0,1,2,3,4,5,2); // usleep(5000); // mavlink_interface->Mav_Set_Cmd_Long_Acceleration(0,100); // usleep(5000); // mavlink_interface->Mav_Set_Cmd_Long_GPIO_Output(0,0x0f0f); // usleep(5000); // mavlink_interface->Mav_Set_Cmd_Long_Analog_Output(0,0,1,2,3,4,5,6); //~ if ((vx != 0) || (wz != 0)) { ret = interface.Mav_Set_Cmd_Long_Velocity(0,vx,wz); //~ printf("vx=%f,wz=%f\n",vx,wz); // usleep(5000); //ret = interface.Mav_Set_Cmd_Long_Frequency(1,2,50,50,50,0,50); if(ret==0) { //cout << "Success! timestamp = " << timestamp <<endl; } else { cout << "Failed!" <<endl; } interface.Mav_Set_Heatbeat(0xff); } } void aimibot::subscribeGpioCommand(const mymsgs::msg::Control::SharedPtr msg) { int ret; int flag = msg->gpio; // mavlink_interface->Mav_Set_Cmd_Long_Mode(0,AMB_MODE_FLAG_SPEED_MODE_ENABLED); // usleep(5000); // mavlink_interface->Mav_Set_Cmd_Long_Torque(0,1,2,3,4,5,2); // usleep(5000); // mavlink_interface->Mav_Set_Cmd_Long_Acceleration(0,100); // usleep(5000); // mavlink_interface->Mav_Set_Cmd_Long_GPIO_Output(0,0x0f0f); // usleep(5000); // mavlink_interface->Mav_Set_Cmd_Long_Analog_Output(0,0,1,2,3,4,5,6); //~ if ((vx != 0) || (wz != 0)) { ret = interface.Mav_Set_Cmd_Long_GPIO_Output(0,flag); //~ printf("vx=%f,wz=%f\n",vx,wz); // usleep(5000); //ret = interface.Mav_Set_Cmd_Long_Frequency(1,2,50,50,50,0,50); if(ret==0) { //cout << "Success! timestamp = " << timestamp <<endl; } else { cout << "Failed!" <<endl; } interface.Mav_Set_Heatbeat(0xff); } }
[ "noreply@github.com" ]
UnmannedVehicle.noreply@github.com
960197a19934902c703f04874e13552a84a919bd
74dfb16f483ef51e87d3a3a4b23e29bdd5296c7c
/BigNumber.hpp
622e478ee285893e5b84c71342d3caa8d52e457f
[ "MIT" ]
permissive
Vicshann/Common
090a692010e0d6c6af14dd9a2c4ab2b531d8b16e
dbd6f57e94d4179edcbee1a29de39a4a59bce9e3
refs/heads/master
2023-09-01T12:08:23.348673
2023-08-28T09:56:46
2023-08-28T09:56:46
123,412,494
13
8
null
null
null
null
UTF-8
C++
false
false
7,275
hpp
#pragma once /* Copyright (c) 2018 Victor Sheinmann, Vicshann@gmail.com 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. */ // TODO: Use Platform endianess by default template<int NumOfBits, bool IsSignedInt, typename ElemType=unsigned int> class CBigInt { static const unsigned int NumOfParts = (NumOfBits / sizeof(ElemType))+(bool)(NumOfBits % sizeof(ElemType)); // static_assert(NumOfBits >= (sizeof(ElemType)*8), "NumOfBits is too small for ElemType!" ); ElemType IntParts[NumOfParts]; static constexpr bool IsPlatformLE(void){int val=1; return *(char*)&val;} // Old style: #define ISLE(((union { unsigned x; unsigned char c; }){1}).c) // Or #if 'ABCD' == 0x41424344 ElemType __cdecl ReverseBytes64(ElemType Val) { ElemType res; for(int ctr=0;ctr < sizeof(ElemType);ctr++)((unsigned char*)&res)[ctr] = ((unsigned char*)&Val)[sizeof(ElemType)-1-ctr]; return res; } //------------------------------------------------------------------------------------------------------------ static void ReverseCopy(ElemType* Dst, ElemType* Src, unsigned int Count) // Platform dependant! // Cross platform compile time way to determine endianess? { for(unsigned int ctr=0;ctr < Count;ctr++)Dst[(Count-1)-ctr] = ReverseBytes64(Src[ctr]); } //------------------------------------------------------------------------------------------------------------ static void BigAddU(ElemType* DstNum, ElemType* SrcNum) { bool HaveCarry = false; for(unsigned int ctr=0;ctr < NumOfParts;ctr++) { ElemType DVal = DstNum[ctr]; ElemType DSum = DVal + (ElemType)HaveCarry; if(DVal <= DSum) { ElemType SVal = SrcNum[ctr]; DstNum[ctr] = SVal + DSum; HaveCarry = SVal > (SVal + DSum); } else DstNum[ctr] = SrcNum[ctr]; } } //------------------------------------------------------------------------------------------------------------ static void BigSubU(ElemType* DstNum, ElemType* SrcNum) { bool HaveCarry = false; for(unsigned int ctr=0;ctr < NumOfParts;ctr++) { ElemType DSVal = DstNum[ctr] - (ElemType)HaveCarry; if(DSVal <= ~(ElemType)HaveCarry) { ElemType SVal = SrcNum[ctr]; ElemType RVal = DSVal - SVal; DstNum[ctr] = RVal; HaveCarry = RVal > ~SVal; } else DstNum[ctr] = ~SrcNum[ctr]; } } //------------------------------------------------------------------------------------------------------------ static unsigned int BigCountValParts(ElemType* BigNum) // How many parts(ElemType) with value the number have { int Ctr = NumOfParts; for(;Ctr > 0;Ctr--) { if(BigNum[Ctr-1])break; } return Ctr; } //------------------------------------------------------------------------------------------------------------ static int BigCmpU(ElemType* Num, ElemType* Tgt) { for(int ctr=NumOfParts-1;ctr >= 0;ctr--) { ElemType Val = Tgt[ctr]; if(Num[ctr] > Val)return 1; // Greater if(Num[ctr] < Val)return -1; // Less } return 0; // Equal } //------------------------------------------------------------------------------------------------------------ static void BigDivRemU(ElemType* DstNum, ElemType* SrcNum) // DstNum = DstNum % SrcNum { for(;;) { if(BigCmpU(DstNum, SrcNum) < 0)break; BigSubU(DstNum, SrcNum); } } //------------------------------------------------------------------------------------------------------------ static void BigPower(ElemType* BigMulA, ElemType* BigMulB, ElemType* BigMod) { ElemType TmpBuf[NumOfParts]; ElemType WrkBuf[NumOfParts]; memset(WrkBuf, 0, sizeof(WrkBuf)); memcpy(TmpBuf, BigMulB, sizeof(TmpBuf)); if(unsigned int VPtCnt = BigCountValParts(BigMulA)) { for(unsigned int Idx=0;Idx < VPtCnt;Idx++) { ElemType Value = BigMulA[Idx]; for(unsigned int Ctr=0;Ctr < NumOfParts;Ctr++,Value >>= 1) { if(!Value && ((Idx+1) >= VPtCnt))break; if(Value & 1) { BigAddU(WrkBuf, TmpBuf); // res = (res*Value) % Modulus; BigDivRemU(WrkBuf, BigMod); } BigAddU(TmpBuf, TmpBuf); // pow // Value = (Value*Value) % Modulus; BigDivRemU(TmpBuf, BigMod); } } } memcpy(BigMulB, WrkBuf, sizeof(WrkBuf)); } //------------------------------------------------------------------------------------------------------------ static void BigPowMod(unsigned char* aValue, unsigned char* aExponent, unsigned char* aModulus, unsigned char* aDstBuf) { ElemType vSrcValue[NumOfParts]; ElemType vExponent[NumOfParts]; ElemType vModulus[NumOfParts]; ElemType vBigRes[NumOfParts]; ReverseCopy(vSrcValue, (ElemType*)aValue, NumOfParts); // License ReverseCopy(vExponent, (ElemType*)aExponent, NumOfParts); ReverseCopy(vModulus, (ElemType*)aModulus, NumOfParts); memset(&vBigRes,0,sizeof(vBigRes)); vBigRes[0] = 1; // Make Big One if(unsigned int DParts = BigCountValParts(vExponent)) // Anything ^ 0 = 1 { for(unsigned int CtrA=0;CtrA < DParts;CtrA++) // Valued parts of exponent { bool Flag = (CtrA+1) < DParts; ElemType ExpVal = vExponent[CtrA]; for(unsigned int CtrB=0;(ExpVal || Flag) && (CtrB < (sizeof(ElemType)*8));CtrB++,ExpVal >>= 1) // ExpVal /= 2 // ExpCtr (Number of bits in ElemType) { if(ExpVal & 1)BigPower(vSrcValue, vBigRes, vModulus); BigPower(vSrcValue, vSrcValue, vModulus); } } } ReverseCopy((ElemType*)aDstBuf, vBigRes, NumOfParts); } //------------------------------------------------------------------------------------------------------------ public: //------------------------------------------------------------------------------------------------------------ CBigInt(void):IntParts(0) {} //------------------------------------------------------------------------------------------------------------ void PowMod(unsigned char* aValue, unsigned char* aExponent, unsigned char* aModulus, unsigned char* aDstBuf) { BigPowMod(aValue, aExponent, aModulus, aDstBuf); } //------------------------------------------------------------------------------------------------------------ }; //------------------------------------------------------------------------------------------------------------
[ "Vicshann@gmail.com" ]
Vicshann@gmail.com
0b5dc127de05952f220089ff6f2cfbc61aa6e773
2e459946616dc440360e9ad6a09fde8ce3b3ca40
/gauss_driver/src/rpi/rpi_diagnostics.cpp
f2bed533717280840666209071b65e9913704fa5
[]
no_license
junjian-zhang/gauss
a09641b831b967ecea69bdf5f60affc21e95461a
849183725d402663d898a93c00a5ba9e4b7ed569
refs/heads/master
2020-04-27T04:22:42.036477
2019-01-31T08:08:47
2019-01-31T08:08:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,333
cpp
#include "gauss_driver/rpi/rpi_diagnostics.h" RpiDiagnostics::RpiDiagnostics() { cpu_temperature = 0; startReadingData(); } int RpiDiagnostics::getRpiCpuTemperature() { return cpu_temperature; } void RpiDiagnostics::readCpuTemperature() { #ifdef __arm__ std::fstream cpu_temp_file("/sys/class/thermal/thermal_zone0/temp", std::ios_base::in); int read_temp; cpu_temp_file >> read_temp; if (read_temp > 0) { cpu_temperature = read_temp / 1000; } #endif } void RpiDiagnostics::startReadingData() { read_hardware_data_thread.reset(new std::thread(boost::bind(&RpiDiagnostics::readHardwareDataLoop, this))); } void RpiDiagnostics::readHardwareDataLoop() { double read_rpi_diagnostics_frequency; ros::param::get("~read_rpi_diagnostics_frequency", read_rpi_diagnostics_frequency); ros::Rate read_rpi_diagnostics_rate = ros::Rate(read_rpi_diagnostics_frequency); while (ros::ok()) { readCpuTemperature(); // check if Rpi is too hot if (cpu_temperature > 75) { ROS_ERROR("Rpi temperature is really high !"); } if (cpu_temperature > 85) { ROS_ERROR("Rpi is too hot, shutdown to avoid any damage"); std::system("sudo shutdown now"); } read_rpi_diagnostics_rate.sleep(); } }
[ "bjq1016@163.com" ]
bjq1016@163.com
aa98b3f1e225fb7a3ccba6013a7f501bcc9a59a3
755f9e1bbc82a8beb0471c0cb932181a6f83dce3
/surfaceflinger/sdk/IServiceConnection.h
aba66ed641f6f4f7821c7ac22f7cad779e57d4c5
[]
no_license
wjfsanhe/AndroidM_SF
f52d3bba070ce7c9c59c3f18749cecdcb43c5dd9
426e4bfa15e44fe8d96f416eb0e404ba84172d30
refs/heads/master
2020-06-23T12:33:10.479615
2017-02-17T03:18:12
2017-02-17T03:18:12
74,648,648
1
0
null
null
null
null
UTF-8
C++
false
false
2,232
h
/* * 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. * @author wangjf * @version 1.0 * @date 2016/11/18 * * */ #ifndef ANDROID_ISERVICE_CONNECTION_H #define ANDROID_ISERVICE_CONNECTION_H #include <utils/Errors.h> #include <utils/RefBase.h> #include <binder/IInterface.h> #include <utils/String8.h> #include <utils/String16.h> namespace android { // ---------------------------------------------------------------------------- class ServiceConnection : public virtual RefBase { public: ServiceConnection(){} virtual ~ServiceConnection(){} /** * Called when a connection to the Service has been established, with * the {@link android.os.IBinder} of the communication channel to the * Service. * * @param name The concrete component name of the service that has * been connected. * * @param service The IBinder of the Service's communication channel, * which you can now make calls on. */ virtual void onServiceConnected(String16 name, sp<IBinder> service)=0; }; class IServiceConnection : public ServiceConnection,public IInterface { public: DECLARE_META_INTERFACE(ServiceConnection) }; class BnServiceConnection:public BnInterface<IServiceConnection>,private IBinder::DeathRecipient { public: virtual status_t onTransact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags = 0); private: // This is required by the IBinder::DeathRecipient interface // Bp ternimal can linktoDeath. virtual void binderDied(const wp<IBinder>& who)=0; }; // ---------------------------------------------------------------------------- }; // namespace android #endif // ANDROIDOID_ISERVICE_CONNECTION_H_
[ "wangjianfeng@baofeng.com" ]
wangjianfeng@baofeng.com
a902c98ce80d4527d2edea0d53c67b7c81060c5f
4a761d25954a9dd9aafbcac677a62e83e6785ba3
/src/test/test_concrete.h
4252d50025d682c34c4ef12fa38448f1e34a3773
[ "MIT" ]
permissive
CONCRETE-Project/CONCRETE
4dce6c776857d0fccef094f29aae1228796bd03c
f446b5335bff7f7a6a1ffeba97777339539263b0
refs/heads/master
2022-12-02T16:07:03.999082
2020-08-24T21:25:18
2020-08-24T21:25:18
256,929,363
1
0
null
null
null
null
UTF-8
C++
false
false
1,823
h
// Copyright (c) 2015-2019 The PIVX Core Developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef CONCRETE_TEST_TEST_CONCRETE_H #define CONCRETE_TEST_TEST_CONCRETE_H #include "txdb.h" #include <boost/filesystem.hpp> #include <boost/thread.hpp> extern uint256 insecure_rand_seed; extern FastRandomContext insecure_rand_ctx; static inline void SeedInsecureRand(bool fDeterministic = false) { if (fDeterministic) { insecure_rand_seed = uint256(); } else { insecure_rand_seed = GetRandHash(); } insecure_rand_ctx = FastRandomContext(insecure_rand_seed); } static inline uint32_t InsecureRand32() { return insecure_rand_ctx.rand32(); } static inline uint256 InsecureRand256() { return insecure_rand_ctx.rand256(); } static inline uint64_t InsecureRandBits(int bits) { return insecure_rand_ctx.randbits(bits); } static inline uint64_t InsecureRandRange(uint64_t range) { return insecure_rand_ctx.randrange(range); } static inline bool InsecureRandBool() { return insecure_rand_ctx.randbool(); } static inline std::vector<unsigned char> InsecureRandBytes(size_t len) { return insecure_rand_ctx.randbytes(len); } /** Basic testing setup. * This just configures logging and chain parameters. */ struct BasicTestingSetup { BasicTestingSetup(); ~BasicTestingSetup(); }; /** Testing setup that configures a complete environment. * Included are data directory, coins database, script check threads * and wallet (if enabled) setup. */ struct TestingSetup: public BasicTestingSetup { CCoinsViewDB *pcoinsdbview; boost::filesystem::path pathTemp; boost::thread_group threadGroup; ECCVerifyHandle globalVerifyHandle; TestingSetup(); ~TestingSetup(); }; #endif
[ "ziofabry@hotmail.com" ]
ziofabry@hotmail.com
7328dc7759fe1361159d8572c9b78bc8b844cd11
1fd507f588b94402a8c1ffe080e470f65a2b7ee6
/Hall Management Project with C/search.cpp
a87fd00d41723bb3c6eafb969af29c78ca8b5794
[]
no_license
MuhiminOsim/Academic-Projects
769ab00013f915fc651d15e4517b6d1d10c439d4
00252b7efbbedbfff5d5a13aa9af0ec04ec7df6f
refs/heads/master
2023-01-12T10:26:26.864981
2019-12-12T04:35:54
2019-12-12T04:35:54
194,081,586
2
0
null
2023-01-04T01:13:41
2019-06-27T11:18:38
HTML
UTF-8
C++
false
false
2,172
cpp
#include <stdio.h> #include <string.h> #include <stdlib.h> #include "hall.h" void searching(int b, int c){ system("cls"); printf("\n\n\t\t\t\t\t~~~~STUDENT DATA SEARCHING~~~~\n"); printf("\t\t\t\t\t______________________________\n"); int x,y; printf("\n\n\t\t\t\t\tSearch Roll Numbers: "); scanf("%d",&x); if(x<1000000 || x>9999999){ while(x<1000000 || x>9999999){ printf("\n\t\t\t\tPlease Enter A 6 Digits Valid Roll: "); scanf("%d",&x); } } int room,roll,border,year,term,lastd,lastm,lasty,temp,halldue; char *name, *dept, *meal; name=(char *)malloc(30*sizeof(char)); dept=(char *)malloc(10*sizeof(char)); meal=(char *)malloc(3*sizeof(char)); FILE *srch; srch=fopen("student data.txt","r"); temp=0; while(!feof(srch)){ fgets(name,30,srch); fscanf(srch,"%d %d %s %d %d %d %s %d %d %d %d",&roll,&room,dept,&year,&term,&border,meal,&lastd,&lastm,&lasty,&halldue); if(roll==x){ y=strlen(name); name[y-1]='\0'; printf("\n\t\t\t\t\t%s's Profile\n",name); printf("\t\t\t\t\tRoll: %d\n",roll); printf("\t\t\t\t\tRoom No.: %d\n",room); printf("\t\t\t\t\tDepartment: %s\n",dept); printf("\t\t\t\t\tYear: %d\n",year); printf("\t\t\t\t\tTerm: %d\n",term); printf("\t\t\t\t\tBorder: %d\n",border); printf("\t\t\t\t\tMeal status: %s\n",meal); printf("\t\t\t\t\tLast hall due date: %d/%d/%d\n",lastd,lastm,lasty); printf("\t\t\t\t\tHall Due: %d\n",halldue); temp=1; break; } } if(temp==0){ printf("\n\t\t\t\t\tNOT FOUND!\n"); } fclose(srch); printf("\t\t\t\t\tChoose: 1.Search Again\n\t\t\t\t\t\t2.Update Data\n\t\t\t\t\t\t3.Exit\n\t\t\t\t\t\t4.Menu\n\t\t\t\t\t\t"); scanf("%d",&y); if(y<1 || y>4){ while(y<1 || y>4){ printf("\n\t\t\t\t\tPlease Enter A Valid Digit: "); scanf("%d",&y); } } if(y==1) searching(b,c); else if(y==2) update(b,c); else if(y==3) exit(0); else menu(); }
[ "muhiminul@gmail.com" ]
muhiminul@gmail.com
8a34bf34ab5df85aa8985f35dd11d9ae19cc328b
683a90831bb591526c6786e5f8c4a2b34852cf99
/HackerRank/Implementation/4_jumping_on_the_clouds-Revisited.cpp
a5fdea82c7be605851116e86376550425065be43
[]
no_license
dbetm/cp-history
32a3ee0b19236a759ce0a6b9ba1b72ceb56b194d
0ceeba631525c4776c21d547e5ab101f10c4fe70
refs/heads/main
2023-04-29T19:36:31.180763
2023-04-15T18:03:19
2023-04-15T18:03:19
164,786,056
8
0
null
null
null
null
UTF-8
C++
false
false
373
cpp
#include <bits/stdc++.h> using namespace std; int main(int argc, char* argv[]){ int n, k, i, e = 100; cin >> n >> k; int C[n]; for (int i = 0; i < n; i++){ cin >> C[i]; } i = 0; while (true) { e--; i = (i + k) % n; if(C[i] == 1) e -= 2; if(i == 0) break; } cout << e << endl; return 0; }
[ "davbetm@gmail.com" ]
davbetm@gmail.com
0e3be275a98160495487495b4ae4c15d9d32b992
81533e098a8fd6d8458ef78bec9b7cd468733328
/linux/javacef/cefclient/client_app.cpp
285ffad93031ed5c45b287813a3c5bcc5ed8ceba
[]
no_license
inaauto/javacef
0ec07da810d3ff48d39b83dd51b690e33e0ee75f
a3a11cfef1aca54d34e1bbc9aaff0aa3fb7d01d7
refs/heads/master
2021-01-23T23:52:37.255643
2017-05-31T12:44:02
2017-05-31T12:44:02
59,431,494
2
0
null
2017-01-05T13:51:36
2016-05-22T19:57:08
C++
UTF-8
C++
false
false
15,186
cpp
// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights // reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. // This file is shared by cefclient and cef_unittests so don't include using // a qualified path. #include "client_app.h" // NOLINT(build/include) #include <string> #include "include/cef_cookie.h" #include "include/cef_process_message.h" #include "include/cef_task.h" #include "include/cef_v8.h" #include "util.h" // NOLINT(build/include) namespace { // Forward declarations. void SetList(CefRefPtr<CefV8Value> source, CefRefPtr<CefListValue> target); void SetList(CefRefPtr<CefListValue> source, CefRefPtr<CefV8Value> target); // Transfer a V8 value to a List index. void SetListValue(CefRefPtr<CefListValue> list, int index, CefRefPtr<CefV8Value> value) { if (value->IsArray()) { CefRefPtr<CefListValue> new_list = CefListValue::Create(); SetList(value, new_list); list->SetList(index, new_list); } else if (value->IsString()) { list->SetString(index, value->GetStringValue()); } else if (value->IsBool()) { list->SetBool(index, value->GetBoolValue()); } else if (value->IsInt()) { list->SetInt(index, value->GetIntValue()); } else if (value->IsDouble()) { list->SetDouble(index, value->GetDoubleValue()); } } // Transfer a V8 array to a List. void SetList(CefRefPtr<CefV8Value> source, CefRefPtr<CefListValue> target) { ASSERT(source->IsArray()); int arg_length = source->GetArrayLength(); if (arg_length == 0) return; // Start with null types in all spaces. target->SetSize(arg_length); for (int i = 0; i < arg_length; ++i) SetListValue(target, i, source->GetValue(i)); } // Transfer a List value to a V8 array index. void SetListValue(CefRefPtr<CefV8Value> list, int index, CefRefPtr<CefListValue> value) { CefRefPtr<CefV8Value> new_value; CefValueType type = value->GetType(index); switch (type) { case VTYPE_LIST: { CefRefPtr<CefListValue> list = value->GetList(index); new_value = CefV8Value::CreateArray(list->GetSize()); SetList(list, new_value); } break; case VTYPE_BOOL: new_value = CefV8Value::CreateBool(value->GetBool(index)); break; case VTYPE_DOUBLE: new_value = CefV8Value::CreateDouble(value->GetDouble(index)); break; case VTYPE_INT: new_value = CefV8Value::CreateInt(value->GetInt(index)); break; case VTYPE_STRING: new_value = CefV8Value::CreateString(value->GetString(index)); break; default: break; } if (new_value.get()) { list->SetValue(index, new_value); } else { list->SetValue(index, CefV8Value::CreateNull()); } } // Transfer a List to a V8 array. void SetList(CefRefPtr<CefListValue> source, CefRefPtr<CefV8Value> target) { ASSERT(target->IsArray()); int arg_length = source->GetSize(); if (arg_length == 0) return; for (int i = 0; i < arg_length; ++i) SetListValue(target, i, source); } // Handles the native implementation for the client_app extension. class ClientAppExtensionHandler : public CefV8Handler { public: explicit ClientAppExtensionHandler(CefRefPtr<ClientApp> client_app) : client_app_(client_app) { } virtual bool Execute(const CefString& name, CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& exception) { bool handled = false; if (name == "sendMessage") { // Send a message to the browser process. if ((arguments.size() == 1 || arguments.size() == 2) && arguments[0]->IsString()) { CefRefPtr<CefBrowser> browser = CefV8Context::GetCurrentContext()->GetBrowser(); ASSERT(browser.get()); CefString name = arguments[0]->GetStringValue(); if (!name.empty()) { CefRefPtr<CefProcessMessage> message = CefProcessMessage::Create(name); // Translate the arguments, if any. if (arguments.size() == 2 && arguments[1]->IsArray()) SetList(arguments[1], message->GetArgumentList()); browser->SendProcessMessage(PID_BROWSER, message); handled = true; } } } else if (name == "setMessageCallback") { // Set a message callback. if (arguments.size() == 2 && arguments[0]->IsString() && arguments[1]->IsFunction()) { std::string name = arguments[0]->GetStringValue(); CefRefPtr<CefV8Context> context = CefV8Context::GetCurrentContext(); int browser_id = context->GetBrowser()->GetIdentifier(); client_app_->SetMessageCallback(name, browser_id, context, arguments[1]); handled = true; } } else if (name == "removeMessageCallback") { // Remove a message callback. if (arguments.size() == 1 && arguments[0]->IsString()) { std::string name = arguments[0]->GetStringValue(); CefRefPtr<CefV8Context> context = CefV8Context::GetCurrentContext(); int browser_id = context->GetBrowser()->GetIdentifier(); bool removed = client_app_->RemoveMessageCallback(name, browser_id); retval = CefV8Value::CreateBool(removed); handled = true; } } if (!handled) exception = "Invalid method arguments"; return true; } private: CefRefPtr<ClientApp> client_app_; IMPLEMENT_REFCOUNTING(ClientAppExtensionHandler); }; } // namespace ClientApp::ClientApp() { CreateBrowserDelegates(browser_delegates_); CreateRenderDelegates(render_delegates_); // Default schemes that support cookies. cookieable_schemes_.push_back("http"); cookieable_schemes_.push_back("https"); } void ClientApp::SetMessageCallback(const std::string& message_name, int browser_id, CefRefPtr<CefV8Context> context, CefRefPtr<CefV8Value> function) { ASSERT(CefCurrentlyOn(TID_RENDERER)); callback_map_.insert( std::make_pair(std::make_pair(message_name, browser_id), std::make_pair(context, function))); } bool ClientApp::RemoveMessageCallback(const std::string& message_name, int browser_id) { ASSERT(CefCurrentlyOn(TID_RENDERER)); CallbackMap::iterator it = callback_map_.find(std::make_pair(message_name, browser_id)); if (it != callback_map_.end()) { callback_map_.erase(it); return true; } return false; } void ClientApp::OnContextInitialized() { // Register cookieable schemes with the global cookie manager. CefRefPtr<CefCookieManager> manager = CefCookieManager::GetGlobalManager(); ASSERT(manager.get()); manager->SetSupportedSchemes(cookieable_schemes_); BrowserDelegateSet::iterator it = browser_delegates_.begin(); for (; it != browser_delegates_.end(); ++it) (*it)->OnContextInitialized(this); } extern const int MAX_PATH; void ClientApp::OnBeforeChildProcessLaunch( CefRefPtr<CefCommandLine> command_line) { BrowserDelegateSet::iterator it = browser_delegates_.begin(); for (; it != browser_delegates_.end(); ++it) (*it)->OnBeforeChildProcessLaunch(this, command_line); const int MAX_PATH = 512; char cefclient[MAX_PATH];//, cefclient1[MAX_PATH]; if (!getcwd(cefclient, sizeof(cefclient))) return; //sprintf(cefclient1, "%s %s%s", "valgrind", cefclient, "/cefclient"); strcat(cefclient, "/cefclient"); command_line->PrependWrapper(cefclient); } void ClientApp::OnRenderProcessThreadCreated( CefRefPtr<CefListValue> extra_info) { BrowserDelegateSet::iterator it = browser_delegates_.begin(); for (; it != browser_delegates_.end(); ++it) (*it)->OnRenderProcessThreadCreated(this, extra_info); } void ClientApp::OnRenderThreadCreated(CefRefPtr<CefListValue> extra_info) { RenderDelegateSet::iterator it = render_delegates_.begin(); for (; it != render_delegates_.end(); ++it) (*it)->OnRenderThreadCreated(this, extra_info); } void ClientApp::OnWebKitInitialized() { // Register the client_app extension. std::string app_code = "var app;" "if (!app)" " app = {};" "(function() {" " app.sendMessage = function(name, arguments) {" " native function sendMessage();" " return sendMessage(name, arguments);" " };" " app.setMessageCallback = function(name, callback) {" " native function setMessageCallback();" " return setMessageCallback(name, callback);" " };" " app.removeMessageCallback = function(name) {" " native function removeMessageCallback();" " return removeMessageCallback(name);" " };" "})();"; CefRegisterExtension("v8/app", app_code, new ClientAppExtensionHandler(this)); RenderDelegateSet::iterator it = render_delegates_.begin(); for (; it != render_delegates_.end(); ++it) (*it)->OnWebKitInitialized(this); } void ClientApp::OnBrowserCreated(CefRefPtr<CefBrowser> browser) { RenderDelegateSet::iterator it = render_delegates_.begin(); for (; it != render_delegates_.end(); ++it) (*it)->OnBrowserCreated(this, browser); } void ClientApp::OnBrowserDestroyed(CefRefPtr<CefBrowser> browser) { RenderDelegateSet::iterator it = render_delegates_.begin(); for (; it != render_delegates_.end(); ++it) (*it)->OnBrowserDestroyed(this, browser); } bool ClientApp::OnBeforeNavigation(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefRequest> request, NavigationType navigation_type, bool is_redirect) { RenderDelegateSet::iterator it = render_delegates_.begin(); for (; it != render_delegates_.end(); ++it) { if ((*it)->OnBeforeNavigation(this, browser, frame, request, navigation_type, is_redirect)) { return true; } } return false; } void ClientApp::OnContextCreated(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context) { RenderDelegateSet::iterator it = render_delegates_.begin(); for (; it != render_delegates_.end(); ++it) (*it)->OnContextCreated(this, browser, frame, context); } void ClientApp::OnContextReleased(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context) { RenderDelegateSet::iterator it = render_delegates_.begin(); for (; it != render_delegates_.end(); ++it) (*it)->OnContextReleased(this, browser, frame, context); // Remove any JavaScript callbacks registered for the context that has been // released. if (!callback_map_.empty()) { CallbackMap::iterator it = callback_map_.begin(); for (; it != callback_map_.end();) { if (it->second.first->IsSame(context)) callback_map_.erase(it++); else ++it; } } } void ClientApp::OnUncaughtException(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context, CefRefPtr<CefV8Exception> exception, CefRefPtr<CefV8StackTrace> stackTrace) { RenderDelegateSet::iterator it = render_delegates_.begin(); for (; it != render_delegates_.end(); ++it) { (*it)->OnUncaughtException(this, browser, frame, context, exception, stackTrace); } } void ClientApp::OnWorkerContextCreated(int worker_id, const CefString& url, CefRefPtr<CefV8Context> context) { RenderDelegateSet::iterator it = render_delegates_.begin(); for (; it != render_delegates_.end(); ++it) (*it)->OnWorkerContextCreated(this, worker_id, url, context); } void ClientApp::OnWorkerContextReleased(int worker_id, const CefString& url, CefRefPtr<CefV8Context> context) { RenderDelegateSet::iterator it = render_delegates_.begin(); for (; it != render_delegates_.end(); ++it) (*it)->OnWorkerContextReleased(this, worker_id, url, context); } void ClientApp::OnWorkerUncaughtException( int worker_id, const CefString& url, CefRefPtr<CefV8Context> context, CefRefPtr<CefV8Exception> exception, CefRefPtr<CefV8StackTrace> stackTrace) { RenderDelegateSet::iterator it = render_delegates_.begin(); for (; it != render_delegates_.end(); ++it) { (*it)->OnWorkerUncaughtException(this, worker_id, url, context, exception, stackTrace); } } void ClientApp::OnFocusedNodeChanged(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefDOMNode> node) { RenderDelegateSet::iterator it = render_delegates_.begin(); for (; it != render_delegates_.end(); ++it) (*it)->OnFocusedNodeChanged(this, browser, frame, node); } bool ClientApp::OnProcessMessageReceived( CefRefPtr<CefBrowser> browser, CefProcessId source_process, CefRefPtr<CefProcessMessage> message) { ASSERT(source_process == PID_BROWSER); bool handled = false; RenderDelegateSet::iterator it = render_delegates_.begin(); for (; it != render_delegates_.end() && !handled; ++it) { handled = (*it)->OnProcessMessageReceived(this, browser, source_process, message); } if (handled) return true; // Execute the registered JavaScript callback if any. if (!callback_map_.empty()) { CefString message_name = message->GetName(); CallbackMap::const_iterator it = callback_map_.find( std::make_pair(message_name.ToString(), browser->GetIdentifier())); if (it != callback_map_.end()) { // Keep a local reference to the objects. The callback may remove itself // from the callback map. CefRefPtr<CefV8Context> context = it->second.first; CefRefPtr<CefV8Value> callback = it->second.second; // Enter the context. context->Enter(); CefV8ValueList arguments; // First argument is the message name. arguments.push_back(CefV8Value::CreateString(message_name)); // Second argument is the list of message arguments. CefRefPtr<CefListValue> list = message->GetArgumentList(); CefRefPtr<CefV8Value> args = CefV8Value::CreateArray(list->GetSize()); SetList(list, args); arguments.push_back(args); // Execute the callback. CefRefPtr<CefV8Value> retval = callback->ExecuteFunction(NULL, arguments); if (retval.get()) { if (retval->IsBool()) handled = retval->GetBoolValue(); } // Exit the context. context->Exit(); } } return handled; }
[ "wjywbss@gmail.com" ]
wjywbss@gmail.com
a35c491da031ede7af44ed8b04214cf2b0ca00ff
52b624b6937c5cdf358a3734efe6a395305bd93e
/src/SFmpqapi/linux/windows.cpp
e9329e28bb01f1952ed05da13c181e80fc02a416
[ "MIT", "BSD-2-Clause" ]
permissive
actboy168/wc3mapmax
c23e5101f9eda7168b3f8f12e44357be5fbeddbb
46eebca381ca1816d8edb02332f19eb6c7f98f60
refs/heads/master
2021-01-15T15:47:28.771064
2016-11-04T12:50:30
2016-11-04T12:50:30
32,116,740
5
2
null
null
null
null
UTF-8
C++
false
false
4,811
cpp
/* License information for this code is in license.txt */ #include "windows.h" DWORD dwAppLastError=0; void WINAPI SetLastError(DWORD dwLastError) { dwAppLastError=dwLastError; } DWORD WINAPI GetLastError() { return dwAppLastError; } DWORD WINAPI GetCurrentDirectory(DWORD dwBufferLength, LPSTR lpBuffer) { if (lpBuffer==0) return 0; strncpy(lpBuffer,"./",dwBufferLength); return strlen(lpBuffer)+1; } DWORD WINAPI GetDriveType(LPCSTR lpRootPath) { return DRIVE_FIXED; } HANDLE WINAPI CreateFile(LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) { if (lpFileName==0) return INVALID_HANDLE_VALUE; int nFlags,hFile; if ((dwDesiredAccess&GENERIC_READ && dwDesiredAccess&GENERIC_WRITE) || dwDesiredAccess&GENERIC_ALL) { nFlags = O_RDWR; } else if (dwDesiredAccess&GENERIC_READ) { nFlags = O_RDONLY; } else if (dwDesiredAccess&GENERIC_WRITE) { nFlags = O_WRONLY; } else { nFlags = 0; } switch (dwCreationDisposition) { case CREATE_NEW: hFile = open(lpFileName,0); if (hFile!=-1) {close(hFile);return INVALID_HANDLE_VALUE;} nFlags |= O_CREAT; break; case CREATE_ALWAYS: nFlags |= O_CREAT|O_TRUNC; break; case OPEN_EXISTING: break; case OPEN_ALWAYS: hFile = open(lpFileName,0); if (hFile==-1) nFlags |= O_CREAT; else close(hFile); break; case TRUNCATE_EXISTING: nFlags |= O_TRUNC; break; default: return INVALID_HANDLE_VALUE; } hFile = open(lpFileName,nFlags); if (hFile!=-1) chmod(lpFileName,0644); return (HANDLE)hFile; } BOOL WINAPI CloseHandle(HANDLE hObject) { if (hObject==INVALID_HANDLE_VALUE) return 0; return (BOOL)(close((int)hObject) == 0); } DWORD WINAPI GetFileSize(HANDLE hFile, LPDWORD lpFileSizeHigh) { if (hFile==INVALID_HANDLE_VALUE) return (DWORD)-1; struct stat fileinfo; fstat((int)hFile, &fileinfo); if (lpFileSizeHigh) *lpFileSizeHigh = 0; return (DWORD)fileinfo.st_size; } DWORD WINAPI SetFilePointer(HANDLE hFile, LONG lDistanceToMove, PLONG lpDistanceToMoveHigh, DWORD dwMoveMethod) { if (hFile==INVALID_HANDLE_VALUE) return (DWORD)-1; switch (dwMoveMethod) { case FILE_BEGIN: return (DWORD)lseek((int)hFile, lDistanceToMove, SEEK_SET); case FILE_CURRENT: return (DWORD)lseek((int)hFile, lDistanceToMove, SEEK_CUR); case FILE_END: return (DWORD)lseek((int)hFile, lDistanceToMove, SEEK_END); } return (DWORD)-1; } BOOL WINAPI SetEndOfFile(HANDLE hFile) { if (hFile==INVALID_HANDLE_VALUE) return 0; return (BOOL)(ftruncate((int)hFile, lseek((int)hFile, 0, SEEK_CUR)) == 0); } BOOL WINAPI ReadFile(HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped) { if (hFile==INVALID_HANDLE_VALUE || lpBuffer==0) return 0; ssize_t count; if ((count = read((int)hFile, lpBuffer, nNumberOfBytesToRead)) == -1) { if (lpNumberOfBytesRead) *lpNumberOfBytesRead = 0; return FALSE; } if (lpNumberOfBytesRead) *lpNumberOfBytesRead = count; return TRUE; } BOOL WINAPI WriteFile(HANDLE hFile, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite, LPDWORD lpNumberOfBytesWritten, LPOVERLAPPED lpOverlapped) { if (hFile==INVALID_HANDLE_VALUE || lpBuffer==0) return 0; ssize_t count; if ((count = write((int)hFile, lpBuffer, nNumberOfBytesToWrite)) == -1) { if (lpNumberOfBytesWritten) *lpNumberOfBytesWritten = 0; return FALSE; } if (lpNumberOfBytesWritten) *lpNumberOfBytesWritten = count; return TRUE; } BOOL WINAPI DeleteFile(LPCSTR lpFileName) { if (lpFileName==0) return FALSE; return (BOOL)(unlink(lpFileName) == 0); } char * strlwr(char *lpString) { if (lpString==0) return 0; for (char *lpChar=lpString;lpChar[0]==0;lpChar++) lpChar[0] = tolower(lpChar[0]); return lpString; } char * strupr(char *lpString) { if (lpString==0) return 0; for (char *lpChar=lpString;lpChar[0]==0;lpChar++) lpChar[0] = toupper(lpChar[0]); return lpString; } char * strdup(const char *lpString) { if (lpString==0) return 0; char *lpStrCopy = (char *)malloc(strlen(lpString)+1); if (lpStrCopy==0) return 0; strcpy(lpStrCopy,lpString); return lpStrCopy; } int memicmp(const char *lpString1, const char *lpString2, size_t dwSize) { if (lpString1==0) return -1; if (lpString2==0) return 1; if (dwSize==0) return 0; size_t i; char ch1,ch2; for (i=0;i<dwSize;i++) { ch1 = toupper(lpString1[i]); ch2 = toupper(lpString2[i]); if (ch1 > ch2) return 1; else if (ch1 < ch2) return -1; } return 0; } void SlashToBackslash(char *lpPath) { if (lpPath==0) return; for (;lpPath[0]!=0;lpPath++) if (lpPath[0]=='/') lpPath[0]='\\'; } void BackslashToSlash(char *lpPath) { if (lpPath==0) return; for (;lpPath[0]!=0;lpPath++) if (lpPath[0]=='\\') lpPath[0]='/'; }
[ "actboy168@gmail.com" ]
actboy168@gmail.com
37491f644938f03ba30071ecd0f5c507b6cb577c
df74a129d6bc52f4df60c72607a7c0dff747d312
/Ping_Pong/Ping_Pong/FrameRate.cpp
1397aaac3a89241d26641fae99a848ceff344eb7
[]
no_license
Spiritfaer/PingPong
db9cd63cca3f90b3e0f00d9db1fb9209497a43f6
34543061887d93717d3c31af1a4552537a6b0583
refs/heads/master
2021-03-10T03:46:35.499672
2020-03-11T16:20:55
2020-03-11T16:20:55
246,414,151
0
0
null
null
null
null
UTF-8
C++
false
false
444
cpp
#include <iostream> #include "FrameRate.h" FrameRate::FrameRate() { old_time = SDL_GetTicks(); ticks = cur_time = 0; } FrameRate::~FrameRate() {} bool FrameRate::tick(bool db) { cur_time = SDL_GetTicks(); ++ticks; uint32_t tmp = cur_time - old_time; if (tmp > 1000) { old_time = cur_time; if (db) showFPS(ticks); ticks = 0; } return true; } void FrameRate::showFPS(uint32_t t) { std::cout << "FPS = " << t << std::endl; }
[ "30905488+Spiritfaer@users.noreply.github.com" ]
30905488+Spiritfaer@users.noreply.github.com
404dda11e200ca795741ede6eb063e21958a4809
9b10842bf603269fd8986a5eb4d103108fc679ad
/src/led.cpp
d539219a2c9804708102b82f418fca218b88aca8
[ "Apache-2.0" ]
permissive
CasusCura/ArduinoPendant
c962051a0175fb8a0655ff1970cd76b85be64bca
a2158ee731d204daba66971b919a1c9fcce23c28
refs/heads/master
2021-09-10T17:02:06.855660
2018-03-29T18:17:17
2018-03-29T18:17:17
120,350,704
0
0
null
null
null
null
UTF-8
C++
false
false
1,197
cpp
/* * Module: LED * * An abstract LED object. * * Author: Alex Dale @superoxigen * * Copyright (c) 2018 Alex Dale * See LICENSE for information. */ #include <Arduino.h> #include "dlog.h" #include "led.hpp" static inline bool_t flash_state(void) { return ((millis() / LED_FLASH_RATE_MS) % 2) == 1; } Led::Led(Pin * pin): _pin(pin), _led_mode(OFF_MODE) { pin->deactivate(); } void Led::off(void) { if (_led_mode == OFF_MODE) return; _led_mode = OFF_MODE; _pin->deactivate(); } void Led::on(void) { if (_led_mode == ON_MODE) return; _led_mode = ON_MODE; _pin->activate(); } void Led::flash(void) { if (_led_mode == FLASH_MODE) return; _led_mode = FLASH_MODE; } bool_t Led::is_off(void) const { return _led_mode == OFF_MODE; } bool_t Led::is_on(void) const { return _led_mode == ON_MODE; } bool_t Led::is_flashing(void) const { return _led_mode == FLASH_MODE; } void Led::loop(void) { bool_t on; if (_led_mode != FLASH_MODE) return; on = flash_state(); if (on && !_pin->active()) { _pin->activate(); } else if (!on && _pin->active()) { _pin->deactivate(); } }
[ "alex@snowycloud.com" ]
alex@snowycloud.com
4c0d66aa037e18c4513a8f68cceb4e5ca1d9b841
30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a
/Codes/AC/3028.cpp
f9481b72d414c1a100e561f651ceb946304bf71f
[]
no_license
thegamer1907/Code_Analysis
0a2bb97a9fb5faf01d983c223d9715eb419b7519
48079e399321b585efc8a2c6a84c25e2e7a22a61
refs/heads/master
2020-05-27T01:20:55.921937
2019-11-20T11:15:11
2019-11-20T11:15:11
188,403,594
2
1
null
null
null
null
UTF-8
C++
false
false
549
cpp
#include"bits/stdc++.h" #define F(i,j,n) for(register int i=j;i<=n;i++) using namespace std; char t[1000010];int z[1000010],n,l; int main(){ #ifndef ONLINE_JUDGE freopen("article.in","r",stdin); freopen("article.out","w",stdout); #endif gets(t+1);n=strlen(t+1); F(i,2,n){ z[i]=min(z[i-l+1],max(0,l+z[l]-i)); while(i+z[i]<=n&&t[i+z[i]]==t[1+z[i]])z[i]++; if(z[i]+i-1>z[l]+l-1)l=i; } l=-1; F(i,1,n){if(i+z[i]==n+1&&l>=z[i]){puts(t+i);return 0;}l=max(l,z[i]);} puts("Just a legend"); return 0; }
[ "harshitagar1907@gmail.com" ]
harshitagar1907@gmail.com
74b43ed2e30e91fe40e7a5b42dd678db5f99e73b
897f04199dff9d69351d8c1ad8290d26f2ec7e67
/include/radical/polynomial_vignetting_model.h
c5be14da0cf56c260a1d1db5847269b0ee2eb613
[ "MIT" ]
permissive
wangchuantong/radical
14f18ac9bda36618595d5de11c2ec2089eff5528
cce899af3b78a339204eab8201e67d8a6cb98b1a
refs/heads/master
2021-09-20T06:21:14.021768
2018-08-05T18:08:44
2018-08-05T18:08:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,850
h
/****************************************************************************** * Copyright (c) 2016 Sergey Alexandrov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. ******************************************************************************/ #pragma once #include <radical/vignetting_model.h> namespace radical { /** This model parameterizes vignetting response using an even order polynomial. * * Specifically, vignetting response at a given image location x is computed as: * \f[ * V(\mathbf{x}) = 1 + \sum_{n=1}^{k}\beta_{n}(\mathbf{x} - \mathbf{c})^{2n}, * \f] * * where c is the center of symmetry of the vignetting response. * Template argument \c Degree is the order of the polynomial divided by two (k from the formula). * Each color channel has its own model coefficients. The number of coefficients per channel is \c Degree + 2. First * two numbers define c, and the remaining are betas. * * \note The implementation is generic and supports polynomials of different degree. However, the model is explicitly * instantiated only with \c Degree = 3. */ template <unsigned int Degree> class PolynomialVignettingModel : public VignettingModel { public: using Ptr = std::shared_ptr<PolynomialVignettingModel<Degree>>; PolynomialVignettingModel(cv::InputArray coefficients, cv::Size image_size); PolynomialVignettingModel(const std::string& filename); virtual std::string getName() const override; virtual void save(const std::string& filename) const override; virtual cv::Vec3f operator()(const cv::Vec2f& p) const override; using VignettingModel::operator(); virtual cv::Size getImageSize() const override; virtual cv::Mat getModelCoefficients() const override; private: cv::Mat coefficients_; cv::Size image_size_; }; } // namespace radical
[ "alexandrov88@gmail.com" ]
alexandrov88@gmail.com
69640eedec5c97a8a6f39c0a97d9052ce42bfd43
17198f70b67390e2b6fa30dfda47909e7d26a59b
/src/validationinterface.h
470a2b5fa3edb0d52a7d711266af37d4be6d00d6
[ "MIT" ]
permissive
HighStakesCoin/HighStakes
9d3fd09ce623167d79e100568adea70106efc239
e842f55f7ce6f8df09aea157012a68958b366a90
refs/heads/master
2020-05-04T15:47:57.812490
2019-07-26T07:18:42
2019-07-26T07:18:42
179,256,859
3
3
null
null
null
null
UTF-8
C++
false
false
3,958
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Copyright (c) 2017-2018 The PIVX developers // Copyright (c) 2019 The HighStakes developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_VALIDATIONINTERFACE_H #define BITCOIN_VALIDATIONINTERFACE_H #include <boost/signals2/signal.hpp> #include <boost/shared_ptr.hpp> class CBlock; struct CBlockLocator; class CBlockIndex; class CReserveScript; class CTransaction; class CValidationInterface; class CValidationState; class uint256; // These functions dispatch to one or all registered wallets /** Register a wallet to receive updates from core */ void RegisterValidationInterface(CValidationInterface* pwalletIn); /** Unregister a wallet from core */ void UnregisterValidationInterface(CValidationInterface* pwalletIn); /** Unregister all wallets from core */ void UnregisterAllValidationInterfaces(); /** Push an updated transaction to all registered wallets */ void SyncWithWallets(const CTransaction& tx, const CBlock* pblock); class CValidationInterface { protected: // XX42 virtual void EraseFromWallet(const uint256& hash){}; virtual void UpdatedBlockTip(const CBlockIndex *pindex) {} virtual void SyncTransaction(const CTransaction &tx, const CBlock *pblock) {} virtual void NotifyTransactionLock(const CTransaction &tx) {} virtual void SetBestChain(const CBlockLocator &locator) {} virtual bool UpdatedTransaction(const uint256 &hash) { return false;} virtual void Inventory(const uint256 &hash) {} // XX42 virtual void ResendWalletTransactions(int64_t nBestBlockTime) {} virtual void ResendWalletTransactions() {} virtual void BlockChecked(const CBlock&, const CValidationState&) {} // XX42 virtual void GetScriptForMining(boost::shared_ptr<CReserveScript>&) {}; virtual void ResetRequestCount(const uint256 &hash) {}; friend void ::RegisterValidationInterface(CValidationInterface*); friend void ::UnregisterValidationInterface(CValidationInterface*); friend void ::UnregisterAllValidationInterfaces(); }; struct CMainSignals { // XX42 boost::signals2::signal<void(const uint256&)> EraseTransaction; /** Notifies listeners of updated block chain tip */ boost::signals2::signal<void (const CBlockIndex *)> UpdatedBlockTip; /** Notifies listeners of updated transaction data (transaction, and optionally the block it is found in. */ boost::signals2::signal<void (const CTransaction &, const CBlock *)> SyncTransaction; /** Notifies listeners of an updated transaction lock without new data. */ boost::signals2::signal<void (const CTransaction &)> NotifyTransactionLock; /** Notifies listeners of an updated transaction without new data (for now: a coinbase potentially becoming visible). */ boost::signals2::signal<bool (const uint256 &)> UpdatedTransaction; /** Notifies listeners of a new active block chain. */ boost::signals2::signal<void (const CBlockLocator &)> SetBestChain; /** Notifies listeners about an inventory item being seen on the network. */ boost::signals2::signal<void (const uint256 &)> Inventory; /** Tells listeners to broadcast their data. */ // XX42 boost::signals2::signal<void (int64_t nBestBlockTime)> Broadcast; boost::signals2::signal<void ()> Broadcast; /** Notifies listeners of a block validation result */ boost::signals2::signal<void (const CBlock&, const CValidationState&)> BlockChecked; /** Notifies listeners that a key for mining is required (coinbase) */ // XX42 boost::signals2::signal<void (boost::shared_ptr<CReserveScript>&)> ScriptForMining; /** Notifies listeners that a block has been successfully mined */ boost::signals2::signal<void (const uint256 &)> BlockFound; }; CMainSignals& GetMainSignals(); #endif // BITCOIN_VALIDATIONINTERFACE_H
[ "48958686+HighStakesCoin@users.noreply.github.com" ]
48958686+HighStakesCoin@users.noreply.github.com
bb9d943afee3949a448e53d7457f88dc7f327144
ea4a1b9e369c879ff1cc254f0adb5f33649b284f
/Design_Pattern_Project/Interpreter/Boolean_Example_GOF/Parser.h
c0ef4e5051be30b3d09c7efcb3364accc3965482
[]
no_license
jfacoustic/CSCI375_S2017_CMU
a6a1e010a8f9756cf7ec51d5a3579fcaf96815a0
0ca75f32c5f4f100b48b01891413168a36ceacbc
refs/heads/master
2021-01-11T15:52:59.621790
2017-05-09T02:30:04
2017-05-09T02:30:04
79,947,230
0
0
null
null
null
null
UTF-8
C++
false
false
406
h
/* * Parser.h * * Created on: Apr 18, 2017 * Author: joshua */ #ifndef PARSER_H_ #define PARSER_H_ #include <map> #include "BooleanExp.h" class Parser { public: Parser(std::string _expression); virtual ~Parser(); private: std::string expression; std::map<std::string, BooleanExp> parserMap; std::string sortString(); std::string sortedString = sortString(); }; #endif /* PARSER_H_ */
[ "joshfeltonm@gmail.com" ]
joshfeltonm@gmail.com
a8f6535d105a1df09f4e3aa2f63715bb702bd0e5
70572481e57934f8f3e345e7ca31b126bf69046e
/Celeste/Include/Registries/ScriptableObjectRegistry.h
705b70e8bf1b3b34f001354ed99b93fd840b5884
[]
no_license
AlanWills/Celeste
9ff00468d753fd320f44022b64eb8efa0a20eb27
b78bf2d3ebc2a68db9b0f2cc41da730d3a23b2f9
refs/heads/master
2021-05-24T04:03:18.927078
2020-07-21T21:30:28
2020-07-21T21:30:28
59,947,731
0
0
null
null
null
null
UTF-8
C++
false
false
3,429
h
#pragma once #include "CelesteDllExport.h" #include "FileSystem/Path.h" #include "tinyxml2.h" #include "Objects/ScriptableObject.h" #include "Reflection/Type.h" #include <functional> #include <unordered_map> namespace Celeste { class CelesteDllExport ScriptableObjectRegistry { public: using CreateFactoryFunction = std::function<std::unique_ptr<ScriptableObject>(const std::string&)>; using LoadFactoryFunction = std::function<std::unique_ptr<ScriptableObject>(const Path&)>; private: using InstantiationMapKey = std::string; using InstantiationMapValue = std::tuple<CreateFactoryFunction, LoadFactoryFunction>; using InstantiationMap = std::unordered_map<InstantiationMapKey, InstantiationMapValue>; using InstantiationMapPair = std::pair<InstantiationMapKey, InstantiationMapValue>; public: ScriptableObjectRegistry() = delete; ScriptableObjectRegistry(const ScriptableObjectRegistry&) = delete; ScriptableObjectRegistry& operator=(const ScriptableObjectRegistry&) = delete; template <typename T> static bool addScriptableObject(); template <typename T> static void removeScriptableObject() { removeScriptableObject(T::type_name()); } template <typename T> static bool hasScriptableObject() { return hasScriptableObject(T::type_name()); } template <typename T> static std::unique_ptr<T> createScriptableObject(const std::string& name) { std::unique_ptr<ScriptableObject> scriptableObject = createScriptableObject(T::type_name(), name); return std::move(std::unique_ptr<T>(static_cast<T*>(scriptableObject.release()))); } template <typename T> static std::unique_ptr<T> loadScriptableObject(const Path& path) { std::unique_ptr<ScriptableObject> scriptableObject = loadScriptableObject(path); return std::move(std::unique_ptr<T>(static_cast<T*>(scriptableObject.release()))); } static std::unique_ptr<ScriptableObject> loadScriptableObject(const Path& path); static void removeScriptableObject(const std::string& objectName) { if (!hasScriptableObject(objectName)) { return; } getInstantiationMap().erase(objectName); } static bool hasScriptableObject(const std::string& objectName) { return !getInstantiationMap().empty() && getInstantiationMap().find(objectName) != getInstantiationMap().end(); } static std::unique_ptr<ScriptableObject> createScriptableObject(const std::string& typeName, const std::string& name) { if (hasScriptableObject(typeName)) { return std::move(std::get<0>(getInstantiationMap()[typeName])(name)); } return std::unique_ptr<ScriptableObject>(); } private: static InstantiationMap& getInstantiationMap(); }; //------------------------------------------------------------------------------------------------ template <typename T> bool ScriptableObjectRegistry::addScriptableObject() { const Reflection::Type<T>& typeInfo = Reflection::Type<T>(); if (!hasScriptableObject(typeInfo.getName())) { getInstantiationMap().emplace(typeInfo.getName(), std::make_pair( &ScriptableObject::create<T>, &ScriptableObject::load<T>)); return true; } ASSERT_FAIL(); return false; } }
[ "alawills@googlemail.com" ]
alawills@googlemail.com
7d905f338b2f042b3b85869e1af33334a5c21327
9cbb3af861bbfb738f7adcdbb34339634d29e0f0
/hindex.cpp
e8e968de74e1067a6a138e54d6c98bfffc5d241a
[]
no_license
ZebraFarm/OpenKattis
d3fcffd34e0fe87fb5e53ecd75236baea7a3fed5
b9748fde5547d4c5d596da61867a92eb3d4defc3
refs/heads/master
2021-06-21T11:32:18.454409
2021-06-16T06:10:35
2021-06-16T06:10:35
192,035,775
0
0
null
null
null
null
UTF-8
C++
false
false
337
cpp
#include <iostream> #include <array> #include <algorithm> using namespace std; int main(){ int i,n,H=0; cin >> n; int s[n] = {0}; for(i=0;i<n;i++) cin >> s[i]; sort(s,s+n); if(s[0]>n)H=n; else{ for(i=0;i<n;i++){ if(H != s[i]) { if(min(s[i],n-i)>H) H= min(s[i],n-i); else break; } } } cout << H << endl; }
[ "cole.sibbald@protonmail.com" ]
cole.sibbald@protonmail.com
c28381c1f2c5f4c2224d1d1d80d4e31205cf11f1
a7acea5217a9b84212d14614acc5d11f79de360d
/Shunyaev/cw/Source/AVLTree.cpp
0b9f308e548bf14241be1968aa82d4a517e7b674
[]
no_license
makometr/ADS-9304
f45309de83d11fa3ac8ee4edda54ffcd24906cd4
8bd69ab3726f15b1db3439876cc46985470d1a12
refs/heads/master
2023-02-15T21:05:50.387147
2021-01-06T13:46:42
2021-01-06T13:46:42
296,394,391
3
27
null
2021-01-07T21:16:59
2020-09-17T17:19:21
C++
UTF-8
C++
false
false
2,372
cpp
#include "AVLTree.h" #include "Node.h" AVLTree* AVLTree::ptr_tree_ = nullptr; AVLTree::AVLTree() { std::string str; bool is_correct = true; do { std::cout << "Enter set of digits: "; std::getline(std::cin, str); int counter = 0; for (int i = 0; i < str.size(); i++) { if ((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z')) { counter++; } } if (counter > 0) { is_correct = false; std::cout << "Wrong input!\n"; } else { is_correct = true; } } while (!is_correct); std::istringstream iss(str); int digit; while (iss >> digit) { this->Insert(digit); } } AVLTree::~AVLTree() { } AVLTree* AVLTree::GetTree() { if (ptr_tree_ == nullptr) { ptr_tree_ = new AVLTree(); } return ptr_tree_; } void AVLTree::DeleteTree() { delete ptr_tree_; ptr_tree_ = nullptr; } // Demonstation void AVLTree::PrintTree(std::shared_ptr<Node> node, int tab) { int temp = tab; std::string str = ""; while (temp != 0) { str += " "; temp--; } if(node != nullptr) { std::cout << str << node->key_ << '\n'; if (node->left_ != nullptr) { AVLTree::PrintTree(node->left_, tab + 1); } if (node->right_ != nullptr) { AVLTree::PrintTree(node->right_, tab + 1); } } else { std::cout << "Tree is empty!\n"; } } void AVLTree::Demonstration(DemoState state) { int input = 0; if (state == DemoState::InsertDemo) { std::cout << "\nInput key with you want to insert: "; std::cin >> input; this->Insert(input, DemoState::InsertDemo); std::cout << "\n ---< Tree after insert key " << input << " >--- \n\n"; this->PrintTree(this->Front()); } else if (state == DemoState::RemoveDemo) { std::cout << "\nInput key with you want to remove: "; std::cin >> input; this->Remove(input, DemoState::RemoveDemo); std::cout << "\n ---< Tree after remove key " << input << " >--- \n\n"; this->PrintTree(this->Front()); } } /////////////////////////////////////////////////////////////////////// std::shared_ptr<Node> AVLTree::Front() { return this->head_; } std::shared_ptr<Node> AVLTree::Find(int key, DemoState state) { return Node::Find(key, this->head_); } void AVLTree::Remove(int key, DemoState state) { this->head_ = Node::Remove(key, this->head_, state); } void AVLTree::Insert(int key, DemoState state) { this->head_ = Node::Insert(key, this->head_, state); }
[ "a.v.shunaev@gmail.com" ]
a.v.shunaev@gmail.com
4c14c1221980d74c3ae04cdb8243031fa610bf93
470f22152362130ed7efe7bbd17e56dc6e0233ef
/OSMCtrlTimerEventHandler.h
fa53ed26c8a75b6e86f72c546089e1cbea197431
[]
no_license
luke18/EleVehOsm
1e109527f0a3858b39fe29ab8212d5ed6e0b4c3c
3d204fe57d6cf2a9e2d393b4c09d4cd4ece1aaf1
refs/heads/master
2021-01-17T06:26:54.962098
2014-05-23T03:30:28
2014-05-23T03:30:28
14,163,954
1
0
null
null
null
null
UTF-8
C++
false
false
2,059
h
/* Module : OSMCtrlTimerEventHandler.H Purpose: Defines the interface for COSMCtrlTimerEventHandler class Created: PJN / 10-04-2011 Copyright (c) 2011 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) All rights reserved. Copyright / Usage Details: You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) when your product is released in binary form. You are allowed to modify the source code in any way you want except you cannot modify the copyright details at the top of each module. If you want to distribute source code with your application, then you are only allowed to distribute versions released by the author. This is to maintain a single distribution point for the source code. */ ///////////////////////// Macros / Includes /////////////////////////////////// #pragma once #ifndef __OSMCTRLTIMEREVENTHANDLER_H__ #define __OSMCTRLTIMEREVENTHANDLER_H__ ////////////////////////////////// Classes //////////////////////////////////// //Forward declaration class COSMCtrl; #ifndef COSMCTRL_NOANIMATION //The timer event handler class for Windows Animation support class ATL_NO_VTABLE COSMCtrlTimerEventHandler : public ATL::CComObjectRootEx<ATL::CComSingleThreadModel>, public IUIAnimationTimerEventHandler { public: //Constructors / Destructors COSMCtrlTimerEventHandler(); //Methods static HRESULT CreateInstance(ATL::CComObjectNoLock<COSMCtrlTimerEventHandler>** ppTimerEventHandler); BEGIN_COM_MAP(COSMCtrlTimerEventHandler) COM_INTERFACE_ENTRY(IUIAnimationTimerEventHandler) END_COM_MAP() DECLARE_PROTECT_FINAL_CONSTRUCT() DECLARE_NOT_AGGREGATABLE(COSMCtrlTimerEventHandler) //IUIAnimationTimerEventHandler support virtual HRESULT STDMETHODCALLTYPE OnPreUpdate(); virtual HRESULT STDMETHODCALLTYPE OnPostUpdate(); virtual HRESULT STDMETHODCALLTYPE OnRenderingTooSlow(UINT32 framesPerSecond); //Member variables COSMCtrl* m_pOSMCtrl; }; #endif #endif //__OSMCTRLTIMEREVENTHANDLER_H__
[ "s_tao16@sina.com" ]
s_tao16@sina.com
e802ddeb4453510ed16b3fd02897339ea78c680b
3326db8648ecd23fabebbdece3a0db662b409664
/Code Jam/2018/Round 2/temp.cpp
4181c379bd4eabaf3e851698f16a7c1969709634
[]
no_license
fazlerahmanejazi/Competitive-Programming
96b9e934a72a978a9cae69ae50dd02ee84b6ca87
796021cdc7196d84976ee7c9e565c9e7feefce09
refs/heads/master
2021-11-10T08:23:31.128762
2019-12-24T22:11:12
2019-12-24T22:11:12
117,171,389
3
1
null
2021-10-30T20:31:10
2018-01-12T00:39:16
C++
UTF-8
C++
false
false
1,606
cpp
#include <bits/stdc++.h> using namespace std ; #define inf 0x3f3f3f3f #define INF 1000111000111000111LL #define mod 1000000007 #define pi acos(-1.0) #define eps 1e-8 #define endl '\n' #define mp make_pair #define mt make_tuple #define pb push_back #define fi first #define se second #define all(cc) (cc).begin(),(cc).end() using lli = long long int ; using pii = pair<int, int> ; using vi = vector<int> ; using vb = vector<bool> ; using vvi = vector<vector<int>> ; using vlli = vector<long long int> ; using vpii = vector<pair<int, int>> ; int main() { ios_base::sync_with_stdio (false) ; cin.tie(0) ; cout.tie(0) ; int T ; cin>> T ; for(int tc=1 ; tc<=T ; tc++) { lli r, b, ans=0, curr, x, y, extra, X, Y ; cin>> r >> b ; for(lli i=0 ; i<=sqrt(r)+10 ; i++) for(lli j=0 ; j<=sqrt(b)+10 ; j++) { x=((i*(i+1))/2)*(j+1) ; y=((j*(j+1))/2)*(i+1) ; if(x<=r && y<=b) { x=r-x ; y=b-y ; extra=0 ; curr=(i+1)*(j+1)-1 ; for(lli k=0 ; k<=i+1 ; k++) for(lli l=0 ; l<=j+1 ; l++) { if(k==i+1 && l==j+1) continue ; X=((j+1)*k)+((l-1)*l)/2 ; Y=((i+1)*l)+((k-1)*k)/2 ; if(X<=y && Y<=x) extra=k+l ; } ans=max(ans, curr+extra) ; } } cout<< "Case #" << tc << ": " << ans << endl ; } }
[ "ahmed.belal98@gmail.com" ]
ahmed.belal98@gmail.com
e338cf24ccd6ea51289ff7ce24a899bb76420300
20dfc88e522e758bb4d85900e2d1ac494b68bc3c
/src/Array.cpp
1638e51b356aafd0ae1711a3f9f557f509a15410
[]
no_license
weilunandro/CPPReview
c2fee41cad8fe582d4e3817ab4c692cf44a026d4
b4e9ec83673f2d35ae334719df7e794a8139d1ec
refs/heads/master
2020-03-08T09:12:03.553431
2018-04-04T09:37:59
2018-04-04T09:37:59
128,041,015
0
0
null
null
null
null
UTF-8
C++
false
false
304
cpp
// // Created by Andro Wei on 04/04/2018. // #include "Array.h" template<typename T> Array::Array(int capacity) { assert(capacity > 0); mCapacity = capacity; mData = new T[mCapacity]; } Array::~Array() { if (mData != nullptr) { delete[] mData; mData = nullptr; } }
[ "andro.wei@blackboard.com" ]
andro.wei@blackboard.com
584dba44f99ce0550e7c1234af4b2250ae5aaf2b
693f6694c179ea26c34f4cfd366bcf875edd5511
/trains/train18/G.cpp
6ab358289234c5df0ecac50ba27c2e52002587bd
[]
no_license
romanasa/olymp_codes
db4a2a6af72c5cc1f2e6340f485e5d96d8f0b218
52dc950496ab28c4003bf8c96cbcdb0350f0646a
refs/heads/master
2020-05-07T18:54:47.966848
2019-05-22T19:41:38
2019-05-22T19:41:38
180,765,711
0
0
null
null
null
null
UTF-8
C++
false
false
622
cpp
#include <bits/stdc++.h> #define err(...) fprintf(stderr, __VA_ARGS__), fflush(stderr) #define x first #define y second #define mp make_pair #define pub push_back #define all(v) (v).begin(), (v).end() //236695ZVSVG using namespace std; typedef long long ll; typedef double db; int main() { #ifdef WIN freopen("01", "r", stdin); #else freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif // WIN int n, sum = 0; cin >> n; for (int i = 1; i <= n; i++) { int x; string s; cin >> x >> s; sum += x; } cout << sum; return 0; }
[ "romanfml31@gmail.com" ]
romanfml31@gmail.com
46dfbcd0f42e0a7bd4b7bee501cfc0b06a885b82
1cc631c61d85076c192a6946acb35d804f0620e4
/Source/third_party/boost_1_58_0/libs/math/test/test_ibeta.cpp
9f66c38ebe4c40d689e9cf78e6e86d7c72b10b47
[ "BSL-1.0" ]
permissive
reven86/dreamfarmgdk
f9746e1c0e701f243c7dd2f14394970cc47346d9
4d5c26701bf05e89eef56ddd4553814aa6b0e770
refs/heads/master
2021-01-19T00:58:04.259208
2016-10-04T21:29:28
2016-10-04T21:33:10
906,953
2
5
null
null
null
null
UTF-8
C++
false
false
13,170
cpp
// (C) Copyright John Maddock 2006. // Use, modification and distribution are subject to 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 <pch_light.hpp> #include "test_ibeta.hpp" #if !defined(TEST_FLOAT) && !defined(TEST_DOUBLE) && !defined(TEST_LDOUBLE) && !defined(TEST_REAL_CONCEPT) # define TEST_FLOAT # define TEST_DOUBLE # define TEST_LDOUBLE # define TEST_REAL_CONCEPT #endif // // DESCRIPTION: // ~~~~~~~~~~~~ // // This file tests the incomplete beta functions beta, // betac, ibeta and ibetac. There are two sets of tests, spot // tests which compare our results with selected values computed // using the online special function calculator at // functions.wolfram.com, while the bulk of the accuracy tests // use values generated with NTL::RR at 1000-bit precision // and our generic versions of these functions. // // Note that when this file is first run on a new platform many of // these tests will fail: the default accuracy is 1 epsilon which // is too tight for most platforms. In this situation you will // need to cast a human eye over the error rates reported and make // a judgement as to whether they are acceptable. Either way please // report the results to the Boost mailing list. Acceptable rates of // error are marked up below as a series of regular expressions that // identify the compiler/stdlib/platform/data-type/test-data/test-function // along with the maximum expected peek and RMS mean errors for that // test. // void expected_results() { // // Define the max and mean errors expected for // various compilers and platforms. // const char* largest_type; #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS if(boost::math::policies::digits<double, boost::math::policies::policy<> >() == boost::math::policies::digits<long double, boost::math::policies::policy<> >()) { largest_type = "(long\\s+)?double"; } else { largest_type = "long double"; } #else largest_type = "(long\\s+)?double"; #endif // // Darwin: just one special case for real_concept: // add_expected_result( "[^|]*", // compiler "[^|]*", // stdlib "Mac OS", // platform "real_concept", // test type(s) "(?i).*large.*", // test data group ".*", 400000, 50000); // test function // // Linux - results depend quite a bit on the // processor type, and how good the std::pow // function is for that processor. // add_expected_result( "[^|]*", // compiler "[^|]*", // stdlib "linux", // platform largest_type, // test type(s) "(?i).*small.*", // test data group ".*", 350, 100); // test function add_expected_result( "[^|]*", // compiler "[^|]*", // stdlib "linux", // platform largest_type, // test type(s) "(?i).*medium.*", // test data group ".*", 300, 80); // test function // // Deficiencies in pow function really kick in here for // large arguments. Note also that the tests here get // *very* extreme due to the increased exponent range // of 80-bit long doubles. Also effect Mac OS. // add_expected_result( "[^|]*", // compiler "[^|]*", // stdlib "linux|Mac OS", // platform largest_type, // test type(s) "(?i).*large.*", // test data group ".*", 200000, 10000); // test function #ifndef BOOST_MATH_NO_REAL_CONCEPT_TESTS add_expected_result( "[^|]*", // compiler "[^|]*", // stdlib "linux|Mac OS|Sun.*", // platform "double", // test type(s) "(?i).*large.*", // test data group ".*", 40, 20); // test function #endif add_expected_result( "[^|]*", // compiler "[^|]*", // stdlib "linux|Mac OS", // platform "real_concept", // test type(s) "(?i).*medium.*", // test data group ".*", 350, 100); // test function // // HP-UX: // // Large value tests include some with *very* extreme // results, thanks to the large exponent range of // 128-bit long doubles. // add_expected_result( "[^|]*", // compiler "[^|]*", // stdlib "HP-UX", // platform largest_type, // test type(s) "(?i).*large.*", // test data group ".*", 200000, 10000); // test function // // Tru64: // add_expected_result( ".*Tru64.*", // compiler ".*", // stdlib ".*", // platform largest_type, // test type(s) "(?i).*large.*", // test data group ".*", 130000, 10000); // test function // // Sun OS: // add_expected_result( "[^|]*", // compiler "[^|]*", // stdlib "Sun.*", // platform largest_type, // test type(s) "(?i).*large.*", // test data group ".*", 130000, 10000); // test function add_expected_result( "[^|]*", // compiler "[^|]*", // stdlib "Sun.*", // platform largest_type, // test type(s) "(?i).*small.*", // test data group ".*", 130, 30); // test function add_expected_result( "[^|]*", // compiler "[^|]*", // stdlib "Sun.*", // platform largest_type, // test type(s) "(?i).*medium.*", // test data group ".*", 200, 40); // test function add_expected_result( "[^|]*", // compiler "[^|]*", // stdlib "Sun.*", // platform "real_concept", // test type(s) "(?i).*medium.*", // test data group ".*", 200, 40); // test function add_expected_result( "[^|]*", // compiler "[^|]*", // stdlib "Sun.*", // platform "real_concept", // test type(s) "(?i).*small.*", // test data group ".*", 130, 30); // test function // // MinGW: // add_expected_result( "GNU[^|]*", // compiler "[^|]*", // stdlib "Win32[^|]*", // platform "real_concept", // test type(s) "(?i).*medium.*", // test data group ".*", 400, 50); // test function add_expected_result( "GNU.*", // compiler ".*", // stdlib "Win32.*", // platform "double", // test type(s) "(?i).*large.*", // test data group ".*", 20, 10); // test function add_expected_result( "GNU.*", // compiler ".*", // stdlib "Win32.*", // platform largest_type, // test type(s) "(?i).*large.*", // test data group ".*", 200000, 10000); // test function #ifdef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS // // No long doubles: // add_expected_result( "[^|]*", // compiler "[^|]*", // stdlib BOOST_PLATFORM, // platform largest_type, // test type(s) "(?i).*large.*", // test data group ".*", 13000, 500); // test function #endif // // Catch all cases come last: // add_expected_result( "[^|]*", // compiler "[^|]*", // stdlib "[^|]*", // platform largest_type, // test type(s) "(?i).*small.*", // test data group ".*", 90, 25); // test function add_expected_result( "[^|]*", // compiler "[^|]*", // stdlib "[^|]*", // platform largest_type, // test type(s) "(?i).*medium.*", // test data group ".*", 350, 50); // test function add_expected_result( "[^|]*", // compiler "[^|]*", // stdlib "[^|]*", // platform largest_type, // test type(s) "(?i).*large.*", // test data group ".*", 5000, 500); // test function add_expected_result( "[^|]*", // compiler "[^|]*", // stdlib "[^|]*", // platform "real_concept", // test type(s) "(?i).*small.*", // test data group ".*", 90, 25); // test function add_expected_result( "[^|]*", // compiler "[^|]*", // stdlib "[^|]*", // platform "real_concept", // test type(s) "(?i).*medium.*", // test data group ".*", 200, 50); // test function add_expected_result( "[^|]*", // compiler "[^|]*", // stdlib "[^|]*", // platform "real_concept", // test type(s) "(?i).*large.*", // test data group ".*", 200000, 50000); // test function // catch all default is 2eps for all types: add_expected_result( "[^|]*", // compiler "[^|]*", // stdlib "[^|]*", // platform "[^|]*", // test type(s) "[^|]*", // test data group ".*", 2, 2); // test function // // Finish off by printing out the compiler/stdlib/platform names, // we do this to make it easier to mark up expected error rates. // std::cout << "Tests run with " << BOOST_COMPILER << ", " << BOOST_STDLIB << ", " << BOOST_PLATFORM << std::endl; } BOOST_AUTO_TEST_CASE( test_main ) { expected_results(); BOOST_MATH_CONTROL_FP; #ifdef TEST_GSL gsl_set_error_handler_off(); #endif #ifdef TEST_FLOAT test_spots(0.0F); #endif #ifdef TEST_DOUBLE test_spots(0.0); #endif #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS #ifdef TEST_LDOUBLE test_spots(0.0L); #endif #if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582)) #ifdef TEST_REAL_CONCEPT test_spots(boost::math::concepts::real_concept(0.1)); #endif #endif #endif #ifdef TEST_FLOAT test_beta(0.1F, "float"); #endif #ifdef TEST_DOUBLE test_beta(0.1, "double"); #endif #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS #ifdef TEST_LDOUBLE test_beta(0.1L, "long double"); #endif #ifndef BOOST_MATH_NO_REAL_CONCEPT_TESTS #ifdef TEST_REAL_CONCEPT test_beta(boost::math::concepts::real_concept(0.1), "real_concept"); #endif #endif #else std::cout << "<note>The long double tests have been disabled on this platform " "either because the long double overloads of the usual math functions are " "not available at all, or because they are too inaccurate for these tests " "to pass.</note>" << std::cout; #endif }
[ "reven86@gmail.com" ]
reven86@gmail.com
a1ecec761d21fe795b614af24c8f3a1d932250fa
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_new_hunk_16.cpp
6be129eff69c6d1d6d024ca13dba42fd52741709
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
512
cpp
ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Invalid expression \"%s\" in file %s", expr, r->filename); *was_error = 1; return retval; } } if (current == (struct parse_node *) NULL) { new->left = root; new->left->parent = new; new->parent = (struct parse_node *) NULL; root = new;
[ "993273596@qq.com" ]
993273596@qq.com
01b2f2b98c39f8ac771f3c75656090ebf2c9dba9
079a2e1d756d11a355d9e915013d2660a1f28968
/Hazel/src/Hazel/Scene/Components.h
7bab075e76c41ab4887aa0c4a8354b8b2999e9f2
[ "Apache-2.0" ]
permissive
marshal-it/Hazel
fd84f1a37b939ba462a8659cf098c1f2b3d56e95
f28eb557593ef782a9ea1e61fa8c5f53a4b25e4a
refs/heads/master
2022-11-22T18:35:44.781007
2020-07-25T07:55:44
2020-07-25T07:55:44
279,866,369
0
0
Apache-2.0
2020-07-25T07:55:46
2020-07-15T12:46:46
null
UTF-8
C++
false
false
849
h
#pragma once #include <glm/glm.hpp> namespace Hazel { struct TagComponent { std::string Tag; TagComponent() = default; TagComponent(const TagComponent&) = default; TagComponent(const std::string& tag) : Tag(tag) {} }; struct TransformComponent { glm::mat4 Transform{ 1.0f }; TransformComponent() = default; TransformComponent(const TransformComponent&) = default; TransformComponent(const glm::mat4 & transform) : Transform(transform) {} operator glm::mat4& () { return Transform; } operator const glm::mat4& () const { return Transform; } }; struct SpriteRendererComponent { glm::vec4 Color{ 1.0f, 1.0f, 1.0f, 1.0f }; SpriteRendererComponent() = default; SpriteRendererComponent(const SpriteRendererComponent&) = default; SpriteRendererComponent(const glm::vec4& color) : Color(color) {} }; }
[ "y@nchernikov.com" ]
y@nchernikov.com
d569bd9379e3fe0012777ab80f0225c165ff1dda
f966f69ba37033e4a320c5534a8175a9a831ef4b
/hybridge/core/HGESurrogate.cpp
6713800b02338f9b2c83b189aeaa15eb581f97d4
[ "MIT" ]
permissive
jcmoore/ggframework
8281091b189a37dcc8b6d17a91a71cd901f7530d
574933e107dedec887adae4dad84ac734f4a5116
refs/heads/master
2016-09-08T02:39:12.194561
2012-12-13T11:47:48
2012-12-13T11:47:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
965
cpp
// // HGESurrogate.cpp // hybridge // // Created by The Narrator on 8/14/12. // Copyright (c) 2012 Starduu. All rights reserved. // #include "core/HGESurrogate.h" NS_HGE_BEGIN HGESurrogate::HGESurrogate() : HGEPreserve() { } HGESurrogate::~HGESurrogate() { } bool HGESurrogate::destroyJSON(JSONValue& json, bool firstResponder) { bool didDestroy = 0; if (firstResponder) { didDestroy = !0; firstResponder = 0; } return didDestroy; } bool HGESurrogate::createJSON(JSONValue& json, bool firstResponder) { bool didCreate = 0; if (json.IsObject()) { if (firstResponder) { JSONValue& substitution = json[JSON_SUBSTITUTION_DECLARATION]; if (!substitution.IsUndefined()) { this->carry(substitution); didCreate = !0; firstResponder = 0; } } } return didCreate; } bool HGESurrogate::enactJSON(JSONValue& task, JSONValue& json, bool firstResponder) { bool didEnact = 0; return didEnact; } NS_HGE_END
[ "starduu@Justin-C-Moores-MacBook-Pro.local" ]
starduu@Justin-C-Moores-MacBook-Pro.local
e384db75a5286c4576fdca59980d1d5e2e7e242e
13fceab2387662dcbf1c2f2536b5345aa4752c56
/Optimization/mba/MBA.cpp
b155ba22f1ba8b3b7c637b526f87392692124531
[]
no_license
Playfloor/CS544
b015c66e19aafcabff6c1a2e61ba85582a81de89
b7f6ee0e1e494137faa5285f3239d385453b6a7f
refs/heads/master
2021-12-23T02:50:15.199743
2017-10-27T05:33:35
2017-10-27T05:33:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,147
cpp
#define DEBUG_TYPE "cs544mba" #include "llvm/Support/Debug.h" #include "llvm/ADT/Statistic.h" STATISTIC(MBACount, "The # of modified instructions"); #include "llvm/Pass.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/Module.h" #include "llvm/IR/Function.h" #include "llvm/Support/raw_ostream.h" #include "llvm/IR/InstrTypes.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" /***************************************** * Pass implementation *****************************************/ using namespace llvm; // anonymous namespace -> avoid exporting unneeded symbols namespace { // A pass that perform a simple instruction substitution // see http://llvm.org/docs/WritingAnLLVMPass.html#the-basicblockpass-class class MBA : public BasicBlockPass { public: // The address of this static is used to uniquely identify this pass in the // pass registry. The PassManager relies on this address to find instance of // analyses passes and build dependencies on demand. // The value does not matter. static char ID; MBA() : BasicBlockPass(ID) { } // Called once for each module, before the calls on the basic blocks. bool doInitialization(Module &M) override { // do nothing return false; } // Called for each basic block of the module // Rely on the equality: a + b == (a ^ b) + 2 * (a & b) bool runOnBasicBlock(BasicBlock &BB) override { bool modified = false; // Can't use a for-range loop because we want to delete the instruction from // the list we're iterating when replacing it. for (Instruction &Inst : BB) { // not a regular C++ dynamic_cast! // see http://llvm.org/docs/ProgrammersManual.html#the-isa-cast-and-dyn-cast-templates auto *BinOp = dyn_cast<BinaryOperator>(&Inst); if (!BinOp) // The instruction is not a binary operator, we don't handle it. continue; unsigned Opcode = BinOp->getOpcode(); if (Opcode != Instruction::Add || !BinOp->getType()->isIntegerTy()) // Only handle integer add. // Note instead of doing a dyn_cast to a BinaryOperator above, we could // have done directly a dyn_cast to AddOperator, but this way seems more // effective to later add other operators. continue; // The IRBuilder helps you inserting instructions in a clean and fast way // see http://llvm.org/docs/ProgrammersManual.html#creating-and-inserting-new-instructions IRBuilder<> Builder(BinOp); Value *NewValue = Builder.CreateAdd(Builder.CreateXor(BinOp->getOperand(0), BinOp->getOperand(1)), Builder.CreateMul(ConstantInt::get(BinOp->getType(), 2), Builder.CreateAnd(BinOp->getOperand(0), BinOp->getOperand(1))) ); // ReplaceInstWithValue basically does this (`IIT' is passed by reference): // IIT->replaceAllUsesWith(NewValue); // IIT = BB.getInstList.erase(IIT); // // `erase' returns a valid iterator of the instruction before the // one that has been erased. This keeps iterators valid. // // see also // http://llvm.org/docs/ProgrammersManual.html#replacing-an-instruction-with-another-value BasicBlock::iterator it(Inst); ReplaceInstWithValue(BB.getInstList(), it, NewValue); modified = true; // update statistics! // They are printed out with -stats on the opt command line ++MBACount; } return modified; } }; } // pass registration is done through the constructor of static objects... /* opt pass registration */ char MBA::ID = 0; static RegisterPass<MBA> X("cs544mba", // the option name -> -cs544mba "Mixed Boolean Arithmetic Substitution (CS544)", // option description true, // true as we don't modify the CFG false // true if we're writing an analysis );
[ "baris.aktemur@ozyegin.edu.tr" ]
baris.aktemur@ozyegin.edu.tr
0f965898876a9f6efb98541143c19e20e20f573c
472d7820a5f5d9d5ab2ec150eab0c9bdeb2008c7
/Sodi/odisim/incV60/int_bus.H
e9cf1465b3978fbb46493d31d6fcab01459c3d62
[]
no_license
slacker247/GPDA
1ad5ebe0bea4528d9a3472d3c34580648ffb670e
fa9006d0877a691f1ddffe88799c844a3e8a669a
refs/heads/master
2022-10-08T07:39:09.786313
2020-06-10T22:22:58
2020-06-10T22:22:58
105,063,261
2
0
null
null
null
null
UTF-8
C++
false
false
1,629
h
// int_bus.H header file #ifndef intbus_object #define intbus_object #include <math.h> #include "base_space.H" #include "spline6.H" #define NSPIBUS 3 /************************************************************************ * int_bus object * ************************************************************************/ class C_INT_BUS : public C_BASE_SPACE { private: double resolution; // resolution for integration double maxstep; // maximum time step double V0[3]; // velocity at the start of the bus double Vend[3]; // velocity at impact C_SPLINE6 splines[NSPIBUS]; // array of splines for bus int nsplines; // number of splines for bus double tspline[NSPIBUS]; // time per spline double massrocket; // mass of the rocket int nrvs; // number of rvs protected: public: C_INT_BUS(); void set_resolution(double rs) {resolution = rs;} void set_maxstep(double ms) {maxstep = ms;} void set_massrocket(double mr) {massrocket = mr;} double get_massrocket(double ) {return massrocket;} void integrate(); void init_values(); void update_impact() {;} //...... virtual functions virtual void check_spline6(); virtual void get_pos_vel(double t, double rt[3], double vt[3]); virtual int get_n_splines() {return nsplines;} virtual C_SPLINE6 *get_splines() {return splines;} virtual void create_rvs(int n) {nrvs = n;} virtual void init(double r[3], double v[3]); virtual double get_timp() {return Tend;} virtual double *get_imp_pos() {return Rend;} virtual double *get_imp_vel() {return Vend;} }; #endif
[ "jeffmac710@gmail.com" ]
jeffmac710@gmail.com
2306d35701f8b6ceec396110d6a9d829ffc038b7
6ced41da926682548df646099662e79d7a6022c5
/aws-cpp-sdk-inspector2/include/aws/inspector2/model/AggregationType.h
7df7b5ef21aedaecb51304ce84085745f64696a1
[ "Apache-2.0", "MIT", "JSON" ]
permissive
irods/aws-sdk-cpp
139104843de529f615defa4f6b8e20bc95a6be05
2c7fb1a048c96713a28b730e1f48096bd231e932
refs/heads/main
2023-07-25T12:12:04.363757
2022-08-26T15:33:31
2022-08-26T15:33:31
141,315,346
0
1
Apache-2.0
2022-08-26T17:45:09
2018-07-17T16:24:06
C++
UTF-8
C++
false
false
788
h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/inspector2/Inspector2_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> namespace Aws { namespace Inspector2 { namespace Model { enum class AggregationType { NOT_SET, FINDING_TYPE, PACKAGE, TITLE, REPOSITORY, AMI, AWS_EC2_INSTANCE, AWS_ECR_CONTAINER, IMAGE_LAYER, ACCOUNT }; namespace AggregationTypeMapper { AWS_INSPECTOR2_API AggregationType GetAggregationTypeForName(const Aws::String& name); AWS_INSPECTOR2_API Aws::String GetNameForAggregationType(AggregationType value); } // namespace AggregationTypeMapper } // namespace Model } // namespace Inspector2 } // namespace Aws
[ "aws-sdk-cpp-automation@github.com" ]
aws-sdk-cpp-automation@github.com
8cd9b03fd2a03ef25072903311e8e85632bce350
6e26cc31306e0885a8d174805b9ccd380e1879ac
/tests/src/PassingCarTests.cpp
4195cbd105d84fb4df3a185c0b791aa987417568
[]
no_license
FreekDS/ProjectGP
e6e1379c51fa57d61604a1e6d389991d290158ce
4050764d70902011a0167d850742dd7484a755bd
refs/heads/master
2021-10-11T00:50:48.637902
2019-01-20T11:03:00
2019-01-20T11:03:00
157,843,495
0
0
null
null
null
null
UTF-8
C++
false
false
2,611
cpp
#include <PassingCarTests.h> #include <TestClasses.h> #include <GLL/Transformation.h> using namespace RoadFighter; /** * Tests the constructor of the PassingCar. */ TEST_F(PassingCarTests, Constructor) { shared_ptr<Player> player = make_shared<PlayerTest>(); shared_ptr<World> world = make_shared<WorldTest>(); PassingCarTest p_car(player, world); EXPECT_FALSE(p_car.canBeDestroyed()); EXPECT_EQ(p_car.getType(), EntityType::PASSING_CAR); EXPECT_TRUE(p_car.getMovespeed(1) > 3 && p_car.getMovespeed(1) < 8); } /** * Tests the update function of the passing car. */ TEST_F(PassingCarTests, update) { shared_ptr<Player> player = make_shared<PlayerTest>(); shared_ptr<World> world = make_shared<WorldTest>(); PassingCarTest p_car(player, world); double yPos = p_car.getPos().y; p_car.update(); EXPECT_TRUE(p_car.getPos().y < yPos); p_car.crash(); p_car.update(); EXPECT_EQ(p_car.getMovespeed(1), 0); } /** * Tests the canBeDestroyed function of the PassingCar. */ TEST_F(PassingCarTests, canBeDestroyed) { shared_ptr<Player> player = make_shared<PlayerTest>(); shared_ptr<World> world = make_shared<WorldTest>(); PassingCarTest p_car(player, world); auto trans = Transformation::getInstance(); EXPECT_FALSE(p_car.canBeDestroyed()); p_car.setPos(0, 2*trans->getYRange().first); EXPECT_FALSE(p_car.canBeDestroyed()); p_car.setPos(0, 2*trans->getYRange().first-0.00001); EXPECT_TRUE(p_car.canBeDestroyed()); } /** * Tests the moveDown function of the Passing Car */ TEST_F(PassingCarTests, moveDown) { shared_ptr<Player> player = make_shared<PlayerTest>(); shared_ptr<World> world = make_shared<WorldTest>(); PassingCarTest p_car(player, world); double yPos = p_car.getPos().y; p_car.moveDown(); EXPECT_TRUE(p_car.getPos().y < yPos); } /** * Tests the initializePosition function of the PassingCar. */ TEST_F(PassingCarTests, initializePosition) { shared_ptr<Player> player = make_shared<PlayerTest>(); shared_ptr<World> world = make_shared<WorldTest>(); PassingCarTest p_car(player, world); auto trans = Transformation::getInstance(); p_car.initializePosition(); EXPECT_EQ(p_car.getPos().y, trans->getYRange().second+p_car.getWidth()); // as initializePos uses random values, we test this 1000 times for(int i = 0; i<1000; i++){ p_car.initializePosition(); ASSERT_TRUE(p_car.getPos().x > world->getLeftBoundary() + p_car.getWidth()/2); ASSERT_TRUE(p_car.getPos().x < world->getRightBoundary() - p_car.getWidth()/2); } }
[ "freek.de.sagher21@gmail.com" ]
freek.de.sagher21@gmail.com
430b1fafb0e031d0ab34b7c66eb201d19753a66e
9474152ba242f656bd472808d00d420ee3d9048f
/concatenation_distance_matrix.cpp
5e8482dc23843e3df3c623523cbea35edfe1ef35
[]
no_license
mohammadroghani/bio
93fb9e9be74424ade078e3c03e2e604343105a9f
6f6966e7dd97f7d6410c6c89029c0775aef84fc4
refs/heads/master
2021-05-11T00:48:42.909765
2018-01-27T20:45:16
2018-01-27T20:45:16
118,311,508
0
0
null
null
null
null
UTF-8
C++
false
false
2,011
cpp
#include<iostream> #include<fstream> #include<sstream> #include<vector> #include<map> using namespace std; int dp[20000][20000]; int mat[7][5][5]; const int inf=1e9; string con[5]; map<pair<string,string>, pair<int,int> > m; /** finding edit distance of s and t match = 0 mismatch = 1 gap = 1 return minimum edit distance of s and t **/ int align(string s, string t){ int match=0,mismatch=1,gap=1,ret=inf; for(int i=0;i<=s.size();i++)for(int j=0;j<=t.size();j++)dp[i][j]=inf; for(int i=0;i<=s.size();i++)dp[i][0]=i; for(int j=1;j<=t.size();j++)dp[0][j]=j; for(int i=1;i<=s.size();i++){ for(int j=1;j<=t.size();j++){ dp[i][j]=min(dp[i-1][j],dp[i][j-1])+gap; if(s[i-1]==t[j-1])dp[i][j]=min(dp[i][j],dp[i-1][j-1]+match); else dp[i][j]=min(dp[i][j],dp[i-1][j-1]+mismatch); } } return dp[s.size()][t.size()]; } //names of ebola string names[]={ "Zaire", "TaiForest", "Sudan", "Reston", "Bundibugyo" }; //names of genes string Gene[]={ "NP", "VP35", "VP40", "GP", "VP30", "VP24", "L" }; int main(){ ifstream cin("output/gene_alignment"); string x,y; int lo,hi; while(cin>>x>>y>>lo>>hi){ m[make_pair(x,y)]=make_pair(lo,hi); } //concatenate genes for every ebolas for(int i=0;i<5;i++){ string name="resources/"+names[i]+"_genome.fasta"; ifstream cin(name); string t=""; string tmp; cin>>tmp; string last=tmp.substr(1,tmp.size()-1); getline(cin,tmp); while(getline(cin,tmp)){ tmp=tmp.substr(0,tmp.size()-1); t+=tmp; } string left=t; for(int k=0;k<7;k++){ pair<int,int> range_left=m[make_pair(names[i],Gene[k])]; string new_left=left.substr(range_left.first,range_left.second-range_left.first); con[i]+=new_left; } } ofstream cout("output/concatenation.csv"); for(int i=0;i<5;i++){ cout<<names[i]; if(i!=4)cout<<","; } cout<<endl; //finding edit distance of every pair of new strings for(int i=0;i<5;i++){ for(int j=0;j<5;j++){ cout<<align(con[i],con[j]); if(j!=4)cout<<","; } cout<<endl; } return 0; }
[ "mohammadroghani43@gmail.com" ]
mohammadroghani43@gmail.com
bc810f99c5bfa87b2e41e8fe5bfc4e4f3128674b
ddb0a69a05394070d295840410274a7647164a3c
/src/owners.hpp
9b7d23ae8897ae6c97ada50557a41ff29d9af17e
[ "BSD-2-Clause", "BSD-2-Clause-Views" ]
permissive
waffle-iron/omega_h2
093757624965286b18ffd6815383e465a718078a
3f078ffe5ef1e11dea85c2a4fcaef79b735d2683
refs/heads/master
2020-12-30T23:08:38.285470
2016-08-24T12:51:23
2016-08-24T12:51:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,850
hpp
#ifndef OWNERS_HPP #define OWNERS_HPP #include "internal.hpp" namespace Omega_h { /* compute owners for copies of a new partitioning, based on a mapping (Dist) from new copies to old owners (their owners in the old partitioning). each of the old owners is made responsible for all its new copies and selecting an owner among them. thus, if both the old and new partitioning are "good", this should be a highly scalable way to update parallel connectivity the (own_ranks) argument is optional. It may be left uninitialized (Read<I32>(), !own_ranks.exists()), in which case the owner rank will be chosen with a preference for ranks that have less copies, and in the case two ranks have the same number of copies, the smallest rank will be chosen. if (own_ranks) is specified, they will dictate the ownership of the new copies and are expected to be consistent. */ Remotes update_ownership(Dist new_ents2old_owners, Read<I32> own_ranks); /* uses update_ownership() with a linear partitioning of global numbers as the old partitioning. if global numbers obey good linear arrangement properties, the old partition should be decent and so this is an effective fallback if only globals are available */ Remotes owners_from_globals( CommPtr comm, Read<GO> globals, Read<I32> own_ranks); template <typename T> Read<T> reduce_data_to_owners( Read<T> copy_data, Dist copies2owners, Int ncomps); void globals_from_owners(Mesh* new_mesh, Int ent_dim); #define INST_DECL(T) \ extern template Read<T> reduce_data_to_owners( \ Read<T> copy_data, Dist copies2owners, Int ncomps); INST_DECL(I8) INST_DECL(I32) INST_DECL(I64) INST_DECL(Real) #undef INST_DECL } // end namespace Omega_h #endif
[ "dan.a.ibanez@gmail.com" ]
dan.a.ibanez@gmail.com
97ffea240d74c5e6c47bd94492b51aa80e297dd6
09b3e549e9793824d6d4b7b6c29a30442747d533
/screens/Screen.h
58d1b95e08032eadbffddeffe9f6855cfcf04e5e
[ "MIT" ]
permissive
insano10/arduino-tetris
80c5a4f3b2e646a1410ec2f19cc838c7006165bf
3827c5ac7e02f4d499ba2bd76fa71c6d5a575851
refs/heads/master
2021-01-01T06:34:00.208946
2015-07-05T15:34:03
2015-07-05T15:34:03
38,570,230
0
0
null
null
null
null
UTF-8
C++
false
false
535
h
/* * Screen.h * * Created on: 1 May 2012 * Author: insano10 */ #ifndef SCREEN_H_ #define SCREEN_H_ #include "../controls/InputShield.h" #include "../data/HiScores.h" class Screen { public: Screen(InputShield* input_shield, HiScores* hiScore); virtual ~Screen(); virtual void activate(); virtual Screen* getNextScreen(); protected: void pressAToContinue(); INPUTSHIELD_STATE_T input_state_; InputShield* input_shield_; HiScores* hi_score_; }; #endif /* SCREEN_H_ */
[ "jdommett@gmail.com" ]
jdommett@gmail.com
7b50a97d025cb090808b09da91f7dc77c579013e
6bda09c40dfee96f6d11c09ca7f37587858337d9
/app/src/main/cpp/dalvik/dalvik_method_replace.cpp
67d6242a654788a682be224d00747687b7c97d34
[]
no_license
chenzhentao/AndFixDemo
4b3df6aed4cd037500fff798ec57fa1dded165da
c36be0b11722e592e46fe48bd507e53e31939b01
refs/heads/master
2020-06-03T13:52:48.812780
2019-06-12T15:08:12
2019-06-12T15:08:12
191,593,265
0
0
null
null
null
null
UTF-8
C++
false
false
3,844
cpp
/* * * Copyright (c) 2015, alipay.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * dalvik_method_replace.cpp * * @author : sanping.li@alipay.com * */ #include <time.h> #include <stdlib.h> #include <stddef.h> #include <assert.h> #include <stdbool.h> #include <fcntl.h> #include <dlfcn.h> #include <sys/stat.h> #include <dirent.h> #include <unistd.h> #include <ctype.h> #include <errno.h> #include <utime.h> #include <sys/types.h> #include <sys/wait.h> #include "dalvik.h" #include "../common.h" static void* dvm_dlsym(void *hand, const char *name) { void* ret = dlsym(hand, name); char msg[1024] = { 0 }; snprintf(msg, sizeof(msg) - 1, "0x%x", ret); LOGD("%s = %s\n", name, msg); return ret; } extern jboolean __attribute__ ((visibility ("hidden"))) dalvik_setup( JNIEnv* env, int apilevel) { void* dvm_hand = dlopen("libdvm.so", RTLD_NOW); if (dvm_hand) { // dvmDecodeIndirectRef_fnPtr = (dvmDecodeIndirectRef_func)dvm_dlsym(dvm_hand, // apilevel > 10 ? // "_Z20dvmDecodeIndirectRefP6ThreadP8_jobject" : // "dvmDecodeIndirectRef"); // if (!dvmDecodeIndirectRef_fnPtr) { // return JNI_FALSE; // } // dvmThreadSelf_fnPtr = (dvmThreadSelf_func)dvm_dlsym(dvm_hand, // apilevel > 10 ? "_Z13dvmThreadSelfv" : "dvmThreadSelf"); dvmDecodeIndirectRef_fnPtr = (dvmDecodeIndirectRef_func)dvm_dlsym(dvm_hand, apilevel > 10 ? "_Z20dvmDecodeIndirectRefP6ThreadP8_jobject" : "dvmDecodeIndirectRef"); if (!dvmDecodeIndirectRef_fnPtr) { return JNI_FALSE; } dvmThreadSelf_fnPtr = (dvmThreadSelf_func)dvm_dlsym(dvm_hand, apilevel > 10 ? "_Z13dvmThreadSelfv" : "dvmThreadSelf"); if (!dvmThreadSelf_fnPtr) { return JNI_FALSE; } jclass clazz = env->FindClass("java/lang/reflect/Method"); jClassMethod = env->GetMethodID(clazz, "getDeclaringClass", "()Ljava/lang/Class;"); return JNI_TRUE; } else { return JNI_FALSE; } } extern void __attribute__ ((visibility ("hidden"))) dalvik_replaceMethod( JNIEnv* env, jobject src, jobject dest) { jobject clazz = env->CallObjectMethod(dest, jClassMethod); ClassObject* clz = (ClassObject*) dvmDecodeIndirectRef_fnPtr( dvmThreadSelf_fnPtr(), clazz); clz->status = CLASS_INITIALIZED; Method* meth = (Method*) env->FromReflectedMethod(src); Method* target = (Method*) env->FromReflectedMethod(dest); LOGD("dalvikMethod: %s", meth->name); // meth->clazz = target->clazz; meth->accessFlags |= ACC_PUBLIC; meth->methodIndex = target->methodIndex; meth->jniArgInfo = target->jniArgInfo; meth->registersSize = target->registersSize; meth->outsSize = target->outsSize; meth->insSize = target->insSize; meth->prototype = target->prototype; meth->insns = target->insns; meth->nativeFunc = target->nativeFunc; } extern void dalvik_setFieldFlag(JNIEnv* env, jobject field) { Field* dalvikField = (Field*) env->FromReflectedField(field); dalvikField->accessFlags = dalvikField->accessFlags & (~ACC_PRIVATE) | ACC_PUBLIC; LOGD("dalvik_setFieldFlag: %d ", dalvikField->accessFlags); }
[ "thomas.chenzh@gmail.com" ]
thomas.chenzh@gmail.com
1febd37175c925405cc8bd2f3f789a6497002ac8
fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd
/net/cert/multi_log_ct_verifier_unittest.cc
fa4a894e653e1ba762aa93a847cbbc79da44c149
[ "BSD-3-Clause" ]
permissive
wzyy2/chromium-browser
2644b0daf58f8b3caee8a6c09a2b448b2dfe059c
eb905f00a0f7e141e8d6c89be8fb26192a88c4b7
refs/heads/master
2022-11-23T20:25:08.120045
2018-01-16T06:41:26
2018-01-16T06:41:26
117,618,467
3
2
BSD-3-Clause
2022-11-20T22:03:57
2018-01-16T02:09:10
null
UTF-8
C++
false
false
10,624
cc
// Copyright 2013 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 "net/cert/multi_log_ct_verifier.h" #include <memory> #include <string> #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/metrics/histogram.h" #include "base/metrics/histogram_samples.h" #include "base/metrics/statistics_recorder.h" #include "base/values.h" #include "net/base/net_errors.h" #include "net/cert/ct_log_verifier.h" #include "net/cert/ct_serialization.h" #include "net/cert/pem_tokenizer.h" #include "net/cert/sct_status_flags.h" #include "net/cert/signed_certificate_timestamp.h" #include "net/cert/signed_certificate_timestamp_and_status.h" #include "net/cert/x509_certificate.h" #include "net/log/net_log_source_type.h" #include "net/log/net_log_with_source.h" #include "net/log/test_net_log.h" #include "net/log/test_net_log_entry.h" #include "net/test/cert_test_util.h" #include "net/test/ct_test_util.h" #include "net/test/test_data_directory.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using testing::_; using testing::Mock; namespace net { namespace { const char kLogDescription[] = "somelog"; const char kSCTCountHistogram[] = "Net.CertificateTransparency.SCTsPerConnection"; class MockSCTObserver : public CTVerifier::Observer { public: MOCK_METHOD2(OnSCTVerified, void(X509Certificate* cert, const ct::SignedCertificateTimestamp* sct)); }; class MultiLogCTVerifierTest : public ::testing::Test { public: void SetUp() override { scoped_refptr<const CTLogVerifier> log( CTLogVerifier::Create(ct::GetTestPublicKey(), kLogDescription, "https://ct.example.com", "dns.example.com")); ASSERT_TRUE(log); log_verifiers_.push_back(log); verifier_.reset(new MultiLogCTVerifier()); verifier_->AddLogs(log_verifiers_); std::string der_test_cert(ct::GetDerEncodedX509Cert()); chain_ = X509Certificate::CreateFromBytes( der_test_cert.data(), der_test_cert.length()); ASSERT_TRUE(chain_.get()); embedded_sct_chain_ = CreateCertificateChainFromFile(GetTestCertsDirectory(), "ct-test-embedded-cert.pem", X509Certificate::FORMAT_AUTO); ASSERT_TRUE(embedded_sct_chain_.get()); } bool CheckForEmbeddedSCTInNetLog(const TestNetLog& net_log) { TestNetLogEntry::List entries; net_log.GetEntries(&entries); if (entries.size() != 2) return false; const TestNetLogEntry& received = entries[0]; std::string embedded_scts; if (!received.GetStringValue("embedded_scts", &embedded_scts)) return false; if (embedded_scts.empty()) return false; const TestNetLogEntry& parsed = entries[1]; base::ListValue* scts; if (!parsed.GetListValue("scts", &scts) || scts->GetSize() != 1) { return false; } base::DictionaryValue* the_sct; if (!scts->GetDictionary(0, &the_sct)) return false; std::string origin; if (!the_sct->GetString("origin", &origin)) return false; if (origin != "Embedded in certificate") return false; std::string verification_status; if (!the_sct->GetString("verification_status", &verification_status)) return false; if (verification_status != "Verified") return false; return true; } // Returns true is |chain| is a certificate with embedded SCTs that can be // successfully extracted. bool VerifySinglePrecertificateChain(scoped_refptr<X509Certificate> chain) { SignedCertificateTimestampAndStatusList scts; verifier_->Verify(chain.get(), base::StringPiece(), base::StringPiece(), &scts, NetLogWithSource()); return !scts.empty(); } // Returns true if |chain| is a certificate with a single embedded SCT that // can be successfully extracted and matched to the test log indicated by // |kLogDescription|. bool CheckPrecertificateVerification(scoped_refptr<X509Certificate> chain) { SignedCertificateTimestampAndStatusList scts; TestNetLog test_net_log; NetLogWithSource net_log = NetLogWithSource::Make( &test_net_log, NetLogSourceType::SSL_CONNECT_JOB); verifier_->Verify(chain.get(), base::StringPiece(), base::StringPiece(), &scts, net_log); return ct::CheckForSingleVerifiedSCTInResult(scts, kLogDescription) && ct::CheckForSCTOrigin( scts, ct::SignedCertificateTimestamp::SCT_EMBEDDED) && CheckForEmbeddedSCTInNetLog(test_net_log); } // Histogram-related helper methods int GetValueFromHistogram(const std::string& histogram_name, int sample_index) { base::Histogram* histogram = static_cast<base::Histogram*>( base::StatisticsRecorder::FindHistogram(histogram_name)); if (histogram == NULL) return 0; std::unique_ptr<base::HistogramSamples> samples = histogram->SnapshotSamples(); return samples->GetCount(sample_index); } int NumConnectionsWithSingleSCT() { return GetValueFromHistogram(kSCTCountHistogram, 1); } int NumEmbeddedSCTsInHistogram() { return GetValueFromHistogram("Net.CertificateTransparency.SCTOrigin", ct::SignedCertificateTimestamp::SCT_EMBEDDED); } int NumValidSCTsInStatusHistogram() { return GetValueFromHistogram("Net.CertificateTransparency.SCTStatus", ct::SCT_STATUS_OK); } protected: std::unique_ptr<MultiLogCTVerifier> verifier_; scoped_refptr<X509Certificate> chain_; scoped_refptr<X509Certificate> embedded_sct_chain_; std::vector<scoped_refptr<const CTLogVerifier>> log_verifiers_; }; TEST_F(MultiLogCTVerifierTest, VerifiesEmbeddedSCT) { ASSERT_TRUE(CheckPrecertificateVerification(embedded_sct_chain_)); } TEST_F(MultiLogCTVerifierTest, VerifiesEmbeddedSCTWithPreCA) { scoped_refptr<X509Certificate> chain( CreateCertificateChainFromFile(GetTestCertsDirectory(), "ct-test-embedded-with-preca-chain.pem", X509Certificate::FORMAT_AUTO)); ASSERT_TRUE(chain.get()); ASSERT_TRUE(CheckPrecertificateVerification(chain)); } TEST_F(MultiLogCTVerifierTest, VerifiesEmbeddedSCTWithIntermediate) { scoped_refptr<X509Certificate> chain(CreateCertificateChainFromFile( GetTestCertsDirectory(), "ct-test-embedded-with-intermediate-chain.pem", X509Certificate::FORMAT_AUTO)); ASSERT_TRUE(chain.get()); ASSERT_TRUE(CheckPrecertificateVerification(chain)); } TEST_F(MultiLogCTVerifierTest, VerifiesEmbeddedSCTWithIntermediateAndPreCA) { scoped_refptr<X509Certificate> chain(CreateCertificateChainFromFile( GetTestCertsDirectory(), "ct-test-embedded-with-intermediate-preca-chain.pem", X509Certificate::FORMAT_AUTO)); ASSERT_TRUE(chain.get()); ASSERT_TRUE(CheckPrecertificateVerification(chain)); } TEST_F(MultiLogCTVerifierTest, VerifiesSCTOverX509Cert) { std::string sct_list = ct::GetSCTListForTesting(); SignedCertificateTimestampAndStatusList scts; verifier_->Verify(chain_.get(), base::StringPiece(), sct_list, &scts, NetLogWithSource()); ASSERT_TRUE(ct::CheckForSingleVerifiedSCTInResult(scts, kLogDescription)); ASSERT_TRUE(ct::CheckForSCTOrigin( scts, ct::SignedCertificateTimestamp::SCT_FROM_TLS_EXTENSION)); } TEST_F(MultiLogCTVerifierTest, IdentifiesSCTFromUnknownLog) { std::string sct_list = ct::GetSCTListWithInvalidSCT(); SignedCertificateTimestampAndStatusList scts; verifier_->Verify(chain_.get(), base::StringPiece(), sct_list, &scts, NetLogWithSource()); EXPECT_EQ(1U, scts.size()); EXPECT_EQ("", scts[0].sct->log_description); EXPECT_EQ(ct::SCT_STATUS_LOG_UNKNOWN, scts[0].status); } TEST_F(MultiLogCTVerifierTest, CountsValidSCTsInStatusHistogram) { int num_valid_scts = NumValidSCTsInStatusHistogram(); ASSERT_TRUE(VerifySinglePrecertificateChain(embedded_sct_chain_)); EXPECT_EQ(num_valid_scts + 1, NumValidSCTsInStatusHistogram()); } TEST_F(MultiLogCTVerifierTest, CountsInvalidSCTsInStatusHistogram) { std::string sct_list = ct::GetSCTListWithInvalidSCT(); SignedCertificateTimestampAndStatusList scts; int num_valid_scts = NumValidSCTsInStatusHistogram(); int num_invalid_scts = GetValueFromHistogram( "Net.CertificateTransparency.SCTStatus", ct::SCT_STATUS_LOG_UNKNOWN); verifier_->Verify(chain_.get(), base::StringPiece(), sct_list, &scts, NetLogWithSource()); ASSERT_EQ(num_valid_scts, NumValidSCTsInStatusHistogram()); ASSERT_EQ(num_invalid_scts + 1, GetValueFromHistogram("Net.CertificateTransparency.SCTStatus", ct::SCT_STATUS_LOG_UNKNOWN)); } TEST_F(MultiLogCTVerifierTest, CountsSingleEmbeddedSCTInConnectionsHistogram) { int old_sct_count = NumConnectionsWithSingleSCT(); ASSERT_TRUE(CheckPrecertificateVerification(embedded_sct_chain_)); EXPECT_EQ(old_sct_count + 1, NumConnectionsWithSingleSCT()); } TEST_F(MultiLogCTVerifierTest, CountsSingleEmbeddedSCTInOriginsHistogram) { int old_embedded_count = NumEmbeddedSCTsInHistogram(); ASSERT_TRUE(CheckPrecertificateVerification(embedded_sct_chain_)); EXPECT_EQ(old_embedded_count + 1, NumEmbeddedSCTsInHistogram()); } TEST_F(MultiLogCTVerifierTest, CountsZeroSCTsCorrectly) { int connections_without_scts = GetValueFromHistogram(kSCTCountHistogram, 0); EXPECT_FALSE(VerifySinglePrecertificateChain(chain_)); ASSERT_EQ(connections_without_scts + 1, GetValueFromHistogram(kSCTCountHistogram, 0)); } TEST_F(MultiLogCTVerifierTest, NotifiesOfValidSCT) { MockSCTObserver observer; verifier_->SetObserver(&observer); EXPECT_CALL(observer, OnSCTVerified(embedded_sct_chain_.get(), _)); ASSERT_TRUE(VerifySinglePrecertificateChain(embedded_sct_chain_)); } TEST_F(MultiLogCTVerifierTest, StopsNotifyingCorrectly) { MockSCTObserver observer; verifier_->SetObserver(&observer); EXPECT_CALL(observer, OnSCTVerified(embedded_sct_chain_.get(), _)).Times(1); ASSERT_TRUE(VerifySinglePrecertificateChain(embedded_sct_chain_)); Mock::VerifyAndClearExpectations(&observer); EXPECT_CALL(observer, OnSCTVerified(embedded_sct_chain_.get(), _)).Times(0); verifier_->SetObserver(nullptr); ASSERT_TRUE(VerifySinglePrecertificateChain(embedded_sct_chain_)); } } // namespace } // namespace net
[ "jacob-chen@iotwrt.com" ]
jacob-chen@iotwrt.com
d35ecd3221d58d111d0ac573388f9a6b1fb65acb
06f822b1f2061f7ce03a9659a7017dfcebd3e209
/ATcoder/Contest/Educaional_DP_Contest_/I_Coins.cpp
f70919a70f64abd6165b724c9c73a89d63c0f72e
[]
no_license
SuuTTT/acm
f5ba1e6365fb0191490cba3dbac35031ec4e23b0
61fe500a89b2d41a17a010a1f65169ef21206fb5
refs/heads/master
2020-12-27T17:32:38.844016
2020-05-13T04:27:53
2020-05-13T04:27:53
237,983,067
0
0
null
null
null
null
UTF-8
C++
false
false
696
cpp
#include <bits/stdc++.h> using namespace std; #define rep(i,j,k) for(int i = (int)j;i <= (int)k;i ++) #define debug(x) cerr<<#x<<":"<<x<<endl const int maxn=(int)1e6+5; double p[maxn],dp[3004][3004],ans; int main(){ ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); int n; cin>>n; rep(i,1,n)cin>>p[i]; dp[0][0]=1; rep(i,1,n)rep(j,0,i){ dp[i][j]=dp[i-1][j]*(1-p[i])+(j>0?dp[i-1][j-1]*p[i]:0); //debug(i),debug(dp[i][j]); } rep(j,0,n){ if(j>n-j)ans+=dp[n][j]; } //cout<<ans<<endl; printf("%.20lf",ans); } /* 3 0.30 0.60 0.80 head>tail 的概率 dp[i][#head] dp[i][j]=dp[i-1][j] dp[i-1][j-1] O(1)计算 最后求和 */
[ "1015011749@qq.com" ]
1015011749@qq.com
7af8f9573736e2b6034ba6d33525f5398ca7740d
82437e831c8e89c092d4125cca71ace24d364f5e
/wasabi/devices/unicone/firmware/genesis/hardware.inc
6d6c597ec73aea6123bc3ad370334033f83d2c75
[]
no_license
qixiaobo/navi-misc
93ac98f3d07eed0a1e6e620fd5f53880c5aac2a4
1f9099d40cc638d681eebbc85c0b8455dab21607
refs/heads/master
2021-06-06T11:53:00.644309
2016-10-27T06:01:26
2016-10-27T06:01:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,391
inc
; ; Sega Genesis Net-controller Interface ; ; Wasabi Net-controllers Project ; Micah Dowty <micah@navi.cx> ; ; This device emulates two 3-button Sega Genesis ; controllers. It accepts low-speed USB requests ; with the desired state of each controller. ; ; The controller interface is described well at: ; http://www-2.cs.cmu.edu/~chuck/infopg/segasix.txt ; ; The prototype was mounted inside the Genesis console ; itself, with a USB type B plug added to the back. ; This gives us control over the reset button and ; frees us from the low-quality connectors used on ; the front. This same firmware should work fine ; with normal DB-9 cables connecting it to the controller ; ports. ; ; The PIC16C745 power and USB are connected as ; described in the data sheet. I/Os are allocated ; as follows. Note that all controller pins were ; connected via resistors so that externally ; attached controllers can override the USB interface. ; This is unnecessary if you're connecting this to the ; genesis externally. The multiplexed outputs on PORTA ; used 1k resistors, (for speed) others used 47k ; resistors (to avoid overpowering the controller's ; 10k pull-up resistors) ; ; RB4: Controller 1, pin 7 (select) ; RB5: Controller 2, pin 7 (select) ; RB6: Reserved (interrupt-on-change) ; RB7: Reserved (interrupt-on-change) ; ; RA0: Controller 1, pin 6 (A/B) ; RA1: Controller 1, pin 9 (Start/C) ; RA2: Controller 2, pin 6 (A/B) ; RA3: Controller 2, pin 9 (Start/C) ; ; RB0: Controller 1, pin 1 (up) ; RB1: Controller 1, pin 2 (down) ; RB2: Controller 1, pin 3 (left) ; RB3: Controller 1, pin 4 (right) ; ; RC0: Controller 2, pin 1 (up) ; RC1: Controller 2, pin 2 (down) ; RC2: Controller 2, pin 3 (left) ; RC6: Controller 2, pin 4 (right) ; ; RA5: Reset button output ; RC7: Power switch output #define PIN_C1_SELECT PORTB, 4 #define PIN_C2_SELECT PORTB, 5 #define PIN_C1_A_B PORTA, 0 #define PIN_C1_START_C PORTA, 1 #define PIN_C2_A_B PORTA, 2 #define PIN_C2_START_C PORTA, 3 #define PIN_C1_UP PORTB, 0 #define PIN_C1_DOWN PORTB, 1 #define PIN_C1_LEFT PORTB, 2 #define PIN_C1_RIGHT PORTB, 3 #define PIN_C2_UP PORTC, 0 #define PIN_C2_DOWN PORTC, 1 #define PIN_C2_LEFT PORTC, 2 #define PIN_C2_RIGHT PORTC, 6 #define PIN_RESET PORTA, 5 ; Pulls high when active, high-z when inactive #define TRIS_RESET TRISA, 5 #define PIN_POWER PORTC, 7 ; --- The End ---
[ "micah@scanlime.org" ]
micah@scanlime.org
68f3b19dffe4001c00d28fa60c1a3ca457985f0c
feea0886aaf6218a3f605bbc4d871a8116e232b0
/LSDFlowInfo.cpp
9c3d1cc83df47d4019144da4f7bb119265651f30
[]
no_license
MNiMORPH/LSDTopoTools_FloodplainTerraceExtraction
4c35aa434f601dce6ef9a21477f67d760ad6fa2d
0d13667f56999cc6d5c7f8d0787a44c4b16337d9
refs/heads/master
2022-05-20T01:55:15.298527
2018-01-05T11:33:40
2018-01-05T11:33:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
268,797
cpp
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // LSDFlowInfo // Land Surface Dynamics FlowInfo // // An object within the University // of Edinburgh Land Surface Dynamics group topographic toolbox // for organizing flow routing under the Fastscape algorithm // (see Braun and Willett, Geomorphology 2013, v180, p 170-179) // // // Developed by: // Simon M. Mudd // Martin D. Hurst // David T. Milodowski // Stuart W.D. Grieve // Declan A. Valters // Fiona Clubb // // Copyright (C) 2013 Simon M. Mudd 2013 // // Developer can be contacted by simon.m.mudd _at_ ed.ac.uk // // Simon Mudd // University of Edinburgh // School of GeoSciences // Drummond Street // Edinburgh, EH8 9XP // Scotland // United Kingdom // // This program is free software; // you can redistribute it and/or modify it under the terms of the // GNU General Public License as published by the Free Software Foundation; // either version 2 of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; // without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the GNU General Public License for more details. // // You should have received a copy of the // GNU General Public License along with this program; // if not, write to: // Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301 // USA // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // LSDFlowInfo.cpp // cpp file for the LSDFlowInfo object // LSD stands for Land Surface Dynamics // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // This object is written by // Simon M. Mudd, University of Edinburgh // David Milodowski, University of Edinburgh // Martin D. Hurst, British Geological Survey // Fiona Clubb, University of Edinburgh // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // Version 0.1.0 21/10/2013 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //----------------------------------------------------------------- //DOCUMENTATION URL: http://www.geos.ed.ac.uk/~s0675405/LSD_Docs/ //----------------------------------------------------------------- #ifndef LSDFlowInfo_CPP #define LSDFlowInfo_CPP #include <iostream> #include <fstream> #include <iomanip> #include <vector> #include <string> #include <cstring> #include <algorithm> #include <math.h> #include "TNT/tnt.h" #include "LSDFlowInfo.hpp" #include "LSDIndexRaster.hpp" #include "LSDStatsTools.hpp" //#include "LSDRaster.hpp" using namespace std; using namespace TNT; //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // Create function, this is empty, you need to include a filename // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= void LSDFlowInfo::create() { //cout << endl << "-------------------------------" << endl; //cout << "I am an empty flow info object. " << endl; //cout << "Did you forget to give me a DEM?" << endl; //cout << endl << "-------------------------------" << endl; //exit(EXIT_FAILURE); } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Create function, this creates from a pickled file // fname is the name of the pickled flow info file // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- void LSDFlowInfo::create(string fname) { unpickle(fname); } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // This defaults to no flux boundary conditions //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- void LSDFlowInfo::create(LSDRaster& TopoRaster) { vector<string> BoundaryConditions(4, "No Flux"); create(BoundaryConditions, TopoRaster); } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // this function calcualtes the receiver nodes // it returns the receiver vector r_i // it also returns a flow direction array in this ordering: // // 7 0 1 // 6 -1 2 // 5 4 3 // // note this is different from ArcMap flowdirection // int Arc_flowdir; // flow direction in arcmap format // // 32 64 128 // // 16 -- 1 // // 8 4 2 // one can convert nthese indices using the LSDIndexRaster object // note in arc the row index increases down (to the south) // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- void LSDFlowInfo::create(vector<string>& temp_BoundaryConditions, LSDRaster& TopoRaster) { // initialize several data members BoundaryConditions = temp_BoundaryConditions; //cout << "TBC" << endl; NRows = TopoRaster.get_NRows(); //cout << "Rows: " << NRows << endl; NCols = TopoRaster.get_NCols(); //cout << "Cols: " << NCols << endl; XMinimum = TopoRaster.get_XMinimum(); //cout << "Xmin: " << XMinimum << endl; YMinimum = TopoRaster.get_YMinimum(); //cout << "Ymin: " << YMinimum << endl; NoDataValue = int(TopoRaster.get_NoDataValue()); //cout << "NDV: " << NoDataValue << endl; DataResolution = TopoRaster.get_DataResolution(); //cout << "Data resolution: " <<DataResolution << endl; GeoReferencingStrings = TopoRaster.get_GeoReferencingStrings(); //cout << "GRS" << endl; //cout << "1" << endl; // Declare matrices for calculating flow routing float one_ov_root2 = 0.707106781; float target_elev; // a placeholder for the elevation of the potential receiver float slope; float max_slope; // the maximum slope away from a node int max_slope_index; // index into the maximum slope int row, col; // index for the rows and column int receive_row,receive_col; string::iterator string_iterator; // used to get characters from string // we need logic for all of the boundaries. // there are 3 kinds of edge boundaries: // no flux // base level // periodic // These are denoted in a vector of strings. // the vector has four elements // North boundary, East boundary, South bondary and West boundary // the strings can be any length, as long as the first letter corresponds to the // first letter of the boundary condition. It is not case sensitive. // go through the boundaries // A NOTE ON CARDINAL DIRECTIONS // If one looks at the raster data, the top row in the data corresponds to the NORTH boundary // This is the row that is first read into the code // so row 0 is the NORTH boundary // row NRows-1 is the SOUTH boundary // column 0 is the WEST boundary // column NCols-1 is the EAST boundary vector<float> slopes(8,NoDataValue); vector<int> row_kernal(8); vector<int> col_kernal(8); int ndv = NoDataValue; NDataNodes = 0; // the number of nodes in the raster that have data int one_if_a_baselevel_node; // this is a switch used to tag baseleve nodes // the first thing you need to do is construct a topoglogy matrix // the donor, receiver, etc lists are as long as the number of nodes. // these are made of vectors that are exactly dimension n, which is the number of nodes with // data. Each of these nodes has several index vectors, that point the program to where the node is // we construct these index vectors first // we need to loop through all the data before we calcualte slopes because the // receiver node indices must be known before the slope calculations are run vector<int> empty_vec; RowIndex = empty_vec; ColIndex = empty_vec; BaseLevelNodeList = empty_vec; ReceiverVector = empty_vec; Array2D<int> ndv_raster(NRows,NCols,ndv); NodeIndex = ndv_raster.copy(); FlowDirection = ndv_raster.copy(); FlowLengthCode = ndv_raster.copy(); //cout << "2" << endl; // loop through the topo data finding places where there is actually data for (row = 0; row<NRows; row++) { for (col = 0; col<NCols; col++) { // only do calcualtions if there is data if(TopoRaster.RasterData[row][col] != NoDataValue) { RowIndex.push_back(row); ColIndex.push_back(col); NodeIndex[row][col] = NDataNodes; NDataNodes++; } } } //cout << "3" << endl; // now the row and col index are populated by the row and col of the node in row i // and the node index has the indeces into the row and col vectors // next up, make d, delta, and D vectors vector<int> ndn_vec(NDataNodes,0); vector<int> ndn_nodata_vec(NDataNodes,ndv); vector<int> ndn_plusone_vec(NDataNodes+1,0); vector<int> w_vector(NDataNodes,0); NDonorsVector = ndn_vec; DonorStackVector = ndn_vec; DeltaVector = ndn_plusone_vec; SVector = ndn_nodata_vec; BLBasinVector = ndn_nodata_vec; // this vector starts out empty and then base level nodes are added to it for (row = 0; row<NRows; row++) { for (col = 0; col<NCols; col++) { // only do calcualtions if there is data if(TopoRaster.RasterData[row][col] != NoDataValue) { // calcualte 8 slopes // no slopes mean get NoDataValue entries // the algorithm loops through the neighbors to the cells, collecting // receiver indices. The order is // 7 0 1 // 6 - 2 // 5 4 3 // where the above directions are cardinal directions // do slope 0 row_kernal[0] = row-1; row_kernal[1] = row-1; row_kernal[2] = row; row_kernal[3] = row+1; row_kernal[4] = row+1; row_kernal[5] = row+1; row_kernal[6] = row; row_kernal[7] = row-1; col_kernal[0] = col; col_kernal[1] = col+1; col_kernal[2] = col+1; col_kernal[3] = col+1; col_kernal[4] = col; col_kernal[5] = col-1; col_kernal[6] = col-1; col_kernal[7] = col-1; // check for periodic boundary conditions if( BoundaryConditions[0].find("P") == 0 || BoundaryConditions[0].find("p") == 0 ) { if( BoundaryConditions[2].find("P") != 0 && BoundaryConditions[2].find("p") != 0 ) { cout << "WARNING!!! North boundary is periodic! Changing South boundary to periodic" << endl; BoundaryConditions[2] = "P"; } } if( BoundaryConditions[1].find("P") == 0 || BoundaryConditions[1].find("p") == 0 ) { if( BoundaryConditions[3].find("P") != 0 && BoundaryConditions[3].find("p") != 0 ) { cout << "WARNING!!! East boundary is periodic! Changing West boundary to periodic" << endl; BoundaryConditions[3] = "P"; } } if( BoundaryConditions[2].find("P") == 0 || BoundaryConditions[2].find("p") == 0 ) { if( BoundaryConditions[0].find("P") != 0 && BoundaryConditions[0].find("p") != 0 ) { cout << "WARNING!!! South boundary is periodic! Changing North boundary to periodic" << endl; BoundaryConditions[0] = "P"; } } if( BoundaryConditions[3].find("P") == 0 || BoundaryConditions[3].find("p") == 0 ) { if( BoundaryConditions[1].find("P") != 0 && BoundaryConditions[1].find("p") != 0 ) { cout << "WARNING!!! West boundary is periodic! Changing East boundary to periodic" << endl; BoundaryConditions[1] = "P"; } } // reset baselevel switch for boundaries one_if_a_baselevel_node = 0; // NORTH BOUNDARY if (row == 0) { if( BoundaryConditions[0].find("B") == 0 || BoundaryConditions[0].find("b") == 0 ) { one_if_a_baselevel_node = 1; } else { // if periodic, reflect across to south boundary if( BoundaryConditions[0].find("P") == 0 || BoundaryConditions[0].find("p") == 0 ) { row_kernal[0] = NRows-1; row_kernal[1] = NRows-1; row_kernal[7] = NRows-1; } else { row_kernal[0] = ndv; row_kernal[1] = ndv; row_kernal[7] = ndv; } } } // EAST BOUNDAY if (col == NCols-1) { if( BoundaryConditions[1].find("B") == 0 || BoundaryConditions[1].find("b") == 0 ) { one_if_a_baselevel_node = 1; } else { if( BoundaryConditions[1].find("P") == 0 || BoundaryConditions[1].find("p") == 0) { col_kernal[1] = 0; col_kernal[2] = 0; col_kernal[3] = 0; } else { col_kernal[1] = ndv; col_kernal[2] = ndv; col_kernal[3] = ndv; } } } // SOUTH BOUNDARY if (row == NRows-1) { if( BoundaryConditions[2].find("B") == 0 || BoundaryConditions[2].find("b") == 0 ) { one_if_a_baselevel_node = 1; } else { if( BoundaryConditions[2].find("P") == 0 || BoundaryConditions[2].find("p") == 0) { row_kernal[3] = 0; row_kernal[4] = 0; row_kernal[5] = 0; } else { row_kernal[3] = ndv; row_kernal[4] = ndv; row_kernal[5] = ndv; } } } // WEST BOUNDARY if (col == 0) { if( BoundaryConditions[3].find("B") == 0 || BoundaryConditions[3].find("b") == 0 ) { one_if_a_baselevel_node = 1; } else { if( BoundaryConditions[3].find("P") == 0 || BoundaryConditions[3].find("p") == 0) { col_kernal[5] = NCols-1; col_kernal[6] = NCols-1; col_kernal[7] = NCols-1; } else { col_kernal[5] = ndv; col_kernal[6] = ndv; col_kernal[7] = ndv; } } } // now loop through the surrounding nodes, calculating the slopes // slopes with NoData get NoData slopes // reminder of ordering: // 7 0 1 // 6 - 2 // 5 4 3 // first logic for baselevel node if (one_if_a_baselevel_node == 1) { // get reciever index FlowDirection[row][col] = -1; ReceiverVector.push_back(NodeIndex[row][col]); FlowLengthCode[row][col] = 0; } // now the rest of the nodes else { FlowLengthCode[row][col] = 0; // set flow length code to 0, this gets reset // if there is a maximum slope max_slope = 0; max_slope_index = -1; receive_row = row; receive_col = col; for (int slope_iter = 0; slope_iter<8; slope_iter++) { if (row_kernal[slope_iter] == ndv || col_kernal[slope_iter] == ndv) { slopes[slope_iter] = NoDataValue; } else { target_elev = TopoRaster.RasterData[ row_kernal[slope_iter] ][ col_kernal[slope_iter] ]; if(target_elev == NoDataValue) { slopes[slope_iter] = NoDataValue; } else { if(slope_iter%2 == 0) { //cout << "LINE 988, cardinal direction, slope iter = " << slope_iter << endl; slope = TopoRaster.RasterData[row][col]-target_elev; } else { slope = one_ov_root2*(TopoRaster.RasterData[row][col]-target_elev); } if (slope > max_slope) { max_slope_index = slope_iter; receive_row = row_kernal[slope_iter]; receive_col = col_kernal[slope_iter]; max_slope = slope; if(slope_iter%2 == 0) { FlowLengthCode[row][col] = 1; } else { FlowLengthCode[row][col] = 2; } } } } } // get reciever index FlowDirection[row][col] = max_slope_index; ReceiverVector.push_back(NodeIndex[receive_row][receive_col]); } // end if baselevel boundary conditional // if the node is a base level node, add it to the base level node list if (FlowLengthCode[row][col] == 0) { BaseLevelNodeList.push_back(NodeIndex[row][col]); } } // end if there is data conditional } // end col loop } // end row loop // first create the number of donors vector // from braun and willett eq. 5 for(int i = 0; i<NDataNodes; i++) { NDonorsVector[ ReceiverVector[i] ]++; } // now create the delta vector // this starts on the last element and works its way backwards // from Braun and Willett eq 7 and 8 DeltaVector[NDataNodes] = NDataNodes; for(int i = NDataNodes; i>0; i--) { DeltaVector[i-1] = DeltaVector[i] - NDonorsVector[i-1]; } // now the DonorStack and the r vectors. These come from Braun and Willett // equation 9. // Note that in the manscript I have there is a typo in eqaution 9 // (Jean Braun's code is correct) // it should be w_{r_i} = w_{r_i}+1 int r_index; int w_index; int delta_index; for (int i = 0; i<NDataNodes; i++) { r_index = ReceiverVector[i]; delta_index = DeltaVector[ r_index ]; w_index = w_vector[ r_index ]; DonorStackVector[ delta_index+w_index ] = i; w_vector[r_index] += 1; //cout << "i: " << i << " r_i: " << r_index << " delta_i: " << delta_index << " w_index: " << w_index << endl; } // now go through the base level node list, building the drainage tree for each of these nodes as one goes along int n_base_level_nodes; n_base_level_nodes = BaseLevelNodeList.size(); int k; int j_index; int begin_delta_index, end_delta_index; int l_index; j_index = 0; for (int i = 0; i<n_base_level_nodes; i++) { k = BaseLevelNodeList[i]; // set k to the base level node // This doesn't seem to be in Braun and Willet but to get the ordering correct you // need to make sure that the base level node appears first in the donorstack // of nodes contributing to the baselevel node. // For example, if base level node is 4, with 4 donors // and the donor stack has 3 4 8 9 // the code has to put the 4 first. if (DonorStackVector[ DeltaVector[k] ] != k) { int this_index = DonorStackVector[ DeltaVector[k] ]; int bs_node = k; for(int ds_node = 1; ds_node < NDonorsVector[k]; ds_node++) { if( DonorStackVector[ DeltaVector[k] + ds_node ] == bs_node ) { DonorStackVector[ DeltaVector[k] ] = k; DonorStackVector[ DeltaVector[k] + ds_node ] = this_index; } } } // now run recursive algorithm begin_delta_index = DeltaVector[k]; end_delta_index = DeltaVector[k+1]; //cout << "base_level_node is: " << k << " begin_index: " << begin_delta_index << " end: " << end_delta_index << endl; for (int delta_index = begin_delta_index; delta_index<end_delta_index; delta_index++) { l_index = DonorStackVector[delta_index]; add_to_stack(l_index, j_index, k); } } // now calcualte the indices calculate_upslope_reference_indices(); } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // // This function returns the x and y location of a row and column // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- void LSDFlowInfo::get_x_and_y_locations(int row, int col, double& x_loc, double& y_loc) { x_loc = XMinimum + float(col)*DataResolution + 0.5*DataResolution; // Slightly different logic for y because the DEM starts from the top corner y_loc = YMinimum + float(NRows-row)*DataResolution - 0.5*DataResolution; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // // This function returns the x and y location of a row and column // Same as above but with floats // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- void LSDFlowInfo::get_x_and_y_locations(int row, int col, float& x_loc, float& y_loc) { x_loc = XMinimum + float(col)*DataResolution + 0.5*DataResolution; // Slightly different logic for y because the DEM starts from the top corner y_loc = YMinimum + float(NRows-row)*DataResolution - 0.5*DataResolution; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // // Function to convert a node position with a row and column to a lat // and long coordinate // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- void LSDFlowInfo::get_lat_and_long_locations(int row, int col, double& lat, double& longitude, LSDCoordinateConverterLLandUTM Converter) { // get the x and y locations of the node double x_loc,y_loc; get_x_and_y_locations(row, col, x_loc, y_loc); // get the UTM zone of the node int UTM_zone; bool is_North; get_UTM_information(UTM_zone, is_North); //cout << endl << endl << "Line 1034, UTM zone is: " << UTM_zone << endl; if(UTM_zone == NoDataValue) { lat = NoDataValue; longitude = NoDataValue; } else { // set the default ellipsoid to WGS84 int eId = 22; double xld = double(x_loc); double yld = double(y_loc); // use the converter to convert to lat and long double Lat,Long; Converter.UTMtoLL(eId, yld, xld, UTM_zone, is_North, Lat, Long); lat = Lat; longitude = Long; } } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // // This function gets the UTM zone // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- void LSDFlowInfo::get_UTM_information(int& UTM_zone, bool& is_North) { // set up strings and iterators map<string,string>::iterator iter; //check to see if there is already a map info string string mi_key = "ENVI_map_info"; iter = GeoReferencingStrings.find(mi_key); if (iter != GeoReferencingStrings.end() ) { string info_str = GeoReferencingStrings[mi_key] ; // now parse the string vector<string> mapinfo_strings; istringstream iss(info_str); while( iss.good() ) { string substr; getline( iss, substr, ',' ); mapinfo_strings.push_back( substr ); } UTM_zone = atoi(mapinfo_strings[7].c_str()); //cout << "Line 1041, UTM zone: " << UTM_zone << endl; //cout << "LINE 1042 LSDRaster, N or S: " << mapinfo_strings[7] << endl; // find if the zone is in the north string n_str = "n"; string N_str = "N"; is_North = false; size_t found = mapinfo_strings[8].find(N_str); if (found!=std::string::npos) { is_North = true; } found = mapinfo_strings[8].find(n_str); if (found!=std::string::npos) { is_North = true; } //cout << "is_North is: " << is_North << endl; } else { UTM_zone = NoDataValue; is_North = false; } } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // // Checks to see is a point is in the raster // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- bool LSDFlowInfo::check_if_point_is_in_raster(float X_coordinate, float Y_coordinate) { bool is_in_raster = true; // Shift origin to that of dataset float X_coordinate_shifted_origin = X_coordinate - XMinimum - DataResolution*0.5; float Y_coordinate_shifted_origin = Y_coordinate - YMinimum - DataResolution*0.5; // Get row and column of point int col_point = int(X_coordinate_shifted_origin/DataResolution); int row_point = (NRows - 1) - int(round(Y_coordinate_shifted_origin/DataResolution)); if(col_point < 0 || col_point > NCols-1 || row_point < 0 || row_point > NRows -1) { is_in_raster = false; } return is_in_raster; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // algorithms for searching the vectors // This gets the reciever of current_node (its node, row, and column) // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= void LSDFlowInfo::retrieve_receiver_information(int current_node, int& receiver_node, int& receiver_row, int& receiver_col) { int rn, rr, rc; rn = ReceiverVector[current_node]; rr = RowIndex[rn]; rc = ColIndex[rn]; receiver_node = rn; receiver_row = rr; receiver_col = rc; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // algorithms for searching the vectors // This gets the row and column of the current node // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= void LSDFlowInfo::retrieve_current_row_and_col(int current_node,int& curr_row, int& curr_col) { int cr, cc; cr = RowIndex[current_node]; cc = ColIndex[current_node]; curr_row = cr; curr_col = cc; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // algorithms for searching the vectors // This gets the X and Y coordinates of the current node // // BG 20/02/2017 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= void LSDFlowInfo::get_x_and_y_from_current_node(int current_node, float& current_X, float& current_Y) { int cr,cc; retrieve_current_row_and_col(current_node, cr,cc); get_x_and_y_locations(cr, cc, current_X, current_Y); } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // algorithms for searching the vectors // This gets the row and column of the current node // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= void LSDFlowInfo::print_vector_of_nodeindices_to_csv_file(vector<int>& nodeindex_vec, string outfilename) { // fid the last '.' in the filename to use in the scv filename unsigned dot = outfilename.find_last_of("."); string prefix = outfilename.substr(0,dot); //string suffix = str.substr(dot); string insert = "_nodeindices_for_Arc.csv"; string outfname = prefix+insert; cout << "the Arc filename is: " << outfname << endl; int n_nodes = nodeindex_vec.size(); int n_nodeindeces = RowIndex.size(); // open the outfile ofstream csv_out; csv_out.open(outfname.c_str()); csv_out.precision(8); csv_out << "x,y,node,row,col" << endl; int current_row, current_col; float x,y; // loop through node indices in vector for (int i = 0; i<n_nodes; i++) { int current_node = nodeindex_vec[i]; // make sure the nodeindex isn't out of bounds if (current_node < n_nodeindeces) { // get the row and column retrieve_current_row_and_col(current_node,current_row, current_col); // get the x and y location of the node // the last 0.0001*DataResolution is to make sure there are no integer data points x = XMinimum + float(current_col)*DataResolution + 0.5*DataResolution + 0.0001*DataResolution; // the last 0.0001*DataResolution is to make sure there are no integer data points // y coord a bit different since the DEM starts from the top corner y = YMinimum + float(NRows-current_row)*DataResolution - 0.5*DataResolution + 0.0001*DataResolution;; csv_out << x << "," << y << "," << current_node << "," << current_row << "," << current_col << endl; } } csv_out.close(); } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // This function takes a list of junctions and prints them to a csv file //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= void LSDFlowInfo::print_vector_of_nodeindices_to_csv_file_with_latlong(vector<int>& nodeindex_vec, string outfilename) { int n_nodes = (nodeindex_vec.size()); int this_node; int row,col; double x_loc,y_loc; double latitude,longitude; // open the outfile ofstream sources_out; sources_out.open(outfilename.c_str()); sources_out.precision(9); sources_out << "node,x,y,latitude,longitude" << endl; // this is for latitude and longitude LSDCoordinateConverterLLandUTM Converter; for (int i = 0; i<n_nodes; i++) { this_node = nodeindex_vec[i]; // get the row and column retrieve_current_row_and_col(this_node,row,col); // get the x and y locations get_x_and_y_locations(row, col, x_loc, y_loc); // get the lat and long locations get_lat_and_long_locations(row, col, latitude, longitude, Converter); // print to file sources_out << this_node << "," << x_loc << "," << y_loc << "," << latitude << "," << longitude << endl; } sources_out.close(); } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // Write nodeindex vector to csv file, and give each row a unique ID // // SWDG after SMM 2/2/2016 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= void LSDFlowInfo::print_vector_of_nodeindices_to_csv_file_Unique(vector<int>& nodeindex_vec, string outfilename) { // fid the last '.' in the filename to use in the scv filename unsigned dot = outfilename.find_last_of("."); string prefix = outfilename.substr(0,dot); //string suffix = str.substr(dot); string insert = "_nodeindices_for_Arc.csv"; string outfname = prefix+insert; cout << "the Arc filename is: " << outfname << endl; int n_nodes = nodeindex_vec.size(); int n_nodeindeces = RowIndex.size(); // open the outfile ofstream csv_out; csv_out.open(outfname.c_str()); csv_out.precision(8); csv_out << "x,y,node,row,col,unique_ID" << endl; int current_row, current_col; float x,y; // loop through node indices in vector for (int i = 0; i<n_nodes; i++) { int current_node = nodeindex_vec[i]; // make sure the nodeindex isn't out of bounds if (current_node < n_nodeindeces) { // get the row and column retrieve_current_row_and_col(current_node,current_row, current_col); // get the x and y location of the node // the last 0.0001*DataResolution is to make sure there are no integer data points x = XMinimum + float(current_col)*DataResolution + 0.5*DataResolution + 0.0001*DataResolution; // the last 0.0001*DataResolution is to make sure there are no integer data points // y coord a bit different since the DEM starts from the top corner y = YMinimum + float(NRows-current_row)*DataResolution - 0.5*DataResolution + 0.0001*DataResolution;; csv_out << x << "," << y << "," << current_node << "," << current_row << "," << current_col << "," << i << endl; } } csv_out.close(); } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // this function returns the base level node with the greatest drainage area // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= int LSDFlowInfo::retrieve_largest_base_level() { int n_bl = BaseLevelNodeList.size(); // get the number of baselevel nodes int max_bl = 0; for (int i = 0; i<n_bl; i++) { if(NContributingNodes[ BaseLevelNodeList[i] ] > max_bl) { max_bl = NContributingNodes[ BaseLevelNodeList[i] ]; } } return max_bl; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // this function returns the base level node with the greatest drainage area // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= int LSDFlowInfo::retrieve_base_level_node(int node) { int CurrentNode = node; int ReceiverNode, ReceiverRow, ReceiverCol; // set initial ReceiverNode so that you can enter while loop retrieve_receiver_information(CurrentNode, ReceiverNode, ReceiverRow, ReceiverCol); // now follow the nodes down to the receiver. while(ReceiverNode != CurrentNode) { CurrentNode = ReceiverNode; retrieve_receiver_information(CurrentNode, ReceiverNode, ReceiverRow, ReceiverCol); } return ReceiverNode; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Get the node for a cell at a given row and column //@author DTM //@date 08/11/2013 //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- int LSDFlowInfo::retrieve_node_from_row_and_column(int row, int column) { int Node = NodeIndex[row][column]; return Node; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // gets a vector of all the donors to a given node // @author SMM // @date 19/09/2014 //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- vector<int> LSDFlowInfo::retrieve_donors_to_node(int current_node) { // get the numver of donors int NDonors = NDonorsVector[current_node]; // create the vecotr of donating nodes vector<int> donorvec(NDonors,NoDataValue); // loop over the donating nodes, getting their nodeindicies for(int dnode = 0; dnode<NDonors; dnode++) { donorvec[dnode] = DonorStackVector[ DeltaVector[current_node]+dnode]; } return donorvec; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // get the drainage area of a node in km^2 // FJC 06/02/17 //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- float LSDFlowInfo::get_DrainageArea_square_km(int this_node) { int NContributingPixels = NContributingNodes[this_node]; float DrainageArea = NContributingPixels*DataResolution*DataResolution; float DrainageAreaKm = DrainageArea/1000000; return DrainageAreaKm; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // recursive add_to_stack routine, from Braun and Willett eq. 12 and 13 // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- void LSDFlowInfo::add_to_stack(int lm_index, int& j_index, int bl_node) { //cout << "j_index: " << j_index << " and s_vec: " << lm_index << endl; SVector[j_index] = lm_index; BLBasinVector[j_index] = bl_node; j_index++; int begin_m,end_m; int l_index; // if donating to itself, need escape hatch if ( lm_index == bl_node) { begin_m = 0; end_m = 0; } else { begin_m = DeltaVector[lm_index]; end_m = DeltaVector[ lm_index+1]; } //cout << "lm_index: " << lm_index << " begin_m: " << begin_m << " end m: " << end_m << endl; for( int m_index = begin_m; m_index<end_m; m_index++) { //cout << "recursion, begin_m: " << begin_m << " and end_m: " << end_m << endl; l_index = DonorStackVector[m_index]; add_to_stack(l_index, j_index, bl_node); } } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // this function pickles the data from the flowInfo object into a binary format // which can be read by the unpickle function later // the filename DOES NOT include and extension: this is added by the // function // // WARNING: These files are HUGE and testing indicates they don't save much time // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= void LSDFlowInfo::pickle(string filename) { string ext = ".FIpickle"; string hdr_ext = ".FIpickle.hdr"; string hdr_fname = filename+hdr_ext; string data_fname = filename+ext; ofstream header_out; header_out.open(hdr_fname.c_str()); int contributing_nodes = int(NContributingNodes.size()); int BLNodes = int(BaseLevelNodeList.size()); // print the header file header_out << "ncols " << NCols << "\nnrows " << NRows << "\nxllcorner " << setprecision(14) << XMinimum << "\nyllcorner " << setprecision(14) << YMinimum << "\ncellsize " << DataResolution << "\nNODATA_value " << NoDataValue << "\nNDataNodes " << NDataNodes << "\nNBaseLevelNodes " << BLNodes << "\nNContributingNodes " << contributing_nodes << "\nBoundaryConditions "; for(int i = 0; i<4; i++) { header_out << " " << BoundaryConditions[i]; } header_out << endl; header_out.close(); cout << "sizes RC indices: " << RowIndex.size() << " " << ColIndex.size() << endl; cout << "BLNL size: " << BaseLevelNodeList.size() << endl; cout << "donors: " << NDonorsVector.size() << " Reciev: " << ReceiverVector.size() << endl; cout << "delta: " << DeltaVector.size() << " S: " << SVector.size() << endl; cout << "donorstack: " << DonorStackVector.size() << " BBasin: " << BLBasinVector.size() << endl; cout << "SVectorIndex " << SVectorIndex.size() << " NContrib: " << NContributingNodes.size() << endl; // now do the main data ofstream data_ofs(data_fname.c_str(), ios::out | ios::binary); int temp; for (int i=0; i<NRows; ++i) { for (int j=0; j<NCols; ++j) { temp = NodeIndex[i][j]; data_ofs.write(reinterpret_cast<char *>(&temp),sizeof(temp)); } } for (int i=0; i<NRows; ++i) { for (int j=0; j<NCols; ++j) { temp = FlowDirection[i][j]; data_ofs.write(reinterpret_cast<char *>(&temp),sizeof(temp)); } } for (int i=0; i<NRows; ++i) { for (int j=0; j<NCols; ++j) { temp = FlowLengthCode[i][j]; data_ofs.write(reinterpret_cast<char *>(&temp),sizeof(temp)); } } for (int i = 0; i<NDataNodes; i++) { temp = RowIndex[i]; data_ofs.write(reinterpret_cast<char *>(&temp),sizeof(temp)); } for (int i = 0; i<NDataNodes; i++) { temp = ColIndex[i]; data_ofs.write(reinterpret_cast<char *>(&temp),sizeof(temp)); } for (int i = 0; i<BLNodes; i++) { temp = BaseLevelNodeList[i]; data_ofs.write(reinterpret_cast<char *>(&temp),sizeof(temp)); } for (int i = 0; i<NDataNodes; i++) { temp = NDonorsVector[i]; data_ofs.write(reinterpret_cast<char *>(&temp),sizeof(temp)); } for (int i = 0; i<NDataNodes; i++) { temp = ReceiverVector[i]; data_ofs.write(reinterpret_cast<char *>(&temp),sizeof(temp)); } for (int i = 0; i<NDataNodes+1; i++) { temp = DeltaVector[i]; data_ofs.write(reinterpret_cast<char *>(&temp),sizeof(temp)); } for (int i = 0; i<NDataNodes; i++) { temp = DonorStackVector[i]; data_ofs.write(reinterpret_cast<char *>(&temp),sizeof(temp)); } for (int i = 0; i<NDataNodes; i++) { temp = SVector[i]; data_ofs.write(reinterpret_cast<char *>(&temp),sizeof(temp)); } for (int i = 0; i<NDataNodes; i++) { temp = BLBasinVector[i]; data_ofs.write(reinterpret_cast<char *>(&temp),sizeof(temp)); } for (int i = 0; i<NDataNodes; i++) { temp = SVectorIndex[i]; data_ofs.write(reinterpret_cast<char *>(&temp),sizeof(temp)); } for (int i = 0; i<contributing_nodes; i++) { temp = NContributingNodes[i]; data_ofs.write(reinterpret_cast<char *>(&temp),sizeof(temp)); } data_ofs.close(); } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // this unpickles a pickled flow info object. It is folded into a create function // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= void LSDFlowInfo::unpickle(string filename) { string ext = ".FIpickle"; string hdr_ext = ".FIpickle.hdr"; string hdr_fname = filename+hdr_ext; string data_fname = filename+ext; ifstream header_in; header_in.open(hdr_fname.c_str()); string temp_str; int contributing_nodes; vector<string> bc(4); int BLNodes; header_in >> temp_str >> NCols >> temp_str >> NRows >> temp_str >> XMinimum >> temp_str >> YMinimum >> temp_str >> DataResolution >> temp_str >> NoDataValue >> temp_str >> NDataNodes >> temp_str >> BLNodes >> temp_str >> contributing_nodes >> temp_str >> bc[0] >> bc[1] >> bc[2] >> bc[3]; header_in.close(); BoundaryConditions = bc; // now read the data, using the binary stream option ifstream ifs_data(data_fname.c_str(), ios::in | ios::binary); if( ifs_data.fail() ) { cout << "\nFATAL ERROR: the data file \"" << data_fname << "\" doesn't exist" << endl; exit(EXIT_FAILURE); } else { // initialze the arrays Array2D<int> data_array(NRows,NCols,NoDataValue); NodeIndex = data_array.copy(); FlowDirection = data_array.copy(); FlowLengthCode = data_array.copy(); vector<int> data_vector(NDataNodes,NoDataValue); vector<int> BLvector(BLNodes,NoDataValue); vector<int> deltaV(NDataNodes+1,NoDataValue); vector<int> CNvec(contributing_nodes,NoDataValue); int temp; for (int i=0; i<NRows; ++i) { for (int j=0; j<NCols; ++j) { ifs_data.read(reinterpret_cast<char*>(&temp), sizeof(temp)); NodeIndex[i][j] =temp; } } for (int i=0; i<NRows; ++i) { for (int j=0; j<NCols; ++j) { ifs_data.read(reinterpret_cast<char*>(&temp), sizeof(temp)); FlowDirection[i][j] =temp; } } for (int i=0; i<NRows; ++i) { for (int j=0; j<NCols; ++j) { ifs_data.read(reinterpret_cast<char*>(&temp), sizeof(temp)); FlowLengthCode[i][j] =temp; } } RowIndex = data_vector; for (int i=0; i<NDataNodes; ++i) { ifs_data.read(reinterpret_cast<char*>(&temp), sizeof(temp)); RowIndex[i] =temp; } ColIndex = data_vector; for (int i=0; i<NDataNodes; ++i) { ifs_data.read(reinterpret_cast<char*>(&temp), sizeof(temp)); ColIndex[i] =temp; } BaseLevelNodeList = BLvector; for (int i=0; i<BLNodes; ++i) { ifs_data.read(reinterpret_cast<char*>(&temp), sizeof(temp)); BaseLevelNodeList[i] =temp; } NDonorsVector = data_vector; for (int i=0; i<NDataNodes; ++i) { ifs_data.read(reinterpret_cast<char*>(&temp), sizeof(temp)); NDonorsVector[i] =temp; } ReceiverVector = data_vector; for (int i=0; i<NDataNodes; ++i) { ifs_data.read(reinterpret_cast<char*>(&temp), sizeof(temp)); ReceiverVector[i] =temp; } DeltaVector = deltaV; for (int i=0; i<NDataNodes+1; ++i) { ifs_data.read(reinterpret_cast<char*>(&temp), sizeof(temp)); DeltaVector[i] =temp; } DonorStackVector = data_vector; for (int i=0; i<NDataNodes; ++i) { ifs_data.read(reinterpret_cast<char*>(&temp), sizeof(temp)); DonorStackVector[i] =temp; } SVector = data_vector; for (int i=0; i<NDataNodes; ++i) { ifs_data.read(reinterpret_cast<char*>(&temp), sizeof(temp)); SVector[i] =temp; } BLBasinVector = data_vector; for (int i=0; i<NDataNodes; ++i) { ifs_data.read(reinterpret_cast<char*>(&temp), sizeof(temp)); BLBasinVector[i] =temp; } SVectorIndex = data_vector; for (int i=0; i<NDataNodes; ++i) { ifs_data.read(reinterpret_cast<char*>(&temp), sizeof(temp)); SVectorIndex[i] =temp; } NContributingNodes = CNvec; for (int i=0; i<contributing_nodes; ++i) { ifs_data.read(reinterpret_cast<char*>(&temp), sizeof(temp)); NContributingNodes[i] =temp; } } ifs_data.close(); cout << "sizes RC indices: " << RowIndex.size() << " " << ColIndex.size() << endl; cout << "BLNL size: " << BaseLevelNodeList.size() << endl; cout << "donors: " << NDonorsVector.size() << " Reciev: " << ReceiverVector.size() << endl; cout << "delta: " << DeltaVector.size() << " S: " << SVector.size() << endl; cout << "donorstack: " << DonorStackVector.size() << " BBasin: " << BLBasinVector.size() << endl; cout << "SVectorIndex " << SVectorIndex.size() << " NContrib: " << NContributingNodes.size() << endl; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // SCRIPTS FOR LOADING CSV DATA // ported from LSDSpatialCSVReader // FJC 23/03/17 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // // This loads a csv file // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- map<string, vector<string> > LSDFlowInfo::load_csv_data(string filename) { // make sure the filename works ifstream ifs(filename.c_str()); if( ifs.fail() ) { cout << "\nFATAL ERROR: Trying to load csv file, but the file" << filename << "doesn't exist; check your filename" << endl; exit(EXIT_FAILURE); } else { cout << "I have opened the csv file." << endl; } // Initiate the data map map<string, vector<string> > data_map; map<string, int > temp_vec_vec_key; vector< vector<string> > temp_vec_vec; map<string, vector<string> > temp_data_map; // << "Data map size is: " << data_map.size() << endl; //cout << "longitude size is: " << longitude.size() << endl; // initiate the string to hold the file string line_from_file; vector<string> empty_string_vec; vector<string> this_string_vec; string temp_string; // get the headers from the first line getline(ifs, line_from_file); // reset the string vec this_string_vec = empty_string_vec; // create a stringstream stringstream ss(line_from_file); ss.precision(9); while( ss.good() ) { string substr; getline( ss, substr, ',' ); // remove the spaces substr.erase(remove_if(substr.begin(), substr.end(), ::isspace), substr.end()); // remove control characters substr.erase(remove_if(substr.begin(), substr.end(), ::iscntrl), substr.end()); // add the string to the string vec this_string_vec.push_back( substr ); } // now check the data map int n_headers = int(this_string_vec.size()); vector<string> header_vector = this_string_vec; for (int i = 0; i<n_headers; i++) { temp_data_map[header_vector[i]] = empty_string_vec; } // now loop through the rest of the lines, getting the data. while( getline(ifs, line_from_file)) { //cout << "Getting line, it is: " << line_from_file << endl; // reset the string vec this_string_vec = empty_string_vec; // create a stringstream stringstream ss(line_from_file); while( ss.good() ) { string substr; getline( ss, substr, ',' ); // remove the spaces substr.erase(remove_if(substr.begin(), substr.end(), ::isspace), substr.end()); // remove control characters substr.erase(remove_if(substr.begin(), substr.end(), ::iscntrl), substr.end()); // add the string to the string vec this_string_vec.push_back( substr ); } //cout << "Yoyoma! size of the string vec: " << this_string_vec.size() << endl; if ( int(this_string_vec.size()) <= 0) { cout << "Hey there, I am trying to load your csv data but you seem not to have" << endl; cout << "enough columns in your file. I am ignoring a line" << endl; } else { int n_cols = int(this_string_vec.size()); //cout << "N cols is: " << n_cols << endl; for (int i = 0; i<n_cols; i++) { temp_data_map[header_vector[i]].push_back(this_string_vec[i]); } //cout << "Done with this line." << endl; } } data_map = temp_data_map; cout << "I loaded a csv with the keys: " << endl; for( map<string, vector<string> >::iterator it = data_map.begin(); it != data_map.end(); ++it) { cout << "Key is: " <<it->first << "\n"; } return data_map; } //============================================================================== //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // // This returns the string vector of data from a given column name // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- vector<string> LSDFlowInfo::get_data_column(string column_name, map<string, vector<string> > data_map) { vector<string> data_vector; if ( data_map.find(column_name) == data_map.end() ) { // not found cout << "I'm afraid the column "<< column_name << " is not in this dataset" << endl; } else { data_vector = data_map[column_name]; } return data_vector; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Converts a data column to a float vector //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- vector<float> LSDFlowInfo::data_column_to_float(string column_name, map<string, vector<string> > data_map) { vector<string> string_vec = get_data_column(column_name, data_map); vector<float> float_vec; int N_data_elements = string_vec.size(); for(int i = 0; i<N_data_elements; i++) { float_vec.push_back( atof(string_vec[i].c_str())); } return float_vec; } // Converts a data column to a float vector vector<int> LSDFlowInfo::data_column_to_int(string column_name, map<string, vector<string> > data_map) { vector<string> string_vec = get_data_column(column_name, data_map); vector<int> int_vec; int N_data_elements = string_vec.size(); if (N_data_elements == 0) { cout << "Couldn't read in the data column. Check the column name!" << endl; } for(int i = 0; i<N_data_elements; i++) { int_vec.push_back( atoi(string_vec[i].c_str())); } return int_vec; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // END OF CSV FUNCTIONS //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // Method to ingest the channel heads raster generated using channel_heads_driver.cpp // into a vector of source nodes so that an LSDJunctionNetwork can be created easily // from them. Assumes the FlowInfo object has the same dimensions as the channel // heads raster. // // Takes the filename and extension of the channel heads raster. // // SWDG 05/12/12 // // Update: 6/6/14 Happy 3rd birthday Skye!!!! // SMM // Now if the file extension is "csv" then the script reads a csv channel heads // file // // Update 30/09/14 Altered structure of function, but key difference is that it // is now much better in how it goes about reading in channel heads using // the coordinates, so that channel heads for a region determined usiong one DEM // can be loaded in to another covering a subsample of the area, or a different // resolution, which was impossible before. // DTM //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= vector<int> LSDFlowInfo::Ingest_Channel_Heads(string filename, string extension, int input_switch){ vector<int> Sources; int CH_node; // if this is a csv file, read its contents directly into the node index vector if(extension == "csv") { if(input_switch != 0 && input_switch != 1 && input_switch != 2) { cout << "\t Note, you have specified an unsupported value for the input switch. Note: \n\t\t 0=take node index\n\t\t 1=take row and column indices\n\t\t 2=take x and y coordinates" << endl; cout << "\t ...taking node index by default" << endl; } ifstream ch_csv_in; string fname = filename +"."+extension; ch_csv_in.open(fname.c_str()); if(not ch_csv_in.good()) { cout << "You are trying to ingest a sources file that doesn't exist!!" << endl; cout << fname << endl; cout << "Check your filename" << endl; exit(EXIT_FAILURE); } cout << "fname is: " << fname << endl; string sline = ""; getline(ch_csv_in,sline); vector<int> nodeindex,rowindex,colindex; vector<float> x_coord,y_coord; // TODO This needs to be rplaced with the csv reader!!! while(!ch_csv_in.eof()) { char name[256]; ch_csv_in.getline(name,256); sline = name; // a very tedious way to get the right bit of data. There is probably a // better way to do this but this way works if (sline.size() > 0) { // column index string prefix = sline.substr(0,sline.size()); unsigned comma = sline.find_last_of(","); string suffix = prefix.substr(comma+1,prefix.size()); colindex.push_back(atoi(suffix.c_str())); // row index prefix = sline.substr(0,comma); comma = prefix.find_last_of(","); suffix = prefix.substr(comma+1,prefix.size()); rowindex.push_back(atoi(suffix.c_str())); // node index prefix = sline.substr(0,comma); comma = prefix.find_last_of(","); suffix = prefix.substr(comma+1,prefix.size()); nodeindex.push_back(atoi(suffix.c_str())); // y coordinate prefix = sline.substr(0,comma); comma = prefix.find_last_of(","); suffix = prefix.substr(comma+1,prefix.size()); y_coord.push_back(atof(suffix.c_str())); // x coordinate prefix = sline.substr(0,comma); comma = prefix.find_last_of(","); suffix = prefix.substr(comma+1,prefix.size()); x_coord.push_back(atof(suffix.c_str())); } } int node; // use row and column indices to locate source nodes. if(input_switch == 1) { for(int i = 0; i < int(rowindex.size()); ++i) { if(rowindex[i]<NRows && rowindex[i]>=0 && colindex[i]<NCols && colindex[i] >=0 && NodeIndex[rowindex[i]][colindex[i]]!=NoDataValue) { node = retrieve_node_from_row_and_column(rowindex[i],colindex[i]); Sources.push_back(node); } } } // Use coordinates to locate source nodes. Note that this enables the use // of LiDAR derived channel heads in coarser DEMs of the same area or // subsets of the original DEM for more efficient processing. else if(input_switch == 2) { vector<int> Sources_temp; int N_coords = x_coord.size(); int N_sources_1 = 0; for(int i = 0; i < N_coords; ++i) { node = get_node_index_of_coordinate_point(x_coord[i], y_coord[i]); if (node != NoDataValue) { // Test 1 - Check for channel heads that fall in same pixel int test1 = 0; N_sources_1 = Sources_temp.size(); for(int i_test=0; i_test<N_sources_1;++i_test) { if(node==Sources_temp[i_test]) test1 = 1; } if(test1==0) Sources_temp.push_back(node); else cout << "\t\t ! removed node from sources list - coincident with another source node" << endl; } } // Test 2 - Need to do some extra checks to load sources correctly. int N_sources_2 = Sources_temp.size(); for(int i = 0; i<N_sources_2; ++i) { int test2 = 0; for(int i_test = 0; i_test<int(Sources_temp.size()); ++i_test) { if(i!=i_test) { if(is_node_upstream(Sources_temp[i],Sources_temp[i_test])==true) test2 = 1; } } if(test2 ==0) Sources.push_back(Sources_temp[i]); else cout << "\t\t ! removed node from sources list - other sources upstream" << endl; } } // Using Node Index directly (default) else Sources = nodeindex; } // if not the code assums a sources raster. else { LSDIndexRaster CHeads(filename, extension); for (int i = 0; i < NRows; ++i) { for (int j = 0; j < NCols; ++j) { if (CHeads.get_data_element(i,j) != NoDataValue) { CH_node = retrieve_node_from_row_and_column(i,j); if (CH_node != NoDataValue) { Sources.push_back(CH_node); } } } } } return Sources; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // Method to ingest the channel heads raster generated using channel_heads_driver.cpp // into a vector of source nodes so that an LSDJunctionNetwork can be created easily // from them. Assumes the FlowInfo object has the same dimensions as the channel // heads raster. // // Takes the filename and extension of the channel heads raster. // // SWDG 05/12/12 // // Update: 6/6/14 Happy 3rd birthday Skye!!!! // SMM // Now if the file extension is "csv" then the script reads a csv channel heads // file // // Update 30/09/14 Altered structure of function, but key difference is that it // is now much better in how it goes about reading in channel heads using // the coordinates, so that channel heads for a region determined usiong one DEM // can be loaded in to another covering a subsample of the area, or a different // resolution, which was impossible before. // DTM // // ******************************************************************************************* // UPDATE 23/03/17 - NEW OVERLOADED CHANNEL HEADS INGESTION ROUTINE. This ONLY works with the // csv file as this seems to be the best way of reading in the channel heads. Other formats // should now be obsolete. // Finds the appropriate column from the csv based on the string of the heading rather // than by column number, so should work with different versions of the output sources // csv file. // // Input switch tells what the columns the code should be looking for: // 0 - use the node index // 1 - use rows and columns // 2 - use x and y (UTM coordinates) // Could add in a 3rd switch for lat long but this requires a bunch of extra porting that // I can't be bothered to do right now. // FJC // ***************************************************************************************** //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= vector<int> LSDFlowInfo::Ingest_Channel_Heads(string filename, int input_switch) { vector<int> Sources; int CH_node; // load the csv file map<string, vector<string> > data_map = load_csv_data(filename+".csv"); // now check the input switch to search for the various columns if (input_switch == 0) { // use the node index vector<int> NodeIndices = data_column_to_int("node", data_map); Sources = NodeIndices; } else if (input_switch == 1) { // use the rows and columns vector<int> rows = data_column_to_int("row", data_map); vector<int> cols = data_column_to_int("col", data_map); for (int i = 0; i < int(rows.size()); i++) { int NI = retrieve_node_from_row_and_column(rows[i], cols[i]); Sources.push_back(NI); } } else if (input_switch == 2) { // use x and y (UTM coordinates) vector<float> x_coord = data_column_to_float("x", data_map); vector<float> y_coord = data_column_to_float("y", data_map); int N_coords = x_coord.size(); vector<int> Sources_temp; int N_sources_1 = 0; for(int i = 0; i < N_coords; ++i) { int node = get_node_index_of_coordinate_point(x_coord[i], y_coord[i]); if (node != NoDataValue) { // Test 1 - Check for channel heads that fall in same pixel int test1 = 0; N_sources_1 = Sources_temp.size(); for(int i_test=0; i_test<N_sources_1;++i_test) { if(node==Sources_temp[i_test]) test1 = 1; } if(test1==0) Sources_temp.push_back(node); else cout << "\t\t ! removed node from sources list - coincident with another source node" << endl; } } // Test 2 - Need to do some extra checks to load sources correctly. int N_sources_2 = Sources_temp.size(); for(int i = 0; i<N_sources_2; ++i) { int test2 = 0; for(int i_test = 0; i_test<int(Sources_temp.size()); ++i_test) { if(i!=i_test) { if(is_node_upstream(Sources_temp[i],Sources_temp[i_test])==true) test2 = 1; } } if(test2 ==0) Sources.push_back(Sources_temp[i]); else cout << "\t\t ! removed node from sources list - other sources upstream" << endl; } } else { cout << "You have not supplied a valid input switch! Please supply either 0, 1, or 2." << endl; } return Sources; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // Method to ingest sources from OS MasterMap Water Network Layer (csv) // into a vector of source nodes so that an LSDJunctionNetwork can be created easily // from them. // // Takes the filename and extension of the channel heads raster. // // FJC 28/11/2016 //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= vector<int> LSDFlowInfo::Ingest_Channel_Heads_OS(string csv_filename) { vector<int> Sources; // read in the CSV file ifstream input_csv; string dot = "."; string extension = "csv"; string fname = csv_filename+dot+extension; cout << "The CSV filename is: " << fname << endl; input_csv.open(fname.c_str()); // check for correct input if (not input_csv.good()) { cout << "I can't read the CSV file! Check your filename." << endl; } //int object_ID, name, source_ID, PosAlong; //float X,Y; vector<float> X_coords, Y_coords; // read in the file while(!input_csv.eof()) { string line; getline(input_csv,line); // get the x and y coords to vectors istringstream ss(line); string param; int i=0; while(getline(ss, param, ',')) { if (i == 4) { X_coords.push_back(atof(param.c_str())); } if (i == 5) { Y_coords.push_back(atof(param.c_str())); } i++; } } vector<int> Sources_temp; int N_coords = X_coords.size(); int N_sources_1 = 0; for(int i = 0; i < N_coords; ++i) { int node = get_node_index_of_coordinate_point(X_coords[i], Y_coords[i]); if (node != NoDataValue) { // Test 1 - Check for channel heads that fall in same pixel int test1 = 0; N_sources_1 = Sources_temp.size(); for(int i_test=0; i_test<N_sources_1;++i_test) { if(node==Sources_temp[i_test]) test1 = 1; } if(test1==0) Sources_temp.push_back(node); else cout << "\t\t ! removed node from sources list - coincident with another source node" << endl; } } // Test 2 - Need to do some extra checks to load sources correctly. int N_sources_2 = Sources_temp.size(); for(int i = 0; i<N_sources_2; ++i) { cout << flush << "\t Source: " << i << " of " << N_sources_2 << "\r"; int test2 = 0; for(int i_test = 0; i_test<int(Sources_temp.size()); ++i_test) { if(i!=i_test) { if(is_node_upstream(Sources_temp[i],Sources_temp[i_test])==true) test2 = 1; } } if(test2 ==0) Sources.push_back(Sources_temp[i]); //else cout << "\t\t ! removed node from sources list - other sources upstream" << endl; } cout << "Returning sources..." << endl; return Sources; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // this prints the flownet information // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= void LSDFlowInfo::print_flow_info_vectors(string filename) { string string_filename; string dot = "."; string extension = "txt"; string_filename = filename+dot+extension; cout << "The filename is " << string_filename << endl; // print out all the donor, reciever and stack info ofstream donor_info_out; donor_info_out.open(string_filename.c_str()); for(int i = 0; i<NDataNodes; i++) { donor_info_out << i << " "; } donor_info_out << endl; for(int i = 0; i<NDataNodes; i++) { donor_info_out << ReceiverVector[i] << " "; } donor_info_out << endl; for(int i = 0; i<NDataNodes; i++) { donor_info_out << NDonorsVector[i] << " "; } donor_info_out << endl; for(int i = 0; i<NDataNodes+1; i++) { donor_info_out << DeltaVector[i] << " "; } donor_info_out << endl; for(int i = 0; i<NDataNodes; i++) { donor_info_out << DonorStackVector[i] << " "; } donor_info_out << endl; for(int i = 0; i<NDataNodes; i++) { donor_info_out << SVector[i] << " "; } donor_info_out << endl; if( int(SVectorIndex.size()) == NDataNodes) { for(int i = 0; i<NDataNodes; i++) { donor_info_out << SVectorIndex[i] << " "; } donor_info_out << endl; for(int i = 0; i<NDataNodes; i++) { donor_info_out << NContributingNodes[i] << " "; } donor_info_out << endl; } donor_info_out.close(); } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // these functions write the index arrays to index rasters // // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= LSDIndexRaster LSDFlowInfo::write_NodeIndex_to_LSDIndexRaster() { cout << "NRows: " << NRows << " and NCols: " << NCols << endl; LSDIndexRaster temp_nodeindex(NRows,NCols,XMinimum,YMinimum,DataResolution,NoDataValue,NodeIndex,GeoReferencingStrings); return temp_nodeindex; } LSDIndexRaster LSDFlowInfo::write_FlowDirection_to_LSDIndexRaster() { LSDIndexRaster temp_flowdir(NRows,NCols,XMinimum,YMinimum,DataResolution,NoDataValue,FlowDirection,GeoReferencingStrings); return temp_flowdir; } LSDIndexRaster LSDFlowInfo::write_FlowLengthCode_to_LSDIndexRaster() { LSDIndexRaster temp_flc(NRows,NCols,XMinimum,YMinimum,DataResolution,NoDataValue,FlowLengthCode,GeoReferencingStrings); return temp_flc; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // This function writes an LSDIndesxRaster given a list of node indices // // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= LSDIndexRaster LSDFlowInfo::write_NodeIndexVector_to_LSDIndexRaster(vector<int>& nodeindexvec) { int n_node_indices = nodeindexvec.size(); //cout << "The number of nodeindices is: " << n_node_indices << endl; Array2D<int> chan(NRows,NCols,NoDataValue); //cout << "Raster nr: " << chan.dim1() << " nc: " << chan.dim2() << endl; int curr_row, curr_col; for(int i = 0; i<n_node_indices; i++) { // make sure there is no segmentation fault for bad data // Note: bad data is ignored if(nodeindexvec[i] <= NDataNodes) { retrieve_current_row_and_col(nodeindexvec[i],curr_row, curr_col); if(chan[curr_row][curr_col] == NoDataValue) { chan[curr_row][curr_col] = 1; } else { chan[curr_row][curr_col]++; } } else { cout << "WARNING: LSDFlowInfo::write_NodeIndexVector_to_LSDIndexRaster" << " node index does not exist!"<< endl; } } LSDIndexRaster temp_chan(NRows,NCols,XMinimum,YMinimum,DataResolution,NoDataValue,chan,GeoReferencingStrings); return temp_chan; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // This function writes an LSDIndesxRaster given a list of node indices, and give every // pixel its nodeindex value, which is unique. // // SWDG after SMM 2/2/16 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= LSDIndexRaster LSDFlowInfo::write_NodeIndexVector_to_LSDIndexRaster_Unique(vector<int>& nodeindexvec) { int n_node_indices = nodeindexvec.size(); Array2D<int> chan(NRows,NCols,NoDataValue); int curr_row, curr_col; for(int i = 0; i<n_node_indices; i++){ // make sure there is no segmentation fault for bad data // Note: bad data is ignored if(nodeindexvec[i] <= NDataNodes){ retrieve_current_row_and_col(nodeindexvec[i], curr_row, curr_col); if(chan[curr_row][curr_col] == NoDataValue){ chan[curr_row][curr_col] = i; } else{ //revisted points will be overwritten, most recent id will be pres chan[curr_row][curr_col] = i; } } else { cout << "WARNING: LSDFlowInfo::write_NodeIndexVector_to_LSDIndexRaster" << " node index does not exist!"<< endl; } } LSDIndexRaster temp_chan(NRows,NCols,XMinimum,YMinimum,DataResolution,NoDataValue,chan,GeoReferencingStrings); return temp_chan; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // // This function calcualtes the contributing pixels // it can be converted to contributing area by multiplying by the // DataResolution^2 // // This function used the S vector index and NContributing nodes to calculate the area // // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= LSDIndexRaster LSDFlowInfo::write_NContributingNodes_to_LSDIndexRaster() { Array2D<int> contributing_pixels(NRows,NCols,NoDataValue); int row,col; // loop through the node vector, adding pixels to receiver nodes for(int node = 0; node<NDataNodes; node++) { row = RowIndex[node]; col = ColIndex[node]; contributing_pixels[row][col] = NContributingNodes[node]; } LSDIndexRaster temp_cp(NRows,NCols,XMinimum,YMinimum,DataResolution,NoDataValue,contributing_pixels,GeoReferencingStrings); return temp_cp; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // writes a index raster in arc format // LSD format: // 7 0 1 // 6 -1 2 // 5 4 3 // int Arc_flowdir; // flow direction in arcmap format // // 32 64 128 // // 16 0 1 // // 8 4 2 // // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= LSDIndexRaster LSDFlowInfo::write_FlowDirection_to_LSDIndexRaster_Arcformat() { Array2D<int> FlowDirectionArc(NRows,NCols,NoDataValue); for(int row = 0; row<NRows; row++) { for (int col = 0; col<NCols; col++) { if ( FlowDirection[row][col] == -1) { FlowDirectionArc[row][col] = 0; } else if ( FlowDirection[row][col] == 0) { FlowDirectionArc[row][col] = 64; } else if ( FlowDirection[row][col] == 1) { FlowDirectionArc[row][col] = 128; } else if ( FlowDirection[row][col] == 2) { FlowDirectionArc[row][col] = 1; } else if ( FlowDirection[row][col] == 3) { FlowDirectionArc[row][col] = 2; } else if ( FlowDirection[row][col] == 4) { FlowDirectionArc[row][col] = 4; } else if ( FlowDirection[row][col] == 5) { FlowDirectionArc[row][col] = 8; } else if ( FlowDirection[row][col] == 6) { FlowDirectionArc[row][col] = 16; } else if ( FlowDirection[row][col] == 7) { FlowDirectionArc[row][col] = 32; } } } LSDIndexRaster temp_fd(NRows,NCols,XMinimum,YMinimum,DataResolution,NoDataValue,FlowDirectionArc,GeoReferencingStrings); return temp_fd; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // This function writes the drainage area (number of contributing nodes // * DataResolution^2) to an LSDRaster object // Added by FC 15/11/12 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= LSDRaster LSDFlowInfo::write_DrainageArea_to_LSDRaster() { // initialise the 2D array int row,col; // node index float ndv = float(NoDataValue); float this_DA; Array2D<float> DrainageArea_local(NRows,NCols,ndv); for(int node = 0; node<NDataNodes; node++) { row = RowIndex[node]; col = ColIndex[node]; //cout << NContributingNodes[node] << endl; this_DA = float(NContributingNodes[node])*DataResolution*DataResolution; DrainageArea_local[row][col] = this_DA; } // create the LSDRaster object LSDRaster DrainageArea(NRows,NCols,XMinimum,YMinimum,DataResolution,ndv,DrainageArea_local,GeoReferencingStrings); return DrainageArea; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // This function calcualtes the contributing pixels // it can be converted to contributing area by multiplying by the // DataResolution^2 // In this function a pixel that has no donors has a contributing pixel value of 0 // // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= LSDIndexRaster LSDFlowInfo::calculate_n_pixels_contributing_from_upslope() { Array2D<int> contributing_pixels(NRows,NCols,NoDataValue); int row,col; int receive_row, receive_col; int receiver_node; // loop through the s vector, adding pixels to receiver nodes for(int node = NDataNodes-1; node>=0; node--) { row = RowIndex[SVector[node]]; col = ColIndex[SVector[node]]; // if the pixel exists and has no contributing pixels, // change from nodata to zero if(contributing_pixels[row][col] == NoDataValue) { contributing_pixels[row][col] = 0; } receiver_node = ReceiverVector[ SVector[node] ] ; receive_row = RowIndex[ receiver_node ]; receive_col = ColIndex[ receiver_node ]; cout << "node " << node << " pixel: " << SVector[node] << " receiver: " << receiver_node << endl; cout << "contributing: " << contributing_pixels[row][col] << endl; if ( receiver_node == SVector[node]) { // do nothing } else if ( contributing_pixels[receive_row][receive_col] == NoDataValue) { contributing_pixels[receive_row][receive_col] = contributing_pixels[row][col]+1; } else { contributing_pixels[receive_row][receive_col] += contributing_pixels[row][col]+1; } cout << "recieving: " << contributing_pixels[receive_row][receive_col] << endl; } LSDIndexRaster temp_cp(NRows,NCols,XMinimum,YMinimum,DataResolution,NoDataValue,contributing_pixels,GeoReferencingStrings); return temp_cp; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // This function calcualtes the contributing pixels // it can be converted to contributing area by multiplying by the // DataResolution^2 // // In this function a pixel that has no donors contributes its own flow // // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= void LSDFlowInfo::calculate_upslope_reference_indices() { vector<int> vectorized_area(NDataNodes,1); SVectorIndex = vectorized_area; int receiver_node; int donor_node; // loop through the s vector, adding pixels to receiver nodes for(int node = NDataNodes-1; node>=0; node--) { donor_node = SVector[node]; receiver_node = ReceiverVector[ donor_node ]; // every node is visited once and only once so we can map the // unique positions of the nodes to the SVector SVectorIndex[donor_node] = node; // add the upslope area (note no action is taken // for base level nodes since they donate to themselves and // we must avoid float counting if (donor_node != receiver_node) { vectorized_area[ receiver_node ] += vectorized_area[ donor_node ]; } } NContributingNodes = vectorized_area; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // This function returns a integer vector containing all the node numbers upslope // of of the node with number node_number_outlet // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- vector<int> LSDFlowInfo::get_upslope_nodes(int node_number_outlet) { vector<int> us_nodes; if(node_number_outlet < 0 || node_number_outlet > NDataNodes-1) { cout << "the node index does not exist" << endl; exit(EXIT_FAILURE); } int start_SVector_node = SVectorIndex[node_number_outlet]; int end_SVector_node = start_SVector_node+NContributingNodes[node_number_outlet]; for(int node = start_SVector_node; node < end_SVector_node; node++) { us_nodes.push_back(SVector[node]); } return us_nodes; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // This function takes a list of source nodes and creates a raster where // the pixels have a value of 1 where there are upslope nodes and nodata otherwise //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- LSDRaster LSDFlowInfo::get_upslope_node_mask(vector<int> source_nodes) { // initiate the data array Array2D<float> this_raster(NRows,NCols,NoDataValue); // loop through the nodes, collecting upslope nodes int n_nodes = int(source_nodes.size()); int this_node; //int us_node; int curr_row,curr_col; float is_us = 1.0; // go through all the source nodes, find their upslope nodes // and set the value of these nodes to 1.0 on the data array for (int n = 0; n<n_nodes; n++) { this_node = source_nodes[n]; // check if it is in the DEM if (this_node < NDataNodes) { vector<int> upslope_nodes = get_upslope_nodes(this_node); int n_us_nodes = int(upslope_nodes.size()); for(int us = 0; us<n_us_nodes; us++) { retrieve_current_row_and_col(upslope_nodes[us],curr_row,curr_col); this_raster[curr_row][curr_col]=is_us; } } } // now create the raster LSDRaster temp_us(NRows,NCols,XMinimum,YMinimum,DataResolution,NoDataValue,this_raster,GeoReferencingStrings); return temp_us; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // This function takes a list of source nodes and creates a raster where // the pixels have a value of upslope_value // where there are upslope nodes and NoData otherwise //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- LSDRaster LSDFlowInfo::get_upslope_node_mask(vector<int> source_nodes, vector<float> upslope_values) { // initiate the data array Array2D<float> this_raster(NRows,NCols,NoDataValue); if (source_nodes.size() == upslope_values.size()) { // loop through the nodes, collecting upslope nodes int n_nodes = int(source_nodes.size()); int this_node; //int us_node; int curr_row,curr_col; // go through all the source nodes, find their upslope nodes // and set the value of these nodes to 1.0 on the data array for (int n = 0; n<n_nodes; n++) { this_node = source_nodes[n]; // check if it is in the DEM if (this_node < NDataNodes) { vector<int> upslope_nodes = get_upslope_nodes(this_node); int n_us_nodes = int(upslope_nodes.size()); for(int us = 0; us<n_us_nodes; us++) { retrieve_current_row_and_col(upslope_nodes[us],curr_row,curr_col); this_raster[curr_row][curr_col]= upslope_values[n]; } } } } else { cout << "The uplsope vlaues vector needs to be the same lengths as the sources vector!" << endl; cout << "Returning an nodata raster" << endl; } // now create the raster LSDRaster temp_us(NRows,NCols,XMinimum,YMinimum,DataResolution,NoDataValue,this_raster,GeoReferencingStrings); return temp_us; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // // Accumulate some variable (such a precipitation) from an accumulation raster // // This requires summing all upslope nodes for every node. It seems a bit inefficient // but the other simple alternative is to do a sort() operation initially and then // move from upslope node down. There is probably a more efficient way to do this // and this algorithm should be revisited later to see if we can speed it up. // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= LSDRaster LSDFlowInfo::upslope_variable_accumulator(LSDRaster& accum_raster) { int raster_NRows, raster_NCols; float raster_XMin, raster_YMin, raster_DataRes; // first check to make sure the raster dimensions match that of the // raster upon which LSDFlowInfo is based raster_NRows = accum_raster.get_NRows(); raster_NCols = accum_raster.get_NCols(); raster_XMin = accum_raster.get_XMinimum(); raster_YMin = accum_raster.get_YMinimum(); raster_DataRes = accum_raster.get_DataResolution(); if (raster_NRows != NRows || raster_NCols != NCols || raster_XMin != XMinimum || raster_YMin != YMinimum || raster_DataRes != DataResolution) { cout << "Warning!!, LSDFlowInfo::upslope_area_accumulator\n" << "Accumulation raster does not match dimensions of original raster" << endl; return accum_raster; } else { // create the data array Array2D<float> accumulated_data_array(NRows,NCols,NoDataValue); // loop through all the nodes, accumulating the areas for(int this_node = 0; this_node <NDataNodes; this_node++) { // get the upslope nodes vector<int> node_vec = get_upslope_nodes(this_node); // loop through these nodes, adding them to the accumulator float this_node_accumulated = 0; int this_row, this_col; for (int ni = 0; ni<int(node_vec.size()); ni++) { retrieve_current_row_and_col(node_vec[ni],this_row,this_col); this_node_accumulated += accum_raster.get_data_element(this_row, this_col); } // write the accumulated variable to the array int curr_row, curr_col; retrieve_current_row_and_col(this_node,curr_row,curr_col); accumulated_data_array[curr_row][curr_col] = this_node_accumulated; } // create the raster LSDRaster accumulated_flow(NRows, NCols, XMinimum, YMinimum, DataResolution, NoDataValue, accumulated_data_array,GeoReferencingStrings); return accumulated_flow; } } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // This function tests whether the test is upstream of the current node // // FC 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= int LSDFlowInfo::is_node_upstream(int current_node, int test_node) { int i = 0; int start_SVector_node = SVectorIndex[current_node]; int end_SVector_node = start_SVector_node+NContributingNodes[current_node]; int SVector_test_node = SVectorIndex[test_node]; for(int node = start_SVector_node; node < end_SVector_node; node++) { if (node == SVector_test_node) { i = 1; } } return i; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // This function tests whether a node is a base level node // // FC 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= int LSDFlowInfo::is_node_base_level(int node) { int i = 0; for (int j = 0; j < int(BaseLevelNodeList.size()); j++) { if (node == BaseLevelNodeList[j]) { i = 1; } } return i; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // This function redurns a vector of node indices to all the donor // nodes of a particular node // // SMM 21/10/2013 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= vector<int> LSDFlowInfo::get_donor_nodes(int current_node) { int start_D = DeltaVector[current_node]; int end_D = DeltaVector[current_node+1]; vector<int> donor_nodes; for(int this_node = start_D; this_node<end_D; this_node++) { //cout << "node " << current_node << " and donor: " << DonorStackVector[ this_node ] << endl; donor_nodes.push_back( DonorStackVector[ this_node ] ); } return donor_nodes; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // This function calculates the chi function for all the nodes upslope a given node // it takes a node list // // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- vector<float> LSDFlowInfo::get_upslope_chi(int starting_node, float m_over_n, float A_0) { vector<int> upslope_pixel_list = get_upslope_nodes(starting_node); vector<float> chi_vec = get_upslope_chi(upslope_pixel_list, m_over_n, A_0); return chi_vec; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // This function calculates the chi function for all the nodes upslope a given node // it takes a node list // // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- vector<float> LSDFlowInfo::get_upslope_chi(int starting_node, float m_over_n, float A_0, LSDRaster& Discharge) { vector<int> upslope_pixel_list = get_upslope_nodes(starting_node); vector<float> chi_vec = get_upslope_chi(upslope_pixel_list, m_over_n, A_0, Discharge); return chi_vec; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // This function is called from the the get_upslope_chi that only has an integer // it returns the acutal chi values in a vector //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- vector<float> LSDFlowInfo::get_upslope_chi(vector<int>& upslope_pixel_list, float m_over_n, float A_0) { int receiver_node; int IndexOfReceiverInUplsopePList; float root2 = 1.41421356; float diag_length = root2*DataResolution; float dx; float pixel_area = DataResolution*DataResolution; int node,row,col; // get the number of nodes upslope int n_nodes_upslope = upslope_pixel_list.size(); vector<float> chi_vec(n_nodes_upslope,0.0); if(n_nodes_upslope != NContributingNodes[ upslope_pixel_list[0] ]) { cout << "LSDFlowInfo::get_upslope_chi, the contributing pixels don't agree" << endl; exit(EXIT_FAILURE); } int start_SVector_node = SVectorIndex[ upslope_pixel_list[0] ]; for (int n_index = 1; n_index<n_nodes_upslope; n_index++) { node = upslope_pixel_list[n_index]; receiver_node = ReceiverVector[ node ]; IndexOfReceiverInUplsopePList = SVectorIndex[receiver_node]-start_SVector_node; row = RowIndex[node]; col = ColIndex[node]; if (FlowLengthCode[row][col] == 2) { dx = diag_length; } else { dx = DataResolution; } chi_vec[n_index] = dx*(pow( (A_0/ (float(NContributingNodes[node])*pixel_area) ),m_over_n)) + chi_vec[IndexOfReceiverInUplsopePList]; // cout << "node: " << upslope_pixel_list[n_index] << " receiver: " << receiver_node // << " SIndexReciever: " << IndexOfReceiverInUplsopePList // << " and checked: " << upslope_pixel_list[IndexOfReceiverInUplsopePList] // << " and chi: " << chi_vec[n_index] << endl; } return chi_vec; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // This function is called from the the get_upslope_chi that only has an integer // it returns the acutal chi values in a vector // same as above but uses a discharge raster //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- vector<float> LSDFlowInfo::get_upslope_chi(vector<int>& upslope_pixel_list, float m_over_n, float A_0, LSDRaster& Discharge) { int receiver_node; int IndexOfReceiverInUplsopePList; float root2 = 1.41421356; float diag_length = root2*DataResolution; float dx; int node,row,col; // get the number of nodes upslope int n_nodes_upslope = upslope_pixel_list.size(); vector<float> chi_vec(n_nodes_upslope,0.0); if(n_nodes_upslope != NContributingNodes[ upslope_pixel_list[0] ]) { cout << "LSDFlowInfo::get_upslope_chi, the contributing pixels don't agree" << endl; exit(EXIT_FAILURE); } int start_SVector_node = SVectorIndex[ upslope_pixel_list[0] ]; for (int n_index = 1; n_index<n_nodes_upslope; n_index++) { node = upslope_pixel_list[n_index]; receiver_node = ReceiverVector[ node ]; IndexOfReceiverInUplsopePList = SVectorIndex[receiver_node]-start_SVector_node; row = RowIndex[node]; col = ColIndex[node]; if (FlowLengthCode[row][col] == 2) { dx = diag_length; } else { dx = DataResolution; } chi_vec[n_index] = dx*(pow( (A_0/ ( Discharge.get_data_element(row, col) ) ),m_over_n)) + chi_vec[IndexOfReceiverInUplsopePList]; // cout << "node: " << upslope_pixel_list[n_index] << " receiver: " << receiver_node // << " SIndexReciever: " << IndexOfReceiverInUplsopePList // << " and checked: " << upslope_pixel_list[IndexOfReceiverInUplsopePList] // << " and chi: " << chi_vec[n_index] << endl; } return chi_vec; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // This function takes a list of starting nodes and calucaltes chi // it assumes each chi value has the same base level. //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- LSDRaster LSDFlowInfo::get_upslope_chi_from_multiple_starting_nodes(vector<int>& starting_nodes, float m_over_n, float A_0, float area_threshold) { // some variables for writing to the raster int curr_row; int curr_col; int curr_node; float PixelArea = DataResolution*DataResolution; float DrainArea; // an array to hold the chi values Array2D<float> new_chi(NRows,NCols,NoDataValue); int n_starting_nodes = int(starting_nodes.size()); for(int sn = 0; sn<n_starting_nodes; sn++) { // first check to see if this node has already been visited. If it has // all upslope nodes have also been visited so there is no point continuing // with this node retrieve_current_row_and_col(starting_nodes[sn],curr_row,curr_col); if(new_chi[curr_row][curr_col] == NoDataValue) { vector<float> us_chi = get_upslope_chi(starting_nodes[sn], m_over_n, A_0); vector<int> upslope_pixel_list = get_upslope_nodes(starting_nodes[sn]); int n_chi_nodes = int(us_chi.size()); for (int cn = 0; cn<n_chi_nodes; cn++) { // get the current row and column curr_node = upslope_pixel_list[cn]; retrieve_current_row_and_col(curr_node,curr_row,curr_col); // check to see if the drainage area is greater than the threshold // if so, calcualte chi DrainArea = PixelArea*NContributingNodes[curr_node]; if(DrainArea > area_threshold) { new_chi[curr_row][curr_col]= us_chi[cn]; } } } } LSDRaster chi_map(NRows, NCols, XMinimum, YMinimum, DataResolution, NoDataValue, new_chi,GeoReferencingStrings); return chi_map; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // This function takes a list of starting nodes and calucaltes chi // it assumes each chi value has the same base level. // Same as above but calculates using discharge //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- LSDRaster LSDFlowInfo::get_upslope_chi_from_multiple_starting_nodes(vector<int>& starting_nodes, float m_over_n, float A_0, float area_threshold, LSDRaster& Discharge ) { // some variables for writing to the raster int curr_row; int curr_col; int curr_node; float PixelArea = DataResolution*DataResolution; float DrainArea; // an array to hold the chi values Array2D<float> new_chi(NRows,NCols,NoDataValue); int n_starting_nodes = int(starting_nodes.size()); for(int sn = 0; sn<n_starting_nodes; sn++) { // first check to see if this node has already been visited. If it has // all upslope nodes have also been visited so there is no point continuing // with this node retrieve_current_row_and_col(starting_nodes[sn],curr_row,curr_col); if(new_chi[curr_row][curr_col] == NoDataValue) { vector<float> us_chi = get_upslope_chi(starting_nodes[sn], m_over_n, A_0,Discharge); vector<int> upslope_pixel_list = get_upslope_nodes(starting_nodes[sn]); int n_chi_nodes = int(us_chi.size()); for (int cn = 0; cn<n_chi_nodes; cn++) { // get the current row and column curr_node = upslope_pixel_list[cn]; retrieve_current_row_and_col(curr_node,curr_row,curr_col); // check to see if the drainage area is greater than the threshold // if so, calcualte chi DrainArea = PixelArea*NContributingNodes[curr_node]; if(DrainArea > area_threshold) { new_chi[curr_row][curr_col]= us_chi[cn]; } } } } LSDRaster chi_map(NRows, NCols, XMinimum, YMinimum, DataResolution, NoDataValue, new_chi,GeoReferencingStrings); return chi_map; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // This function assumes all base level nodes are at the same base level // and calculates chi for them. Essentially it covers the entire map in // chi values. // This function is probably most appropriate for looking at numerical // model results //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- LSDRaster LSDFlowInfo::get_upslope_chi_from_all_baselevel_nodes(float m_over_n, float A_0, float area_threshold) { LSDRaster all_chi = get_upslope_chi_from_multiple_starting_nodes(BaseLevelNodeList, m_over_n, A_0, area_threshold); return all_chi; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // This function assumes all base level nodes are at the same base level // and calculates chi for them. Essentially it covers the entire map in // chi values. // This function is probably most appropriate for looking at numerical // model results // same as above but calculates with a discharge //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- LSDRaster LSDFlowInfo::get_upslope_chi_from_all_baselevel_nodes(float m_over_n, float A_0, float area_threshold, LSDRaster& Discharge) { LSDRaster all_chi = get_upslope_chi_from_multiple_starting_nodes(BaseLevelNodeList, m_over_n, A_0, area_threshold, Discharge); return all_chi; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // // distance from outlet function // this is overloaded. // if it isn't provided any argument, it calculates the distance from outlet // of all the base level nodes // if it is given a node index number or a row and column, then // the distance from outlet includes all the distances upstream of that node // // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= LSDRaster LSDFlowInfo::distance_from_outlet() { // initialize the array2d that will become the LSDRaster float ndv = float(NoDataValue); Array2D<float> flow_distance(NRows,NCols,ndv); // initialize the 1/root(2) float root2 = 1.41421356; float diag_length = root2*DataResolution; int row,col,bl_row,bl_col,receive_row,receive_col; int start_node = 0; int end_node; int nodes_in_bl_tree; int baselevel_node; // loop through the base level node list int n_base_level_nodes = BaseLevelNodeList.size(); for(int bl = 0; bl<n_base_level_nodes; bl++) { baselevel_node = BaseLevelNodeList[bl]; bl_row = RowIndex[baselevel_node]; bl_col = ColIndex[baselevel_node]; // get the number of nodes upslope and including this node nodes_in_bl_tree = NContributingNodes[baselevel_node]; //cout << "LINE 938, FlowInfo, base level: " << bl << " with " << nodes_in_bl_tree << " nodes upstream" << endl; end_node = start_node+nodes_in_bl_tree; // set the distance of the outlet to zero flow_distance[bl_row][bl_col] = 0; // now loop through stack for(int s_node = start_node; s_node < end_node; s_node++) { //cout << "Line 953 flow info, s_node is: " << s_node << endl; //cout << SVector.size() << " " << ReceiverVector.size() << " " << RowIndex.size() << " " << ColIndex.size() << endl; row = RowIndex[ SVector[ s_node] ]; col = ColIndex[ SVector[ s_node] ]; //cout << "got rows and columns " << row << " " << col << endl; receive_row = RowIndex[ ReceiverVector[SVector[s_node] ]]; receive_col = ColIndex[ ReceiverVector[SVector[s_node] ]]; //cout << "get receive " << receive_row << " " << receive_col << endl; if ( FlowLengthCode[row][col] == 1) { flow_distance[row][col] = flow_distance[receive_row][receive_col]+DataResolution; } else if ( FlowLengthCode[row][col] == 2 ) { flow_distance[row][col] = flow_distance[receive_row][receive_col] + diag_length; } //cout << "Flow distance: " << flow_distance << endl; } start_node = end_node; } //cout << "LINE 971 FlowInfo Flow distance complete, flow_distance is: " << endl; //cout << flow_distance << endl; LSDRaster FlowLength(NRows,NCols,XMinimum,YMinimum,DataResolution,ndv, flow_distance,GeoReferencingStrings); return FlowLength; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // // This function get the d8 slope. It points downslope from each node // // SMM 22/09/2014 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- LSDRaster LSDFlowInfo::calculate_d8_slope(LSDRaster& Elevation) { float ndv = float(NoDataValue); Array2D<float> d8_slope(NRows,NCols,ndv); // these save a bit of computational expense. float root_2 = pow(2, 0.5); float dx_root2 = root_2*DataResolution; int this_row; int this_col; int r_row; int r_col; int r_node; float dx; for (int node = 0; node<NDataNodes; node++) { // get the row and column retrieve_current_row_and_col(node,this_row,this_col); // get the distance between nodes. Depends on flow direction switch (retrieve_flow_length_code_of_node(node)) { case 0: dx = -99; break; case 1: dx = DataResolution; break; case 2: dx = dx_root2; break; default: dx = -99; break; } // get the reciever information retrieve_receiver_information(node,r_node, r_row, r_col); // now calculate the slope if (r_node == node) { d8_slope[this_row][this_col] = 0; } else { d8_slope[this_row][this_col] = (1/dx)* (Elevation.get_data_element(this_row,this_col) -Elevation.get_data_element(r_row,r_col)); } } LSDRaster d8_slope_raster(NRows,NCols,XMinimum,YMinimum,DataResolution,ndv, d8_slope,GeoReferencingStrings); return d8_slope_raster; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // // // this finds the node that is farthest upstream from a given node // // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= int LSDFlowInfo::find_farthest_upslope_node(int node, LSDRaster& DistFromOutlet) { // set the farthest node to the current node; if the node has no contributing pixels // the function will just return itself int farthest_upslope_node = node; // first get the nodes that are upslope vector<int> upslope_node_list = get_upslope_nodes(node); int row, col; float this_flow_distance; // now loop through these, looking for the farthest upstream node float farthest = 0.0; int n_upslope_nodes = upslope_node_list.size(); for (int i = 0; i<n_upslope_nodes; i++) { // get the row and col of upslope nodes row = RowIndex[ upslope_node_list[i] ]; col = ColIndex[ upslope_node_list[i] ]; // get the flow distance this_flow_distance = DistFromOutlet.get_data_element(row, col); // test if it is the farthest if (this_flow_distance > farthest) { farthest = this_flow_distance; farthest_upslope_node = upslope_node_list[i]; } } return farthest_upslope_node; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // // This function takes a list of nodes and sorts them according to a sorting // raster // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- vector<int> LSDFlowInfo::sort_node_list_based_on_raster(vector<int> node_vec, LSDRaster& SortingRaster) { // First make a vector of the data from the sorting vector vector<float> VectorisedData; vector<float> SortedData; vector<int> SortedNodes; vector<size_t> index_map; int row,col; // loop through node vec, getting the value of the raster at each node int n_nodes = int(node_vec.size()); for (int n = 0; n<n_nodes; n++) { retrieve_current_row_and_col(node_vec[n],row,col); // now get the data element VectorisedData.push_back(SortingRaster.get_data_element(row,col)); } // now sort that data using the matlab sort matlab_float_sort(VectorisedData, SortedData, index_map); // now sort the nodes based on this sorting matlab_int_reorder(node_vec, index_map, SortedNodes); return SortedNodes; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // // This function takes a list of nodes and sorts them according to a sorting // raster // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- vector<int> LSDFlowInfo::sort_node_list_based_on_raster(vector<int> node_vec, LSDIndexRaster& SortingRaster) { // First make a vector of the data from the sorting vector vector<int> VectorisedData; vector<int> SortedData; vector<int> SortedNodes; vector<size_t> index_map; int row,col; // loop through node vec, getting the value of the raster at each node int n_nodes = int(node_vec.size()); for (int n = 0; n<n_nodes; n++) { retrieve_current_row_and_col(node_vec[n],row,col); // now get the data element VectorisedData.push_back(SortingRaster.get_data_element(row,col)); } // now sort that data using the matlab sort matlab_int_sort(VectorisedData, SortedData, index_map); // now sort the nodes based on this sorting matlab_int_reorder(node_vec, index_map, SortedNodes); return SortedNodes; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // get node index of point from X and Y coordinates // this is different from the above function in that it does not snap to the nearest channel // // FJC 11/02/14 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= int LSDFlowInfo::get_node_index_of_coordinate_point(float X_coordinate, float Y_coordinate) { // Shift origin to that of dataset float X_coordinate_shifted_origin = X_coordinate - XMinimum - DataResolution*0.5; float Y_coordinate_shifted_origin = Y_coordinate - YMinimum - DataResolution*0.5; // Get row and column of point int col_point = int(X_coordinate_shifted_origin/DataResolution); int row_point = (NRows-1) - int(round(Y_coordinate_shifted_origin/DataResolution)); // Get node of point int CurrentNode; if(col_point>=0 && col_point<NCols && row_point>=0 && row_point<NRows) { CurrentNode = retrieve_node_from_row_and_column(row_point, col_point); } else { CurrentNode = NoDataValue; } return CurrentNode; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Get vector of nodeindices from a csv file with X and Y coordinates // The csv file must have the format: ID, X, Y // // FJC 14/02/17 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= void LSDFlowInfo::get_nodeindices_from_csv(string csv_filename, vector<int>& NIs, vector<float>& X_coords, vector<float>& Y_coords) { ifstream csv_input(csv_filename.c_str()); vector<int> temp_NIs; vector<float> temp_X_Coords; vector<float> temp_Y_Coords; //initiate the string to hold the file string line_from_file; vector<string> empty_string_vec; vector<string> this_string_vec; string temp_string; // discard the first line getline(csv_input, line_from_file); // now loop through the rest of the lines while (getline(csv_input,line_from_file)) { // reset the string vec this_string_vec = empty_string_vec; // create a stringstream stringstream ss(line_from_file); while (ss.good()) { string substr; getline(ss,substr,','); // remove the spaces substr.erase(remove_if(substr.begin(), substr.end(), ::isspace), substr.end()); // remove control characters substr.erase(remove_if(substr.begin(), substr.end(), ::iscntrl), substr.end()); // add the string to the string vec this_string_vec.push_back( substr ); } // for some reason our compiler can't deal with stof so converting to doubles double X_coordinate = atof(this_string_vec[1].c_str()); double Y_coordinate = atof(this_string_vec[2].c_str()); // Shift origin to that of dataset float X_coordinate_shifted_origin = X_coordinate - XMinimum - DataResolution*0.5; float Y_coordinate_shifted_origin = Y_coordinate - YMinimum - DataResolution*0.5; // Get row and column of point int col_point = int(X_coordinate_shifted_origin/DataResolution); int row_point = (NRows-1) - int(round(Y_coordinate_shifted_origin/DataResolution)); // Get node of point int CurrentNode = NoDataValue; if(col_point>=0 && col_point<NCols && row_point>=0 && row_point<NRows) { CurrentNode = retrieve_node_from_row_and_column(row_point, col_point); } if (CurrentNode != NoDataValue) { temp_X_Coords.push_back(float(X_coordinate)); temp_Y_Coords.push_back(float(Y_coordinate)); temp_NIs.push_back(CurrentNode); } } //copy to output vectors NIs = temp_NIs; X_coords = temp_X_Coords; Y_coords = temp_Y_Coords; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // For a given node, find the nearest point in the raster that is not a NoDataValue and // snap it to the node. User must specify the search radius in pixels. // FJC 08/02/17 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= float LSDFlowInfo::snap_RasterData_to_Node(int NodeIndex, LSDRaster& InputRaster, int search_radius) { float RasterValue_at_Node; Array2D<float> InputRasterData = InputRaster.get_RasterData(); int i,j; retrieve_current_row_and_col(NodeIndex,i,j); if (InputRasterData[i][j] != NoDataValue) { // The node index already has a raster value! RasterValue_at_Node = InputRasterData[i][j]; } else { vector<float> Data_in_window; vector<float> Dists_in_window; vector<float> Dists_in_window_sorted; vector<size_t> index_map; Data_in_window.reserve(4 * search_radius); Dists_in_window.reserve(4 * search_radius); Dists_in_window_sorted.reserve(4 * search_radius); index_map.reserve(4 * search_radius); //set up the bounding box int i_min = i - search_radius; int i_max = i + search_radius; int j_min = j - search_radius; int j_max = j + search_radius; //out of bounds checking if (i_min < 0){i_min = 0;} if (j_min < 0){j_min = 0;} if (i_max > (NRows - 1)){i_max = (NRows - 1);} if (j_max > (NCols - 1)){j_max = (NCols - 1);} // only iterate over the search area. for (int row = i_min; row < i_max; ++row){ for (int col = j_min; col < j_max; ++col){ if (InputRasterData[row][col] != NoDataValue) { //get the raster data and distance at each point in the window Data_in_window.push_back(InputRasterData[row][col]); float Dist = distbetween(i,j,row,col); Dists_in_window.push_back(Dist); } } } if (int(Data_in_window.size()) != 0) { matlab_float_sort(Dists_in_window, Dists_in_window_sorted, index_map); // return the raster value at the smallest distance from the point RasterValue_at_Node = Data_in_window[index_map[0]]; } else { // if no raster values in the window then return nodatavalue RasterValue_at_Node = NoDataValue; } } return RasterValue_at_Node; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // a get sources version that uses the flow accumulation pixels // // // SMM 01/06/2012 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= vector<int> LSDFlowInfo::get_sources_index_threshold(LSDIndexRaster& FlowPixels, int threshold) { vector<int> sources; int row,col; //int n_donors; int donor_row,donor_col; int thresh_switch; int donor_node; // drop down through the stack // if the node is greater than or equal to the threshold // check all the donors // if there are no donors, then the node is a source // if none of the donors are greater than the threshold, then it also is a source for (int node = 0; node<NDataNodes; node++) { row = RowIndex[node]; col = ColIndex[node]; // see if node is greater than threshold if(FlowPixels.get_data_element(row,col)>=threshold) { //cout << "node " << node << " is a potential source, it has a value of " // << FlowPixels.get_data_element(row,col) // << "and it has " << NDonorsVector[node] <<" donors " << endl; // if it doesn't have donors, it is a source if(NDonorsVector[node] == 0) { sources.push_back(node); } else { thresh_switch = 1; // figure out where the donor nodes are, and if // the donor node is greater than the threshold for(int dnode = 0; dnode<NDonorsVector[node]; dnode++) { donor_node = DonorStackVector[ DeltaVector[node]+dnode]; donor_row = RowIndex[ donor_node ]; donor_col = ColIndex[ donor_node ]; // we don't float count base level nodes, which donate to themselves if (donor_node != node) { // if the donor node is greater than the threshold, // then this node is not a threhold if(FlowPixels.get_data_element(donor_row,donor_col)>=threshold) { thresh_switch = 0; } } //cout << "thresh_switch is: " << thresh_switch << endl; } // if all of the donors are below the threhold, this is a source if (thresh_switch == 1) { sources.push_back(node); } } } } return sources; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // a get sources version that uses a threshold of drainage area * slope^2 // // // FJC 11/02/14 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= vector<int> LSDFlowInfo::get_sources_slope_area(LSDIndexRaster& FlowPixels, LSDRaster& Slope, int threshold) { vector<int> sources; int row,col; //int n_donors; int donor_row,donor_col; int thresh_switch; int donor_node; // drop down through the stack // if the node is greater than or equal to the threshold // check all the donors // if there are no donors, then the node is a source // if none of the donors are greater than the threshold, then it also is a source for (int node = 0; node<NDataNodes; node++) { row = RowIndex[node]; col = ColIndex[node]; float area = FlowPixels.get_data_element(row,col); float slope = Slope.get_data_element(row,col); float SA_product = area * (slope*slope); // see if node is greater than threshold if(SA_product >= threshold) { //cout << "node " << node << " is a potential source, it has a value of " // << SA_product // << "and it has " << NDonorsVector[node] <<" donors " << endl; // if it doesn't have donors, it is a source if(NDonorsVector[node] == 0) { sources.push_back(node); } else { thresh_switch = 1; // figure out where the donor nodes are, and if // the donor node is greater than the threshold for(int dnode = 0; dnode<NDonorsVector[node]; dnode++) { donor_node = DonorStackVector[ DeltaVector[node]+dnode]; donor_row = RowIndex[ donor_node ]; donor_col = ColIndex[ donor_node ]; // we don't float count base level nodes, which donate to themselves if (donor_node != node) { // if the donor node is greater than the threshold, // then this node is not a threhold float area_donor = FlowPixels.get_data_element(donor_row,donor_col); float slope_donor = Slope.get_data_element(donor_row,donor_col); float SA_product_donor = area_donor * (slope_donor*slope_donor); if(SA_product_donor >= threshold) { thresh_switch = 0; } } //cout << "thresh_switch is: " << thresh_switch << endl; } // if all of the donors are below the threhold, this is a source if (thresh_switch == 1) { sources.push_back(node); } } } } return sources; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // a get sources version that uses the X and Y coordinates of mapped channel heads // // // FJC 17/02/14 // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= vector<int> LSDFlowInfo::get_sources_from_mapped_channel_heads(vector<float>& X_coords, vector<float>& Y_coords) { vector<int> SourceNodes; cout << "N of channel heads: " << X_coords.size() << endl; for (unsigned int i = 0; i < X_coords.size(); i++) { int NI = get_node_index_of_coordinate_point(X_coords[i], Y_coords[i]); if (NI != NoDataValue) { SourceNodes.push_back(NI); } } return SourceNodes; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // Perform a downslope trace using D8 from a given point source (i,j). //Overwrites input parameters to return a raster of the path, the length of the //trace and the final pixel coordinates of the trace. // SWDG 20/1/14 //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= void LSDFlowInfo::D8_Trace(int i, int j, LSDIndexRaster StreamNetwork, float& length, int& receiver_row, int& receiver_col, Array2D<int>& Path){ float root_2 = 1.4142135623; Array2D<int> stnet = StreamNetwork.get_RasterData(); length = 0; int node; int reciever_node = retrieve_node_from_row_and_column(i, j); receiver_row = i; receiver_col = j; Path[receiver_row][receiver_col] = 1; while (StreamNetwork.get_data_element(receiver_row, receiver_col) == NoDataValue){ // need to do edge checking retrieve_receiver_information(reciever_node, node, receiver_row, receiver_col); Path[receiver_row][receiver_col] = 1; //update length if (retrieve_flow_length_code_of_node(reciever_node) == 1){ length += DataResolution; } else if (retrieve_flow_length_code_of_node(reciever_node) == 2){ length += (DataResolution * root_2); } reciever_node = node; } } // Move the location of the channel head downslope by a user defined distance. // Returns A vector of node indexes pointing to the moved heads. // SWDG 27/11/15 void LSDFlowInfo::MoveChannelHeadDown(vector<int> Sources, float MoveDist, vector<int>& DownslopeSources, vector<int>& FinalHeads){ float root_2 = 1.4142135623; float length; int receiver_row; int receiver_col; int node; //for loop goes here to iterate over the Sources vector for(int q=0; q<int(Sources.size());++q){ length = 0; int reciever_node = Sources[q]; while (length < MoveDist){ retrieve_receiver_information(reciever_node, node, receiver_row, receiver_col); //update length if (retrieve_flow_length_code_of_node(reciever_node) == 1){ length += DataResolution; } else if (retrieve_flow_length_code_of_node(reciever_node) == 2){ length += (DataResolution * root_2); } else if (retrieve_flow_length_code_of_node(reciever_node) == 0){break;} reciever_node = node; } DownslopeSources.push_back(reciever_node); FinalHeads.push_back(Sources[q]); } //end of for loop } // Move the location of the channel head upslope by a user defined distance. // Returns A vector of node indexes pointing to the moved heads. // SWDG 27/11/15 void LSDFlowInfo::MoveChannelHeadUp(vector<int> Sources, float MoveDist, LSDRaster DEM, vector<int>& UpslopeSources, vector<int>& FinalHeads){ float root_2 = 1.4142135623; float length; Array2D<float> Elevation = DEM.get_RasterData(); int new_node; int new_i; int new_j; //for loop goes here to iterate over the Sources vector for(int q=0; q<int(Sources.size());++q){ length = 0; int i; int j; retrieve_current_row_and_col(Sources[q], i, j); //test for channel heads at edges if (i == 0 || i == NRows - 1 || j == 0 || j == NCols - 1){ cout << "Hit an edge, skipping" << endl; } else{ while (length < MoveDist){ float currentElevation; int Direction; //1 is cardinal 2 is diagonal //find the neighbour with the maximum Elevation currentElevation = Elevation[i][j]; //top left if(currentElevation < Elevation[i-1][j-1]){ currentElevation = Elevation[i-1][j-1]; new_i = i-1; new_j = j-1; Direction = 2; } //top if(currentElevation < Elevation[i][j-1]){ currentElevation = Elevation[i][j-1]; new_i = i; new_j = j-1; Direction = 1; } //top right if(currentElevation < Elevation[i+1][j-1]){ currentElevation = Elevation[i+1][j-1]; new_i = i+1; new_j = j-1; Direction = 2; } //right if(currentElevation < Elevation[i+1][j]){ currentElevation = Elevation[i+1][j]; new_i = i+1; new_j = j; Direction = 1; } //botom right if(currentElevation < Elevation[i+1][j+1]){ currentElevation = Elevation[i+1][j+1]; new_i = i+1; new_j = j+1; Direction = 2; } //bottom if(currentElevation < Elevation[i][j+1]){ currentElevation = Elevation[i][j+1]; new_i = i; new_j = j+1; Direction = 1; } //bottom left if(currentElevation < Elevation[i-1][j+1]){ currentElevation = Elevation[i-1][j+1]; new_i = i-1; new_j = j+1; Direction = 2; } //left if(currentElevation < Elevation[i-1][j]){ currentElevation = Elevation[i-1][j]; new_i = i-1; new_j = j; Direction = 1; } //test that we have not hit the ridge //this will exit the loop and add the final visited //node to the upper soureces vector if (currentElevation == Elevation[i][j]){ cout << "Warning, unable to move channel head " << Sources[q] << " up by user defined distance" << endl; break; } //update length if (Direction == 1){ length += DataResolution; } else if (Direction == 2){ length += (DataResolution * root_2); } i = new_i; j = new_j; } } new_node = retrieve_node_from_row_and_column(i,j); UpslopeSources.push_back(new_node); FinalHeads.push_back(Sources[q]); } //end of for loop } void LSDFlowInfo::HilltopFlowRoutingOriginal(LSDRaster Elevation, LSDRaster Hilltops, LSDRaster Slope, LSDRaster Aspect, LSDIndexRaster StreamNetwork) { //Declare parameters int i,j,a,b; //double X,Y; float dem_res = DataResolution; //float mean_slope, relief; int ndv = NoDataValue; double slope_total, length, d; int flag, count; double PI = 3.14159265; double degs, degs_old, degs_new, theta; double s_local, s_edge; double xo, yo, xi, yi, temp_yo1, temp_yo2, temp_xo1, temp_xo2; // a direction flag numbered 1,2,3,4 for E,S,W,N respectively int dir; double xmin = XMinimum; double ymin = YMinimum; double ymax = ymin + NRows*dem_res; //double xmax = xmin + NCols*dem_res; //Declare Arrays //Get data arrays from LSDRasters Array2D<float> zeta = Elevation.get_RasterData(); //elevation Array2D<int> stnet = StreamNetwork.get_RasterData(); // stream network Array2D<float> aspect = Aspect.get_RasterData(); //aspect Array2D<float> hilltops = Hilltops.get_RasterData(); //hilltops Array2D<float> slope = Slope.get_RasterData(); //hilltops Array2D<float> rads(NRows,NCols); Array2D<float> path(NRows, NCols); Array2D<float> blank(NRows,NCols,NoDataValue); int vec_size = 1000000; Array1D<double> easting(NCols); Array1D<double> northing(NRows); Array1D<double> east_vec(vec_size); Array1D<double> north_vec(vec_size); //for creating file names for hillslope profiles string file_part_1 = "prof_"; string file_part_2; string file_part_3 = ".txt"; string filename; char filename_c[256]; //calculate northing and easting for (i=0;i<NRows;++i){ northing[i] = ymax - i*dem_res - 0.5; } for (j=0;j<NCols;++j){ easting[j] = xmin + j*dem_res + 0.5; } int ht_count = 0; // cycle through study area, find hilltops and trace downstream for (i=1; i<NRows-1; ++i) { for (j=1; j<NCols-1; ++j) { // ignore edge cells and non-hilltop cells // route initial node by aspect and get outlet coordinates if (hilltops[i][j] != ndv) { //reset slope, length, hillslope flag and pixel counter slope_total = 0; length = 0; flag = true; count = 1; //copt blank raster to map hillslope trace path = blank.copy(); //update hilltop counter ++ht_count; //get aspect in radians degs = aspect[i][j]; theta = (M_PI/180.)*((-1*degs)+90.); //setup indices a = i; b = j; path[a][b] = 1; //add first pixel to easting northing vectors east_vec[0] = easting[b]; north_vec[0] = northing[a]; //get local slope s_local = slope[a][b]; //test direction, calculate outlet coordinates and update indicies // easterly, dir == 1 if (degs >= 45 && degs < 135) { //find location where trace exits the cell and distance xo = 1., yo = (1.+tan(theta))/2.; d = abs(1./(2.*cos(theta))); //transmit to next cell over xi = 0., yi = yo; dir = 1; //add to vector east_vec[count] = easting[b] + 0.5*dem_res; north_vec[count] = northing[a] + yo - 0.5*dem_res; //increment indices ++b; //check we're not right in the corner! if (yi == 0) yi = 0.00001; else if (yi == 1) yi = 1 - 0.00001; } //southerly else if (degs >= 135 && degs < 225) { //find location where trace exits the cell and distance xo = (1-(1/tan(theta)))/2, yo = 0; d = abs(1/(2*cos((PI/2)-theta))); //transmit to next cell over xi = xo, yi = 1; dir = 2; //add to vector east_vec[count] = easting[b] + xo - 0.5*dem_res; north_vec[count] = northing[a] - 0.5*dem_res; //increment indices ++a; //check we're not right in the corner! if (xi == 0) xi = 0.00001; else if (xi == 1) xi = 1 - 0.00001; } // westerly else if (degs >= 225 && degs < 315) { //find location where trace exits the cell and distance xo = 0, yo = (1-tan(theta))/2; d = abs(1/(2*cos(theta))); //transmit to next cell over xi = 1, yi = yo; dir = 3; //add to vector east_vec[count] = easting[b] -0.5*dem_res; north_vec[count] = northing[a] + yo - 0.5*dem_res; //increment indices --b; //check we're not right in the corner! if (yi == 0) yi = 0.00001; else if (yi == 1) yi = 1 - 0.00001; } //northerly else if (degs >= 315 || degs < 45) { //find location where trace exits the cell and distance xo = (1+(1/tan(theta)))/2, yo = 1; d = abs(1/(2*cos((PI/2) - theta))); //transmit to next cell over xi = xo, yi = 0; dir = 4; //add to vector east_vec[count] = easting[b] + xo - 0.5*dem_res; north_vec[count] = northing[a] + 0.5*dem_res; //increment indices --a; //check we're not right in the corner! if (xi == 0) xi = 0.00001; else if (xi == 1) xi = 1 - 0.00001; } else { cout << "FATAL ERROR, Kinematic routing algorithm encountered null aspect value" << endl; exit(EXIT_FAILURE); } //collect slopes and totals weighted by path length //slope_total += s_local*d; //length += d; s_local = slope[a][b]; //continue trace until a stream node is encountered while (flag == true) { path[a][b] = 1; degs_old = degs; degs_new = aspect[a][b]; theta = (M_PI/180.)*((-1*degs_new)+90.); ++ count; //Test for perimeter flow paths if ((dir == 1 && degs_new > 0 && degs_new < 180) || (dir == 2 && degs_new > 90 && degs_new < 270) || (dir == 3 && degs_new > 180 && degs_new < 360) || ((dir == 4 && degs_new > 270) || (dir == 4 && degs_new < 90))) { //DO NORMAL FLOW PATH //set xo, yo to 0 and 1 in turn and test for true outlet (xi || yi == 0 || 1) temp_yo1 = yi + (1-xi)*tan(theta); // xo = 1 temp_xo1 = xi + (1-yi)*(1/tan(theta)); // yo = 1 temp_yo2 = yi - xi*tan(theta); // xo = 0 temp_xo2 = xi - yi*(1/tan(theta)); // yo = 0 // can't outlet at same point as inlet if (dir == 1) temp_yo2 = -1; else if (dir == 2) temp_xo1 = -1; else if (dir == 3) temp_yo1 = -1; else if (dir == 4) temp_xo2 = -1; s_local = slope[a][b]; if (temp_yo1 <= 1 && temp_yo1 > 0) { xo = 1, yo = temp_yo1; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 0, yi = yo, dir = 1; east_vec[count] = easting[b] + 0.5*dem_res; north_vec[count] = northing[a] + yo - 0.5*dem_res; ++b; if (xi== 0 && yi == 0) yi = 0.00001; else if (xi== 0 && yi == 1) yi = 1 - 0.00001; } else if (temp_xo2 <= 1 && temp_xo2 > 0) { xo = temp_xo2, yo = 0; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1, dir = 2; east_vec[count] = easting[b] + xo - 0.5*dem_res; north_vec[count] = northing[a] - 0.5*dem_res; ++a; if (xi== 0 && yi == 1) xi = 0.00001; else if (xi== 1 && yi == 1) xi = 1 - 0.00001; } else if (temp_yo2 <= 1 && temp_yo2 > 0) { xo = 0, yo = temp_yo2; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1, yi = yo, dir = 3; east_vec[count] = easting[b] -0.5*dem_res; north_vec[count] = northing[a] + yo - 0.5*dem_res; --b; if (xi== 1 && yi == 0) yi = 0.00001; else if (xi== 1 && yi == 1) yi = 1 - 0.00001; } else if (temp_xo1 <= 1 && temp_xo1 > 0) { xo = temp_xo1, yo = 1; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 0, dir = 4; east_vec[count] = easting[b] + xo - 0.5*dem_res; north_vec[count] = northing[a] + 0.5*dem_res; --a; if (xi == 0 && yi == 0) xi = 0.00001; else if (xi== 1 && yi == 0) xi = 1 - 0.00001; } slope_total += s_local*d; } else { // ROUTE ALONG EDGES if (dir == 1) { if (degs_old <= 90 || degs_new >= 270) { xo = 0.00001, yo = 1; s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1-yo; dir = 4; east_vec[count] = easting[b] + xo - 0.5*dem_res; north_vec[count] = northing[a] + 0.5*dem_res; --a; } else if (degs_old > 90 && degs_new < 270) { xo = 0.00001, yo = 0; s_edge = abs(s_local*sin((PI/2)-theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1-yo; dir = 2; east_vec[count] = easting[b] + xo - 0.5*dem_res; north_vec[count] = northing[a] - 0.5*dem_res; ++a; } else { cout << "Flow unable to route N or S" << endl; exit(EXIT_FAILURE); } } else if (dir == 2) { if (degs_old <= 180 && degs_new >= 0) { xo = 1, yo = 1-0.00001; s_edge = abs(s_local*sin((2/PI)-theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*dem_res; north_vec[count] = northing[a] + yo - 0.5*dem_res; ++b; } else if (degs_old > 180 && degs_new < 360) { xo = 0, yo = 1-0.00001; s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*dem_res; north_vec[count] = northing[a] + yo - 0.5*dem_res; --b; } else { cout << "Flow unable to route E or W" << endl; exit(EXIT_FAILURE); } } else if (dir == 3) { if (degs_old <= 270 && degs_new >= 90) { xo = 1-0.00001, yo = 0; s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1-yo; dir = 2; east_vec[count] = easting[b] + xo - 0.5*dem_res; north_vec[count] = northing[a] - 0.5*dem_res; ++a; } else if (degs_old > 270 || degs_new < 90) { xo = 1-0.00001, yo = 1; s_edge = abs(s_local*sin((2/PI) - theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1- yo; dir = 4; east_vec[count] = easting[b] + xo - 0.5*dem_res; north_vec[count] = northing[a] + 0.5*dem_res; --a; } else { cout << "Flow unable to route N or S" << endl; exit(EXIT_FAILURE); } } else if (dir == 4) { if (degs_old <= 360 && degs_new >= 180) { xo = 0, yo = 0.00001; s_edge = abs(s_local*sin((PI/2) - theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*dem_res; north_vec[count] = northing[a] + yo - 0.5*dem_res; --b; } else if (degs_old > 0 && degs_new < 180) { xo = 1, yo = 0.00001; s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*dem_res; north_vec[count] = northing[a] + yo - 0.5*dem_res; ++b; } else { cout << "Flow unable to route E or W" << endl; exit(EXIT_FAILURE); } } slope_total += s_edge*d; } length += d; degs = degs_new; //cout << "[a][b]: " << a << " " << b << endl; if (a <= 0 || b <= 0 || a >= NRows-1 || b >= NCols-1) flag = false; else if (stnet[a][b] != ndv || path[a][b] == 1) flag = false; } //if trace finished at a stream, print hillslope info. if (a <= 0 || b <= 0 || a >= NRows-1 || b >= NCols-1) continue; else { if (path[a][b] == 1) { cout << "Didn't make it to a channel!" << endl; } // // PRINT TO FILE Cht Sbar Relief Lh // X = xmin + j*dem_res; // Y = ymin + (NRows-i)*dem_res; // relief = zeta[i][j] - zeta[a][b]; // length = length*dem_res; // mean_slope = slope_total/(length/dem_res); // ofs << X << " " << Y << " " << seg[i][j] << " " // << cht[i][j] << " " << mean_slope << " " // << relief << " " << length << " " << "/n"; //area[a][b] << "\n"; //PRINT FILE OF PATH NODES FOR EACH HILLSLOPE VECTOR stringstream s; s << ht_count; file_part_2 = s.str(); filename = file_part_1; filename.append(file_part_2), filename.append(file_part_3); strcpy(filename_c,filename.c_str()); ofstream prof_out; prof_out.open(filename_c); prof_out << "Easting " << "Northing" << endl; prof_out.precision(10); for (int c=0;c<count;++c) { prof_out << east_vec[c] << " " << north_vec[c] << endl; } prof_out.close(); } } //return condition for debugging purposes only //if (ht_count > 50) return; } } } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // Hilltop flow routing code built around original code from Martin Hurst. Based on // Lea (1992), with improvements discussed by Tarboton (1997) and a solution to the // problem of looping flow paths implemented. // // This code is SLOW but robust, a refactored version may appear, but there may not be // enough whisky in Scotland to support that endeavour. // // The algorithm now checks for local uphill flows and in the case of identifying one, // D8 flow path is used to push the flow into the centre of the steepest downslope // cell, at which point the trace is restarted. The same technique is used to cope // with self intersections of the flow path. These problems are not solved in the // original paper and I think they are caused at least in part by the high resolution // topogrpahy we are using. // // The code is also now built to take a d infinity flow direction raster instead of an // aspect raster. See Tarboton (1997) for discussions on why this is the best solution. // // The Basins input raster is used to code each hilltop into a basin to allow basin // averaging to take place. // // The final 5 parameters are used to set up printing flow paths to files for visualisation, // if this is not needed simply pass in false to the two boolean switches and empty variables for the // others, and the code will run as normal. // // The structure of the returned vector< Array2D<float> > is as follows: // [0] Hilltop Network coded with stream ID // [1] Hillslope Lengths // [2] Slope // [3] Relief // // SWDG 12/2/14 //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= vector< Array2D<float> > LSDFlowInfo::HilltopFlowRouting(LSDRaster Elevation, LSDRaster Hilltops, LSDRaster Slope, LSDIndexRaster StreamNetwork, LSDRaster Aspect, string Prefix, LSDIndexRaster Basins, LSDRaster PlanCurvature, bool print_paths_switch, int thinning, string trace_path, bool basin_filter_switch, vector<int> Target_Basin_Vector){ //Declare parameters int i,j; int a = 0; int b = 0; float X,Y; float mean_slope, relief; float length, d; int flag; int count = 0; int DivergentCountFlag = 0; //Flag used to count the number of divergent cells encountered in a trace int PlanarCountFlag; float PI = 3.14159265; float degs, degs_new, theta; float s_local, s_edge; float xo, yo, xi, yi, temp_yo1, temp_yo2, temp_xo1, temp_xo2; bool skip_trace; //flag used to skip traces where no path to a stream can be found. Will only occur on noisy, raw topography float E_Star = 0; float R_Star = 0; float EucDist = 0; //debugging counters int ns_count = 0; int s_count = 0; int neg_count = 0; int edge_count = 0; int ht_count = 0; // a direction flag numbered 1,2,3,4 for E,S,W,N respectively int dir; float ymax = YMinimum + NRows*DataResolution; //Get data arrays from LSDRasters Array2D<float> zeta = Elevation.get_RasterData(); //elevation Array2D<int> stnet = StreamNetwork.get_RasterData(); // stream network Array2D<float> aspect = Aspect.get_RasterData(); //aspect Array2D<float> hilltops = Hilltops.get_RasterData(); //hilltops Array2D<float> slope = Slope.get_RasterData(); //hilltops Array2D<int> basin = Basins.get_RasterData(); //basins //empty arrays for data to be stored in Array2D<float> rads(NRows,NCols); Array2D<float> path(NRows, NCols, 0.0); Array2D<float> blank(NRows, NCols, 0.0); Array2D<float> RoutedHilltops(NRows,NCols,NoDataValue); Array2D<float> HillslopeLength_Array(NRows,NCols,NoDataValue); Array2D<float> Slope_Array(NRows,NCols,NoDataValue); Array2D<float> Relief_Array(NRows,NCols,NoDataValue); //vector to store the output data arrays in one vector that can be returned vector< Array2D<float> > OutputArrays; int vec_size = 1000000; Array1D<double> easting(NCols); Array1D<double> northing(NRows); Array1D<double> east_vec(vec_size); Array1D<double> north_vec(vec_size); ofstream ofs; //create the output filename from the user supplied filename prefix stringstream ss_filename; ss_filename << Prefix << "_HilltopData.csv"; ofs.open(ss_filename.str().c_str()); if( ofs.fail() ){ cout << "\nFATAL ERROR: unable to write to " << ss_filename.str() << endl; exit(EXIT_FAILURE); } ofs << "X,Y,i,j,hilltop_id,S,R,Lh,BasinID,a,b,StreamID,HilltopSlope,DivergentCount\n"; //calculate northing and easting for (i=0;i<NRows;++i){ northing[i] = ymax - i*DataResolution - 0.5; } for (j=0;j<NCols;++j){ easting[j] = XMinimum + j*DataResolution + 0.5; } //convert aspects to radians with east as theta = 0/2*pi for (i=0; i<NRows; ++i) { for (j=0; j<NCols; ++j) { //convert aspects to radians with east as theta = 0/2*pi if (rads[i][j] != NoDataValue) rads[i][j] = BearingToRad(aspect[i][j]); } } // cycle through study area, find hilltops and trace downstream for (i=1; i<NRows-1; ++i) { cout << flush << "\tRow: " << i << " of = " << NRows-1 << " \r"; for (j=1; j<NCols-1; ++j) { // ignore edge cells and non-hilltop cells // route initial node by aspect and get outlet coordinates if (hilltops[i][j] != NoDataValue) { length = 0; flag = true; count = 1; path = blank.copy(); DivergentCountFlag = 0; //initialise count of divergent cells in trace PlanarCountFlag = 0; skip_trace = false; //initialise skip trace flag as false, will only be switched if no path to stream can be found. Very rare. E_Star = 0; R_Star = 0; EucDist = 0; ++ht_count; degs = aspect[i][j]; theta = rads[i][j]; a = i; b = j; path[a][b] += 1; east_vec[0] = easting[b]; north_vec[0] = northing[a]; s_local = slope[a][b]; //test direction, calculate outlet coordinates and update indicies // easterly if (degs >= 45 && degs < 135) { //cout << "\neasterly" << endl; xo = 1, yo = (1+tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 0, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; if (yi == 0) yi = 0.00001; else if (yi == 1) yi = 1 - 0.00001; } //southerly else if (degs >= 135 && degs < 225) { //cout << "\nsoutherly" << endl; xo = (1-(1/tan(theta)))/2, yo = 0; d = abs(1/(2*cos((PI/2)-theta))); xi = xo, yi = 1; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; if (xi == 0) xi = 0.00001; else if (xi == 1) xi = 1 - 0.00001; } // westerly else if (degs >= 225 && degs < 315) { xo = 0, yo = (1-tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 1, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; if (yi == 0) yi = 0.00001; else if (yi == 1) yi = 1 - 0.00001; } //northerly else if (degs >= 315 || degs < 45) { xo = (1+(1/tan(theta)))/2, yo = 1; d = abs(1/(2*cos((PI/2) - theta))); xi = xo, yi = 0; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; if (xi == 0) xi = 0.00001; else if (xi == 1) xi = 1 - 0.00001; } else { cout << "FATAL ERROR, Kinematic routing algorithm enountered null aspect value" << endl; exit(EXIT_FAILURE); } //collect slopes and totals weighted by path length length += d; s_local = slope[a][b]; //continue trace until a stream node is encountered while (flag == true && a > 0 && a < NRows-1 && b > 0 && b < NCols-1) { //added boudary checking to catch cells which flow off the edge of the DEM tile. path[a][b] += 1; degs_new = aspect[a][b]; theta = rads[a][b]; ++count; //Test for perimeter flow paths if ((dir == 1 && degs_new > 0 && degs_new < 180) || (dir == 2 && degs_new > 90 && degs_new < 270) || (dir == 3 && degs_new > 180 && degs_new < 360) || ((dir == 4 && degs_new > 270) || (dir == 4 && degs_new < 90))) { //DO NORMAL FLOW PATH //set xo, yo to 0 and 1 in turn and test for true outlet (xi || yi == 0 || 1) temp_yo1 = yi + (1-xi)*tan(theta); // xo = 1 temp_xo1 = xi + (1-yi)*(1/tan(theta)); // yo = 1 temp_yo2 = yi - xi*tan(theta); // xo = 0 temp_xo2 = xi - yi*(1/tan(theta)); // yo = 0 // can't outlet at same point as inlet if (dir == 1) temp_yo2 = -1; else if (dir == 2) temp_xo1 = -1; else if (dir == 3) temp_yo1 = -1; else if (dir == 4) temp_xo2 = -1; s_local = slope[a][b]; if (temp_yo1 <= 1 && temp_yo1 > 0) { xo = 1, yo = temp_yo1; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 0, yi = yo, dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; if (xi== 0 && yi == 0) yi = 0.00001; else if (xi== 0 && yi == 1) yi = 1 - 0.00001; } else if (temp_xo2 <= 1 && temp_xo2 > 0) { xo = temp_xo2, yo = 0; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1, dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; if (xi== 0 && yi == 1) xi = 0.00001; else if (xi== 1 && yi == 1) xi = 1 - 0.00001; } else if (temp_yo2 <= 1 && temp_yo2 > 0) { xo = 0, yo = temp_yo2; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1, yi = yo, dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; if (xi== 1 && yi == 0) yi = 0.00001; else if (xi== 1 && yi == 1) yi = 1 - 0.00001; } else if (temp_xo1 <= 1 && temp_xo1 > 0) { xo = temp_xo1, yo = 1; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 0, dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; if (xi == 0 && yi == 0) xi = 0.00001; else if (xi== 1 && yi == 0) xi = 1 - 0.00001; } } else { // ROUTE ALONG EDGES if (dir == 1) { if (degs_new <= 90 || degs_new >= 270) { //secondary compenent of flow is north xo = 0.00001, yo = 1; s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1-yo; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; } else if (degs_new > 90 && degs_new < 270) { //secondary component is south xo = 0.00001, yo = 0; s_edge = abs(s_local*sin((PI/2)-theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1-yo; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; } else { cout << "Flow unable to route N or S " << endl; //something has gone very wrong... cout << "Trace skipped.\n" << endl; skip_trace = true; //exit(EXIT_FAILURE); } } else if (dir == 2) { if (degs_new >= 0 && degs_new <= 180) { //secondary component is East xo = 1, yo = 1-0.00001; s_edge = abs(s_local*sin((2/PI)-theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; } else if (degs_new > 180 && degs_new <= 360) { //secondary component is West xo = 0, yo = 1-0.00001; s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; } else { cout << "Flow unable to route E or W" << endl; //something has gone very wrong... cout << "Trace skipped.\n" << endl; skip_trace = true; //exit(EXIT_FAILURE); } } else if (dir == 3) { if (degs_new >= 90 && degs_new <= 270) { //secondary component is South xo = 1-0.00001, yo = 0; s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1-yo; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; } else if (degs_new > 270 || degs_new < 90) { //secondary component is North xo = 1-0.00001, yo = 1; s_edge = abs(s_local*sin((2/PI) - theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1- yo; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; } else { cout << "Flow unable to route N or S" << endl; //something has gone very wrong... cout << "Trace skipped.\n" << endl; skip_trace = true; //exit(EXIT_FAILURE); } } else if (dir == 4) { if (degs_new >= 180 && degs_new <= 360) { //secondary component is West xo = 0, yo = 0.00001; s_edge = abs(s_local*sin((PI/2) - theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; } else if (degs_new >= 0 && degs_new < 180) { //secondary component is East xo = 1, yo = 0.00001; s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; } else { cout << "Flow unable to route E or W" << endl; //something has gone very wrong... cout << "Trace skipped.\n" << endl; skip_trace = true; //exit(EXIT_FAILURE); } } } if (path[a][b] < 1){ // only update length on 'first slosh' length += d; } else if (path[a][b] >= 3){ //update the skip trace flag so we can categorise each trace skip_trace = true; } degs = degs_new; // test for plan curvature here and set a flag if flow is divergent or convergent but continue trace regardless // The larger the counter the more convergent or divergent the trace is if (abs(PlanCurvature.get_data_element(a,b)) > (0.001)){ ++DivergentCountFlag; } else { ++PlanarCountFlag; } if (a == 0 || b == 0 || a == NRows-1 || b == NCols-1 || stnet[a][b] != NoDataValue || stnet[a-1][b-1] != NoDataValue || stnet[a][b-1] != NoDataValue || stnet[a+1][b-1] != NoDataValue || stnet[a+1][b] != NoDataValue || stnet[a+1][b+1] != NoDataValue || stnet[a][b+1] != NoDataValue || stnet[a-1][b+1] != NoDataValue || stnet[a-1][b] != NoDataValue || path[a][b] >= 3 || skip_trace == true) flag = false; } if (a == 0 || b == 0 || a == NRows-1 || b == NCols-1 ){ // avoid going out of bounds. // this is caused by having a hilltop on the first row or col away from the border // eg i or j == 1 or nrows/ncols - 2 and flowing towards the edge. // can fix with a test here for if streamnet[a][b] != NDV otherwise trace will fail *correctly* ++edge_count; } else { //if trace finished at a stream, print hillslope info. if (stnet[a][b] != NoDataValue || stnet[a-1][b-1] != NoDataValue || stnet[a][b-1] != NoDataValue || stnet[a+1][b-1] != NoDataValue || stnet[a+1][b] != NoDataValue || stnet[a+1][b+1] != NoDataValue || stnet[a][b+1] != NoDataValue || stnet[a-1][b+1] != NoDataValue || stnet[a-1][b] != NoDataValue) { path[a][b] = 1; ++s_count; X = XMinimum + j*DataResolution; Y = YMinimum - (NRows-i)*DataResolution; relief = zeta[i][j] - zeta[a][b]; mean_slope = relief/(length * DataResolution); // update arrays with the current metrics RoutedHilltops[i][j] = 1; HillslopeLength_Array[i][j] = (length * DataResolution); Slope_Array[i][j] = mean_slope; Relief_Array[i][j] = relief; //calculate an E* and R* Value assuming S_c of 0.8 E_Star = (2.0 * abs(hilltops[i][j])*(length*DataResolution))/0.8; R_Star = relief/((length*DataResolution)*0.8); //calulate the Euclidean distance between the start and end points of the trace EucDist = sqrt((pow(((i+0.5)-(a+yo)),2) + pow(((j+0.5)-(b+xo)),2))) * DataResolution; if (relief > 0){ ofs << X << "," << Y << "," << i << "," << j << "," << hilltops[i][j] << "," << mean_slope << "," << relief << "," << length*DataResolution << "," << basin[i][j] << "," << a << "," << b << "," << stnet[a][b] << "," << slope[i][j] << "," << DivergentCountFlag << "," << PlanarCountFlag << "," << E_Star << "," << R_Star << "," << EucDist << "\n"; } else { ++neg_count; } } else{ //unable to route using aspects //this will encompass skipped traces ofs << "fail: " << a << " " << b << " " << i << " " << j << endl; ++ns_count; } } //This block checks the various path printing options and writes the data out accordingly if (print_paths_switch == true){ if (ht_count % thinning == 0){ if (hilltops[i][j] != NoDataValue && skip_trace == false){ //check that the current i,j tuple corresponds to a hilltop, ie there is actually a trace to write to file, and check that the trace was valid. //create stringstream object to create filename ofstream pathwriter; //create the output filename from the user supplied path stringstream ss_path; ss_path << trace_path << i << "_" << j << "_trace.txt"; pathwriter.open(ss_path.str().c_str()); if(pathwriter.fail() ){ cout << "\nFATAL ERROR: unable to write to " << ss_path.str() << endl; exit(EXIT_FAILURE); } for (int v = 0; v < count+1; ++v){ if (basin_filter_switch == false){ pathwriter << setiosflags(ios::fixed) << setprecision(7) << east_vec[v] << " " << north_vec[v] << " " << DivergentCountFlag << " " << length << " " << PlanarCountFlag << " " << E_Star << " " << R_Star << " " << EucDist << endl; } else if (basin_filter_switch == true && find(Target_Basin_Vector.begin(), Target_Basin_Vector.end(), basin[a][b]) != Target_Basin_Vector.end() && find(Target_Basin_Vector.begin(), Target_Basin_Vector.end(), basin[i][j]) != Target_Basin_Vector.end()){ //is this correct? evaulating to not equal one past the end of the vector should equal that the value is found pathwriter << setiosflags(ios::fixed) << setprecision(7) << east_vec[v] << " " << north_vec[v] << " " << DivergentCountFlag << " " << length << " " << PlanarCountFlag << " " << E_Star << " " << R_Star << " " << EucDist << endl; } } pathwriter.close(); } } } // End of path printing logic } } //for loop i,j } ofs.close(); //add the data arrays to the output vector OutputArrays.push_back(RoutedHilltops); OutputArrays.push_back(HillslopeLength_Array); OutputArrays.push_back(Slope_Array); OutputArrays.push_back(Relief_Array); //Print debugging info to screen cout << endl; //push output onto new line cout << "Hilltop count: " << ht_count << endl; cout << "Stream count: " << s_count << endl; cout << "Fail count: " << ns_count << endl; cout << "Uphill count: " << neg_count << endl; cout << "Edge count: " << edge_count << endl; return OutputArrays; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // Hilltop flow routing code built around original code from Martin Hurst. Based on // Lea (1992), with improvements discussed by Tarboton (1997) and a solution to the // problem of looping flow paths implemented. // // THIS VERSION OF THE CODE RETAINS THE FLOODING METHOD TO ALLOW TRACES TO BE USED // ON RAW TOPOGRPAHY TO GET EVENT SCALE HILLSLOPE LENGTHS WITH NO SMOOTHING. IN // MOST CASES USE THE MAIN METHOD, TO ANALYSE SEDIMENT TRANSPORT OVER GEOMORPHIC TIME. // // This code is SLOW but robust, a refactored version may appear, but there may not be // enough whisky in Scotland to support that endeavour. // // The algorithm now checks for local uphill flows and in the case of identifying one, // D8 flow path is used to push the flow into the centre of the steepest downslope // cell, at which point the trace is restarted. The same technique is used to cope // with self intersections of the flow path. These problems are not solved in the // original paper and I think they are caused at least in part by the high resolution // topogrpahy we are using. // // The code is also now built to take a d infinity flow direction raster instead of an // aspect raster. See Tarboton (1997) for discussions on why this is the best solution. // // The Basins input raster is used to code each hilltop into a basin to allow basin // averaging to take place. // // The final 5 parameters are used to set up printing flow paths to files for visualisation, // if this is not needed simply pass in false to the two boolean switches and empty variables for the // others, and the code will run as normal. // // The structure of the returned vector< Array2D<float> > is as follows: // [0] Hilltop Network coded with stream ID // [1] Hillslope Lengths // [2] Slope // [3] Relief // // SWDG 12/2/14 //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= vector< Array2D<float> > LSDFlowInfo::HilltopFlowRouting_RAW(LSDRaster Elevation, LSDRaster Hilltops, LSDRaster Slope, LSDIndexRaster StreamNetwork, LSDRaster D_inf_Flowdir, string Prefix, LSDIndexRaster Basins, LSDRaster PlanCurvature, bool print_paths_switch, int thinning, string trace_path, bool basin_filter_switch, vector<int> Target_Basin_Vector){ //Declare parameters int i,j; int a = 0; int b = 0; float X,Y; float mean_slope, relief; float length, d; int flag; int count = 0; int DivergentCountFlag = 0; //Flag used to count the number of divergent cells encountered in a trace int PlanarCountFlag = 0; float PI = 3.14159265; float degs, degs_old, degs_new, theta; float s_local, s_edge; float xo, yo, xi, yi, temp_yo1, temp_yo2, temp_xo1, temp_xo2; bool skip_trace; //flag used to skip traces where no path to a stream can be found. Will only occur on noisy, raw topography float E_Star = 0; float R_Star = 0; float EucDist = 0; //debugging counters int ns_count = 0; int s_count = 0; int neg_count = 0; int edge_count = 0; int ht_count = 0; // a direction flag numbered 1,2,3,4 for E,S,W,N respectively int dir; float ymax = YMinimum + NRows*DataResolution; //Get data arrays from LSDRasters Array2D<float> zeta = Elevation.get_RasterData(); //elevation Array2D<int> stnet = StreamNetwork.get_RasterData(); // stream network Array2D<float> aspect = D_inf_Flowdir.get_RasterData(); //aspect Array2D<float> hilltops = Hilltops.get_RasterData(); //hilltops Array2D<float> slope = Slope.get_RasterData(); //hilltops Array2D<int> basin = Basins.get_RasterData(); //basins //empty arrays for data to be stored in Array2D<float> rads(NRows,NCols); Array2D<float> path(NRows, NCols, 0.0); Array2D<float> blank(NRows, NCols, 0.0); Array2D<float> RoutedHilltops(NRows,NCols,NoDataValue); Array2D<float> HillslopeLength_Array(NRows,NCols,NoDataValue); Array2D<float> Slope_Array(NRows,NCols,NoDataValue); Array2D<float> Relief_Array(NRows,NCols,NoDataValue); //vector to store the output data arrays in one vector that can be returned vector< Array2D<float> > OutputArrays; int vec_size = 1000000; Array1D<double> easting(NCols); Array1D<double> northing(NRows); Array1D<double> east_vec(vec_size); Array1D<double> north_vec(vec_size); ofstream ofs; //create the output filename from the user supplied filename prefix stringstream ss_filename; ss_filename << Prefix << "_HilltopData_RAW.csv"; ofs.open(ss_filename.str().c_str()); if( ofs.fail() ){ cout << "\nFATAL ERROR: unable to write to " << ss_filename.str() << endl; exit(EXIT_FAILURE); } ofs << "X,Y,hilltop_id,S,R,Lh,BasinID,StreamID,HilltopSlope,DivergentCount\n"; //calculate northing and easting for (i=0;i<NRows;++i){ northing[i] = ymax - i*DataResolution - 0.5; } for (j=0;j<NCols;++j){ easting[j] = XMinimum + j*DataResolution + 0.5; } //convert aspects to radians with east as theta = 0/2*pi for (i=0; i<NRows; ++i) { for (j=0; j<NCols; ++j) { //convert aspects to radians with east as theta = 0/2*pi if (rads[i][j] != NoDataValue) rads[i][j] = BearingToRad(aspect[i][j]); } } // cycle through study area, find hilltops and trace downstream for (i=1; i<NRows-1; ++i) { cout << flush << "\tRow: " << i << " of = " << NRows-1 << " \r"; for (j=1; j<NCols-1; ++j) { // ignore edge cells and non-hilltop cells // route initial node by aspect and get outlet coordinates if (hilltops[i][j] != NoDataValue) { length = 0; flag = true; count = 1; path = blank.copy(); DivergentCountFlag = 0; //initialise count of divergent cells in trace skip_trace = false; //initialise skip trace flag as false, will only be switched if no path to stream can be found. Very rare. ++ht_count; degs = aspect[i][j]; theta = rads[i][j]; a = i; b = j; path[a][b] += 1; east_vec[0] = easting[b]; north_vec[0] = northing[a]; s_local = slope[a][b]; //test direction, calculate outlet coordinates and update indicies // easterly if (degs >= 45 && degs < 135) { //cout << "\neasterly" << endl; xo = 1, yo = (1+tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 0, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; if (yi == 0) yi = 0.00001; else if (yi == 1) yi = 1 - 0.00001; } //southerly else if (degs >= 135 && degs < 225) { //cout << "\nsoutherly" << endl; xo = (1-(1/tan(theta)))/2, yo = 0; d = abs(1/(2*cos((PI/2)-theta))); xi = xo, yi = 1; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; if (xi == 0) xi = 0.00001; else if (xi == 1) xi = 1 - 0.00001; } // westerly else if (degs >= 225 && degs < 315) { xo = 0, yo = (1-tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 1, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; if (yi == 0) yi = 0.00001; else if (yi == 1) yi = 1 - 0.00001; } //northerly else if (degs >= 315 || degs < 45) { xo = (1+(1/tan(theta)))/2, yo = 1; d = abs(1/(2*cos((PI/2) - theta))); xi = xo, yi = 0; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; if (xi == 0) xi = 0.00001; else if (xi == 1) xi = 1 - 0.00001; } else { cout << "FATAL ERROR, Kinematic routing algorithm enountered null aspect value" << endl; exit(EXIT_FAILURE); } //collect slopes and totals weighted by path length length += d; s_local = slope[a][b]; //continue trace until a stream node is encountered while (flag == true && a > 0 && a < NRows-1 && b > 0 && b < NCols-1) { //added boudary checking to catch cells which flow off the edge of the DEM tile. int a_2 = a; int b_2 = b; path[a][b] += 1; degs_old = degs; degs_new = aspect[a][b]; theta = rads[a][b]; ++count; //Test for perimeter flow paths if ((dir == 1 && degs_new > 0 && degs_new < 180) || (dir == 2 && degs_new > 90 && degs_new < 270) || (dir == 3 && degs_new > 180 && degs_new < 360) || ((dir == 4 && degs_new > 270) || (dir == 4 && degs_new < 90))) { //DO NORMAL FLOW PATH //set xo, yo to 0 and 1 in turn and test for true outlet (xi || yi == 0 || 1) temp_yo1 = yi + (1-xi)*tan(theta); // xo = 1 temp_xo1 = xi + (1-yi)*(1/tan(theta)); // yo = 1 temp_yo2 = yi - xi*tan(theta); // xo = 0 temp_xo2 = xi - yi*(1/tan(theta)); // yo = 0 // can't outlet at same point as inlet if (dir == 1) temp_yo2 = -1; else if (dir == 2) temp_xo1 = -1; else if (dir == 3) temp_yo1 = -1; else if (dir == 4) temp_xo2 = -1; s_local = slope[a][b]; if (temp_yo1 <= 1 && temp_yo1 > 0) { xo = 1, yo = temp_yo1; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 0, yi = yo, dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; if (xi== 0 && yi == 0) yi = 0.00001; else if (xi== 0 && yi == 1) yi = 1 - 0.00001; } else if (temp_xo2 <= 1 && temp_xo2 > 0) { xo = temp_xo2, yo = 0; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1, dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; if (xi== 0 && yi == 1) xi = 0.00001; else if (xi== 1 && yi == 1) xi = 1 - 0.00001; } else if (temp_yo2 <= 1 && temp_yo2 > 0) { xo = 0, yo = temp_yo2; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1, yi = yo, dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; if (xi== 1 && yi == 0) yi = 0.00001; else if (xi== 1 && yi == 1) yi = 1 - 0.00001; } else if (temp_xo1 <= 1 && temp_xo1 > 0) { xo = temp_xo1, yo = 1; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 0, dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; if (xi == 0 && yi == 0) xi = 0.00001; else if (xi== 1 && yi == 0) xi = 1 - 0.00001; } } else { // ROUTE ALONG EDGES if (dir == 1) { if (degs_new <= 90 || degs_new >= 270) { //secondary compenent of flow is north xo = 0.00001, yo = 1; s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1-yo; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; } else if (degs_new > 90 && degs_new < 270) { //secondary component is south xo = 0.00001, yo = 0; s_edge = abs(s_local*sin((PI/2)-theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1-yo; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; } else { cout << "Flow unable to route N or S " << endl; //something has gone very wrong... cout << "Trace skipped.\n" << endl; skip_trace = true; //exit(EXIT_FAILURE); } } else if (dir == 2) { if (degs_new >= 0 && degs_new <= 180) { //secondary component is East xo = 1, yo = 1-0.00001; s_edge = abs(s_local*sin((2/PI)-theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; } else if (degs_new > 180 && degs_new <= 360) { //secondary component is West xo = 0, yo = 1-0.00001; s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; } else { cout << "Flow unable to route E or W" << endl; //something has gone very wrong... cout << "Trace skipped.\n" << endl; //something has gone very wrong... skip_trace = true; //exit(EXIT_FAILURE); } } else if (dir == 3) { if (degs_new >= 90 && degs_new <= 270) { //secondary component is South xo = 1-0.00001, yo = 0; s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1-yo; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; } else if (degs_new > 270 || degs_new < 90) { //secondary component is North xo = 1-0.00001, yo = 1; s_edge = abs(s_local*sin((2/PI) - theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1- yo; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; } else { cout << "Flow unable to route N or S" << endl; //something has gone very wrong... cout << "Trace skipped.\n" << endl; //something has gone very wrong... skip_trace = true; //exit(EXIT_FAILURE); } } else if (dir == 4) { if (degs_new >= 180 && degs_new <= 360) { //secondary component is West xo = 0, yo = 0.00001; s_edge = abs(s_local*sin((PI/2) - theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; } else if (degs_new >= 0 && degs_new < 180) { //secondary component is East xo = 1, yo = 0.00001; s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; } else { cout << "Flow unable to route E or W" << endl; //something has gone very wrong... cout << "Trace skipped.\n" << endl; //something has gone very wrong... skip_trace = true; //exit(EXIT_FAILURE); } } } if (path[a][b] < 1){ // only update length on 'first slosh' length += d; } degs = degs_new; if(zeta[a][b] - zeta[a_2][b_2] > 0){ length -= d; //remove uphill length from trace a = a_2; b = b_2; //restart trace degs = aspect[a][b]; theta = rads[a][b]; path[a][b] += 1; s_local = slope[a][b]; length += sqrt((pow((xo-0.5),2) + pow((yo-0.5),2))); //update length to cope with the 'jump' to the centre of the cell to restart the trace //test direction, calculate outlet coordinates and update indicies // easterly if (degs >= 45 && degs < 135) { xo = 1, yo = (1+tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 0, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; } //southerly else if (degs >= 135 && degs < 225) { xo = (1-(1/tan(theta)))/2, yo = 0; d = abs(1/(2*cos((PI/2)-theta))); xi = xo, yi = 1; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; } // westerly else if (degs >= 225 && degs < 315) { xo = 0, yo = (1-tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 1, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; } //northerly else if (degs >= 315 || degs < 45) { xo = (1+(1/tan(theta)))/2, yo = 1; d = abs(1/(2*cos((PI/2) - theta))); xi = xo, yi = 0; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; } else { cout << "FATAL ERROR, Kinematic routing algorithm enountered null aspect value" << endl; exit(EXIT_FAILURE); } //collect slopes and totals weighted by path length length += d; s_local = slope[a][b]; } if (path[a][b] >= 1){ //self intersect/'slosh' degs = aspect[a][b]; theta = rads[a][b]; path[a][b] += 1; s_local = slope[a][b]; a_2 = a; b_2 = b; length += sqrt((pow((xo-0.5),2) + pow((yo-0.5),2))); //update length to cope with the 'jump' to the centre of the cell to restart the trace //test direction, calculate outlet coordinates and update indicies // easterly if (degs >= 45 && degs < 135) { xo = 1, yo = (1+tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 0, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; } //southerly else if (degs >= 135 && degs < 225) { xo = (1-(1/tan(theta)))/2, yo = 0; d = abs(1/(2*cos((PI/2)-theta))); xi = xo, yi = 1; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; } // westerly else if (degs >= 225 && degs < 315) { xo = 0, yo = (1-tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 1, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; } //northerly else if (degs >= 315 || degs < 45) { xo = (1+(1/tan(theta)))/2, yo = 1; d = abs(1/(2*cos((PI/2) - theta))); xi = xo, yi = 0; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; } else { cout << "FATAL ERROR, Kinematic routing algorithm enountered null aspect value" << endl; exit(EXIT_FAILURE); } //collect slopes and totals weighted by path length length += d; s_local = slope[a][b]; } // test for plan curvature here and set a flag if flow is divergent or convergent but continue trace regardless // The larger the counter the more convergent or divergent the trace is if (abs(PlanCurvature.get_data_element(a,b)) > (0.001)){ ++DivergentCountFlag; } else { ++PlanarCountFlag; } if (path[a][b] >=3){ //update flag if a trace cannot complete, so that we can track errors. skip_trace = true; } if (a == 0 || b == 0 || a == NRows-1 || b == NCols-1 || stnet[a][b] != NoDataValue || stnet[a-1][b-1] != NoDataValue || stnet[a][b-1] != NoDataValue || stnet[a+1][b-1] != NoDataValue || stnet[a+1][b] != NoDataValue || stnet[a+1][b+1] != NoDataValue || stnet[a][b+1] != NoDataValue || stnet[a-1][b+1] != NoDataValue || stnet[a-1][b] != NoDataValue || path[a][b] >= 3 || skip_trace == true) flag = false; } if (a == 0 || b == 0 || a == NRows-1 || b == NCols-1 ){ // avoid going out of bounds. // this is caused by having a hilltop on the first row or col away from the border // eg i or j == 1 or nrows/ncols - 2 and flowing towards the edge. // can fix with a test here for if streamnet[a][b] != NDV otherwise trace will fail *correctly* ++edge_count; } else { //if trace finished at a stream, print hillslope info. if (stnet[a][b] != NoDataValue || stnet[a-1][b-1] != NoDataValue || stnet[a][b-1] != NoDataValue || stnet[a+1][b-1] != NoDataValue || stnet[a+1][b] != NoDataValue || stnet[a+1][b+1] != NoDataValue || stnet[a][b+1] != NoDataValue || stnet[a-1][b+1] != NoDataValue || stnet[a-1][b] != NoDataValue) { path[a][b] = 1; ++s_count; X = XMinimum + j*DataResolution; Y = YMinimum - (NRows-i)*DataResolution; relief = zeta[i][j] - zeta[a][b]; mean_slope = relief/(length * DataResolution); // update arrays with the current metrics RoutedHilltops[i][j] = 1; HillslopeLength_Array[i][j] = (length * DataResolution); Slope_Array[i][j] = mean_slope; Relief_Array[i][j] = relief; //calculate an E* and R* Value assuming S_c of 0.8 E_Star = (2.0 * abs(hilltops[i][j])*(length*DataResolution))/0.8; R_Star = relief/((length*DataResolution)*0.8); //calulate the Euclidean distance between the start and end points of the trace EucDist = sqrt((pow(((i+0.5)-(a+yo)),2) + pow(((j+0.5)-(b+xo)),2))) * DataResolution; if (relief > 0){ ofs << X << "," << Y << "," << hilltops[i][j] << "," << mean_slope << "," << relief << "," << length*DataResolution << "," << basin[i][j] << "," << stnet[a][b] << "," << slope[i][j] << "," << DivergentCountFlag << "," << PlanarCountFlag << "," << E_Star << "," << R_Star << "," << EucDist << "\n"; } else { ++neg_count; } } else{ //unable to route using aspects //this will encompass the skipped traces ofs << "fail: " << a << " " << b << " " << i << " " << j << endl; ++ns_count; } } //This block checks the various path printing options and writes the data out accordingly if (print_paths_switch == true){ if (ht_count % thinning == 0){ if (hilltops[i][j] != NoDataValue && skip_trace == false){ //check that the current i,j tuple corresponds to a hilltop and has a valid trace, ie there is actually a trace to write to file. //create stringstream object to create filename ofstream pathwriter; //create the output filename from the user supplied path stringstream ss_path; ss_path << trace_path << i << "_" << j << "_trace.txt"; pathwriter.open(ss_path.str().c_str()); if(pathwriter.fail() ){ cout << "\nFATAL ERROR: unable to write to " << ss_path.str() << endl; exit(EXIT_FAILURE); } for (int v = 0; v < count+1; ++v){ if (basin_filter_switch == false){ pathwriter << setiosflags(ios::fixed) << setprecision(7) << east_vec[v] << " " << north_vec[v] << " " << DivergentCountFlag << " " << length << " " << PlanarCountFlag << " " << E_Star << " " << R_Star << " " << EucDist << endl; } else if (basin_filter_switch == true && find(Target_Basin_Vector.begin(), Target_Basin_Vector.end(), basin[a][b]) != Target_Basin_Vector.end() && find(Target_Basin_Vector.begin(), Target_Basin_Vector.end(), basin[i][j]) != Target_Basin_Vector.end()){ //is this correct? evaulating to not equal one past the end of the vector should equal that the value is found pathwriter << setiosflags(ios::fixed) << setprecision(7) << east_vec[v] << " " << north_vec[v] << " " << DivergentCountFlag << " " << length << " " << PlanarCountFlag << " " << E_Star << " " << R_Star << " " << EucDist << endl; } } pathwriter.close(); } } } // End of path printing logic } } //for loop i,j } ofs.close(); //add the data arrays to the output vector OutputArrays.push_back(RoutedHilltops); OutputArrays.push_back(HillslopeLength_Array); OutputArrays.push_back(Slope_Array); OutputArrays.push_back(Relief_Array); //Print debugging info to screen cout << endl; //push output onto new line cout << "Hilltop count: " << ht_count << endl; cout << "Stream count: " << s_count << endl; cout << "Fail count: " << ns_count << endl; cout << "Uphill count: " << neg_count << endl; cout << "Edge count: " << edge_count << endl; return OutputArrays; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // Hilltop flow routing code built around original code from Martin Hurst. Based on // Lea (1992), with improvements discussed by Tarboton (1997) and a solution to the // problem of looping flow paths implemented. // // THIS VERSION OF THE CODE RETAINS THE FLOODING METHOD TO ALLOW TRACES TO BE USED // ON RAW TOPOGRPAHY TO GET EVENT SCALE HILLSLOPE LENGTHS WITH NO SMOOTHING. IN // MOST CASES USE THE MAIN METHOD, TO ANALYSE SEDIMENT TRANSPORT OVER GEOMORPHIC TIME. // // This code is SLOW but robust, a refactored version may appear, but there may not be // enough whisky in Scotland to support that endeavour. // // The algorithm now checks for local uphill flows and in the case of identifying one, // D8 flow path is used to push the flow into the centre of the steepest downslope // cell, at which point the trace is restarted. The same technique is used to cope // with self intersections of the flow path. These problems are not solved in the // original paper and I think they are caused at least in part by the high resolution // topogrpahy we are using. // // The code is also now built to take a d infinity flow direction raster instead of an // aspect raster. See Tarboton (1997) for discussions on why this is the best solution. // // The Basins input raster is used to code each hilltop into a basin to allow basin // averaging to take place. // // The final 5 parameters are used to set up printing flow paths to files for visualisation, // if this is not needed simply pass in false to the two boolean switches and empty variables for the // others, and the code will run as normal. // // This version is used to generate elevation profiles of the traces. The elevation data is encoded within // the trace files. // // The structure of the returned vector< Array2D<float> > is as follows: // [0] Hilltop Network coded with stream ID // [1] Hillslope Lengths // [2] Slope // [3] Relief // // SWDG 25/3/15 //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= vector< Array2D<float> > LSDFlowInfo::HilltopFlowRouting_Profile(LSDRaster Elevation, LSDRaster Hilltops, LSDRaster Slope, LSDIndexRaster StreamNetwork, LSDRaster D_inf_Flowdir, string Prefix, LSDIndexRaster Basins, bool print_paths_switch, int thinning, string trace_path, bool basin_filter_switch, vector<int> Target_Basin_Vector){ //Declare parameters int i,j; int a = 0; int b = 0; float X,Y; float mean_slope, relief; float length, d; int flag; int count = 0; float PI = 3.14159265; float degs, degs_old, degs_new, theta; float s_local, s_edge; float xo, yo, xi, yi, temp_yo1, temp_yo2, temp_xo1, temp_xo2; bool skip_trace; //flag used to skip traces where no path to a stream can be found. Will only occur on noisy, raw topography //debugging counters int ns_count = 0; int s_count = 0; int neg_count = 0; int edge_count = 0; int ht_count = 0; // a direction flag numbered 1,2,3,4 for E,S,W,N respectively int dir; float ymax = YMinimum + NRows*DataResolution; //Get data arrays from LSDRasters Array2D<float> zeta = Elevation.get_RasterData(); //elevation Array2D<int> stnet = StreamNetwork.get_RasterData(); // stream network Array2D<float> aspect = D_inf_Flowdir.get_RasterData(); //aspect Array2D<float> hilltops = Hilltops.get_RasterData(); //hilltops Array2D<float> slope = Slope.get_RasterData(); //hilltops Array2D<int> basin = Basins.get_RasterData(); //basins //empty arrays for data to be stored in Array2D<float> rads(NRows,NCols); Array2D<float> path(NRows, NCols, 0.0); Array2D<float> blank(NRows, NCols, 0.0); Array2D<float> RoutedHilltops(NRows,NCols,NoDataValue); Array2D<float> HillslopeLength_Array(NRows,NCols,NoDataValue); Array2D<float> Slope_Array(NRows,NCols,NoDataValue); Array2D<float> Relief_Array(NRows,NCols,NoDataValue); //vector to store the output data arrays in one vector that can be returned vector< Array2D<float> > OutputArrays; int vec_size = 1000000; Array1D<double> easting(NCols); Array1D<double> northing(NRows); Array1D<double> east_vec(vec_size); Array1D<double> north_vec(vec_size); vector<float> ZetaList; vector<float> LengthList; ofstream ofs; //create the output filename from the user supplied filename prefix stringstream ss_filename; ss_filename << Prefix << "_HilltopData_RAW.csv"; ofs.open(ss_filename.str().c_str()); if( ofs.fail() ){ cout << "\nFATAL ERROR: unable to write to " << ss_filename.str() << endl; exit(EXIT_FAILURE); } ofs << "X,Y,hilltop_id,S,R,Lh,BasinID,StreamID,HilltopSlope\n"; //calculate northing and easting for (i=0;i<NRows;++i){ northing[i] = ymax - i*DataResolution - 0.5; } for (j=0;j<NCols;++j){ easting[j] = XMinimum + j*DataResolution + 0.5; } //convert aspects to radians with east as theta = 0/2*pi for (i=0; i<NRows; ++i) { for (j=0; j<NCols; ++j) { //convert aspects to radians with east as theta = 0/2*pi if (rads[i][j] != NoDataValue) rads[i][j] = BearingToRad(aspect[i][j]); } } // cycle through study area, find hilltops and trace downstream for (i=1; i<NRows-1; ++i) { cout << flush << "\tRow: " << i << " of = " << NRows-1 << " \r"; for (j=1; j<NCols-1; ++j) { // ignore edge cells and non-hilltop cells // route initial node by aspect and get outlet coordinates if (hilltops[i][j] != NoDataValue) { length = 0; flag = true; count = 1; path = blank.copy(); skip_trace = false; //initialise skip trace flag as false, will only be switched if no path to stream can be found. Very rare. ++ht_count; degs = aspect[i][j]; theta = rads[i][j]; a = i; b = j; path[a][b] += 1; east_vec[0] = easting[b]; north_vec[0] = northing[a]; s_local = slope[a][b]; ZetaList.clear(); LengthList.clear(); //test direction, calculate outlet coordinates and update indicies // easterly if (degs >= 45 && degs < 135) { //cout << "\neasterly" << endl; xo = 1, yo = (1+tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 0, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; if (yi == 0) yi = 0.00001; else if (yi == 1) yi = 1 - 0.00001; } //southerly else if (degs >= 135 && degs < 225) { //cout << "\nsoutherly" << endl; xo = (1-(1/tan(theta)))/2, yo = 0; d = abs(1/(2*cos((PI/2)-theta))); xi = xo, yi = 1; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; if (xi == 0) xi = 0.00001; else if (xi == 1) xi = 1 - 0.00001; } // westerly else if (degs >= 225 && degs < 315) { xo = 0, yo = (1-tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 1, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; if (yi == 0) yi = 0.00001; else if (yi == 1) yi = 1 - 0.00001; } //northerly else if (degs >= 315 || degs < 45) { xo = (1+(1/tan(theta)))/2, yo = 1; d = abs(1/(2*cos((PI/2) - theta))); xi = xo, yi = 0; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; if (xi == 0) xi = 0.00001; else if (xi == 1) xi = 1 - 0.00001; } else { cout << "FATAL ERROR, Kinematic routing algorithm enountered null aspect value" << endl; exit(EXIT_FAILURE); } //collect slopes and totals weighted by path length length += d; s_local = slope[a][b]; //continue trace until a stream node is encountered while (flag == true && a > 0 && a < NRows-1 && b > 0 && b < NCols-1) { //added boudary checking to catch cells which flow off the edge of the DEM tile. int a_2 = a; int b_2 = b; path[a][b] += 1; degs_old = degs; degs_new = aspect[a][b]; theta = rads[a][b]; ++count; //Test for perimeter flow paths if ((dir == 1 && degs_new > 0 && degs_new < 180) || (dir == 2 && degs_new > 90 && degs_new < 270) || (dir == 3 && degs_new > 180 && degs_new < 360) || ((dir == 4 && degs_new > 270) || (dir == 4 && degs_new < 90))) { //DO NORMAL FLOW PATH //set xo, yo to 0 and 1 in turn and test for true outlet (xi || yi == 0 || 1) temp_yo1 = yi + (1-xi)*tan(theta); // xo = 1 temp_xo1 = xi + (1-yi)*(1/tan(theta)); // yo = 1 temp_yo2 = yi - xi*tan(theta); // xo = 0 temp_xo2 = xi - yi*(1/tan(theta)); // yo = 0 // can't outlet at same point as inlet if (dir == 1) temp_yo2 = -1; else if (dir == 2) temp_xo1 = -1; else if (dir == 3) temp_yo1 = -1; else if (dir == 4) temp_xo2 = -1; s_local = slope[a][b]; if (temp_yo1 <= 1 && temp_yo1 > 0) { xo = 1, yo = temp_yo1; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 0, yi = yo, dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; if (xi== 0 && yi == 0) yi = 0.00001; else if (xi== 0 && yi == 1) yi = 1 - 0.00001; } else if (temp_xo2 <= 1 && temp_xo2 > 0) { xo = temp_xo2, yo = 0; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1, dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; if (xi== 0 && yi == 1) xi = 0.00001; else if (xi== 1 && yi == 1) xi = 1 - 0.00001; } else if (temp_yo2 <= 1 && temp_yo2 > 0) { xo = 0, yo = temp_yo2; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1, yi = yo, dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; if (xi== 1 && yi == 0) yi = 0.00001; else if (xi== 1 && yi == 1) yi = 1 - 0.00001; } else if (temp_xo1 <= 1 && temp_xo1 > 0) { xo = temp_xo1, yo = 1; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 0, dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; if (xi == 0 && yi == 0) xi = 0.00001; else if (xi== 1 && yi == 0) xi = 1 - 0.00001; } } else { // ROUTE ALONG EDGES if (dir == 1) { if (degs_new <= 90 || degs_new >= 270) { //secondary compenent of flow is north xo = 0.00001, yo = 1; s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1-yo; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; } else if (degs_new > 90 && degs_new < 270) { //secondary component is south xo = 0.00001, yo = 0; s_edge = abs(s_local*sin((PI/2)-theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1-yo; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; } else { cout << "Flow unable to route N or S " << endl; //something has gone very wrong... cout << "Trace skipped.\n" << endl; skip_trace = true; //exit(EXIT_FAILURE); } } else if (dir == 2) { if (degs_new >= 0 && degs_new <= 180) { //secondary component is East xo = 1, yo = 1-0.00001; s_edge = abs(s_local*sin((2/PI)-theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; } else if (degs_new > 180 && degs_new <= 360) { //secondary component is West xo = 0, yo = 1-0.00001; s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; } else { cout << "Flow unable to route E or W" << endl; //something has gone very wrong... cout << "Trace skipped.\n" << endl; //something has gone very wrong... skip_trace = true; //exit(EXIT_FAILURE); } } else if (dir == 3) { if (degs_new >= 90 && degs_new <= 270) { //secondary component is South xo = 1-0.00001, yo = 0; s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1-yo; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; } else if (degs_new > 270 || degs_new < 90) { //secondary component is North xo = 1-0.00001, yo = 1; s_edge = abs(s_local*sin((2/PI) - theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1- yo; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; } else { cout << "Flow unable to route N or S" << endl; //something has gone very wrong... cout << "Trace skipped.\n" << endl; //something has gone very wrong... skip_trace = true; //exit(EXIT_FAILURE); } } else if (dir == 4) { if (degs_new >= 180 && degs_new <= 360) { //secondary component is West xo = 0, yo = 0.00001; s_edge = abs(s_local*sin((PI/2) - theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; } else if (degs_new >= 0 && degs_new < 180) { //secondary component is East xo = 1, yo = 0.00001; s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; } else { cout << "Flow unable to route E or W" << endl; //something has gone very wrong... cout << "Trace skipped.\n" << endl; //something has gone very wrong... skip_trace = true; //exit(EXIT_FAILURE); } } } if (path[a][b] < 1){ // only update length on 'first slosh' length += d; } degs = degs_new; if(zeta[a][b] - zeta[a_2][b_2] > 0){ length -= d; //remove uphill length from trace a = a_2; b = b_2; //restart trace degs = aspect[a][b]; theta = rads[a][b]; path[a][b] += 1; s_local = slope[a][b]; length += sqrt((pow((xo-0.5),2) + pow((yo-0.5),2))); //update length to cope with the 'jump' to the centre of the cell to restart the trace //test direction, calculate outlet coordinates and update indicies // easterly if (degs >= 45 && degs < 135) { xo = 1, yo = (1+tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 0, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; } //southerly else if (degs >= 135 && degs < 225) { xo = (1-(1/tan(theta)))/2, yo = 0; d = abs(1/(2*cos((PI/2)-theta))); xi = xo, yi = 1; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; } // westerly else if (degs >= 225 && degs < 315) { xo = 0, yo = (1-tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 1, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; } //northerly else if (degs >= 315 || degs < 45) { xo = (1+(1/tan(theta)))/2, yo = 1; d = abs(1/(2*cos((PI/2) - theta))); xi = xo, yi = 0; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; } else { cout << "FATAL ERROR, Kinematic routing algorithm enountered null aspect value" << endl; exit(EXIT_FAILURE); } //collect slopes and totals weighted by path length length += d; s_local = slope[a][b]; } if (path[a][b] >= 1){ //self intersect/'slosh' degs = aspect[a][b]; theta = rads[a][b]; path[a][b] += 1; s_local = slope[a][b]; a_2 = a; b_2 = b; length += sqrt((pow((xo-0.5),2) + pow((yo-0.5),2))); //update length to cope with the 'jump' to the centre of the cell to restart the trace //test direction, calculate outlet coordinates and update indicies // easterly if (degs >= 45 && degs < 135) { xo = 1, yo = (1+tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 0, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; } //southerly else if (degs >= 135 && degs < 225) { xo = (1-(1/tan(theta)))/2, yo = 0; d = abs(1/(2*cos((PI/2)-theta))); xi = xo, yi = 1; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; } // westerly else if (degs >= 225 && degs < 315) { xo = 0, yo = (1-tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 1, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; } //northerly else if (degs >= 315 || degs < 45) { xo = (1+(1/tan(theta)))/2, yo = 1; d = abs(1/(2*cos((PI/2) - theta))); xi = xo, yi = 0; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; } else { cout << "FATAL ERROR, Kinematic routing algorithm enountered null aspect value" << endl; exit(EXIT_FAILURE); } //collect slopes and totals weighted by path length length += d; s_local = slope[a][b]; } if (path[a][b] >=3){ //update flag if a trace cannot complete, so that we can track errors. skip_trace = true; } ZetaList.push_back(zeta[a][b]); LengthList.push_back(length*DataResolution); if (a == 0 || b == 0 || a == NRows-1 || b == NCols-1 || stnet[a][b] != NoDataValue || stnet[a-1][b-1] != NoDataValue || stnet[a][b-1] != NoDataValue || stnet[a+1][b-1] != NoDataValue || stnet[a+1][b] != NoDataValue || stnet[a+1][b+1] != NoDataValue || stnet[a][b+1] != NoDataValue || stnet[a-1][b+1] != NoDataValue || stnet[a-1][b] != NoDataValue || path[a][b] >= 3 || skip_trace == true) flag = false; } if (a == 0 || b == 0 || a == NRows-1 || b == NCols-1 ){ // avoid going out of bounds. // this is caused by having a hilltop on the first row or col away from the border // eg i or j == 1 or nrows/ncols - 2 and flowing towards the edge. // can fix with a test here for if streamnet[a][b] != NDV otherwise trace will fail *correctly* ++edge_count; } else { //if trace finished at a stream, print hillslope info. if (stnet[a][b] != NoDataValue || stnet[a-1][b-1] != NoDataValue || stnet[a][b-1] != NoDataValue || stnet[a+1][b-1] != NoDataValue || stnet[a+1][b] != NoDataValue || stnet[a+1][b+1] != NoDataValue || stnet[a][b+1] != NoDataValue || stnet[a-1][b+1] != NoDataValue || stnet[a-1][b] != NoDataValue) { path[a][b] = 1; ++s_count; X = XMinimum + j*DataResolution; Y = YMinimum - (NRows-i)*DataResolution; relief = zeta[i][j] - zeta[a][b]; mean_slope = relief/(length * DataResolution); // update arrays with the current metrics RoutedHilltops[i][j] = 1; HillslopeLength_Array[i][j] = (length * DataResolution); Slope_Array[i][j] = mean_slope; Relief_Array[i][j] = relief; if (relief > 0){ ofs << X << "," << Y << "," << hilltops[i][j] << "," << mean_slope << "," << relief << "," << length*DataResolution << "," << basin[i][j] << "," << stnet[a][b] << "," << slope[i][j] << "\n"; } else { ++neg_count; } } else{ //unable to route using aspects //this will encompass the skipped traces ofs << "fail: " << a << " " << b << " " << i << " " << j << endl; ++ns_count; } } //This block checks the various path printing options and writes the data out accordingly if (print_paths_switch == true){ if (ht_count % thinning == 0){ if (hilltops[i][j] != NoDataValue && skip_trace == false){ //check that the current i,j tuple corresponds to a hilltop and has a valid trace, ie there is actually a trace to write to file. //create stringstream object to create filename ofstream pathwriter; //create the output filename from the user supplied path stringstream ss_path; ss_path << trace_path << i << "_" << j << "_trace.txt"; pathwriter.open(ss_path.str().c_str()); if(pathwriter.fail() ){ cout << "\nFATAL ERROR: unable to write to " << ss_path.str() << endl; exit(EXIT_FAILURE); } for (int v = 0; v < count+1; ++v){ if (basin_filter_switch == false){ pathwriter << setiosflags(ios::fixed) << setprecision(7) << east_vec[v] << " " << north_vec[v] << " " << ZetaList[v] << " " << LengthList[v] << endl; } else if (basin_filter_switch == true && find(Target_Basin_Vector.begin(), Target_Basin_Vector.end(), basin[a][b]) != Target_Basin_Vector.end() && find(Target_Basin_Vector.begin(), Target_Basin_Vector.end(), basin[i][j]) != Target_Basin_Vector.end()){ //is this correct? evaulating to not equal one past the end of the vector should equal that the value is found pathwriter << setiosflags(ios::fixed) << setprecision(7) << east_vec[v] << " " << north_vec[v] << " " << ZetaList[v] << " " << LengthList[v] << endl; } } pathwriter.close(); } } } // End of path printing logic } } //for loop i,j } ofs.close(); //add the data arrays to the output vector OutputArrays.push_back(RoutedHilltops); OutputArrays.push_back(HillslopeLength_Array); OutputArrays.push_back(Slope_Array); OutputArrays.push_back(Relief_Array); //Print debugging info to screen cout << endl; //push output onto new line cout << "Hilltop count: " << ht_count << endl; cout << "Stream count: " << s_count << endl; cout << "Fail count: " << ns_count << endl; cout << "Uphill count: " << neg_count << endl; cout << "Edge count: " << edge_count << endl; return OutputArrays; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // // This function makes a mask of all the pixels that recieve flow (d8) // from a pixel that is either nodata or is on the boundary of the DEM // //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- LSDIndexRaster LSDFlowInfo::find_cells_influenced_by_nodata(LSDIndexRaster& Bordered_mask, LSDRaster& Topography) { // set up the array Array2D<int> influenced_mask(NRows,NCols,int(NoDataValue)); for(int row = 0; row <NRows; row++) { for(int col = 0; col<NCols; col++) { if(Topography.get_data_element(row,col) != NoDataValue) { influenced_mask[row][col] = 0; } } } int curr_node; int next_node; int next_row,next_col; // now loop through every node in the array for(int row = 0; row <NRows; row++) { for(int col = 0; col<NCols; col++) { if(Topography.get_data_element(row,col) != NoDataValue) { // this node has data. // first see if it has already been tagged if(influenced_mask[row][col] != 1) { //See if it is borderd by a NDV if(Bordered_mask.get_data_element(row,col) == 1) { // it is bordered by nodata. Work your way down the node list curr_node = retrieve_node_from_row_and_column(row, col); next_node = ReceiverVector[curr_node]; influenced_mask[row][col] = 1; retrieve_current_row_and_col(next_node, next_row, next_col); //cout << "I am bordered by NDV, entering search loop" << endl; //cout << "Row: " << row << " col: " << col << " node: " << curr_node // << " receiver: " << next_node << " next infl mask: " // << influenced_mask[next_row][next_col] << endl; // loop until you hit another influenced node or a baselevel node while(next_node != curr_node && influenced_mask[next_row][next_col] != 1 ) { curr_node = next_node; next_node = ReceiverVector[curr_node]; // the index here say next row and column but actually this is // preserved from the previous loop so is the current node. influenced_mask[next_row][next_col] = 1; // get the row and column of the receiver retrieve_current_row_and_col(next_node, next_row, next_col); //cout << "Looping thought influence, next influenced is: " // << influenced_mask[next_row][next_col] << endl; } } } } } } // now write the mask as an LSDIndexRaster LSDIndexRaster Influence_by_NDV(NRows,NCols,XMinimum,YMinimum, DataResolution,int(NoDataValue),influenced_mask,GeoReferencingStrings); return Influence_by_NDV; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //---------------------------------------------------------------------------------------- // get_raster_values_for_nodes //---------------------------------------------------------------------------------------- // This function gets the values from a raster corresponding to the given nodes. vector<float> LSDFlowInfo::get_raster_values_for_nodes(LSDRaster& Raster, vector<int>& node_indices) { int N_nodes = node_indices.size(); vector<float> return_values(N_nodes,float(NoDataValue)); int row=0; int col=0; for(int i = 0; i < N_nodes; ++i) { if(node_indices[i] == NoDataValue) { return_values[i] = NoDataValue; } else { retrieve_current_row_and_col(node_indices[i],row,col); return_values[i] = Raster.get_data_element(row,col); } } return return_values; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // Hilltop flow routing code built around original code from Martin Hurst. Based on // Lea (1992), with improvements discussed by Tarboton (1997) and a solution to the // problem of looping flow paths implemented. // // This version performs a single trace from a specified node, and routes down until it // reaches a channel pixel // // THIS VERSION OF THE CODE RETAINS THE FLOODING METHOD TO ALLOW TRACES TO BE USED // ON RAW TOPOGRPAHY TO GET EVENT SCALE HILLSLOPE LENGTHS WITH NO SMOOTHING. IN // MOST CASES USE THE MAIN METHOD, TO ANALYSE SEDIMENT TRANSPORT OVER GEOMORPHIC TIME. // // This code is SLOW but robust, a refactored version may appear, but there may not be // enough whisky in Scotland to support that endeavour. // // The algorithm now checks for local uphill flows and in the case of identifying one, // D8 flow path is used to push the flow into the centre of the steepest downslope // cell, at which point the trace is restarted. The same technique is used to cope // with self intersections of the flow path. These problems are not solved in the // original paper and I think they are caused at least in part by the high resolution // topogrpahy we are using. // // The code is also now built to take a d infinity flow direction raster instead of an // aspect raster. See Tarboton (1997) for discussions on why this is the best solution. // // There are 4 outputs: // output_trace_coordinates - the output coordinates tracing the flow path // output_trace_metrics - the metrics derived from the flow routing // (i) X // (i) Y // (i) mean slope // (i) hillslope relief // (i) hillslope length // (i) channel ID @ lower boundary // output_channel_node -the nodeindex at the bounding channel // skip_trace - a bool object that specifies whether this trace has routed // successfully to the channel. // // SWDG (adapted by DTM) 23/3/15 //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= void LSDFlowInfo::D_Inf_single_trace_to_channel(LSDRaster Elevation, int start_node, LSDIndexRaster StreamNetwork, LSDRaster D_inf_Flowdir, vector< vector<float> >& output_trace_coordinates, vector<float>& output_trace_metrics, int& output_channel_node, bool& skip_trace) { //Declare parameters int i,j; int a = 0; int b = 0; float X,Y; float mean_slope, relief; float length, d; // int flag; int count = 0; // int DivergentCountFlag = 0; //Flag used to count the number of divergent cells encountered in a trace float PI = 3.14159265; float degs, degs_old, degs_new, theta; // float s_local, s_edge; float xo, yo, xi, yi, temp_yo1, temp_yo2, temp_xo1, temp_xo2; // bool skip_trace; //flag used to skip traces where no path to a stream can be found. Will only occur on noisy, raw topography //debugging counters int ns_count = 0; int s_count = 0; int neg_count = 0; int edge_count = 0; // int ht_count = 0; // a direction flag numbered 1,2,3,4 for E,S,W,N respectively int dir; float ymax = YMinimum + NRows*DataResolution; //Get data arrays from LSDRasters Array2D<float> zeta = Elevation.get_RasterData(); //elevation Array2D<int> stnet = StreamNetwork.get_RasterData(); // stream network Array2D<float> aspect = D_inf_Flowdir.get_RasterData(); //aspect // Array2D<float> slope = Slope.get_RasterData(); //slope Array2D<float> rads(NRows,NCols,NoDataValue); Array2D<float> path(NRows, NCols,0.0); Array2D<float> blank(NRows,NCols,0.0); int channel_node = int(NoDataValue); vector<float> trace_metrics; vector< vector<float> > trace_coordinates; vector<float> empty; trace_coordinates.push_back(empty); trace_coordinates.push_back(empty); int vec_size = 1000000; Array1D<double> easting(NCols); Array1D<double> northing(NRows); Array1D<double> east_vec(vec_size); Array1D<double> north_vec(vec_size); //calculate northing and easting for (i=0;i<NRows;++i) { northing[i] = ymax - i*DataResolution - 0.5; } for (j=0;j<NCols;++j) { easting[j] = XMinimum + j*DataResolution + 0.5; } // find node and trace downstream // ignore edge cells and non-hilltop cells // route initial node by aspect and get outlet coordinates int start_row, start_col; retrieve_current_row_and_col(start_node,start_row,start_col); bool flag = false; if (zeta[start_row][start_col] != NoDataValue) { length = 0; flag = true; count = 1; path = blank.copy(); // DivergentCountFlag = 0; //initialise count of divergent cells in trace skip_trace = false; //initialise skip trace flag as false, will only be switched if no path to stream can be found. Very rare. // ++ht_count; degs = aspect[start_row][start_col]; theta = BearingToRad(aspect[start_row][start_col]); a = start_row; b = start_col; path[a][b] += 1; east_vec[0] = easting[b]; north_vec[0] = northing[a]; // s_local = slope[a][b]; //test direction, calculate outlet coordinates and update indicies // easterly if (degs >= 45 && degs < 135) { //cout << "\neasterly" << endl; xo = 1, yo = (1+tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 0, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; if (yi == 0) yi = 0.00001; else if (yi == 1) yi = 1 - 0.00001; } //southerly else if (degs >= 135 && degs < 225) { //cout << "\nsoutherly" << endl; xo = (1-(1/tan(theta)))/2, yo = 0; d = abs(1/(2*cos((PI/2)-theta))); xi = xo, yi = 1; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; if (xi == 0) xi = 0.00001; else if (xi == 1) xi = 1 - 0.00001; } // westerly else if (degs >= 225 && degs < 315) { xo = 0, yo = (1-tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 1, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; if (yi == 0) yi = 0.00001; else if (yi == 1) yi = 1 - 0.00001; } //northerly else if (degs >= 315 || degs < 45) { xo = (1+(1/tan(theta)))/2, yo = 1; d = abs(1/(2*cos((PI/2) - theta))); xi = xo, yi = 0; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; if (xi == 0) xi = 0.00001; else if (xi == 1) xi = 1 - 0.00001; } else { cout << "FATAL ERROR, Kinematic routing algorithm enountered null aspect value" << endl; exit(EXIT_FAILURE); } //collect slopes and totals weighted by path length length += d; // s_local = slope[a][b]; // place coordinates into output vector trace_coordinates[0].push_back(east_vec[count]); trace_coordinates[1].push_back(north_vec[count]); //continue trace until a stream node is encountered while (flag == true && a > 0 && a < NRows-1 && b > 0 && b < NCols-1) //added boudary checking to catch cells which flow off the edge of the DEM tile. { int a_2 = a; int b_2 = b; path[a][b] += 1; degs_old = degs; degs_new = aspect[a][b]; theta = BearingToRad(aspect[a][b]); ++count; // cout << "TEST1" << endl; //Test for perimeter flow paths if ((dir == 1 && degs_new > 0 && degs_new < 180) || (dir == 2 && degs_new > 90 && degs_new < 270) || (dir == 3 && degs_new > 180 && degs_new < 360) || ((dir == 4 && degs_new > 270) || (dir == 4 && degs_new < 90))) { // cout << "TEST1a" << endl; //DO NORMAL FLOW PATH //set xo, yo to 0 and 1 in turn and test for true outlet (xi || yi == 0 || 1) temp_yo1 = yi + (1-xi)*tan(theta); // xo = 1 temp_xo1 = xi + (1-yi)*(1/tan(theta)); // yo = 1 temp_yo2 = yi - xi*tan(theta); // xo = 0 temp_xo2 = xi - yi*(1/tan(theta)); // yo = 0 // can't outlet at same point as inlet if (dir == 1) temp_yo2 = -1; else if (dir == 2) temp_xo1 = -1; else if (dir == 3) temp_yo1 = -1; else if (dir == 4) temp_xo2 = -1; // s_local = slope[a][b]; if (temp_yo1 <= 1 && temp_yo1 > 0) { xo = 1, yo = temp_yo1; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 0; yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; if (xi== 0 && yi == 0) yi = 0.00001; else if (xi== 0 && yi == 1) yi = 1 - 0.00001; } else if (temp_xo2 <= 1 && temp_xo2 > 0) { xo = temp_xo2, yo = 0; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo; yi = 1; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; if (xi== 0 && yi == 1) xi = 0.00001; else if (xi== 1 && yi == 1) xi = 1 - 0.00001; } else if (temp_yo2 <= 1 && temp_yo2 > 0) { xo = 0, yo = temp_yo2; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1; yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; if (xi== 1 && yi == 0) yi = 0.00001; else if (xi== 1 && yi == 1) yi = 1 - 0.00001; } else if (temp_xo1 <= 1 && temp_xo1 > 0) { xo = temp_xo1, yo = 1; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo; yi = 0; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; if (xi == 0 && yi == 0) xi = 0.00001; else if (xi== 1 && yi == 0) xi = 1 - 0.00001; } // cout << "TEST1_end" << endl; } else { // ROUTE ALONG EDGES // cout << "TEST-" << endl; if (dir == 1) { // cout << "TEST2" << endl; if (degs_new <= 90 || degs_new >= 270) //secondary compenent of flow is north { xo = 0.00001; yo = 1; // s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo; yi = 1-yo; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; } else if (degs_new > 90 && degs_new < 270) //secondary component is south { xo = 0.00001; yo = 0; // s_edge = abs(s_local*sin((PI/2)-theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo; yi = 1-yo; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; } else { cout << "Flow unable to route N or S " << endl; //something has gone very wrong... cout << "Trace skipped.\n" << endl; skip_trace = true; //exit(EXIT_FAILURE); } } else if (dir == 2) { // cout << "TEST3" << endl; if (degs_new >= 0 && degs_new <= 180) //secondary component is East { xo = 1, yo = 1-0.00001; // s_edge = abs(s_local*sin((2/PI)-theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; } else if (degs_new > 180 && degs_new <= 360) //secondary component is West { xo = 0, yo = 1-0.00001; // s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; } else { cout << "Flow unable to route E or W" << endl; //something has gone very wrong... cout << "Trace skipped.\n" << endl; //something has gone very wrong... skip_trace = true; //exit(EXIT_FAILURE); } } else if (dir == 3) { // cout << "TEST4" << endl; if(degs_new >= 90 && degs_new <= 270) //secondary component is South { xo = 1-0.00001; yo = 0; // s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo; yi = 1-yo; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; } else if (degs_new > 270 || degs_new < 90) //secondary component is North { xo = 1-0.00001, yo = 1; // s_edge = abs(s_local*sin((2/PI) - theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo; yi = 1- yo; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; } else { cout << "Flow unable to route N or S" << endl; //something has gone very wrong... cout << "Trace skipped.\n" << endl; //something has gone very wrong... skip_trace = true; //exit(EXIT_FAILURE); } } else if (dir == 4) { // cout << "TEST5" << endl; if(degs_new >= 180 && degs_new <= 360) //secondary component is West { xo = 0, yo = 0.00001; // s_edge = abs(s_local*sin((PI/2) - theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo; yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; } else if (degs_new >= 0 && degs_new < 180) //secondary component is East { xo = 1, yo = 0.00001; // s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; } else { cout << "Flow unable to route E or W" << endl; //something has gone very wrong... cout << "Trace skipped.\n" << endl; //something has gone very wrong... skip_trace = true; //exit(EXIT_FAILURE); } } // cout << "TEST6" << endl; } if (path[a][b] < 1) length += d; // only update length on 'first slosh' degs = degs_new; if(zeta[a][b] - zeta[a_2][b_2] > 0) { length -= d; //remove uphill length from trace a = a_2; b = b_2; // cout << "TEST7" << endl; //restart trace degs = aspect[a][b]; theta = BearingToRad(aspect[a][b]); path[a][b] += 1; // s_local = slope[a][b]; length += sqrt((pow((xo-0.5),2) + pow((yo-0.5),2))); //update length to cope with the 'jump' to the centre of the cell to restart the trace //test direction, calculate outlet coordinates and update indices easterly if (degs >= 45 && degs < 135) { xo = 1, yo = (1+tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 0, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; } //southerly else if (degs >= 135 && degs < 225) { xo = (1-(1/tan(theta)))/2, yo = 0; d = abs(1/(2*cos((PI/2)-theta))); xi = xo, yi = 1; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; } // westerly else if (degs >= 225 && degs < 315) { xo = 0, yo = (1-tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 1, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; } //northerly else if (degs >= 315 || degs < 45) { xo = (1+(1/tan(theta)))/2, yo = 1; d = abs(1/(2*cos((PI/2) - theta))); xi = xo, yi = 0; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; } else { cout << "FATAL ERROR, Kinematic routing algorithm enountered null aspect value" << endl; exit(EXIT_FAILURE); } //collect slopes and totals weighted by path length length += d; // s_local = slope[a][b]; } if (path[a][b] >= 1) //self intersect/'slosh' { degs = aspect[a][b]; theta = rads[a][b]; path[a][b] += 1; // s_local = slope[a][b]; a_2 = a; b_2 = b; length += sqrt((pow((xo-0.5),2) + pow((yo-0.5),2))); //update length to cope with the 'jump' to the centre of the cell to restart the trace //test direction, calculate outlet coordinates and update indices // easterly if (degs >= 45 && degs < 135) { xo = 1, yo = (1+tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 0, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; } //southerly else if (degs >= 135 && degs < 225) { xo = (1-(1/tan(theta)))/2, yo = 0; d = abs(1/(2*cos((PI/2)-theta))); xi = xo, yi = 1; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; } // westerly else if (degs >= 225 && degs < 315) { xo = 0, yo = (1-tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 1, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; } //northerly else if (degs >= 315 || degs < 45) { xo = (1+(1/tan(theta)))/2, yo = 1; d = abs(1/(2*cos((PI/2) - theta))); xi = xo, yi = 0; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; } else { cout << "FATAL ERROR, Kinematic routing algorithm enountered null aspect value" << endl; exit(EXIT_FAILURE); } //collect slopes and totals weighted by path length length += d; // s_local = slope[a][b]; } // test for plan curvature here and set a flag if flow is divergent or convergent but continue trace regardless // The larger the counter the more convergent or divergent the trace is // if (abs(PlanCurvature.get_data_element(a,b)) > (0.001)) ++DivergentCountFlag; if (path[a][b] >=3) skip_trace = true;//update flag if a trace cannot complete, so that we can track errors. if (a == 0 || b == 0 || a == NRows-1 || b == NCols-1 || stnet[a][b] != NoDataValue || stnet[a-1][b-1] != NoDataValue || stnet[a][b-1] != NoDataValue || stnet[a+1][b-1] != NoDataValue || stnet[a+1][b] != NoDataValue || stnet[a+1][b+1] != NoDataValue || stnet[a][b+1] != NoDataValue || stnet[a-1][b+1] != NoDataValue || stnet[a-1][b] != NoDataValue || path[a][b] >= 3 || skip_trace == true) flag = false; // save trace coordinates for this iteration. trace_coordinates[0].push_back(east_vec[count]); trace_coordinates[1].push_back(north_vec[count]); } if (a == 0 || b == 0 || a == NRows-1 || b == NCols-1 ) { // avoid going out of bounds. // this is caused by having a hilltop on the first row or col away from the border // eg i or j == 1 or nrows/ncols - 2 and flowing towards the edge. // can fix with a test here for if streamnet[a][b] != NDV otherwise trace will fail *correctly* ++edge_count; } else { //if trace finished at a stream, print hillslope info. if (stnet[a][b] != NoDataValue || stnet[a-1][b-1] != NoDataValue || stnet[a][b-1] != NoDataValue || stnet[a+1][b-1] != NoDataValue || stnet[a+1][b] != NoDataValue || stnet[a+1][b+1] != NoDataValue || stnet[a][b+1] != NoDataValue || stnet[a-1][b+1] != NoDataValue || stnet[a-1][b] != NoDataValue) { path[a][b] = 1; ++s_count; X = XMinimum + j*DataResolution; Y = YMinimum - (NRows-i)*DataResolution; relief = zeta[start_row][start_col] - zeta[a][b]; mean_slope = relief/(length * DataResolution); trace_metrics.push_back(X); trace_metrics.push_back(Y); trace_metrics.push_back(float(start_node)); trace_metrics.push_back(mean_slope); trace_metrics.push_back(relief); trace_metrics.push_back(length*DataResolution); if (stnet[a][b] != NoDataValue) { channel_node = retrieve_node_from_row_and_column(a,b); trace_metrics.push_back(float(channel_node)); } // find nearest channel pixel within 1m buffer - if more than one, choose furthest downstream else { float min_elev=NoDataValue; if (stnet[a-1][b-1] != NoDataValue) { if (min_elev == NoDataValue || zeta[a-1][b-1] < min_elev) { min_elev = zeta[a-1][b-1]; channel_node = retrieve_node_from_row_and_column(a-1,b-1); } } else if (stnet[a-1][b] != NoDataValue) { if (min_elev == NoDataValue || zeta[a-1][b] < min_elev) { min_elev = zeta[a-1][b]; channel_node = retrieve_node_from_row_and_column(a-1,b); } } else if (stnet[a-1][b+1] != NoDataValue) { if (min_elev == NoDataValue || zeta[a-1][b+1] < min_elev) { min_elev = zeta[a-1][b+1]; channel_node = retrieve_node_from_row_and_column(a-1,b+1); } } else if (stnet[a][b-1] != NoDataValue) { if (min_elev == NoDataValue || zeta[a][b-1] < min_elev) { min_elev = zeta[a][b-1]; channel_node = retrieve_node_from_row_and_column(a,b-1); } } else if (stnet[a][b+1] != NoDataValue) { if (min_elev == NoDataValue || zeta[a][b+1] < min_elev) { min_elev = zeta[a][b+1]; channel_node = retrieve_node_from_row_and_column(a,b+1); } } else if (stnet[a+1][b-1] != NoDataValue) { if (min_elev == NoDataValue || zeta[a+1][b-1] < min_elev) { min_elev = zeta[a+1][b-1]; channel_node = retrieve_node_from_row_and_column(a+1,b-1); } } else if (stnet[a+1][b] != NoDataValue) { if (min_elev == NoDataValue || zeta[a+1][b] < min_elev) { min_elev = zeta[a+1][b]; channel_node = retrieve_node_from_row_and_column(a+1,b); } } else if (stnet[a+1][b+1] != NoDataValue) { if (min_elev == NoDataValue || zeta[a+1][b+1] < min_elev) { min_elev = zeta[a+1][b+1]; channel_node = retrieve_node_from_row_and_column(a+1,b+1); } } trace_metrics.push_back(float(channel_node)); } // if (relief > 0) ofs << X << "," << Y << "," << hilltops[i][j] << "," << mean_slope << "," << relief << "," << length*DataResolution << "," << basin[i][j] << "," << stnet[a][b] << "," << slope[i][j] << "," << DivergentCountFlag << "\n"; // else ++neg_count; if (relief <= 0) ++neg_count; } else { //unable to route using aspects //this will encompass the skipped traces // ofs << "fail: " << a << " " << b << " " << i << " " << j << endl; ++ns_count; } } } output_trace_coordinates = trace_coordinates; output_trace_metrics = trace_metrics; output_channel_node = channel_node; } //---------------------------------------------------------------------------------------------------------------------- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // Hilltop flow routing code built around original code from Martin Hurst. Based on // Lea (1992), with improvements discussed by Tarboton (1997) and a solution to the // problem of looping flow paths implemented. // // This code is SLOW but robust, a refactored version may appear, but there may not be // enough whisky in Scotland to support that endeavour. // // The algorithm now checks for local uphill flows and in the case of identifying one, // D8 flow path is used to push the flow into the centre of the steepest downslope // cell, at which point the trace is restarted. The same technique is used to cope // with self intersections of the flow path. These problems are not solved in the // original paper and I think they are caused at least in part by the high resolution // topogrpahy we are using. // // The code is also now built to take a d infinity flow direction raster instead of an // aspect raster. See Tarboton (1997) for discussions on why this is the best solution. // // The Basins input raster is used to code each hilltop into a basin to allow basin // averaging to take place. // // The final 5 parameters are used to set up printing flow paths to files for visualisation, // if this is not needed simply pass in false to the two boolean switches and empty variables for the // others, and the code will run as normal. // // The structure of the returned vector< Array2D<float> > is as follows: // [0] Hilltop Network coded with stream ID // [1] Hillslope Lengths // [2] Slope // [3] Relief // (4) Fraction Rock Exposure // // SWDG 12/2/14 //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= vector< Array2D<float> > LSDFlowInfo::HilltopFlowRoutingBedrock(LSDRaster Elevation, LSDRaster Hilltops, LSDRaster Slope, LSDIndexRaster StreamNetwork, LSDRaster Aspect, string Prefix, LSDIndexRaster Basins, LSDRaster PlanCurvature, bool print_paths_switch, int thinning, string trace_path, bool basin_filter_switch, vector<int> Target_Basin_Vector, LSDRaster RockExposure){ //Declare parameters int i,j; int a = 0; int b = 0; float X,Y; float mean_slope, relief; float length, d; float rock_exposure; int flag; int count = 0; int DivergentCountFlag = 0; //Flag used to count the number of divergent cells encountered in a trace int PlanarCountFlag; float PI = 3.14159265; float degs, degs_new, theta; float s_local, s_edge; float xo, yo, xi, yi, temp_yo1, temp_yo2, temp_xo1, temp_xo2; bool skip_trace; //flag used to skip traces where no path to a stream can be found. Will only occur on noisy, raw topography float E_Star = 0; float R_Star = 0; float EucDist = 0; //debugging counters int ns_count = 0; int s_count = 0; int neg_count = 0; int edge_count = 0; int ht_count = 0; // a direction flag numbered 1,2,3,4 for E,S,W,N respectively int dir; float ymax = YMinimum + NRows*DataResolution; //Get data arrays from LSDRasters Array2D<float> zeta = Elevation.get_RasterData(); //elevation Array2D<int> stnet = StreamNetwork.get_RasterData(); // stream network Array2D<float> aspect = Aspect.get_RasterData(); //aspect Array2D<float> hilltops = Hilltops.get_RasterData(); //hilltops Array2D<float> slope = Slope.get_RasterData(); //hilltops Array2D<int> basin = Basins.get_RasterData(); //basins Array2D<float> rock = RockExposure.get_RasterData(); // Rock Exposure //empty arrays for data to be stored in Array2D<float> rads(NRows,NCols); Array2D<float> path(NRows, NCols, 0.0); Array2D<float> blank(NRows, NCols, 0.0); Array2D<float> RoutedHilltops(NRows,NCols,NoDataValue); Array2D<float> HillslopeLength_Array(NRows,NCols,NoDataValue); Array2D<float> Slope_Array(NRows,NCols,NoDataValue); Array2D<float> Relief_Array(NRows,NCols,NoDataValue); Array2D<float> Rock_Array(NRows,NCols,NoDataValue); //vector to store the output data arrays in one vector that can be returned vector< Array2D<float> > OutputArrays; int vec_size = 1000000; Array1D<double> easting(NCols); Array1D<double> northing(NRows); Array1D<double> east_vec(vec_size); Array1D<double> north_vec(vec_size); ofstream ofs; //create the output filename from the user supplied filename prefix stringstream ss_filename; ss_filename << Prefix << "_HilltopData.csv"; ofs.open(ss_filename.str().c_str()); if( ofs.fail() ){ cout << "\nFATAL ERROR: unable to write to " << ss_filename.str() << endl; exit(EXIT_FAILURE); } ofs << "X,Y,hilltop_id,S,R,Lh,BasinID,StreamID,HilltopSlope,DivergentCount\n"; //calculate northing and easting for (i=0;i<NRows;++i){ northing[i] = ymax - i*DataResolution - 0.5; } for (j=0;j<NCols;++j){ easting[j] = XMinimum + j*DataResolution + 0.5; } //convert aspects to radians with east as theta = 0/2*pi for (i=0; i<NRows; ++i) { for (j=0; j<NCols; ++j) { //convert aspects to radians with east as theta = 0/2*pi if (rads[i][j] != NoDataValue) rads[i][j] = BearingToRad(aspect[i][j]); } } // cycle through study area, find hilltops and trace downstream for (i=1; i<NRows-1; ++i) { cout << flush << "\tRow: " << i << " of = " << NRows-1 << " \r"; for (j=1; j<NCols-1; ++j) { // ignore edge cells and non-hilltop cells // route initial node by aspect and get outlet coordinates if (hilltops[i][j] != NoDataValue) { length = 0; rock_exposure = 0; flag = true; count = 1; path = blank.copy(); DivergentCountFlag = 0; //initialise count of divergent cells in trace PlanarCountFlag = 0; skip_trace = false; //initialise skip trace flag as false, will only be switched if no path to stream can be found. Very rare. E_Star = 0; R_Star = 0; EucDist = 0; ++ht_count; degs = aspect[i][j]; theta = rads[i][j]; a = i; b = j; path[a][b] += 1; east_vec[0] = easting[b]; north_vec[0] = northing[a]; s_local = slope[a][b]; //test direction, calculate outlet coordinates and update indicies // easterly if (degs >= 45 && degs < 135) { //cout << "\neasterly" << endl; xo = 1, yo = (1+tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 0, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; if (yi == 0) yi = 0.00001; else if (yi == 1) yi = 1 - 0.00001; } //southerly else if (degs >= 135 && degs < 225) { //cout << "\nsoutherly" << endl; xo = (1-(1/tan(theta)))/2, yo = 0; d = abs(1/(2*cos((PI/2)-theta))); xi = xo, yi = 1; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; if (xi == 0) xi = 0.00001; else if (xi == 1) xi = 1 - 0.00001; } // westerly else if (degs >= 225 && degs < 315) { xo = 0, yo = (1-tan(theta))/2; d = abs(1/(2*cos(theta))); xi = 1, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; if (yi == 0) yi = 0.00001; else if (yi == 1) yi = 1 - 0.00001; } //northerly else if (degs >= 315 || degs < 45) { xo = (1+(1/tan(theta)))/2, yo = 1; d = abs(1/(2*cos((PI/2) - theta))); xi = xo, yi = 0; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; if (xi == 0) xi = 0.00001; else if (xi == 1) xi = 1 - 0.00001; } else { cout << "FATAL ERROR, Kinematic routing algorithm enountered null aspect value" << endl; exit(EXIT_FAILURE); } //collect slopes and totals weighted by path length length += d; s_local = slope[a][b]; rock_exposure += rock[a][b]*d; //continue trace until a stream node is encountered while (flag == true && a > 0 && a < NRows-1 && b > 0 && b < NCols-1) { //added boudary checking to catch cells which flow off the edge of the DEM tile. path[a][b] += 1; degs_new = aspect[a][b]; theta = rads[a][b]; ++count; //Test for perimeter flow paths if ((dir == 1 && degs_new > 0 && degs_new < 180) || (dir == 2 && degs_new > 90 && degs_new < 270) || (dir == 3 && degs_new > 180 && degs_new < 360) || ((dir == 4 && degs_new > 270) || (dir == 4 && degs_new < 90))) { //DO NORMAL FLOW PATH //set xo, yo to 0 and 1 in turn and test for true outlet (xi || yi == 0 || 1) temp_yo1 = yi + (1-xi)*tan(theta); // xo = 1 temp_xo1 = xi + (1-yi)*(1/tan(theta)); // yo = 1 temp_yo2 = yi - xi*tan(theta); // xo = 0 temp_xo2 = xi - yi*(1/tan(theta)); // yo = 0 // can't outlet at same point as inlet if (dir == 1) temp_yo2 = -1; else if (dir == 2) temp_xo1 = -1; else if (dir == 3) temp_yo1 = -1; else if (dir == 4) temp_xo2 = -1; s_local = slope[a][b]; if (temp_yo1 <= 1 && temp_yo1 > 0) { xo = 1, yo = temp_yo1; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 0, yi = yo, dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; if (xi== 0 && yi == 0) yi = 0.00001; else if (xi== 0 && yi == 1) yi = 1 - 0.00001; } else if (temp_xo2 <= 1 && temp_xo2 > 0) { xo = temp_xo2, yo = 0; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1, dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; if (xi== 0 && yi == 1) xi = 0.00001; else if (xi== 1 && yi == 1) xi = 1 - 0.00001; } else if (temp_yo2 <= 1 && temp_yo2 > 0) { xo = 0, yo = temp_yo2; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1, yi = yo, dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; if (xi== 1 && yi == 0) yi = 0.00001; else if (xi== 1 && yi == 1) yi = 1 - 0.00001; } else if (temp_xo1 <= 1 && temp_xo1 > 0) { xo = temp_xo1, yo = 1; d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 0, dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; if (xi == 0 && yi == 0) xi = 0.00001; else if (xi== 1 && yi == 0) xi = 1 - 0.00001; } } else { // ROUTE ALONG EDGES if (dir == 1) { if (degs_new <= 90 || degs_new >= 270) { //secondary compenent of flow is north xo = 0.00001, yo = 1; s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1-yo; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; } else if (degs_new > 90 && degs_new < 270) { //secondary component is south xo = 0.00001, yo = 0; s_edge = abs(s_local*sin((PI/2)-theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1-yo; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; } else { cout << "Flow unable to route N or S " << endl; //something has gone very wrong... cout << "Trace skipped.\n" << endl; skip_trace = true; //exit(EXIT_FAILURE); } } else if (dir == 2) { if (degs_new >= 0 && degs_new <= 180) { //secondary component is East xo = 1, yo = 1-0.00001; s_edge = abs(s_local*sin((2/PI)-theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; } else if (degs_new > 180 && degs_new <= 360) { //secondary component is West xo = 0, yo = 1-0.00001; s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; } else { cout << "Flow unable to route E or W" << endl; //something has gone very wrong... cout << "Trace skipped.\n" << endl; skip_trace = true; //exit(EXIT_FAILURE); } } else if (dir == 3) { if (degs_new >= 90 && degs_new <= 270) { //secondary component is South xo = 1-0.00001, yo = 0; s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1-yo; dir = 2; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] - 0.5*DataResolution; ++a; } else if (degs_new > 270 || degs_new < 90) { //secondary component is North xo = 1-0.00001, yo = 1; s_edge = abs(s_local*sin((2/PI) - theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = xo, yi = 1- yo; dir = 4; east_vec[count] = easting[b] + xo - 0.5*DataResolution; north_vec[count] = northing[a] + 0.5*DataResolution; --a; } else { cout << "Flow unable to route N or S" << endl; //something has gone very wrong... cout << "Trace skipped.\n" << endl; skip_trace = true; //exit(EXIT_FAILURE); } } else if (dir == 4) { if (degs_new >= 180 && degs_new <= 360) { //secondary component is West xo = 0, yo = 0.00001; s_edge = abs(s_local*sin((PI/2) - theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 3; east_vec[count] = easting[b] -0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; --b; } else if (degs_new >= 0 && degs_new < 180) { //secondary component is East xo = 1, yo = 0.00001; s_edge = abs(s_local*sin(theta)); d = sqrt((pow((xo-xi),2) + pow((yo-yi),2))); xi = 1-xo, yi = yo; dir = 1; east_vec[count] = easting[b] + 0.5*DataResolution; north_vec[count] = northing[a] + yo - 0.5*DataResolution; ++b; } else { cout << "Flow unable to route E or W" << endl; //something has gone very wrong... cout << "Trace skipped.\n" << endl; skip_trace = true; //exit(EXIT_FAILURE); } } } if (path[a][b] < 1){ // only update length on 'first slosh' length += d; rock_exposure += rock[a][b]*d; } else if (path[a][b] >= 3){ //update the skip trace flag so we can categorise each trace skip_trace = true; } degs = degs_new; // test for plan curvature here and set a flag if flow is divergent or convergent but continue trace regardless // The larger the counter the more convergent or divergent the trace is if (abs(PlanCurvature.get_data_element(a,b)) > (0.001)){ ++DivergentCountFlag; } else { ++PlanarCountFlag; } if (a == 0 || b == 0 || a == NRows-1 || b == NCols-1 || stnet[a][b] != NoDataValue || stnet[a-1][b-1] != NoDataValue || stnet[a][b-1] != NoDataValue || stnet[a+1][b-1] != NoDataValue || stnet[a+1][b] != NoDataValue || stnet[a+1][b+1] != NoDataValue || stnet[a][b+1] != NoDataValue || stnet[a-1][b+1] != NoDataValue || stnet[a-1][b] != NoDataValue || path[a][b] >= 3 || skip_trace == true) flag = false; } if (a == 0 || b == 0 || a == NRows-1 || b == NCols-1 ){ // avoid going out of bounds. // this is caused by having a hilltop on the first row or col away from the border // eg i or j == 1 or nrows/ncols - 2 and flowing towards the edge. // can fix with a test here for if streamnet[a][b] != NDV otherwise trace will fail *correctly* ++edge_count; } else { //if trace finished at a stream, print hillslope info. if (stnet[a][b] != NoDataValue || stnet[a-1][b-1] != NoDataValue || stnet[a][b-1] != NoDataValue || stnet[a+1][b-1] != NoDataValue || stnet[a+1][b] != NoDataValue || stnet[a+1][b+1] != NoDataValue || stnet[a][b+1] != NoDataValue || stnet[a-1][b+1] != NoDataValue || stnet[a-1][b] != NoDataValue) { path[a][b] = 1; ++s_count; X = XMinimum + j*DataResolution; Y = YMinimum - (NRows-i)*DataResolution; relief = zeta[i][j] - zeta[a][b]; mean_slope = relief/(length * DataResolution); // update arrays with the current metrics RoutedHilltops[i][j] = 1; HillslopeLength_Array[i][j] = (length * DataResolution); Slope_Array[i][j] = mean_slope; Relief_Array[i][j] = relief; Rock_Array[i][j] = rock_exposure/length; //calculate an E* and R* Value assuming S_c of 0.8 E_Star = (2.0 * abs(hilltops[i][j])*(length*DataResolution))/0.8; R_Star = relief/((length*DataResolution)*0.8); //calulate the Euclidean distance between the start and end points of the trace EucDist = sqrt((pow(((i+0.5)-(a+yo)),2) + pow(((j+0.5)-(b+xo)),2))) * DataResolution; if (relief > 0){ ofs << X << "," << Y << "," << hilltops[i][j] << "," << mean_slope << "," << relief << "," << length*DataResolution << "," << basin[i][j] << "," << stnet[a][b] << "," << slope[i][j] << "," << DivergentCountFlag << "," << PlanarCountFlag << "," << E_Star << "," << R_Star << "," << EucDist << "," << rock_exposure/length << "\n"; } else { ++neg_count; } } else{ //unable to route using aspects //this will encompass skipped traces ofs << "fail: " << a << " " << b << " " << i << " " << j << endl; ++ns_count; } } //This block checks the various path printing options and writes the data out accordingly if (print_paths_switch == true){ if (ht_count % thinning == 0){ if (hilltops[i][j] != NoDataValue && skip_trace == false){ //check that the current i,j tuple corresponds to a hilltop, ie there is actually a trace to write to file, and check that the trace was valid. //create stringstream object to create filename ofstream pathwriter; //create the output filename from the user supplied path stringstream ss_path; ss_path << trace_path << i << "_" << j << "_trace.txt"; pathwriter.open(ss_path.str().c_str()); if(pathwriter.fail() ){ cout << "\nFATAL ERROR: unable to write to " << ss_path.str() << endl; exit(EXIT_FAILURE); } for (int v = 0; v < count+1; ++v){ if (basin_filter_switch == false){ pathwriter << setiosflags(ios::fixed) << setprecision(7) << east_vec[v] << " " << north_vec[v] << " " << DivergentCountFlag << " " << length << " " << PlanarCountFlag << " " << E_Star << " " << R_Star << " " << EucDist << "," << rock_exposure/length << endl; } else if (basin_filter_switch == true && find(Target_Basin_Vector.begin(), Target_Basin_Vector.end(), basin[a][b]) != Target_Basin_Vector.end() && find(Target_Basin_Vector.begin(), Target_Basin_Vector.end(), basin[i][j]) != Target_Basin_Vector.end()){ //is this correct? evaulating to not equal one past the end of the vector should equal that the value is found pathwriter << setiosflags(ios::fixed) << setprecision(7) << east_vec[v] << " " << north_vec[v] << " " << DivergentCountFlag << " " << length << " " << PlanarCountFlag << " " << E_Star << " " << R_Star << " " << EucDist << "," << rock_exposure/length << endl; } } pathwriter.close(); } } } // End of path printing logic } } //for loop i,j } ofs.close(); //add the data arrays to the output vector OutputArrays.push_back(RoutedHilltops); OutputArrays.push_back(HillslopeLength_Array); OutputArrays.push_back(Slope_Array); OutputArrays.push_back(Relief_Array); OutputArrays.push_back(Rock_Array); //Print debugging info to screen cout << endl; //push output onto new line cout << "Hilltop count: " << ht_count << endl; cout << "Stream count: " << s_count << endl; cout << "Fail count: " << ns_count << endl; cout << "Uphill count: " << neg_count << endl; cout << "Edge count: " << edge_count << endl; return OutputArrays; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // This method removes end nodes which are not the uppermost extent of the channel network. // SWDG 23/7/15 //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= vector<int> LSDFlowInfo::ProcessEndPointsToChannelHeads(LSDIndexRaster Ends){ Array2D<int> EndArray = Ends.get_RasterData(); vector<int> Sources; //make a map containing each nodeindex where true means it is a valid channel head, eg the top of the network map<int,bool> EndStatus; vector<int> EndNodes; for(int i=1; i<NRows-1; ++i){ for(int j=1; j<NCols-1; ++j){ if (EndArray[i][j] != NoDataValue){ int nodeindex = retrieve_node_from_row_and_column (i,j); EndStatus[nodeindex] = true; EndNodes.push_back(nodeindex); } } } for (int q = 0; q < int(EndNodes.size());++q){ cout << flush << q << " of " << EndNodes.size() << "\r"; int CurrentNode = EndNodes[q]; if (EndStatus[CurrentNode] == true){ bool stop = false; while (stop == false){ int DownslopeNode; int Downslopei; int Downslopej; //get steepest descent neighbour retrieve_receiver_information(CurrentNode,DownslopeNode,Downslopei,Downslopej); if (find(EndNodes.begin(), EndNodes.end(), DownslopeNode) != EndNodes.end()){ EndStatus[DownslopeNode] = false; stop = true; } //check for out of bounds if (Downslopei == 0 || Downslopei == NRows - 1 || Downslopej == 0 || Downslopej == NCols - 1){ stop = true; } //check for a node with no downslope neughbours if (CurrentNode == DownslopeNode){ stop = true; } CurrentNode = DownslopeNode; } } } cout << endl; for (int q = 0; q < int(EndNodes.size());++q){ if (EndStatus[EndNodes[q]] == true){ Sources.push_back(EndNodes[q]); } } return Sources; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // This method removes single pixel channels from a channel network. // SWDG 23/7/15 //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- vector<int> LSDFlowInfo::RemoveSinglePxChannels(LSDIndexRaster StreamNetwork, vector<int> Sources){ for (int q = 0; q < int(Sources.size());++q){ int CurrentNode = Sources[q]; int Currenti; int Currentj; retrieve_current_row_and_col(CurrentNode,Currenti,Currentj); int CurrentOrder = StreamNetwork.get_data_element(Currenti,Currentj); //get steepest descent neighbour int DownslopeNode; int Downslopei; int Downslopej; retrieve_receiver_information(CurrentNode,DownslopeNode,Downslopei,Downslopej); int DownslopeOrder = StreamNetwork.get_data_element(Downslopei,Downslopej); if (CurrentOrder != DownslopeOrder){ //remove the value from the list of nodes -> Sources is passed by val, so this will not change values in sources outide this method Sources.erase(remove(Sources.begin(), Sources.end(), Sources[q]), Sources.end()); } } return Sources; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // This function starts from a given node index and then goes downstream // until it either hits a baselevel node or until it has accumulated a // number of visited pixels //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- int LSDFlowInfo::get_downslope_node_after_fixed_visited_nodes(int source_node, int outlet_node, int n_nodes_to_visit, LSDIndexRaster& VisitedRaster) { int n_visited = 0; int current_node, receiver_node,row, col; int bottom_node; bool Am_I_at_the_bottom_of_the_channel = false; current_node = source_node; // you start from the source node and work your way downstream while( Am_I_at_the_bottom_of_the_channel == false ) { // get the reciever node retrieve_receiver_information(current_node,receiver_node, row,col); // check if this is a base level node if (current_node == receiver_node) { Am_I_at_the_bottom_of_the_channel = true; bottom_node = receiver_node; } else if (receiver_node == outlet_node) { Am_I_at_the_bottom_of_the_channel = true; bottom_node = receiver_node; } else { // check to see if this node has been visited, if so increment the n_visited // iterator if (VisitedRaster.get_data_element(row,col) == 1) { n_visited++; } else { VisitedRaster.set_data_element(row, col, 1); } // see if we have collected enough nodes to visit if (n_visited >= n_nodes_to_visit) { Am_I_at_the_bottom_of_the_channel = true; bottom_node = receiver_node; } } current_node = receiver_node; } return bottom_node; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // This function gets the flow length between two nodes. // FJC 29/09/16 //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- float LSDFlowInfo::get_flow_length_between_nodes(int UpstreamNode, int DownstreamNode) { float length = 0; float root_2 = 1.4142135623; if (UpstreamNode == DownstreamNode) { cout << "You've picked the same node! Flow Length is 0." << endl; } else { int upstream_test = is_node_upstream(DownstreamNode, UpstreamNode); if (upstream_test != 1) { cout << "FlowInfo 7430: FATAL ERROR: The selected node is not upstream" << endl; length = float(NoDataValue); } else { bool ReachedChannel = false; int CurrentNode = UpstreamNode; while (ReachedChannel == false) { //get receiver information int ReceiverNode, ReceiverRow, ReceiverCol; retrieve_receiver_information(CurrentNode, ReceiverNode, ReceiverRow, ReceiverCol); //if node is at baselevel then exit if (CurrentNode == ReceiverNode) { ReachedChannel = true; //cout << "You reached a baselevel node, returning baselevel" << endl; } //if receiver is a channel > threshold then get the stream order if (ReceiverNode == DownstreamNode) { ReachedChannel = true; } else { //move downstream CurrentNode = ReceiverNode; // update length if (retrieve_flow_length_code_of_node(ReceiverNode) == 1){ length += DataResolution; } else if (retrieve_flow_length_code_of_node(ReceiverNode) == 2){ length += (DataResolution * root_2); } } } } } return length; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // This function gets the Euclidian distance between two nodes in metres // FJC 17/02/17 //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- float LSDFlowInfo::get_Euclidian_distance(int node_A, int node_B) { int row_A, row_B, col_A, col_B; // get the row and cols of the nodes retrieve_current_row_and_col(node_A, row_A, col_A); retrieve_current_row_and_col(node_B, row_B, col_B); float row_length = (row_B - row_A)*DataResolution; float col_length = (col_B - col_A)*DataResolution; //find the distance between these nodes float dist = sqrt(row_length*row_length + col_length*col_length); return dist; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Snap a given point to the nearest hilltop pixel, within a search radius. // Returns the nodeindex of the snapped point. // SWDG 23/1/17 //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- int LSDFlowInfo::snap_to_hilltop(int a, int b, int search_radius, LSDRaster& Hilltops){ int tmpNode; if (Hilltops.get_data_element(a,b) != NoDataValue){ // The point is already on a hilltop pixel! tmpNode = retrieve_node_from_row_and_column(a,b); } else{ vector<int> Nodes_in_window; vector<float> Dists_in_window; vector<float> Dists_in_window_sorted; vector<size_t> index_map; Nodes_in_window.reserve(4 * search_radius); Dists_in_window.reserve(4 * search_radius); Dists_in_window_sorted.reserve(4 * search_radius); index_map.reserve(4 * search_radius); //set up the bounding box int a_min = a - search_radius; int a_max = a + search_radius; int b_min = b - search_radius; int b_max = b + search_radius; //out of bounds checking if (a_min < 0){a_min = 0;} if (b_min < 0){b_min = 0;} if (a_max > (NRows - 1)){a_max = (NRows - 1);} if (b_max > (NCols - 1)){b_max = (NCols - 1);} // only iterate over the search area. for (int i = a_min; i < a_max; ++i){ for (int j = b_min; j < b_max; ++j){ if (Hilltops.get_data_element(i, j) != NoDataValue){ //get the nodeindex and distance from user defined point for each cell in the search window tmpNode = retrieve_node_from_row_and_column(i,j); Nodes_in_window.push_back(tmpNode); float Dist = distbetween(a,b,i,j); Dists_in_window.push_back(Dist); } } } matlab_float_sort(Dists_in_window, Dists_in_window_sorted, index_map); //the hilltop node with the smallest distance to the user defined point tmpNode = Nodes_in_window[index_map[0]]; } return tmpNode; } //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // Wrapper around snap_to_hilltop function to process a collection of utm points. // Writes the the nodeindex of each snapped point to SnappedNodes and the // coordinate count (first coordinate pair is 0, second is 1 and so on) is written // to Valid_node_IDs. // SWDG 23/1/17 //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- void LSDFlowInfo::snap_to_hilltops(vector<float> x_locs, vector<float> y_locs, int search_radius, LSDRaster& Hilltops, vector<int>& SnappedNodes, vector<int>& Valid_node_IDs){ for (int q = 0; q < int(x_locs.size()); ++q){ bool is_in_raster = check_if_point_is_in_raster(x_locs[q], y_locs[q]); if (is_in_raster){ // Shift origin to that of dataset float X_coordinate_shifted_origin = x_locs[q] - XMinimum; float Y_coordinate_shifted_origin = y_locs[q] - YMinimum; // Get row and column of point int col_point = int(X_coordinate_shifted_origin/DataResolution); int row_point = (NRows - 1) - int(round(Y_coordinate_shifted_origin/DataResolution)); int tmpNode = snap_to_hilltop(row_point, col_point, search_radius, Hilltops); SnappedNodes.push_back(tmpNode); Valid_node_IDs.push_back(q); } } } #endif
[ "f.clubb@ed.ac.uk" ]
f.clubb@ed.ac.uk
5f51bef74fab6a12e19d140069cd2b0c4ba626a4
88ae8695987ada722184307301e221e1ba3cc2fa
/sandbox/win/src/service_resolver_64.cc
b96816037a221347ed58def272979fd334ad024c
[ "BSD-3-Clause" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C++
false
false
8,712
cc
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "sandbox/win/src/service_resolver.h" #include <ntstatus.h> #include <stddef.h> #include <memory> #include "sandbox/win/src/sandbox_nt_util.h" #include "sandbox/win/src/win_utils.h" namespace { #if defined(_M_X64) #pragma pack(push, 1) const ULONG kMmovR10EcxMovEax = 0xB8D18B4C; const USHORT kSyscall = 0x050F; const BYTE kRetNp = 0xC3; const ULONG64 kMov1 = 0x54894808244C8948; const ULONG64 kMov2 = 0x4C182444894C1024; const ULONG kMov3 = 0x20244C89; const USHORT kTestByte = 0x04F6; const BYTE kPtr = 0x25; const BYTE kRet = 0xC3; const USHORT kJne = 0x0375; // Service code for 64 bit systems. struct ServiceEntry { // This struct contains roughly the following code: // 00 mov r10,rcx // 03 mov eax,52h // 08 syscall // 0a ret // 0b xchg ax,ax // 0e xchg ax,ax ULONG mov_r10_rcx_mov_eax; // = 4C 8B D1 B8 ULONG service_id; USHORT syscall; // = 0F 05 BYTE ret; // = C3 BYTE pad; // = 66 USHORT xchg_ax_ax1; // = 66 90 USHORT xchg_ax_ax2; // = 66 90 }; // Service code for 64 bit Windows 8 and Windows 10 1507 (build 10240). struct ServiceEntryW8 { // This struct contains the following code: // 00 48894c2408 mov [rsp+8], rcx // 05 4889542410 mov [rsp+10], rdx // 0a 4c89442418 mov [rsp+18], r8 // 0f 4c894c2420 mov [rsp+20], r9 // 14 4c8bd1 mov r10,rcx // 17 b825000000 mov eax,25h // 1c 0f05 syscall // 1e c3 ret // 1f 90 nop ULONG64 mov_1; // = 48 89 4C 24 08 48 89 54 ULONG64 mov_2; // = 24 10 4C 89 44 24 18 4C ULONG mov_3; // = 89 4C 24 20 ULONG mov_r10_rcx_mov_eax; // = 4C 8B D1 B8 ULONG service_id; USHORT syscall; // = 0F 05 BYTE ret; // = C3 BYTE nop; // = 90 }; // Service code for 64 bit systems with int 2e fallback. Windows 10 1511+ struct ServiceEntryWithInt2E { // This struct contains roughly the following code: // 00 4c8bd1 mov r10,rcx // 03 b855000000 mov eax,52h // 08 f604250803fe7f01 test byte ptr SharedUserData!308, 1 // 10 7503 jne [over syscall] // 12 0f05 syscall // 14 c3 ret // 15 cd2e int 2e // 17 c3 ret ULONG mov_r10_rcx_mov_eax; // = 4C 8B D1 B8 ULONG service_id; USHORT test_byte; // = F6 04 BYTE ptr; // = 25 ULONG user_shared_data_ptr; BYTE one; // = 01 USHORT jne_over_syscall; // = 75 03 USHORT syscall; // = 0F 05 BYTE ret; // = C3 USHORT int2e; // = CD 2E BYTE ret2; // = C3 }; // We don't have an internal thunk for x64. struct ServiceFullThunk { union { ServiceEntry original; ServiceEntryW8 original_w8; ServiceEntryWithInt2E original_int2e_fallback; }; }; #pragma pack(pop) bool IsService(const void* source) { const ServiceEntry* service = reinterpret_cast<const ServiceEntry*>(source); return (kMmovR10EcxMovEax == service->mov_r10_rcx_mov_eax && kSyscall == service->syscall && kRetNp == service->ret); } bool IsServiceW8(const void* source) { const ServiceEntryW8* service = reinterpret_cast<const ServiceEntryW8*>(source); return (kMmovR10EcxMovEax == service->mov_r10_rcx_mov_eax && kMov1 == service->mov_1 && kMov2 == service->mov_2 && kMov3 == service->mov_3); } bool IsServiceWithInt2E(const void* source) { const ServiceEntryWithInt2E* service = reinterpret_cast<const ServiceEntryWithInt2E*>(source); return (kMmovR10EcxMovEax == service->mov_r10_rcx_mov_eax && kTestByte == service->test_byte && kPtr == service->ptr && kJne == service->jne_over_syscall && kSyscall == service->syscall && kRet == service->ret && kRet == service->ret2); } bool IsAnyService(const void* source) { return IsService(source) || IsServiceW8(source) || IsServiceWithInt2E(source); } #elif defined(_M_ARM64) #pragma pack(push, 4) const ULONG kSvc = 0xD4000001; const ULONG kRetNp = 0xD65F03C0; const ULONG kServiceIdMask = 0x001FFFE0; struct ServiceEntry { ULONG svc; ULONG ret; ULONG64 unused; }; struct ServiceFullThunk { ServiceEntry original; }; #pragma pack(pop) bool IsService(const void* source) { const ServiceEntry* service = reinterpret_cast<const ServiceEntry*>(source); return (kSvc == (service->svc & ~kServiceIdMask) && kRetNp == service->ret && 0 == service->unused); } bool IsAnyService(const void* source) { return IsService(source); } #else #error "Unsupported Windows 64-bit Arch" #endif } // namespace namespace sandbox { NTSTATUS ServiceResolverThunk::Setup(const void* target_module, const void* interceptor_module, const char* target_name, const char* interceptor_name, const void* interceptor_entry_point, void* thunk_storage, size_t storage_bytes, size_t* storage_used) { NTSTATUS ret = Init(target_module, interceptor_module, target_name, interceptor_name, interceptor_entry_point, thunk_storage, storage_bytes); if (!NT_SUCCESS(ret)) return ret; size_t thunk_bytes = GetThunkSize(); std::unique_ptr<char[]> thunk_buffer(new char[thunk_bytes]); ServiceFullThunk* thunk = reinterpret_cast<ServiceFullThunk*>(thunk_buffer.get()); if (!IsFunctionAService(&thunk->original)) return STATUS_OBJECT_NAME_COLLISION; ret = PerformPatch(thunk, thunk_storage); if (storage_used) *storage_used = thunk_bytes; return ret; } size_t ServiceResolverThunk::GetThunkSize() const { return sizeof(ServiceFullThunk); } NTSTATUS ServiceResolverThunk::CopyThunk(const void* target_module, const char* target_name, BYTE* thunk_storage, size_t storage_bytes, size_t* storage_used) { NTSTATUS ret = ResolveTarget(target_module, target_name, &target_); if (!NT_SUCCESS(ret)) return ret; size_t thunk_bytes = GetThunkSize(); if (storage_bytes < thunk_bytes) return STATUS_UNSUCCESSFUL; ServiceFullThunk* thunk = reinterpret_cast<ServiceFullThunk*>(thunk_storage); if (!IsFunctionAService(&thunk->original)) return STATUS_OBJECT_NAME_COLLISION; if (storage_used) *storage_used = thunk_bytes; return ret; } bool ServiceResolverThunk::IsFunctionAService(void* local_thunk) const { ServiceFullThunk function_code; SIZE_T read; if (!::ReadProcessMemory(process_, target_, &function_code, sizeof(function_code), &read)) return false; if (sizeof(function_code) != read) return false; if (!IsAnyService(&function_code)) return false; // Save the verified code. memcpy(local_thunk, &function_code, sizeof(function_code)); return true; } NTSTATUS ServiceResolverThunk::PerformPatch(void* local_thunk, void* remote_thunk) { // Patch the original code. ServiceEntry local_service; DCHECK_NT(GetInternalThunkSize() <= sizeof(local_service)); if (!SetInternalThunk(&local_service, sizeof(local_service), nullptr, interceptor_)) return STATUS_UNSUCCESSFUL; // Copy the local thunk buffer to the child. SIZE_T actual; if (!::WriteProcessMemory(process_, remote_thunk, local_thunk, sizeof(ServiceFullThunk), &actual)) return STATUS_UNSUCCESSFUL; if (sizeof(ServiceFullThunk) != actual) return STATUS_UNSUCCESSFUL; // And now change the function to intercept, on the child. if (ntdll_base_) { // Running a unit test. if (!::WriteProcessMemory(process_, target_, &local_service, sizeof(local_service), &actual)) return STATUS_UNSUCCESSFUL; } else { if (!WriteProtectedChildMemory(process_, target_, &local_service, sizeof(local_service))) return STATUS_UNSUCCESSFUL; } return STATUS_SUCCESS; } bool ServiceResolverThunk::VerifyJumpTargetForTesting(void*) const { return true; } } // namespace sandbox
[ "jengelh@inai.de" ]
jengelh@inai.de
c19ca24ed0298c053af0672731a051182c101e22
f441609b808e945299e0c425621cfa032f6eec77
/LIstaRange/q8.cpp
a84b0375eea1b0ea21abbdeff44c35b89bb2af9a
[]
no_license
gbrsouza/Lists
b0de7df1f16ca027960f1a784951b10563bd8a47
096bf896d9052629cc28d3ed88e8ebc683c4ce98
refs/heads/master
2021-06-13T14:16:23.646716
2017-04-03T17:40:13
2017-04-03T17:40:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
987
cpp
#include <iostream> #include <iterator> #include <utility> int * unique ( int *first , int *last ); int main () { int A [] = { 1 , 2 , 1 , 2 , 3 , 3 , 1 , 2 , 4 , 5 , 3 , 4 , 5 }; // aplicar unique sobre A auto last = unique( std::begin(A), std::end(A)); // O comando abaixo deveria imprimir A com o conteudo 1 , 2 , 3 , 4 , 5. for ( auto i(std::begin(A)); i != last ; ++i ) std::cout << * i << " " ; std::cout << std::endl ; // Mostra o novo tamanho de A , que seria 5. std::cout << " >>> O comprimento ( logico ) de A apos unique ()e: " << std::distance ( std::begin ( A ) , last ) << " \n "; return 0; } int * unique ( int *first , int *last ) { auto iSlow(first+1); auto iFast(first+1); auto aux(first); bool unico; for(/*empty*/; iFast != last; ++iFast) { unico = true; for (auto i(aux); i != iSlow and unico; ++i) { if(*i == *iFast) unico = false; } if (unico){ std::swap(*iSlow,*iFast); iSlow++; } } return iSlow; }
[ "gabriel_feg@hotmail.com" ]
gabriel_feg@hotmail.com
6a7ffd24188e61e3b97f984803b9771823b35c8c
de731acd890706423eced969f3195a2b5f084ae1
/lib/childrens-price.cpp
1862e75f24549f21f2e2e9d0f988276ae8ed31a2
[]
no_license
guydunton/Refactoring-example-cpp
e3c7e054f813f05336b12101a6da9242fb62c6c3
46b90c46f039829378a41dd464572d419adbc4ae
refs/heads/master
2020-04-26T11:10:09.953891
2019-03-02T23:22:30
2019-03-02T23:22:30
173,507,686
1
0
null
null
null
null
UTF-8
C++
false
false
413
cpp
#include "childrens-price.hpp" #include "movie.hpp" int ChildrensPrice::getPriceCode() const { return Movie::CHILDREN; } std::unique_ptr<Price> ChildrensPrice::clonePrice() { return std::make_unique<ChildrensPrice>(*this); } double ChildrensPrice::getCharge(int daysRented) const { const double baseCharge = 1.5; if (daysRented > 3) return baseCharge + (daysRented - 3) * 1.5; return baseCharge; }
[ "guy.dunton@gmail.com" ]
guy.dunton@gmail.com
360cfd406f686374fb1c6b3b21b6a354c1264a19
265620eb6a8de39b6eaf28c909b34e3bd25117ba
/OutExcelFileThread.h
d8246adaa69b3df7ec1e1e1173ca83f8a77e0fac
[]
no_license
isliulin/uesoft-AutoIPED
7e6f4d961ddc899b5f3c990f67beaca947ba4ff0
c11e3ea3a7d08faa462bc731e142844d4d4c3ed9
refs/heads/master
2022-01-13T15:32:45.190482
2013-09-30T08:33:08
2013-09-30T08:33:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,518
h
#if !defined(AFX_OUTEXCELFILETHREAD_H__70F153EE_80C8_426D_81CF_1D2C4A65AF78__INCLUDED_) #define AFX_OUTEXCELFILETHREAD_H__70F153EE_80C8_426D_81CF_1D2C4A65AF78__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // OutExcelFileThread.h : header file // #include "Autoipedview.h" ///////////////////////////////////////////////////////////////////////////// // COutExcelFileThread thread class COutExcelFileThread : public CWinThread { DECLARE_DYNCREATE(COutExcelFileThread) protected: // Attributes public: COutExcelFileThread(); // protected constructor used by dynamic creation virtual ~COutExcelFileThread(); // Operations public: bool SetPow(long double _x, long _y); void OutInsulExplainTbl(); void PutCurView(CAutoIPEDView* pCurView); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(COutExcelFileThread) public: virtual BOOL InitInstance(); virtual int ExitInstance(); //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(COutExcelFileThread) // NOTE - the ClassWizard will add and remove member functions here. //}}AFX_MSG DECLARE_MESSAGE_MAP() private: CAutoIPEDView* m_pCurView; }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_OUTEXCELFILETHREAD_H__70F153EE_80C8_426D_81CF_1D2C4A65AF78__INCLUDED_)
[ "uesoft@163.com" ]
uesoft@163.com
f15955bcc109a30873408038a7e88c4c7b3a9e75
136247b5cb638464a05592618633aa5ffb88d007
/ui/widget/logwidget.cpp
20c507c04b4227a84c153c45d7f3a2760e038711
[]
no_license
dongdong-2009/spinnery-system
e198fb6fb314b7459bf4e6f0f66d8e55f675e927
14566665407c72cbe9fcef901d55eea48c106797
refs/heads/master
2021-05-28T16:21:47.725660
2014-10-29T12:07:39
2014-10-29T12:07:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
422
cpp
#include "logwidget.h" #include "ui_logwidget.h" #include <QDebug> LogWidget::LogWidget(QWidget *parent) : QWidget(parent), ui(new Ui::LogWidget) { ui->setupUi(this); } LogWidget::~LogWidget() { delete ui; } void LogWidget::on_listWidget_itemSelectionChanged() { int selectIndex=ui->listWidget->currentRow(); if(selectIndex!=-1){ emit this->selectIndexChange(selectIndex); } }
[ "kyyblabla@163.com" ]
kyyblabla@163.com
ad0f3883f54c1b3fb6dca942b487d272060b8525
2c19ace35b57b17411575984f1656ec0c237436c
/Map.cpp
b9e9d9c0398b449832b35aab1a920d240eb2f9c1
[]
no_license
rane1700/ex4
51ca9154b373f56762695437286cd2288318b452
2024de009dde405e49ee713be9ed1ef9bd87696d
refs/heads/master
2021-04-29T01:09:16.946390
2017-01-02T19:20:15
2017-01-02T19:20:15
77,784,885
0
0
null
null
null
null
UTF-8
C++
false
false
639
cpp
// // Created by shani on 11/28/16. // #include "Map.h" #include "Node.h" #include "PointHistory.h" /** * constractor */ Map::Map(){} /** * destructor */ Map::~Map(){} /** * prints map */ /** * prints map */ void Map::print(){} /** * gets the path from a start point to a goal point * @param speed - the speed of the cab (1 or 2) * @return false if there is no path to the goal point, else return true. */ bool Map::run(int speed){} /** * gets neighbors of certian points according to map */ bool Map::getNeighbors(){} /** * * @return current point */ Node* Map::getCurrent(){} std::vector<Node*> Map:: getPass(){}
[ "ranee1700@gmail.com" ]
ranee1700@gmail.com
bc2076be3336f9b46da44dbf37c07e9a3e1db7e5
728688c8496619a15cdc7130e8f3236b2600238a
/실습3/RangeArray.cpp
547dd3872dab23119aec3f2299e6e31b8baae7bc
[]
no_license
jennifer06065/comsil_3_github
a0f9f186b4fb0c5da117c9f8112a070aa17795a4
caf333ea482a2b72e84108e09f71ebc02bd692c3
refs/heads/master
2022-12-29T10:40:41.402334
2020-10-06T07:46:29
2020-10-06T07:46:29
301,641,672
0
0
null
null
null
null
UTF-8
C++
false
false
432
cpp
#include <iostream> using namespace std; #include "RangeArray.h" RangeArray::RangeArray(int a, int b) : Array(b-a+1) { low = a; high = b; } RangeArray::~RangeArray() {} int RangeArray::baseValue() { return low; } int RangeArray::endValue() { return high; } int& RangeArray::operator[](int i) { i=i-low; return Array::operator[](i); } int RangeArray::operator[](int i) const { i=i-low; return Array::operator[](i); }
[ "jennifer0606@naver.com" ]
jennifer0606@naver.com
c2dbc74835e4e9a8977bdb00ca1c18ca7f85f1c8
c8a8b1b2739ff50c3565cdc1497e6abf4492b3dd
/src/csapex_core_test/src/processing_test.cpp
f97b4955a74760e139dc1f9e13a516b793905132
[]
permissive
betwo/csapex
645eadced88e65d6e78aae4049a2cda5f0d54b4b
dd8e24f14cdeef59bedb8f974ebdc0b0c656ab4c
refs/heads/master
2022-06-13T06:15:10.306698
2022-06-01T08:50:51
2022-06-01T09:03:05
73,413,991
0
0
BSD-3-Clause
2020-01-02T14:01:01
2016-11-10T19:26:29
C++
UTF-8
C++
false
false
4,032
cpp
#include <csapex/model/graph_facade_impl.h> #include <csapex/model/graph/graph_impl.h> #include <csapex/model/graph.h> #include <csapex/model/node_facade_impl.h> #include <csapex/model/node.h> #include <csapex/model/node_handle.h> #include <csapex/model/node_modifier.h> #include <csapex/model/node_worker.h> #include <csapex/msg/direct_connection.h> #include <csapex/msg/generic_value_message.hpp> #include <csapex/msg/input.h> #include <csapex/msg/input_transition.h> #include <csapex/msg/io.h> #include <csapex/msg/output_transition.h> #include <csapex/msg/static_output.h> #include <csapex/utility/uuid_provider.h> #include <csapex_testing/csapex_test_case.h> #include <csapex_testing/mockup_nodes.h> #include <csapex_testing/test_exception_handler.h> #include <mutex> #include <condition_variable> #include <csapex_testing/stepping_test.h> namespace csapex { class ProcessingTest : public NodeConstructingTest { }; TEST_F(ProcessingTest, DirectCallToProcess) { NodeFacadeImplementationPtr times_4 = factory.makeNode("StaticMultiplier4", UUIDProvider::makeUUID_without_parent("StaticMultiplier4"), graph); Node& node = *times_4->getNode(); NodeHandle& nh = *times_4->getNodeHandle(); ASSERT_TRUE(node.canProcess()); // set the input message TokenPtr token_in = msg::createToken(23); InputPtr input = nh.getInput(UUIDProvider::makeUUID_without_parent("StaticMultiplier4:|:in_0")); ASSERT_NE(nullptr, input); input->setToken(token_in); // no inputs are sent now -> node should multiply the input by 4 ASSERT_TRUE(node.canProcess()); node.process(nh, node); // commit the messages produced by the node OutputPtr output = nh.getOutput(UUIDProvider::makeUUID_without_parent("StaticMultiplier4:|:out_0")); ASSERT_NE(nullptr, output); output->commitMessages(false); // view outputs TokenPtr token_out = output->getToken(); TokenDataConstPtr data_out = token_out->getTokenData(); ASSERT_NE(nullptr, data_out); auto msg_out = std::dynamic_pointer_cast<connection_types::GenericValueMessage<int> const>(data_out); ASSERT_NE(nullptr, msg_out); ASSERT_EQ(23 * 4, msg_out->value); } TEST_F(ProcessingTest, CallToProcessViaNodeWorker) { NodeFacadeImplementationPtr times_4 = factory.makeNode("StaticMultiplier4", UUIDProvider::makeUUID_without_parent("StaticMultiplier4"), graph); Node& node = *times_4->getNode(); NodeHandle& nh = *times_4->getNodeHandle(); ASSERT_TRUE(node.canProcess()); ASSERT_FALSE(times_4->isProcessing()); ASSERT_FALSE(times_4->canProcess()); // create a temporary output and connect it to the input OutputPtr tmp_out = std::make_shared<StaticOutput>(UUIDProvider::makeUUID_without_parent("tmp_out")); InputPtr input = nh.getInput(UUIDProvider::makeUUID_without_parent("StaticMultiplier4:|:in_0")); ASSERT_NE(nullptr, input); ConnectionPtr connection = DirectConnection::connect(tmp_out, input); // set the input message msg::publish(tmp_out.get(), 23); // mark the messages as committed tmp_out->commitMessages(false); tmp_out->publish(); ASSERT_TRUE(node.canProcess()); ASSERT_TRUE(times_4->canProcess()); ASSERT_TRUE(nh.getInputTransition()->isEnabled()); ASSERT_TRUE(nh.getOutputTransition()->isEnabled()); // no inputs are sent now -> node should multiply the input by 4 ASSERT_FALSE(times_4->isProcessing()); ASSERT_TRUE(times_4->startProcessingMessages()); // commit the messages produced by the node OutputPtr output = nh.getOutput(UUIDProvider::makeUUID_without_parent("StaticMultiplier4:|:out_0")); ASSERT_NE(nullptr, output); // view outputs TokenPtr token_out = output->getToken(); TokenDataConstPtr data_out = token_out->getTokenData(); ASSERT_NE(nullptr, data_out); auto msg_out = std::dynamic_pointer_cast<connection_types::GenericValueMessage<int> const>(data_out); ASSERT_NE(nullptr, msg_out); ASSERT_EQ(23 * 4, msg_out->value); } } // namespace csapex
[ "sebastian.buck@uni-tuebingen.de" ]
sebastian.buck@uni-tuebingen.de
b96d60f553227b510c31d16cfb745e590cc8f16b
874124925d861bc8d003f09490d823f44d1b0ca0
/src/include/Terrain/TerrainOperationEditPoint.hpp
c4250390f92896cb95021d260386c929d1a2c766
[ "MIT" ]
permissive
foxostro/PinkTopaz
2e5555b0495e493d3ca8bafbd98dd1b00e099bdd
cd8275a93ea34a56f640f915d4b6c769e82e9dc2
refs/heads/master
2021-01-22T22:24:07.097116
2018-06-17T04:14:59
2018-06-17T04:15:01
85,535,947
1
0
null
null
null
null
UTF-8
C++
false
false
1,219
hpp
// // TerrainOperationEditPoint.hpp // PinkTopaz // // Created by Andrew Fox on 5/8/18. // // #ifndef TerrainOperationEditPoint_hpp #define TerrainOperationEditPoint_hpp #include "TerrainOperation.hpp" #include "CerealGLM.hpp" class VoxelData; // An operation which edits a single voxel block. // This is useful for edits made with the mouse cursor ala Minecraft. class TerrainOperationEditPoint : public TerrainOperation { public: // Default destructor. virtual ~TerrainOperationEditPoint() = default; // Default constructor TerrainOperationEditPoint() = default; // Constructor. TerrainOperationEditPoint(glm::vec3 location, Voxel newValue); // Performs the operation. void perform(VoxelData &voxelData) override; // Serialize the operation. template<typename Archive> void serialize(Archive &archive) { archive(cereal::base_class<TerrainOperation>(this), cereal::make_nvp("location", _location), cereal::make_nvp("newValue", _newValue)); } private: glm::vec3 _location; Voxel _newValue; }; CEREAL_REGISTER_TYPE(TerrainOperationEditPoint); #endif /* TerrainOperationEditPoint_hpp */
[ "foxostro@gmail.com" ]
foxostro@gmail.com
6ccf9c05890a08f3fcf7110cf8d36c7cab9374ab
0cf1e9215a3c5b7ad113b6707eae4dddb23568c0
/String/KMP-next.cpp
b28789f67e13a57ef6f1a31b8f4ea262317a1388
[]
no_license
CrazyPigAndCat/DataStructure
5e1979078a775c014b568823896ae323a6446d1a
004b82087bd356238783158d8ce0b92f4f0bca0b
refs/heads/master
2023-01-10T10:55:53.897841
2020-11-06T13:42:57
2020-11-06T13:42:57
295,995,299
0
0
null
null
null
null
UTF-8
C++
false
false
928
cpp
// // Created by puppet on 2020/10/2. // #include <stdio.h> #define MAXLEN 255 typedef struct{ char ch[MAXLEN]; int length; }SString; int Index_KMP(SString S,SString T,int nextval[]){ int i=1,j=1; while (i<=S.length&&j<T.length){ if(j==0||S.ch[i]==T.ch[j]){ ++i; ++j; }else{ j=nextval[j]; } } if(j>T.length) return i-T.length; else return 0; } void get_next(SString T,int next[]){ int i=1,j=0; next[1]=0; while (i<T.length){ if{j==0||T.ch[i]==Y.ch[j]}{ ++i; ++j; next[i]=j; }else{ j=next[j]; } } } void get_nextval(int next[],int nextval[],SString T){ nextval[1]=0; for(int j=2;j<=T.length;j++){ if(T.ch[next[j]]==T.ch[j]) nextval[j]=nextval[next[j]]; else nextval[j]=next[j]; } }
[ "909395091@qq.com" ]
909395091@qq.com
208d0eb4210fd31427bfca2576203321b9163e6b
d54d424ecd73e0444bc04d7f024db8d7c864a85a
/speedwriter/src/wordchecker.h
3983a1b9703c9ba0431fd5f1df8f4c70b94189ab
[ "Apache-2.0" ]
permissive
jsoref/Cascades-Samples
51adc41e4d3b33e8507c629e10c0413c515a6906
ef941b803756d09cff12db1977687dfc2ea5ff46
refs/heads/master
2021-04-15T09:45:37.648754
2012-11-28T00:15:13
2012-11-29T20:35:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,806
h
/* Copyright (c) 2012 Research In Motion Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _WORDCHECKER_H_ #define _WORDCHECKER_H_ #include <QObject> // Evaluation of the word check may result in one of the following enumeration states; correct, wrong, newline, and end enum WordResult { WordResult_Correct, WordResult_Wrong, WordResult_NewLine, WordResult_End }; /** * WordChecker Description: * * This class is to evaluate if the string being sent * to it corresponds to a given string in the text to be typed. * In other words, the word (string) passed is valid or invalid * relative to what should be typed. * */ class WordChecker: public QObject { Q_OBJECT /** * Property that holds the entire speed text that the player is supposed to type */ Q_PROPERTY(QString speedText READ speedText WRITE setSpeedText NOTIFY speedTextChanged) /** * Property that reflects the number of correctly entered lines so far by the user */ Q_PROPERTY(int line READ line NOTIFY lineChanged) /** * Property that holds the number of correctly inputed characters so far by the user */ Q_PROPERTY(int nbrOfCharacters READ nbrOfCharacters NOTIFY nbrOfCharactersChanged) /** * Property that holds the text of all entered lines entered up to the current line */ Q_PROPERTY(QString enteredLines READ enteredLines NOTIFY enteredLinesChanged) /** * The part of current line that has been entered correctly. */ Q_PROPERTY(QString currentCorrectLine READ currentCorrectLine NOTIFY currentCorrectLineChanged) public: /** * This is our constructor which initializes the member variables. * @param parent The parent Container, if not specified, 0 is used. */ WordChecker(QObject *parent = 0); ~WordChecker(); /** * This function sets the speedText property. * * @param speedText The text that the checker will compare against including end of line characters. */ void setSpeedText(QString speedText); /** * This function return the entire speed text including end of line characters as a QString. * * @return The current speed text */ QString speedText(); /** * This function returns the number of lines correctly entered so far. * * @return The number of lines correctly entered so far */ int line(); /** * This function returns the number of correctly entered characters so far. * * @return The number of correctly entered characters so far */ int nbrOfCharacters(); /** * This function returns a QString of all the text that has been entered prior to the current line. * * @return A QString of all entered text before the current line */ QString enteredLines(); /** * This function returns a string of all the correctly entered text for the current line. */ QString currentCorrectLine(); /** * This function checks the current input towards the actual * text that should be written (hence forth called the speed text). * * @param currentWord The current word entered into the text input field. * @return The WordResult of checking the text (enum state defined above) */ Q_INVOKABLE WordResult checkWord(const QString currentWord); signals: /** * This signal is emitted when a new speed text has been set */ void speedTextChanged(QString speedText); /** * This signal is emitted when a line break as reached, the parameter, line, is the number of lines */ void lineChanged(int line); /** * This signal is emitted when progress has been made on correctly entering text on the current line. */ void currentCorrectLineChanged(QString currentCorrectLine); /** * This signal is emitted when the correctly entered lines changes (the parameter contains only full lines). */ void enteredLinesChanged(QString enteredLines); /** * This signal is emitted the number of correctly entered characters have changed. */ void nbrOfCharactersChanged(int nbrOfCharacters); /** * This signal is emitted when all text has been entered correctly. */ void ended(); private: // State variables int mSpeedTextLength; // Property variables QString mSpeedText; QString mEnteredLines; QString mCurrentCorrectLine; int mLine; int mNbrOfCharacters; }; #endif // _WORDCHECKER_H_
[ "jlarsby@rim.com" ]
jlarsby@rim.com
954acad462398cc3b0af0a93b56e67d43d900323
4164e13053dab51d02affb94c46c529b37a08347
/tkir_game/tkir_game/PathFinder.h
a759565f8b6e74d5ca72a8e6344e279341aac98e
[]
no_license
tkir/goldenbyte2016
656629f500a4afc0892a7df456ba583cb4791ced
8f2ebeeff24e9b0d96b6cb4a897be1bc5fe0bb67
refs/heads/master
2021-01-10T02:39:04.951688
2016-01-25T19:15:25
2016-01-25T19:15:25
49,377,365
1
0
null
null
null
null
UTF-8
C++
false
false
1,528
h
#pragma once #include "include.h" struct object { Vector2f point[4]; Vector2f centerPoint; float furthestPoint; bool isWall; object(){} object create(Vector2f position, float tileSize); }; class MiniMap { public: object obj; object** miniMap; Vector2u mapSize, countMiniMapTyles; float miniMapTyleSize; std::vector<tmx::MapObject>* solid; void createObj(Vector2f _pos); bool collision(object& _miniMapObj); bool contains(object& _mapObj, sf::Vector2f point); public: MiniMap(){} void create(Vector2u _mapSize, unsigned int _miniMapObjSize = 16, std::vector<tmx::MapObject>* _solid = nullptr); object**& getMiniMap(){ return miniMap; } Vector2u getMiniMapSize(){ return countMiniMapTyles; } std::vector<tmx::MapObject>* getSolid(){ return solid; }; Vector2i getMiniPositionEntyty(Vector2f _entityPosition);//returns number cell in minimap }; class PathFinder { private: MiniMap* map; object*** miniMap; int** distanceMap; Vector2i mapSize, start, target; Vector2f m_start, m_target; tmx::MapObject* entityObj; std::vector<sf::Vector2i> resultPath; std::vector<sf::Vector2f>* smoothPath; bool isPathExist; std::vector<tmx::MapObject>* solid; void smoothing(); bool isObstacle(Vector2f A, Vector2f B, tmx::MapObject* _solid); bool isLinesCross(float x11, float y11, float x12, float y12, float x21, float y21, float x22, float y22); public: PathFinder(tmx::MapObject* entityObj, MiniMap* map, std::vector<sf::Vector2f>* smoothPath = nullptr); void aStar(Vector2f target); };
[ "kirill.titenko@gmail.com" ]
kirill.titenko@gmail.com
2228540270eb8d2f9bd3baa9eef2d33b3dc2244b
5f79f9c1feade5b8aa505ce999f78acff1864e7e
/ns-3.20/src/applications/model/trickles-appcont.h
da3f4ba48221cd0a7c6c96cc11b9188b4197ac61
[]
no_license
dchaly/stateless
52a26938c0c45e553569eb5e64f7a90fdf0d16e5
230344eafa24cc426b3c44b68d84a40125d17fe8
refs/heads/master
2021-01-22T07:32:32.845106
2015-10-30T09:25:49
2015-10-30T09:25:49
29,728,783
1
0
null
null
null
null
UTF-8
C++
false
false
1,413
h
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2014 P.G. Demidov Yaroslavl State University * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Dmitry Chalyy <chaly@uniyar.ac.ru> */ #ifndef TRICKLES_APPCONT_H #define TRICKLES_APPCONT_H #include "ns3/tag.h" using namespace ns3; class TricklesRequestSizeTag : public Tag { public: TricklesRequestSizeTag(); void SetRequestSize(uint16_t rqSize); uint16_t GetRequestSize() const; static TypeId GetTypeId(void); virtual TypeId GetInstanceTypeId(void) const; virtual uint32_t GetSerializedSize(void) const; virtual void Serialize(TagBuffer i) const; virtual void Deserialize(TagBuffer i); virtual void Print(std::ostream &os) const; private: uint16_t m_rqSize; }; #endif
[ "dmitry.chaly@gmail.com" ]
dmitry.chaly@gmail.com
227decd6dc576104cecfa2ffe65fe438cfa0bfd8
e2029872bcf1feead431d3eb155ddc91036d9317
/Compiler/AST/ASTLiterals_CG.cpp
835fe84a332c46d8f12a051d76ed4bd1c6977ef2
[ "Artistic-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
FingerLeakers/emojicode
604d14a11ca7716b0488bc0d3d5ce3f573bfe2a3
1e5b1a6f287998639cd43152f37482125ab3d96a
refs/heads/master
2020-03-12T06:16:48.757828
2018-04-09T13:02:51
2018-04-09T13:02:51
130,481,785
2
0
null
2018-04-21T14:34:08
2018-04-21T14:34:08
null
UTF-8
C++
false
false
3,287
cpp
// // ASTLiterals_CG.cpp // Emojicode // // Created by Theo Weidmann on 03/09/2017. // Copyright © 2017 Theo Weidmann. All rights reserved. // #include "ASTLiterals.hpp" #include "ASTInitialization.hpp" #include "Compiler.hpp" #include "Generation/CallCodeGenerator.hpp" #include "Generation/FunctionCodeGenerator.hpp" #include "Types/Class.hpp" namespace EmojicodeCompiler { Value* ASTStringLiteral::generate(FunctionCodeGenerator *fg) const { return fg->generator()->stringPool().pool(value_); } Value* ASTBooleanTrue::generate(FunctionCodeGenerator *fg) const { return llvm::ConstantInt::getTrue(fg->generator()->context()); } Value* ASTBooleanFalse::generate(FunctionCodeGenerator *fg) const { return llvm::ConstantInt::getFalse(fg->generator()->context()); } Value* ASTNumberLiteral::generate(FunctionCodeGenerator *fg) const { switch (type_) { case NumberType::Byte: return fg->int8(integerValue_); case NumberType::Integer: return fg->int64(integerValue_); case NumberType::Double: return llvm::ConstantFP::get(llvm::Type::getDoubleTy(fg->generator()->context()), doubleValue_); } } Value* ASTSymbolLiteral::generate(FunctionCodeGenerator *fg) const { return llvm::ConstantInt::get(llvm::Type::getInt32Ty(fg->generator()->context()), value_); } Value* ASTThis::generate(FunctionCodeGenerator *fg) const { return fg->thisValue(); } Value* ASTNoValue::generate(FunctionCodeGenerator *fg) const { if (type_.storageType() == StorageType::Box) { return fg->getBoxOptionalWithoutValue(); } return fg->getSimpleOptionalWithoutValue(type_); } Value* ASTDictionaryLiteral::generate(FunctionCodeGenerator *fg) const { auto dict = ASTInitialization::initObject(fg, ASTArguments(position()), std::u32string(1, 0x1F438), type_); for (auto it = values_.begin(); it != values_.end(); it++) { auto args = ASTArguments(position()); args.addArguments(*it); args.addArguments(*(++it)); CallCodeGenerator(fg, CallType::StaticDispatch).generate(dict, type_, args, std::u32string(1, 0x1F437)); } return dict; } Value* ASTListLiteral::generate(FunctionCodeGenerator *fg) const { auto list = ASTInitialization::initObject(fg, ASTArguments(position()), std::u32string(1, 0x1F438), type_); for (auto value : values_) { auto args = ASTArguments(position()); args.addArguments(value); CallCodeGenerator(fg, CallType::StaticDispatch).generate(list, type_, args, std::u32string(1, 0x1F43B)); } return list; } Value* ASTConcatenateLiteral::generate(FunctionCodeGenerator *fg) const { auto strbuilder = ASTInitialization::initObject(fg, ASTArguments(position()), std::u32string(1, 0x1F195), type_); for (auto &stringNode : values_) { auto args = ASTArguments(position()); args.addArguments(stringNode); CallCodeGenerator(fg, CallType::StaticDispatch).generate(strbuilder, type_, args, std::u32string(1, 0x1F43B)); } return CallCodeGenerator(fg, CallType::StaticDispatch).generate(strbuilder, type_, ASTArguments(position()), std::u32string(1, 0x1F521)); } } // namespace EmojicodeCompiler
[ "hi@idmean.xyz" ]
hi@idmean.xyz
cc38085f77287d06fa5622aa5d375c4e40b8f94a
83bacfbdb7ad17cbc2fc897b3460de1a6726a3b1
/third_party/WebKit/Source/core/layout/ClipRect.cpp
48f1e01c3d3c950196fe6622eb232113b190256a
[ "Apache-2.0", "BSD-2-Clause", "LGPL-2.1-only", "LGPL-2.0-only", "BSD-3-Clause", "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "GPL-1.0-or-later", "GPL-2.0-only", "LicenseRef-scancode-other-copyleft" ]
permissive
cool2528/miniblink49
d909e39012f2c5d8ab658dc2a8b314ad0050d8ea
7f646289d8074f098cf1244adc87b95e34ab87a8
refs/heads/master
2020-06-05T03:18:43.211372
2019-06-01T08:57:37
2019-06-01T08:59:56
192,294,645
2
0
Apache-2.0
2019-06-17T07:16:28
2019-06-17T07:16:27
null
UTF-8
C++
false
false
1,639
cpp
/* * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. 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 "config.h" #include "core/layout/ClipRect.h" #include "core/layout/HitTestLocation.h" namespace blink { bool ClipRect::intersects(const HitTestLocation& hitTestLocation) const { return hitTestLocation.intersects(m_rect); } } // namespace blink
[ "22249030@qq.com" ]
22249030@qq.com
898f9b20295f684592c6a130ba665d71bfb56e14
b49621154ebcd28a10df8e8e5ef90d76d963f8b6
/Grayscale/OpenCVInterface/OpenCVInterface/Bin2Val.cpp
2cee15efc6c1493389aa549448a469f1db2b9b59
[]
no_license
alduleacristi/proiect-procesare-imagini
b8fdfc7720cdb1b2c67871114dfd6ae9affd0bb4
980c784c5bd48c5e6d13776048fd37f1bdd34ea3
refs/heads/master
2016-08-12T06:47:37.981466
2013-12-09T11:02:03
2013-12-09T11:02:03
44,041,915
0
0
null
null
null
null
UTF-8
C++
false
false
851
cpp
// Bin2Val.cpp : implementation file // #include "stdafx.h" #include "OpenCVInterface.h" #include "Bin2Val.h" #include "afxdialogex.h" // Bin2Val dialog IMPLEMENT_DYNAMIC(Bin2Val, CDialogEx) Bin2Val::Bin2Val(CWnd* pParent /*=NULL*/) : CDialogEx(Bin2Val::IDD, pParent) { } Bin2Val::~Bin2Val() { } void Bin2Val::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(Bin2Val, CDialogEx) ON_BN_CLICKED(IDOK, &Bin2Val::OnBnClickedOk) END_MESSAGE_MAP() // Bin2Val message handlers void Bin2Val::OnBnClickedOk() { CString s1,s2; GetDlgItem(IDC_T1)->GetWindowText(s1); GetDlgItem(IDC_T2)->GetWindowText(s2); t1=atoi(s1); t2=atoi(s2); CDialogEx::OnOK(); } int Bin2Val::getT1(void) { return t1; } int Bin2Val::getT2(void) { return t2; }
[ "vereseniko11@gmail.com" ]
vereseniko11@gmail.com
4fbd36fef826e06b5fe8d1984f744780ec92fec0
211bb4bf4a7a1683befd887e421876a95b3eae7e
/studyalg/helper.h
b247f3579988cc87c29b722c8bbbb2dc40c65e78
[ "BSD-3-Clause" ]
permissive
heyihan/scodes
ee7f90fad4af1fe1f4ef0794de67b3e517e389a5
342518b548a723916c9273d8ebc1b345a0467e76
refs/heads/master
2021-10-09T20:59:05.279783
2021-08-24T07:17:21
2021-08-24T07:17:21
59,666,962
0
0
null
null
null
null
UTF-8
C++
false
false
1,046
h
#ifndef _STUDY_ALG_H_HELPER_ #define _STUDY_ALG_H_HELPER_ #include <iostream> #include <ctime> class ProcessTime { public: ProcessTime() { clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &lastTime_); } int64_t elapsedNs(bool renew = false) { timespec now; clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &now); if(renew) { lastTime_ = now; } return (now.tv_sec-lastTime_.tv_sec)*1e9 + (now.tv_nsec-lastTime_.tv_nsec); } private: timespec lastTime_; }; typedef void (*func)(); void runOnce(const std::string & title, func f) { f(); } template<typename T> std::ostream & operator<<(std::ostream & os, const std::vector<T> & elems) { bool first = true; os << '['; for(auto &e : elems) { if(!first) { os << ','; } os << e; first = false; } os << ']' << std::endl; return os; } #endif
[ "heyihan1988@163.com" ]
heyihan1988@163.com
f6b0043c57266cb73d5bfed86c83895be9fe396b
4d4822b29e666cea6b2d99d5b9d9c41916b455a9
/Example/Pods/Headers/Private/GeoFeatures/boost/geometry/multi/algorithms/remove_spikes.hpp
96bfa1b9c53e63ec90436116074af98f2960410b
[ "BSL-1.0", "Apache-2.0" ]
permissive
eswiss/geofeatures
7346210128358cca5001a04b0e380afc9d19663b
1ffd5fdc49d859b829bdb8a9147ba6543d8d46c4
refs/heads/master
2020-04-05T19:45:33.653377
2016-01-28T20:11:44
2016-01-28T20:11:44
50,859,811
0
0
null
2016-02-01T18:12:28
2016-02-01T18:12:28
null
UTF-8
C++
false
false
88
hpp
../../../../../../../../../GeoFeatures/boost/geometry/multi/algorithms/remove_spikes.hpp
[ "hatter24@gmail.com" ]
hatter24@gmail.com
a9fb9d2b18afd8678aa0903cfdd8cb631b883b89
5d01a2a16078b78fbb7380a6ee548fc87a80e333
/MarketDataAdapters/iseprovider/isestdpriceprovider.h
84623f8762a5e59a0f2ccf83e635314dc14e3feb
[]
no_license
WilliamQf-AI/IVRMstandard
2fd66ae6e81976d39705614cfab3dbfb4e8553c5
761bbdd0343012e7367ea111869bb6a9d8f043c0
refs/heads/master
2023-04-04T22:06:48.237586
2013-04-17T13:56:40
2013-04-17T13:56:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,539
h
// ISEStdPriceProvider.h : Declaration of the CISEStdPriceProvider #ifndef __ISESTDPRICEPROVIDER_H_ #define __ISESTDPRICEPROVIDER_H_ #include "resource.h" // main symbols #include "ISEEvents.h" #include "ObjectID.h" ///////////////////////////////////////////////////////////////////////////// // CISEStdPriceProvider class ATL_NO_VTABLE CISEStdPriceProvider : public CComObjectRootEx<CComMultiThreadModel>, public CComCoClass<CISEStdPriceProvider, &CLSID_ISEPriceProvider>, public ISupportErrorInfoImpl<&IID_IPriceProvider>, public IConnectionPointContainerImpl<CISEStdPriceProvider>, public IDispatchImpl<IPriceProvider, &IID_IPriceProvider, &LIBID_ISEPROVIDERLib>, public IDispatchImpl<IGroupPrice, &IID_IGroupPrice, &LIBID_ISEPROVIDERLib>, public IConnectionPointImpl<CISEStdPriceProvider, &DIID__IPriceProviderEvents, CComDynamicUnkArray>, public CISEPriceBase { public: CISEStdPriceProvider() { } DECLARE_REGISTRY_RESOURCEID(IDR_ISESTDPRICEPROVIDER) DECLARE_PROTECT_FINAL_CONSTRUCT() BEGIN_COM_MAP(CISEStdPriceProvider) COM_INTERFACE_ENTRY(IPriceProvider) COM_INTERFACE_ENTRY(IGroupPrice) COM_INTERFACE_ENTRY2(IDispatch, IGroupPrice) COM_INTERFACE_ENTRY(ISupportErrorInfo) COM_INTERFACE_ENTRY(IConnectionPointContainer) END_COM_MAP() BEGIN_CONNECTION_POINT_MAP(CISEStdPriceProvider) CONNECTION_POINT_ENTRY(DIID__IPriceProviderEvents) END_CONNECTION_POINT_MAP() public: void FinalRelease() { EgTrace("CISEStdPriceProvider::Release"); Disconnect(); } // CP virtual HRESULT OnLastQuote(const CComVariant &varParams, const CComVariant &varResults); virtual HRESULT OnQuoteUpdate(const CComVariant &varParams, const CComVariant &varResults); virtual HRESULT OnError(ErrorNumberEnum enumError, _bstr_t bstrDescription, RequestsTypeEnum enumRequest, const CComVariant &varRequest); virtual HRESULT OnEvent(const EventNumberEnum EventNumber, _bstr_t Description); // ISupportsErrorInfo //STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid); // IPriceProvider public: STDMETHOD(RequestLastQuote)(QuoteUpdateParams* Params); STDMETHOD(CancelLastQuote)(VARIANT Params); STDMETHOD(SubscribeQuote)(QuoteUpdateParams* Params); STDMETHOD(UnSubscribeQuote)(VARIANT Params); STDMETHOD(Connect)(); STDMETHOD(Disconnect)(); //IGroupPrice STDMETHOD(RequestGroup)(QuoteUpdateParams* Params,/*[in]*/ GroupRequestType enTypeGroupRequest); STDMETHOD(CancelGroup)(VARIANT Params); }; #endif //__ISESTDPRICEPROVIDER_H_
[ "chuchev@egartech.com" ]
chuchev@egartech.com
24603918be3ecd006da4f36446c27c97b0996f2d
f6ab96101246c8764dc16073cbea72a188a0dc1a
/OnlineJudge/ZEROJUDGE/b208 A. 蜜蜂的約會.cpp
b498b8767d319c71bf104b94352c690fff21ab49
[]
no_license
nealwu/UVa
c87ddc8a0bf07a9bd9cadbf88b7389790bc321cb
10ddd83a00271b0c9c259506aa17d03075850f60
refs/heads/master
2020-09-07T18:52:19.352699
2019-05-01T09:41:55
2019-05-01T09:41:55
220,883,015
3
2
null
2019-11-11T02:14:54
2019-11-11T02:14:54
null
UTF-8
C++
false
false
709
cpp
#include <stdio.h> #include <string.h> int mapped[262144], LIS[100005]; int main() { int n, i, x; while(scanf("%d", &n) == 1) { memset(mapped, 0, sizeof(mapped)); for(i = 0; i < n; i++) scanf("%d", &x), mapped[x+100000] = i; int L = -1, l, r, m; for(i = 0; i < n; i++) { scanf("%d", &x); x = mapped[x+100000]; l = 0, r = L; while(l <= r) { m = (l+r)/2; if(LIS[m] < x) l = m+1; else r = m-1; } LIS[l] = x; if(l > L) L = l; } printf("%d\n", L+1); } return 0; }
[ "morris821028@gmail.com" ]
morris821028@gmail.com
3135aeba2588f0ef4e186b67192bc7ccfc48d935
9fb456a0f1cc77d148a9c5334c084c2a65630592
/Procession/include/ConcurrentQueue.h
f8e940786adb56f610ce5ee32925562edddb6dba
[ "Apache-2.0" ]
permissive
eighteight/CinderEight
4deba73910eb3e02d2f881da303205159a77f052
d9dfc6a0ad9a9e6c5b82624971127f0335d91639
refs/heads/master
2021-06-19T14:46:18.448625
2021-01-16T20:55:22
2021-01-16T20:55:22
16,152,693
6
1
null
null
null
null
UTF-8
C++
false
false
2,757
h
/* Copyright (C) 2010-2012 Paul Houx 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. Based on the excellent article by Anthony Williams: http://www.justsoftwaresolutions.co.uk/threading/implementing-a-thread-safe-queue-using-condition-variables.html 01/15/2015 -- eight_io replaced boost and updated for Cinder glNext branch */ #pragma once #include "cinder/Thread.h" #include <queue> namespace ph { template<typename Data> class ConcurrentQueue { public: ConcurrentQueue(void){}; ~ConcurrentQueue(void){}; void push(Data const& data) { std::unique_lock<std::mutex> lock(mMutex); mQueue.push(data); lock.unlock(); mCondition.notify_one(); } bool empty() const { std::unique_lock<std::mutex> lock(mMutex); return mQueue.empty(); } bool try_pop(Data& popped_value) { std::unique_lock<std::mutex> lock(mMutex); if(mQueue.empty()) { return false; } popped_value=mQueue.front(); mQueue.pop(); return true; } void wait_and_pop(Data& popped_value) { std::unique_lock<std::mutex> lock(mMutex); while(mQueue.empty()) { mCondition.wait(lock); } popped_value=mQueue.front(); mQueue.pop(); } std::size_t size() const { return mQueue.size(); } private: std::queue<Data> mQueue; mutable std::mutex mMutex; std::condition_variable mCondition; }; } // namespace ph
[ "bo-ba@mail.ru" ]
bo-ba@mail.ru
b1f8bb22cf5ab0a14c8106abe344437fdac0fda9
ede874b59555fd65ab2aa44f17a71a5a748eafa6
/include/etl/std.hpp
060e1bbe66213f7f0fb2eb3e053e66329d8d9278
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
bechirzf/etl-2
aad392dc07f42dd772914931ed192829d2d64a74
32e8153b38e0029176ca4fe2395b7fa6babe3189
refs/heads/master
2020-06-11T10:52:16.362349
2018-05-07T08:41:17
2018-05-07T08:41:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,061
hpp
//======================================================================= // Copyright (c) 2014-2018 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once // STL #include <complex> #include <vector> #include <array> #include <algorithm> //For value_testable #include <iosfwd> //For stream support #include <type_traits> //For static assertions tests #include <tuple> //For TMP stuff #include <thread> // cpp_utils #include "cpp_utils/compat.hpp" #include "cpp_utils/tmp.hpp" #include "cpp_utils/likely.hpp" #include "cpp_utils/assert.hpp" #include "cpp_utils/parallel.hpp" // Macro to handle noexcept and cpp_assert namespace etl { #ifdef NDEBUG constexpr bool assert_nothrow = true; #else #ifdef CPP_UTILS_ASSERT_EXCEPTION constexpr bool assert_nothrow = false; #else constexpr bool assert_nothrow = true; #endif #endif /*! * \brief Alignment flag to aligned expressions * * This can be used to make expressions more clear. */ constexpr bool aligned = false; /*! * \brief Alignment flag to unaligned expressions. * * This can be used to make expressions more clear. */ constexpr bool unaligned = false; /*! * \brief The current major version number of the library */ constexpr size_t version_major = 1; /*! * \brief The current minor version number of the library */ constexpr size_t version_minor = 3; /*! * \brief The current revision version number of the library */ constexpr size_t version_revision = 0; } //end of namespace etl /*! * \brief String representation of the current version of the library. */ #define ETL_VERSION_STR "1.3.0" /*! * \brief The current major version number of the library */ #define ETL_VERSION_MAJOR 1 /*! * \brief The current minor version number of the library */ #define ETL_VERSION_MINOR 3 /*! * \brief The current revision version number of the library */ #define ETL_VERSION_REVISION 0
[ "baptiste.wicht@gmail.com" ]
baptiste.wicht@gmail.com
908b05f0bad557b440e1ea1dc5f0506825cb1ae4
2daa40b22b1a5374e7932863fc57f8a3821c2081
/pwm.ino
ad0c0d7e23c6c479f794561dacb0fe4dbe39637b
[]
no_license
leenabushqair/arduinoBasics
ceea517c1cf621f1e6a81a891781902617a8e406
bb41a774a8eeba60af653b5cadec38f79963ebaa
refs/heads/master
2022-07-05T05:23:09.993236
2020-05-12T20:42:44
2020-05-12T20:42:44
263,447,194
0
0
null
null
null
null
UTF-8
C++
false
false
200
ino
void setup() { pinMode( 6, OUTPUT); } void loop() { for(int i=0; i<=255; i++){ analogWrite(6, i); delay(5); } for(int i=255; i>=0; i--){ analogWrite(6, i); delay(5); } }
[ "noreply@github.com" ]
leenabushqair.noreply@github.com
16d6aa24e766c9f6fe27b57b2a892ef5b582344a
9ee3e1553fe2ad320d73ca7e0c7fb77abfe6aa74
/MyCppGame/Classes/src/Vibrator.cpp
151682014feb038c5e82505662ea2b47703b46f7
[ "MIT" ]
permissive
Crasader/FinalYearProject
be70553a1adfc844d813fe72c328d1c525c30a9b
359c0cb74f3f246ae0ecb6a2627e02aa3df68aee
refs/heads/master
2021-05-31T20:02:09.308199
2016-04-20T20:38:16
2016-04-20T20:38:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
586
cpp
#include "Vibrator.h" void Vibrator::Vibrate(int time) { #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) JniMethodInfo t; if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "vibrate", "(I)V")) { t.env->CallStaticVoidMethod(t.classID, t.methodID, time); t.env->DeleteLocalRef(t.classID); } #endif } void Vibrator::CancelVibrate() { #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) JniMethodInfo t; if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "cancelVibrate", "()V")) { t.env->CallStaticVoidMethod(t.classID, t.methodID); t.env->DeleteLocalRef(t.classID); } #endif }
[ "shane.dooley94@gmail.com" ]
shane.dooley94@gmail.com
b1ecbf1c286bbbb24b4cece306d9fd8f4314518e
ddd1627528684416cba58a9432ec3036435056a8
/GFX/GFX/GFXExMan.h
1429be4c9098416eb10c2ee6da4dc8ccf1a005a5
[]
no_license
sunhanpt/GFEffect
70b027b023c455bdafd58a02eb7af4aa6fccc4ce
79f2194a9899aeb84ce742ab9aff860cefa664db
refs/heads/master
2021-05-06T02:08:48.533451
2017-12-17T03:43:59
2017-12-17T03:43:59
114,505,475
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
230
h
#pragma once /* ** Name: GFXExMan.h ** By: pengtong.pt ** Desc: GFXExµÄ¹ÜÀíÀà */ #include <vector> class GFXEx; class GFXExMan { public: GFXExMan() {} virtual ~GFXExMan() {} public: std::vector<GFXEx*> m_GFXExArr; };
[ "763737898@qq.com" ]
763737898@qq.com
08100b362395043420f286bc6895f0425652cd2f
f5ffab38ba16c51b3e4d01598d01f4ee17ae93ae
/NinjaGaiden/SwordManAttackRight.cpp
25d49be6c295fe227559a331c84f6fbe48c8e160
[]
no_license
thanhgit/NinjaGaiden
b497c8477907193ada397630c5cbe6a08ab91547
d475c671cddbb80c6c544f2a9c487dedd2d4567a
refs/heads/master
2021-06-19T11:59:01.074268
2021-01-24T01:27:53
2021-01-24T01:45:49
176,050,004
0
0
null
2021-01-29T20:31:04
2019-03-17T03:03:56
C++
UTF-8
C++
false
false
304
cpp
#include"SwordManAttackRight.h" SwordManAttackRight::SwordManAttackRight(SwordManGraphics* _graphics) { this->graphics = _graphics; } SwordManAttackRight::~SwordManAttackRight() { } void SwordManAttackRight::update(Box* swordMan) { this->graphics->actackRight(swordMan->GetX(), swordMan->GetY()); }
[ "thanh29695@gmail.com" ]
thanh29695@gmail.com