hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
sequencelengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
sequencelengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
sequencelengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
cebefcfa86ed528de60b9fc78e36968ef9615386
8,855
cpp
C++
tests/is_base_of/overview.cpp
connojd/bsl
9adebf89bf34ac14d92b26007cb19d5508de54ac
[ "MIT" ]
null
null
null
tests/is_base_of/overview.cpp
connojd/bsl
9adebf89bf34ac14d92b26007cb19d5508de54ac
[ "MIT" ]
null
null
null
tests/is_base_of/overview.cpp
connojd/bsl
9adebf89bf34ac14d92b26007cb19d5508de54ac
[ "MIT" ]
null
null
null
/// @copyright /// Copyright (C) 2020 Assured Information Security, Inc. /// /// @copyright /// 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: /// /// @copyright /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// @copyright /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE /// SOFTWARE. #include <bsl/is_base_of.hpp> #include <bsl/ut.hpp> namespace { class myclass final {}; struct mystruct final {}; union myunion final {}; enum class myenum : bsl::int32 { }; class myclass_abstract // NOLINT { public: virtual ~myclass_abstract() noexcept = default; virtual void foo() noexcept = 0; }; class myclass_base {}; class myclass_subclass : public myclass_base {}; } /// <!-- description --> /// @brief Main function for this unit test. If a call to ut_check() fails /// the application will fast fail. If all calls to ut_check() pass, this /// function will successfully return with bsl::exit_success. /// /// <!-- inputs/outputs --> /// @return Always returns bsl::exit_success. /// bsl::exit_code main() noexcept { using namespace bsl; static_assert(is_base_of<myclass_base, myclass_subclass>::value); static_assert(is_base_of<myclass_base const, myclass_subclass>::value); static_assert(is_base_of<myclass_subclass, myclass_subclass>::value); static_assert(is_base_of<myclass_subclass const, myclass_subclass>::value); static_assert(!is_base_of<bool, myclass_subclass>::value); static_assert(!is_base_of<bool const, myclass_subclass>::value); static_assert(!is_base_of<bsl::int8, myclass_subclass>::value); static_assert(!is_base_of<bsl::int8 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::int16, myclass_subclass>::value); static_assert(!is_base_of<bsl::int16 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::int32, myclass_subclass>::value); static_assert(!is_base_of<bsl::int32 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::int64, myclass_subclass>::value); static_assert(!is_base_of<bsl::int64 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::int_least8, myclass_subclass>::value); static_assert(!is_base_of<bsl::int_least8 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::int_least16, myclass_subclass>::value); static_assert(!is_base_of<bsl::int_least16 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::int_least32, myclass_subclass>::value); static_assert(!is_base_of<bsl::int_least32 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::int_least64, myclass_subclass>::value); static_assert(!is_base_of<bsl::int_least64 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::int_fast8, myclass_subclass>::value); static_assert(!is_base_of<bsl::int_fast8 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::int_fast16, myclass_subclass>::value); static_assert(!is_base_of<bsl::int_fast16 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::int_fast32, myclass_subclass>::value); static_assert(!is_base_of<bsl::int_fast32 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::int_fast64, myclass_subclass>::value); static_assert(!is_base_of<bsl::int_fast64 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::intptr, myclass_subclass>::value); static_assert(!is_base_of<bsl::intptr const, myclass_subclass>::value); static_assert(!is_base_of<bsl::intmax, myclass_subclass>::value); static_assert(!is_base_of<bsl::intmax const, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint8, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint8 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint16, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint16 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint32, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint32 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint64, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint64 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint_least8, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint_least8 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint_least16, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint_least16 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint_least32, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint_least32 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint_least64, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint_least64 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint_fast8, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint_fast8 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint_fast16, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint_fast16 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint_fast32, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint_fast32 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint_fast64, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint_fast64 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::uintptr, myclass_subclass>::value); static_assert(!is_base_of<bsl::uintptr const, myclass_subclass>::value); static_assert(!is_base_of<bsl::uintmax, myclass_subclass>::value); static_assert(!is_base_of<bsl::uintmax const, myclass_subclass>::value); static_assert(!is_base_of<myclass, myclass_subclass>::value); static_assert(!is_base_of<myclass const, myclass_subclass>::value); static_assert(!is_base_of<mystruct, myclass_subclass>::value); static_assert(!is_base_of<mystruct const, myclass_subclass>::value); static_assert(!is_base_of<myunion, myclass_subclass>::value); static_assert(!is_base_of<myunion const, myclass_subclass>::value); static_assert(!is_base_of<myenum, myclass_subclass>::value); static_assert(!is_base_of<myenum const, myclass_subclass>::value); static_assert(!is_base_of<bool[], myclass_subclass>::value); // NOLINT static_assert(!is_base_of<bool[1], myclass_subclass>::value); // NOLINT static_assert(!is_base_of<bool[][1], myclass_subclass>::value); // NOLINT static_assert(!is_base_of<bool[1][1], myclass_subclass>::value); // NOLINT static_assert(!is_base_of<bool const[], myclass_subclass>::value); // NOLINT static_assert(!is_base_of<bool const[1], myclass_subclass>::value); // NOLINT static_assert(!is_base_of<bool const[][1], myclass_subclass>::value); // NOLINT static_assert(!is_base_of<bool const[1][1], myclass_subclass>::value); // NOLINT static_assert(!is_base_of<void, myclass_subclass>::value); static_assert(!is_base_of<void const, myclass_subclass>::value); static_assert(!is_base_of<void *, myclass_subclass>::value); static_assert(!is_base_of<void const *, myclass_subclass>::value); static_assert(!is_base_of<void *const, myclass_subclass>::value); static_assert(!is_base_of<void const *const, myclass_subclass>::value); static_assert(!is_base_of<bool &, myclass_subclass>::value); static_assert(!is_base_of<bool &&, myclass_subclass>::value); static_assert(!is_base_of<bool const &, myclass_subclass>::value); static_assert(!is_base_of<bool const &&, myclass_subclass>::value); static_assert(!is_base_of<bool(bool), myclass_subclass>::value); static_assert(!is_base_of<bool (*)(bool), myclass_subclass>::value); return bsl::ut_success(); }
53.993902
87
0.74026
connojd
cebf3cf1108f22fd2fd3cb3140f720d05ef77d67
974
hpp
C++
include/Vnavbar.hpp
LeandreBl/sfml-scene
3fb0d1167f1585c0c82775a23b44df46ec7378d5
[ "Apache-2.0" ]
2
2020-12-10T20:22:17.000Z
2020-12-10T20:23:35.000Z
include/Vnavbar.hpp
LeandreBl/sfml-scene
3fb0d1167f1585c0c82775a23b44df46ec7378d5
[ "Apache-2.0" ]
null
null
null
include/Vnavbar.hpp
LeandreBl/sfml-scene
3fb0d1167f1585c0c82775a23b44df46ec7378d5
[ "Apache-2.0" ]
null
null
null
#pragma once #include "UI.hpp" #include "BasicShape.hpp" namespace sfs { class Vnavbar : public UI { public: Vnavbar(Scene &scene, const sf::Vector2f &position = sf::Vector2f(0, 0), const sf::Vector2f &size = sf::Vector2f(30, 100), const sf::Color &color = sf::Color::White) noexcept; Vnavbar(const Vnavbar &) noexcept = default; Vnavbar &operator=(Vnavbar &) noexcept = default; void start() noexcept; void update() noexcept; void onDestroy() noexcept; void onEvent(const sf::Event &event) noexcept; float getValue() const noexcept; sf::FloatRect getGlobalBounds() const noexcept; void setCursorTexture(const sf::Texture &texture) noexcept; void setTexture(const sf::Texture &texture) noexcept; protected: float maxOffset() const noexcept; float minOffset() const noexcept; void setCursorColor(int x, int y) noexcept; Rectangle &_background; Rectangle &_cursor; sf::Color _color; float _clickPosY; bool _clicked; }; } // namespace sfs
28.647059
73
0.726899
LeandreBl
cebffae855066159637830ad06838055ad8e69cf
621
cpp
C++
cpp/ql/test/library-tests/ptr_to_member/segfault/segfault.cpp
vadi2/codeql
a806a4f08696d241ab295a286999251b56a6860c
[ "MIT" ]
4,036
2020-04-29T00:09:57.000Z
2022-03-31T14:16:38.000Z
cpp/ql/test/library-tests/ptr_to_member/segfault/segfault.cpp
vadi2/codeql
a806a4f08696d241ab295a286999251b56a6860c
[ "MIT" ]
2,970
2020-04-28T17:24:18.000Z
2022-03-31T22:40:46.000Z
cpp/ql/test/library-tests/ptr_to_member/segfault/segfault.cpp
ScriptBox99/github-codeql
2ecf0d3264db8fb4904b2056964da469372a235c
[ "MIT" ]
794
2020-04-29T00:28:25.000Z
2022-03-30T08:21:46.000Z
class F { public: }; typedef int (F::* FMethod) (int prefix); typedef int F::* FData; struct piecewise_construct_t { }; struct index { }; class tuple { }; template<unsigned long __i, typename... _Elements> void get(tuple __t); template<class T> struct S { T second; S(piecewise_construct_t, tuple __second) : S(__second, index()) { } template<unsigned long... uls> S(tuple t, index) : second(get<uls>(t)...) { } }; void f() { S<FMethod>* x; x = new S<FMethod>(piecewise_construct_t(), tuple()); } void g() { S<FData>* x; x = new S<FData>(piecewise_construct_t(), tuple()); }
14.44186
67
0.616747
vadi2
cec25dfc8d1e980d4b72f5d0dcc40ca37b3b6b65
828
hpp
C++
contrib/backends/nntpchan-daemon/include/nntpchan/staticfile_frontend.hpp
majestrate/nntpchan
f92f68c3cdce4b7ce6d4121ca4356b36ebcd933f
[ "MIT" ]
233
2015-08-06T02:51:52.000Z
2022-02-14T11:29:13.000Z
contrib/backends/nntpchan-daemon/include/nntpchan/staticfile_frontend.hpp
Revivify/nntpchan
0d555bb88a2298dae9aacf11348e34c52befa3d8
[ "MIT" ]
98
2015-09-19T22:29:00.000Z
2021-06-12T09:43:13.000Z
contrib/backends/nntpchan-daemon/include/nntpchan/staticfile_frontend.hpp
Revivify/nntpchan
0d555bb88a2298dae9aacf11348e34c52befa3d8
[ "MIT" ]
49
2015-08-06T02:51:55.000Z
2020-03-11T04:23:56.000Z
#ifndef NNTPCHAN_STATICFILE_FRONTEND_HPP #define NNTPCHAN_STATICFILE_FRONTEND_HPP #include "frontend.hpp" #include "message.hpp" #include "model.hpp" #include "template_engine.hpp" #include <experimental/filesystem> namespace nntpchan { namespace fs = std::experimental::filesystem; class StaticFileFrontend : public Frontend { public: StaticFileFrontend(TemplateEngine *tmpl, const std::string &templateDir, const std::string &outDir, uint32_t pages); virtual ~StaticFileFrontend(); virtual void ProcessNewMessage(const fs::path &fpath); virtual bool AcceptsNewsgroup(const std::string &newsgroup); virtual bool AcceptsMessage(const std::string &msgid); private: MessageDB_ptr m_MessageDB; TemplateEngine_ptr m_TemplateEngine; fs::path m_TemplateDir; fs::path m_OutDir; uint32_t m_Pages; }; } #endif
23.657143
118
0.786232
majestrate
cec715d578e6c654d9056e2632f77b75d882218c
2,932
cpp
C++
quicksort_vs_insertion_sort/main.cpp
saarioka/CPP-snippets
e8f07d76ee0b532f2c90b7360d666342ab7c8291
[ "Apache-2.0" ]
null
null
null
quicksort_vs_insertion_sort/main.cpp
saarioka/CPP-snippets
e8f07d76ee0b532f2c90b7360d666342ab7c8291
[ "Apache-2.0" ]
null
null
null
quicksort_vs_insertion_sort/main.cpp
saarioka/CPP-snippets
e8f07d76ee0b532f2c90b7360d666342ab7c8291
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <ctime> #include <algorithm> // random_shuffle #include <vector> #include <ctime> #include <stdio.h> #include <chrono> using namespace std; // quicksort template <class T> void quicksort(T &A, int a1, int y1){ if(a1 >= y1) return; int x = A[(a1+y1)/2]; int a = a1-1; int y = y1 + 1; int apu; while(a < y){ a++; y--; while(A[a] < x) a++; while(A[y] > x) y--; if(a < y){ apu = A[a]; A[a] = A[y]; A[y] = apu; } } if(a == a1) a++; quicksort(A,a1,a-1); quicksort(A,a,y1); } // insertion sort template <class T> void insertionsort(T &A, unsigned koko){ int apu, j; for(unsigned i = 1; i<koko; i++){ apu = A[i]; j = i-1; while(j >= 0 && (A[j] > apu)){ A[j+1] = A[j]; j--; } A[j+1] = apu; } } // tulosta sailio template <class T> void tulosta(T &A, unsigned koko){ for(unsigned i=0; i < koko; i++) cout << A[i] << " "; cout << "\n"; } int main() { const unsigned koko = 19; vector <int> A(koko); // sailion taytto srand (time(NULL)); for(unsigned i = 0; i<koko; i++){ A[i] = i+1; } random_shuffle(&A[0], &A[koko-1]); tulosta(A,20); cout << "\n"; // quicksort auto alku = chrono::high_resolution_clock::now(); for(unsigned i = 0; i<1000; i++){ srand (time(NULL)); random_shuffle(&A[0], &A[koko-1]); quicksort(A,0,koko-1); } auto loppu = chrono::high_resolution_clock::now(); auto kesto = chrono::duration_cast<std::chrono::nanoseconds>(loppu - alku).count(); tulosta(A,20); cout <<"Quick sort: koko " << koko << " ,kesto " << kesto << "ns.\n\n"; // sailion sekoitus random_shuffle(&A[0], &A[koko-1]); tulosta(A,20); cout << "\n"; // insertion sort alku = chrono::high_resolution_clock::now(); for(unsigned i = 0; i<1000; i++){ srand (time(NULL)); random_shuffle(&A[0], &A[koko-1]); insertionsort(A,koko); } loppu = chrono::high_resolution_clock::now(); kesto = chrono::duration_cast<std::chrono::nanoseconds>(loppu - alku).count(); tulosta(A, 20); cout <<"Insertion sort: koko " << koko << " ,kesto " << kesto << "ns.\n\n"; return 0; } /* * T. 59 * a) n^2 on pienillä n arvoilla pienempi, kuin 10*n*log n + 2*n * * * b) matemaattisesti: n on väh. 62 * ks. kuva * * kokeellisesti: n on n. 20 * ks. T. 60 * * * * T. 60 * * 4 2 16 17 11 10 13 1 5 6 15 3 14 12 19 8 7 9 18 20 * * 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 * Quick sort: koko 20 ,kesto 12000700ns. * * 12 4 10 19 17 6 7 5 16 11 1 14 3 9 2 18 15 8 13 20 * * 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 * Insertion sort: koko 20 ,kesto 12000100ns. * * Press <RETURN> to close this window... * * */
22.212121
87
0.518076
saarioka
cec809df4d3df0f7b134a7afaf19661f4c6c4dc2
49,510
cpp
C++
filters/Tracker3dFilter/src/Tracker3dFilter.cpp
nzjrs/opencv_old_libdc1394
b4ed48568cd774e8ec47336d59887261eb8d518c
[ "BSD-3-Clause" ]
1
2016-05-09T04:17:32.000Z
2016-05-09T04:17:32.000Z
filters/Tracker3dFilter/src/Tracker3dFilter.cpp
hcl3210/opencv
b34b1c3540716a3dadfd2b9e3bbc4253774c636d
[ "BSD-3-Clause" ]
null
null
null
filters/Tracker3dFilter/src/Tracker3dFilter.cpp
hcl3210/opencv
b34b1c3540716a3dadfd2b9e3bbc4253774c636d
[ "BSD-3-Clause" ]
null
null
null
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // Intel License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2002, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of Intel Corporation may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation 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. // //M*/ #pragma warning(disable:4786) #include <vector> #include <algorithm> #include <streams.h> #include "autorelease.h" #include <initguid.h> #include "Tracker3dFilter.h" #include "Tracker3dPropertyPage.h" #include "cvaux.h" #define ARRAY_SIZEOF(a) (sizeof(a)/sizeof((a)[0])) // locks a critical section, and unlocks it automatically // when the lock goes out of scope. Also allows explicit unlocking. class AutoLock { CCritSec *m_lock; public: AutoLock(CCritSec *lock) { m_lock = lock; m_lock->Lock(); }; ~AutoLock() { Unlock(); }; void Unlock() { if (m_lock) { m_lock->Unlock(); m_lock = NULL; } }; }; //#define TRACE #ifdef TRACE #include <stdarg.h> #include <stdio.h> void Trace(const char *fmt, ...) { char buf[200]; va_list args; va_start(args, fmt); vsprintf(buf, fmt, args); va_end(args); OutputDebugString(buf) ; } #endif // // CreateInstance // // Provide the way for COM to create a Tracker3dFilter object // CUnknown *Tracker3dFilter::CreateInstance(IUnknown *unk, HRESULT *phr) { try { *phr = NOERROR; return new Tracker3dFilter(NAME("3d Tracker"), unk); } catch(HRESULT hr) { *phr = hr; return NULL; } catch (...) { *phr = E_OUTOFMEMORY; return NULL; } } // CreateInstance // // Constructor // Tracker3dFilter::Tracker3dFilter(TCHAR *name, IUnknown *unk) : CBaseFilter(name, unk, &m_cs, CLSID_Tracker3dFilter) { m_num_streams = 0; m_streams = NULL; m_camera_configuration_loaded = false; m_pCameraInfo = NULL; m_tracker_clsid = GUID_NULL; m_calibrate_cameras = 0; m_camera_intrinsics = NULL; m_viewing_stream = 0; m_preferred_size = SIZE_Any; m_end_of_stream_count = 0; } Tracker3dFilter::~Tracker3dFilter() { for (int i = 0; i < m_callbacks.size(); i++) m_callbacks[i]->Release(); delete [] m_streams; delete [] m_pCameraInfo; delete [] m_camera_intrinsics; } // // NonDelegatingQueryInterface // STDMETHODIMP Tracker3dFilter::NonDelegatingQueryInterface(REFIID riid, void **ppv) { CheckPointer(ppv,E_POINTER); if (riid == IID_ITracker3dFilter) return GetInterface(static_cast<ITracker3dFilter *>(this), ppv); else if (riid == IID_ITracker3dInternal) return GetInterface(static_cast<ITracker3dInternal *>(this), ppv); else if (riid == IID_ISpecifyPropertyPages) return GetInterface(static_cast<ISpecifyPropertyPages *>(this), ppv); else if (riid == IID_IPersist) return GetInterface(static_cast<IPersist *>(static_cast<IPersistStream *>(this)), ppv); else if (riid == IID_IPersistStream) return GetInterface(static_cast<IPersistStream *>(this), ppv); else return CBaseFilter::NonDelegatingQueryInterface(riid, ppv); } int Tracker3dFilter::GetPinCount() { return 2 * m_num_streams; } CBasePin *Tracker3dFilter::GetPin(int n) { if (n > GetPinCount()) return NULL; if (n % 2) return m_streams[n/2].output_pin; else return m_streams[n/2].input_pin; } static HRESULT InitImageHeader(IplImage *image_header, const CMediaType *mt) { const GUID *subtype = mt->Subtype(); ASSERT(*mt->FormatType() == FORMAT_VideoInfo); VIDEOINFO *fmt = (VIDEOINFO *)mt->Format(); int channels; int origin; // We assume that RGB images are inverted and YUV images are not... if (*subtype == MEDIASUBTYPE_RGB24 || *subtype == MEDIASUBTYPE_RGB32) { channels = fmt->bmiHeader.biBitCount / 8; origin = IPL_ORIGIN_BL; } else if (*subtype == MEDIASUBTYPE_YVU9 || *subtype == MEDIASUBTYPE_YV12 || *subtype == MEDIASUBTYPE_IYUV) { // Note: these are planar images, which for our purposes we treat as // a single plane of Y8 and ignore the rest. channels = 1; origin = IPL_ORIGIN_TL; } else // Other trackers could support other formats, which should be handled here { return E_FAIL; } cvInitImageHeader(image_header, cvSize(fmt->bmiHeader.biWidth, fmt->bmiHeader.biHeight), IPL_DEPTH_8U, channels, origin, 4); return NOERROR; } HRESULT Tracker3dFilter::CheckMediaType(int pin, const CMediaType *mt) { Stream &stream = m_streams[pin]; if (stream.media_type.IsValid()) return *mt == stream.media_type ? S_OK : E_FAIL; if (*mt->Type() != MEDIATYPE_Video || *mt->FormatType() != FORMAT_VideoInfo) return E_FAIL; IplImage image_header; HRESULT hr = InitImageHeader(&image_header, mt); if (FAILED(hr)) return hr; if (m_preferred_size == SIZE_320x240 && (image_header.width != 320 || image_header.height != 240)) { return E_FAIL; } if (m_preferred_size == SIZE_640x480 && (image_header.width != 640 || image_header.height != 480)) { return E_FAIL; } if (stream.tracker != NULL) { hr = stream.tracker->CheckFormat(&image_header); if (FAILED(hr)) return hr; } return S_OK; } HRESULT Tracker3dFilter::SetMediaType(int pin, const CMediaType *mt) { Stream &stream = m_streams[pin]; if (stream.media_type.IsValid()) return *mt == stream.media_type ? S_OK : E_FAIL; HRESULT hr = CheckMediaType(pin, mt); if (FAILED(hr)) return hr; hr = InitImageHeader(&stream.image_header1, mt); if (FAILED(hr)) return hr; stream.image_header2 = stream.image_header1; if (stream.tracker != NULL) stream.tracker->SetFormat(&stream.image_header1); stream.media_type = *mt; return NOERROR; } HRESULT Tracker3dFilter::GetMediaType(int pin, int pos, CMediaType *mt) { if (pos < 0) return E_INVALIDARG; #define IYUV 0x56555949 static const struct { const GUID *subtype; FOURCC fourcc; int width, height, depth; } types[] = { { &MEDIASUBTYPE_IYUV, IYUV, 640, 480, 12 }, { &MEDIASUBTYPE_RGB24, BI_RGB, 640, 480, 24 }, { &MEDIASUBTYPE_RGB24, BI_RGB, 640, 480, 32 }, { &MEDIASUBTYPE_RGB32, BI_RGB, 640, 480, 32 }, { &MEDIASUBTYPE_IYUV, IYUV, 320, 240, 12 }, { &MEDIASUBTYPE_RGB24, BI_RGB, 320, 240, 24 }, { &MEDIASUBTYPE_RGB24, BI_RGB, 320, 240, 32 }, { &MEDIASUBTYPE_RGB32, BI_RGB, 320, 240, 32 }, }; // If our media type has been set, we respond only with that type; // otherwise, we respond with each of the types we know about. if (m_streams[pin].media_type.IsValid()) { if (pos == 0) { *mt = m_streams[pin].media_type; return S_OK; } } else if (pos < ARRAY_SIZEOF(types)) { const GUID *subtype = types[pos].subtype; FOURCC fourcc = types[pos].fourcc; int width = types[pos].width; int height = types[pos].height; int depth = types[pos].depth; VIDEOINFOHEADER fmt = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, 30*width*height*depth, 0, 333333, { sizeof(BITMAPINFOHEADER), width, height, 1, depth, fourcc, width*height*depth/8, 0, 0, 0, 0 } }; mt->SetType(&MEDIATYPE_Video); mt->SetTemporalCompression(false); mt->SetSubtype(subtype); mt->SetSampleSize(width*height*depth/8); mt->SetFormatType(&FORMAT_VideoInfo); mt->SetFormat((BYTE *)&fmt, sizeof(fmt)); return S_OK; } return VFW_S_NO_MORE_ITEMS; } STDMETHODIMP Tracker3dFilter::Run(REFERENCE_TIME t) { if (!m_camera_configuration_loaded && m_calibrate_cameras == 0) LoadCameraConfiguration(); return CBaseFilter::Run(t); } STDMETHODIMP Tracker3dFilter::Pause() { return CBaseFilter::Pause(); } STDMETHODIMP Tracker3dFilter::Stop() { AutoLock lock1(&m_cs); AutoLock lock2(&m_recv_cs); HRESULT hr = CBaseFilter::Stop(); if (FAILED(hr)) return hr; for (int i = 0; i < m_num_streams; i++) Flush(i); m_end_of_stream_count = 0; return NOERROR; } HRESULT Tracker3dFilter::Flush(int pin) { Stream::SampleQueue &q = m_streams[pin].queue; while (!q.empty()) q.pop_front(); return NOERROR; } Tracker3dFilter::Stream::Stream() : input_pin(NULL), output_pin(NULL), tracker(NULL), discarded_frames(0), total_frames(0) { } Tracker3dFilter::Stream::~Stream() { SAFE_RELEASE(input_pin); SAFE_RELEASE(output_pin); SAFE_RELEASE(tracker); } void Tracker3dFilter::Stream::operator =(Stream &s) { SAFE_RELEASE(input_pin); SAFE_RELEASE(output_pin); SAFE_RELEASE(tracker); input_pin = s.input_pin; s.input_pin = NULL; output_pin = s.output_pin; s.output_pin = NULL; tracker = s.tracker; s.tracker = NULL; image_header1 = image_header2 = s.image_header1; media_type = s.media_type; } inline Tracker3dFilter::Stream::Sample::Sample(IMediaSample *s, const ITracker::TrackingInfo &t) : sample(s), tracking_info(t) { sample->AddRef(); sample->GetTime(&ts, &te); sample->GetPointer(&data); } inline Tracker3dFilter::Stream::Sample::Sample(const Sample &s) : sample(s.sample), ts(s.ts), te(s.te), data(s.data), tracking_info(s.tracking_info) { sample->AddRef(); } inline void Tracker3dFilter::Stream::Sample::operator=(const Sample &s) { sample->Release(); sample = s.sample; ts = s.ts; te = s.te; data = s.data; tracking_info = s.tracking_info; sample->AddRef(); } inline Tracker3dFilter::Stream::Sample::~Sample() { sample->Release(); } //----------------------- // This is an attempt to match the frames up across the streams which are connected to the tracker. // The goal is to minimize the time differences between the frames in one set. This is necessary since // there is no available syncronization mechanism for the independant USB cameras or other video sources. //----------------------- bool Tracker3dFilter::QueuesReady() { int i; REFERENCE_TIME greatest = 0; REFERENCE_TIME least = 0; for (i = 0; i < m_num_streams; i++) { Stream::SampleQueue &q = m_streams[i].queue; if (q.empty()) return false; REFERENCE_TIME ts = q.front().ts; if (ts > greatest) greatest = ts; if (ts < least || least == 0) least = ts; } // If the difference between the greatest timestamp and the least is less than // the specified difference (1/60 sec or 1/2 nominal frame time), all queues // are ready. #define MAX_DIFF (10000000/60) if (greatest - least <= MAX_DIFF) return true; // Otherwise, check in each queue whether the 'greatest' frame is a closer time // match to the second frame in the queue than to the first frame in the queue. // If so, discard the first frame in the queue. // This algorithm requires a second frame in each queue, so it introduces one // full frame delay. for (i = 0; i < m_num_streams; i++) { Stream::SampleQueue &q = m_streams[i].queue; while (q.size() > 1 && abs(q.begin()->ts - greatest) > abs((q.begin() + 1)->ts - greatest)) { m_streams[i].discarded_frames++; #ifdef TRACE Trace("Discard: %*s %5lu\n", 6*i, "", (unsigned long)q.front().ts/10000); #endif q.pop_front(); } if (q.size() > 1) continue; if (abs(greatest - q.front().ts) <= MAX_DIFF) continue; return false; } return true; } //----------------------- // Performs the frame to frame work... //----------------------- HRESULT Tracker3dFilter::Receive(int pin, IMediaSample *sample) { int i; Stream &stream = m_streams[pin]; ITracker::TrackingInfo tracking_info; if (stream.tracker != NULL && m_calibrate_cameras == 0) { unsigned char *data; sample->GetPointer(&data); stream.image_header1.imageData = (char *)data; try { stream.tracker->Process(&stream.image_header1); stream.tracker->GetTrackedObjects(tracking_info); } catch (...) { } stream.image_header1.imageData = NULL; } AutoLock lock(&m_recv_cs); stream.queue.push_back(Stream::Sample(sample, tracking_info)); #ifdef TRACE Trace("Receive(%d):%*s %5lu\n", pin, 6*pin, "", (unsigned long)stream.queue.back().ts/10000); #endif if (!QueuesReady()) return NOERROR; #ifdef TRACE char buf[100] = "Process: "; char *p = buf + strlen(buf); REFERENCE_TIME greatest = 0; REFERENCE_TIME least = 0; for (i = 0; i < m_num_streams; i++) { REFERENCE_TIME ts = m_streams[i].queue.front().ts; if (ts > greatest) greatest = ts; if (ts < least || least == 0) least = ts; sprintf(p, " %5lu", (unsigned long)ts/10000); p += strlen(p); } sprintf(p, " %4ld", (long)((greatest - least)/10000)); p += strlen(p); static unsigned long processed_frames; sprintf(p, "; %4lu", ++processed_frames); p += strlen(p); for (i = 0; i < m_num_streams; i++) { Stream &s = m_streams[i]; sprintf(p, " %4lu (%2lu%%)", s.discarded_frames, (100*s.discarded_frames/(processed_frames+s.discarded_frames))); p += strlen(p); } Trace("%s\n", buf); #endif if (m_calibrate_cameras != 0) { std::vector<IplImage *> samples(m_num_streams); for (i = 0; i < m_num_streams; i++) { m_streams[i].image_header2.imageData = (char *)m_streams[i].queue.front().data; samples[i] = &m_streams[i].image_header2; } // // This is the second most significant call in the filter, this is how the relative locations of // all of the cameras are determined. This information is vital to the later process of determining // the location of the targets in 3D from the set of 2D results provided by the trackers. // if (cv3dTrackerCalibrateCameras(m_num_streams, m_camera_intrinsics, m_etalon_size, m_square_size, &samples[0], m_pCameraInfo)) { if (m_calibrate_cameras == 1) { m_calibrate_cameras = 0; SaveCameraConfiguration(); } } } else { int num_objects = 0; for (i = 0; i < m_num_streams; i++) { int n = m_streams[i].queue.front().tracking_info.size(); if (n > num_objects) num_objects = n; } if (num_objects != 0) { std::vector<Cv3dTracker2dTrackedObject> tracking_info(m_num_streams * num_objects, cv3dTracker2dTrackedObject(-1, CvPoint())); for (i = 0; i < m_num_streams; i++) { ITracker::TrackingInfo &t = m_streams[i].queue.front().tracking_info; if (m_streams[i].image_header2.origin == IPL_ORIGIN_BL) for (int j = 0; j < t.size(); j++) t[j].p.y = m_streams[i].image_header2.height - 1 - t[j].p.y; for (int j = 0; j < t.size(); j++) tracking_info[i*num_objects+j] = t[j]; } m_tracked_objects.resize(num_objects); // // This is it. The whole point of this is this call. // For each matched set of results from the trackers this call will compute the 3D coordinates of the targets. // int n = cv3dTrackerLocateObjects(m_num_streams, num_objects, m_pCameraInfo, &tracking_info[0], &m_tracked_objects[0]); m_tracked_objects.resize(n); } else m_tracked_objects.clear(); } // Copy viewing sample out of queue before releasing lock. Stream::Sample viewing_sample = m_streams[m_viewing_stream].queue.front(); for (i = 0; i < m_num_streams; i++) { m_streams[i].output_pin->Deliver(m_streams[i].queue.front().sample); m_streams[i].queue.pop_front(); } lock.Unlock(); for (i = 0; i < m_callbacks.size(); i++) m_callbacks[i]->Callback(m_tracked_objects, viewing_sample.data, (IUnknown *)viewing_sample.sample); return NOERROR; } HRESULT Tracker3dFilter::EndOfStream(int pin) { AutoLock lock(&m_recv_cs); m_end_of_stream_count++; if (m_end_of_stream_count == m_num_streams) { for (int i = 0; i < m_num_streams; i++) { Flush(i); m_streams[i].output_pin->DeliverEndOfStream(); } } return NOERROR; } void Tracker3dFilter::SetNumberOfStreams(int num_streams) { if (num_streams == m_num_streams) return; delete [] m_camera_intrinsics; m_camera_intrinsics = NULL; Stream *streams = NULL; Cv3dTrackerCameraInfo *camera_info = NULL; if (num_streams > 0) { int i; camera_info = new Cv3dTrackerCameraInfo [ num_streams ]; streams = new Stream [ num_streams ]; for (i = 0; i < num_streams; i++) { if (i < m_num_streams) { streams[i] = m_streams[i]; camera_info[i] = m_pCameraInfo[i]; } else { streams[i].input_pin = new Tracker3dInputPin(i, this, &m_cs); streams[i].output_pin = new Tracker3dOutputPin(i, this, &m_cs); if (m_tracker_clsid != GUID_NULL) { // If CoCreateInstance fails, m_streams[i].tracker is left as NULL. CoCreateInstance(m_tracker_clsid, NULL, CLSCTX_INPROC_SERVER, IID_ITracker, (void **)&streams[i].tracker); } camera_info[i].valid = false; } } } delete [] m_streams; m_streams = streams; delete [] m_pCameraInfo; m_pCameraInfo = camera_info; m_num_streams = num_streams; IncrementPinVersion(); } // // GetPages // // Returns the clsid's of the property pages we support // STDMETHODIMP Tracker3dFilter::GetPages(CAUUID *pPages) { std::vector<GUID> pages; pages.push_back(CLSID_Tracker3dPropertyPage); // In addition to our property page, return a separate property page for each type of tracker. // Normally all the trackers will be the same, so only one property page will be returned, // but we call each tracker to see if it wants a different property page. // It is up to each property page to call GetTrackers and connect to all the trackers // that are of the appropriate type. if (m_streams != NULL) { for (int i = 0; i < m_num_streams; i++) { GUID page; if (m_streams[i].tracker != NULL && SUCCEEDED(m_streams[i].tracker->GetPropertyPage(&page))) { if (std::find(pages.begin(), pages.end(), page) == pages.end()) pages.push_back(page); } } } // Now that we've determined how many pages we need, allocate the memory // and fill it in. pPages->cElems = pages.size(); pPages->pElems = (GUID *) CoTaskMemAlloc(pages.size() * sizeof(GUID)); if (pPages->pElems == NULL) return E_OUTOFMEMORY; for (int i = 0; i < pages.size(); i++) pPages->pElems[i] = pages[i]; return NOERROR; } // IPersistStream STDMETHODIMP Tracker3dFilter::GetClassID(CLSID *clsid) { *clsid = CLSID_Tracker3dFilter; return NOERROR; } STDMETHODIMP Tracker3dFilter::IsDirty() { return S_OK; } static const int PERSIST_STREAM_VERSION0 = 0; static const int PERSIST_STREAM_VERSION0_SIZE = 3; static const int PERSIST_STREAM_VERSION1 = 1; static const int PERSIST_STREAM_VERSION1_SIZE = 4; static const int PERSIST_STREAM_VERSION2 = 2; static const int PERSIST_STREAM_VERSION2_SIZE = PERSIST_STREAM_VERSION1_SIZE; static const int PERSIST_STREAM_VERSION3 = 3; static const int PERSIST_STREAM_VERSION3_SIZE = 3 + sizeof(GUID); STDMETHODIMP Tracker3dFilter::Load(IStream *stream) { unsigned long nread; unsigned char buf[3]; HRESULT hr = stream->Read(buf, 3, &nread); if (FAILED(hr)) return hr; if (nread != 3) return E_FAIL; int num_streams; if (buf[0] == PERSIST_STREAM_VERSION0 && buf[1] == PERSIST_STREAM_VERSION0_SIZE) { num_streams = buf[2]; } else if (buf[0] == PERSIST_STREAM_VERSION1 && buf[1] == PERSIST_STREAM_VERSION1_SIZE) { num_streams = buf[2]; } else if (buf[0] == PERSIST_STREAM_VERSION2 && buf[1] == PERSIST_STREAM_VERSION2_SIZE) { num_streams = buf[2] & 0x3f; m_preferred_size = (InputSize)((buf[2] >> 6) & 0x03); } else if (buf[0] == PERSIST_STREAM_VERSION3) { num_streams = buf[2] & 0x3f; m_preferred_size = (InputSize)((buf[2] >> 6) & 0x03); if (buf[1] == PERSIST_STREAM_VERSION3_SIZE) { GUID guid; hr = stream->Read(&guid, sizeof(GUID), &nread); if (FAILED(hr)) return hr; if (nread != sizeof(GUID)) return E_FAIL; m_tracker_clsid = guid; } } else { return E_FAIL; } if (buf[0] == PERSIST_STREAM_VERSION1 || buf[0] == PERSIST_STREAM_VERSION2) { unsigned char lib_name_len; hr = stream->Read(&lib_name_len, 1, &nread); if (FAILED(hr)) return hr; if (nread != 1) return E_FAIL; if (lib_name_len > 0) { char lib_name[256]; hr = stream->Read(lib_name, lib_name_len, &nread); // We don't support this format any more; ignore the // default tracker dll name, but allow the graph // to load. //if (SUCCEEDED(hr) && nread == lib_name_len) //{ // lib_name[lib_name_len] = '\0'; // SetDefaultTrackerDLL(lib_name); //} } } SetTrackers(num_streams, NULL); return NOERROR; } STDMETHODIMP Tracker3dFilter::Save(IStream *stream, BOOL clear_dirty) { HRESULT hr; unsigned long dummy; unsigned char buf[PERSIST_STREAM_VERSION3_SIZE] = { PERSIST_STREAM_VERSION3, PERSIST_STREAM_VERSION3_SIZE, (unsigned char)((m_num_streams & 0x7f) | (m_preferred_size << 6)) }; if (m_tracker_clsid != GUID_NULL) memcpy(buf+3, &m_tracker_clsid, sizeof(GUID)); else buf[1] = 3; hr = stream->Write(&buf, buf[1], &dummy); if (FAILED(hr)) return hr; return NOERROR; } STDMETHODIMP Tracker3dFilter::GetSizeMax(ULARGE_INTEGER *size) { size->QuadPart = PERSIST_STREAM_VERSION3_SIZE; return NOERROR; } // ITracker3dFilter STDMETHODIMP Tracker3dFilter::GetNumberOfCameras(int &num_streams) { num_streams = m_num_streams; return NOERROR; } class AutoClose { FILE ** m_ppfile; public: AutoClose(FILE ** ppfile) : m_ppfile(ppfile) { }; ~AutoClose() { if (*m_ppfile != NULL) { fclose(*m_ppfile); *m_ppfile = NULL; } }; }; #define AUTO_CLOSE(f) AutoClose AutoClose##f(&f) STDMETHODIMP Tracker3dFilter::LoadCameraConfiguration(const char *filename) { FILE *f = fopen(filename, "r"); AUTO_CLOSE(f); if (f == NULL) return E_FAIL; int num_streams; int r; r = fscanf(f, "%ld\n", &num_streams); if (r != 1 || num_streams <= 0) return E_FAIL; SetNumberOfStreams(num_streams); for (int c = 0; c < m_num_streams; c++) { Cv3dTrackerCameraInfo &camera = m_pCameraInfo[c]; char camera_name[80]; if (fscanf(f, "%[^:]:", camera_name) != 1) return E_FAIL; if (fscanf(f, "%g, %g;", &camera.principal_point.x, &camera.principal_point.y) != 2) return E_FAIL; for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) if (fscanf(f, "%g", &camera.mat[i][j]) != 1) return E_FAIL; //camera.camera_name = camera_name; camera.valid = true; } m_camera_configuration_loaded = true; return NOERROR; } STDMETHODIMP Tracker3dFilter::SaveCameraConfiguration(const char *filename) { if (m_pCameraInfo == NULL) return E_FAIL; FILE *f = fopen(filename, "w"); if (f == NULL) return E_FAIL; fprintf(f, "%lu\n", m_num_streams); for (int c = 0; c < m_num_streams; c++) { Cv3dTrackerCameraInfo &camera = m_pCameraInfo[c]; fprintf(f, "Camera %d: ", c); //fprintf(f, "%s: ", camera.camera_name.c_str()); fprintf(f, " %g, %g;", camera.principal_point.x, camera.principal_point.y); for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) fprintf(f, " %g", camera.mat[i][j]); fprintf(f, "\n"); } fclose(f); return NOERROR; } static std::string subst(std::string s, char i, char o) { std::string::size_type pos = 0; while ((pos = s.find(i, pos)) != std::string::npos) s.replace(pos, 1, 1, o); return s; } std::string Tracker3dFilter::CalibrationName(int i) { std::string camera_name; GetCameraName(i, camera_name); return subst(camera_name, '\\', '#'); } class AutoCloseKey { HKEY *m_pkey; public: AutoCloseKey(HKEY *pkey) : m_pkey(pkey) { }; ~AutoCloseKey() { if (*m_pkey != 0) { RegCloseKey(*m_pkey); *m_pkey = 0; } }; }; #define AUTO_CLOSE_KEY(f) AutoCloseKey AutoCloseKey##f(&f) static const char key_name[] = "Software\\Intel\\VAI\\3d Tracker\\"; //------------------ // Once camera extrinsic parameters are determined they are stored in the registry in the key // Software\\Intel\\VAI\\3d Tracker\\ // Read them back from here when the app starts. //------------------ void Tracker3dFilter::LoadCameraConfiguration() { LONG r; HKEY key = 0; AUTO_CLOSE_KEY(key); r = RegOpenKeyEx(HKEY_LOCAL_MACHINE, key_name, 0,KEY_READ, &key); if (r != ERROR_SUCCESS) return; int valid_count = 0; for (int c = 0; c < m_num_streams; c++) { Cv3dTrackerCameraInfo &camera = m_pCameraInfo[c]; char buf[18*15]; DWORD size = sizeof(buf); r = RegQueryValueEx(key, CalibrationName(c).c_str(), 0, NULL, (BYTE *)buf, &size); if (r != ERROR_SUCCESS) continue; if (sscanf(buf, "%g %g; %g %g %g %g, %g %g %g %g, %g %g %g %g, %g %g %g %g", &camera.principal_point.x, &camera.principal_point.y, &camera.mat[0][0], &camera.mat[0][1], &camera.mat[0][2], &camera.mat[0][3], &camera.mat[1][0], &camera.mat[1][1], &camera.mat[1][2], &camera.mat[1][3], &camera.mat[2][0], &camera.mat[2][1], &camera.mat[2][2], &camera.mat[2][3], &camera.mat[3][0], &camera.mat[3][1], &camera.mat[3][2], &camera.mat[3][3]) != 18) continue; camera.valid = true; valid_count++; } m_camera_configuration_loaded = (valid_count == m_num_streams); } void Tracker3dFilter::SaveCameraConfiguration() { LONG r; HKEY key = 0; AUTO_CLOSE_KEY(key); r = RegCreateKeyEx(HKEY_LOCAL_MACHINE, key_name, 0, NULL, 0, KEY_WRITE, NULL, &key, NULL); if (r != ERROR_SUCCESS) return; for (int c = 0; c < m_num_streams; c++) { Cv3dTrackerCameraInfo &camera = m_pCameraInfo[c]; char buf[18*15]; char *p = buf; int len = sprintf(p, "%g %g;", camera.principal_point.x, camera.principal_point.y); p += len; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { len = sprintf(p, " %g", camera.mat[i][j]); p += len; } *p++ = ','; } RegSetValueEx(key, CalibrationName(c).c_str(), 0, REG_SZ, (BYTE *)buf, p - buf + 1); } } STDMETHODIMP Tracker3dFilter::GetDefaultTracker(GUID &tracker_clsid) { tracker_clsid = m_tracker_clsid; return NOERROR; } STDMETHODIMP Tracker3dFilter::SetDefaultTracker(const GUID &tracker_clsid) { m_tracker_clsid = tracker_clsid; return NOERROR; } STDMETHODIMP Tracker3dFilter::SetTrackers(int num_streams, ITracker * const *trackers) { SetNumberOfStreams(num_streams); if (trackers == NULL) { for (int i = 0; i < m_num_streams; i++) { SAFE_RELEASE(m_streams[i].tracker); if (m_tracker_clsid != GUID_NULL) { // If CoCreateInstance fails, m_streams[i].tracker is left as NULL. CoCreateInstance(m_tracker_clsid, NULL, CLSCTX_INPROC_SERVER, IID_ITracker, (void **)&m_streams[i].tracker); if (m_streams[i].media_type.IsValid()) m_streams[i].tracker->SetFormat(&m_streams[i].image_header1); } } } else { for (int i = 0; i < m_num_streams; i++) { SAFE_RELEASE(m_streams[i].tracker); // Store and addref new tracker m_streams[i].tracker = trackers[i]; if (m_streams[i].tracker != NULL) { m_streams[i].tracker->AddRef(); if (m_streams[i].media_type.IsValid()) m_streams[i].tracker->SetFormat(&m_streams[i].image_header1); } } } return NOERROR; } STDMETHODIMP Tracker3dFilter::GetTrackers(std::vector<ITracker *> &trackers) { trackers.resize(m_num_streams); for (int i = 0; i < m_num_streams; i++) { trackers[i] = m_streams[i].tracker; if (trackers[i] != NULL) trackers[i]->AddRef(); } return NOERROR; } //---------------------- // Read the intrinsics information for all of the from a list of files. // The following is an example of the format that the file is reading. // The top left 2 diagonal elements of the matrix are the horizontal and // vertical focal lengths and the top 2 elements in the last column // indicate the image center coordinates, x in the top row, y in the second. // // The Distortion parameters indicate the radial and barrel distortion of the lens. // // All of these results are further discussed in the documentation concerning // the CalibFilter. //---------------------- /* Camera Matrix: M[0.0]= 401.3238525M[0.1]= 0.0000000M[0.2]= 135.9540710 M[1.0]= 0.0000000M[1.1]= 403.9630737M[1.2]= 116.6698456 M[2.0]= 0.0000000M[2.1]= 0.0000000M[2.2]= 1.0000000 Distortion: D[0]=-0.011825 D[1]=0.241698 D[2]=0.001189 D[3]=0.003923 */ HRESULT Tracker3dFilter::ReadCameraIntrinsics(const char *filenames[]) { // read camera intrinsics for all cameras: focal length[2], principal_point.x&y, distortion[4] if (m_camera_intrinsics == NULL) m_camera_intrinsics = new Cv3dTrackerCameraIntrinsics [ m_num_streams ]; for (int c = 0; c < m_num_streams; c++) { Cv3dTrackerCameraIntrinsics &camera = m_camera_intrinsics[c]; FILE *file = fopen(filenames[c], "r"); AUTO_CLOSE(file); if (file == NULL) return E_FAIL; #define BUF_SIZE 500 char buffer[BUF_SIZE+1]; int sz = fread( buffer, 1, BUF_SIZE, file ); buffer[sz] = '\0'; int i, j, k; float camera_matrix[3][3]; char* ptr = buffer; /* read matrix */ for( k = 0; k < 9; k++ ) { ptr = strstr( ptr, "M[" ); if( ptr ) { int s = 0; ptr += 2; if( sscanf( ptr, "%d%*[.,]%d%n", &i, &j, &s ) == 2 && i == k/3 && j == k%3 ) { ptr += s; ptr = strstr( ptr, "=" ); if( ptr ) { s = 0; ptr++; if( sscanf( ptr, "%f%n", &camera_matrix[i][j], &s ) == 1 ) { ptr += s; continue; } } } } return E_FAIL; } camera.focal_length[0] = camera_matrix[0][0]; camera.focal_length[1] = camera_matrix[1][1]; camera.principal_point.x = camera_matrix[0][2]; camera.principal_point.y = camera_matrix[1][2]; /* read distortion */ for( k = 0; k < 4; k++ ) { ptr = strstr( ptr, "D[" ); if( ptr ) { int s = 0; ptr += 2; if( sscanf( ptr, "%d%n", &i, &s ) == 1 && i == k ) { ptr += s; ptr = strstr( ptr, "=" ); if( ptr ) { s = 0; ptr++; if( sscanf( ptr, "%f%n", &camera.distortion[k], &s ) == 1 ) { ptr += s; continue; } } } } return E_FAIL; } } return NOERROR; } //--------------------- // Initiate the camera calibration process. Actual calibration call is made in Receive() //--------------------- STDMETHODIMP Tracker3dFilter::CalibrateCameras(int checkerboard_width, int checkerboard_height, const char *camera_intrinsics_filenames[], float square_size, bool continuous) { AutoLock lock(&m_recv_cs); HRESULT hr = ReadCameraIntrinsics(camera_intrinsics_filenames); if (FAILED(hr)) return hr; m_tracked_objects.clear(); m_etalon_size = cvSize(checkerboard_width-1, checkerboard_height-1); m_calibrate_cameras = continuous ? 2 : 1; m_square_size = square_size; for (int c = 0; c < m_num_streams; c++) m_pCameraInfo[c].valid = false; return NOERROR; } STDMETHODIMP Tracker3dFilter::GetTrackedObjects(std::vector<Cv3dTrackerTrackedObject> &tracked_objects) { AutoLock lock(&m_recv_cs); tracked_objects = m_tracked_objects; return NOERROR; } STDMETHODIMP Tracker3dFilter::AddCallback(ITracker3dCallback *new_callback) { if (new_callback == NULL) return E_INVALIDARG; new_callback->AddRef(); m_callbacks.push_back(new_callback); return NOERROR; } STDMETHODIMP Tracker3dFilter::RemoveCallback(ITracker3dCallback *callback) { if (callback == NULL) return E_INVALIDARG; std::vector<ITracker3dCallback *>::iterator i = std::find(m_callbacks.begin(), m_callbacks.end(), callback); if (i != m_callbacks.end()) { m_callbacks.erase(i); callback->Release(); } return NOERROR; } STDMETHODIMP Tracker3dFilter::SetViewingStream(int stream) { if (stream < 0 || stream >= m_num_streams) return E_INVALIDARG; m_viewing_stream = stream; return NOERROR; } STDMETHODIMP Tracker3dFilter::GetViewingStream(int &stream) { stream = m_viewing_stream; return NOERROR; } //-------------------- // Begin at input pin 'i' and work upstream in the graph to find the source filter. Return // the name of the source in the string name. //-------------------- STDMETHODIMP Tracker3dFilter::GetCameraName(int i, std::string &name) { // Set up a default, in case we can't generate something better // (This could be improved.) name = (char)('0'+i); // Work upstream from input pin 'i' to find the capture filter HRESULT hr; IPin *input_pin = m_streams[i].input_pin; input_pin->AddRef(); AUTO_RELEASE(input_pin); IBaseFilter *capture_filter = NULL; AUTO_RELEASE(capture_filter); while (1) { IPin *output_pin = NULL; AUTO_RELEASE(output_pin); hr = input_pin->ConnectedTo(&output_pin); if (FAILED(hr)) return hr; PIN_INFO pin_info; hr = output_pin->QueryPinInfo(&pin_info); if (FAILED(hr)) return hr; IBaseFilter *filter = pin_info.pFilter; AUTO_RELEASE(filter); FILTER_INFO filter_info; hr = filter->QueryFilterInfo(&filter_info); filter_info.pGraph->Release(); filter_info.pGraph = NULL; IEnumPins *e = NULL; AUTO_RELEASE(e); hr = filter->EnumPins(&e); if (FAILED(hr)) return hr; input_pin->Release(); input_pin = NULL; while (e->Next(1, &input_pin, NULL) == S_OK) { hr = input_pin->QueryPinInfo(&pin_info); if (FAILED(hr)) return hr; pin_info.pFilter->Release(); if (pin_info.dir == PINDIR_INPUT) break; input_pin->Release(); input_pin = NULL; } if (input_pin == NULL) // No input pin found; this must be the capture filter { capture_filter = filter; capture_filter->AddRef(); break; } } // Use IPersistStream to save the filter data, which includes a text representation of the device id. IPersistStream *persist_stream = NULL; AUTO_RELEASE(persist_stream); hr = capture_filter->QueryInterface(IID_IPersistStream, (void **)&persist_stream); if (FAILED(hr)) return hr; HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, 0); if (mem == 0) return E_OUTOFMEMORY; IStream *stream = NULL; AUTO_RELEASE(stream); CreateStreamOnHGlobal(mem, true, &stream); hr = persist_stream->Save(stream, false); if (FAILED(hr)) return hr; STATSTG stat; hr = stream->Stat(&stat, STATFLAG_NONAME); if (FAILED(hr)) return hr; int size = stat.cbSize.LowPart; wchar_t *p = (wchar_t *)GlobalLock(mem); wchar_t *end = p + size; wchar_t *id = NULL; while (p < end-8) { if (wcsncmp(p, L"@device:", 8) == 0) { id = p; break; } p++; } if (id == NULL)// Didn't find something we recognize return E_FAIL; p = id + 8; while (p < end && *p != L'\0') p++; int len = p - id; name.resize(len); for (i = 0; i < len; i++) name[i] = (char)id[i]; return NOERROR; } STDMETHODIMP Tracker3dFilter::SetPreferredInputSize(InputSize size) { m_preferred_size = size; return NOERROR; } STDMETHODIMP Tracker3dFilter::GetPreferredInputSize(InputSize &size) { size = m_preferred_size; return NOERROR; } STDMETHODIMP Tracker3dFilter::IsConnected(bool &any_connected, bool &all_connected) { any_connected = false; all_connected = true; for (int i = 0; i < m_num_streams; i++) { if (m_streams[i].input_pin->IsConnected()) any_connected = true; else all_connected = false; if (m_streams[i].output_pin->IsConnected()) any_connected = true; else all_connected = false; } return NOERROR; } // ITracker3dInternal STDMETHODIMP Tracker3dFilter::GetCameraInfo(std::vector<Cv3dTrackerCameraInfo> &info) { info.resize(m_num_streams); for (int i = 0; i < m_num_streams; i++) info[i] = m_pCameraInfo[i]; return NOERROR; } // Implementation of pins for Tracker 3d Filter static const wchar_t *PinName(PIN_DIRECTION pin_dir, int pin_number) { static wchar_t buf[14]; swprintf(buf, L"%s %d", pin_dir == PINDIR_INPUT ? L"Input" : L"Output", pin_number); return buf; } Tracker3dInputPin::Tracker3dInputPin(int pin_number, Tracker3dFilter *filter, CCritSec *cs) : CBaseInputPin("Tracker3dInputPin", filter, cs, NULL, PinName(PINDIR_INPUT, pin_number)), m_pin_number(pin_number), m_pFilter(filter), m_refcnt(1) { } Tracker3dInputPin::~Tracker3dInputPin() { } STDMETHODIMP_(ULONG) Tracker3dInputPin::NonDelegatingAddRef() { InterlockedIncrement(&m_refcnt); return CBaseInputPin::NonDelegatingAddRef(); } STDMETHODIMP_(ULONG) Tracker3dInputPin::NonDelegatingRelease() { if (InterlockedDecrement(&m_refcnt) == 0) { delete this; return 0; } return CBaseInputPin::NonDelegatingRelease(); } STDMETHODIMP Tracker3dInputPin::GetAllocator(IMemAllocator **allocator) { if (m_pAllocator == NULL) return VFW_E_NO_ALLOCATOR; *allocator = m_pAllocator; (*allocator)->AddRef(); return NOERROR; } STDMETHODIMP Tracker3dInputPin::NotifyAllocator(IMemAllocator *allocator, BOOL read_only) { ALLOCATOR_PROPERTIES props, actual; allocator->GetProperties(&props); props.cBuffers = 5; allocator->SetProperties(&props, &actual); return CBaseInputPin::NotifyAllocator(allocator, read_only); } HRESULT Tracker3dInputPin::CheckMediaType(const CMediaType *mt) { return m_pFilter->CheckMediaType(m_pin_number, mt); } HRESULT Tracker3dInputPin::SetMediaType(const CMediaType *mt) { CBaseInputPin::SetMediaType(mt); return m_pFilter->SetMediaType(m_pin_number, mt); } HRESULT Tracker3dInputPin::GetMediaType(int pos, CMediaType *mt) { return m_pFilter->GetMediaType(m_pin_number, pos, mt); } HRESULT Tracker3dInputPin::Receive(IMediaSample *sample) { HRESULT hr = CBaseInputPin::Receive(sample); if (FAILED(hr)) return hr; return m_pFilter->Receive(m_pin_number, sample); } HRESULT Tracker3dInputPin::EndOfStream() { m_pFilter->EndOfStream(m_pin_number); return NOERROR; } HRESULT Tracker3dInputPin::BeginFlush() { HRESULT hr = CBaseInputPin::BeginFlush(); if (FAILED(hr)) return hr; m_pFilter->Flush(m_pin_number); return static_cast<Tracker3dOutputPin *>(m_pFilter->GetPin(m_pin_number*2+1))->DeliverBeginFlush(); } HRESULT Tracker3dInputPin::EndFlush() { HRESULT hr = static_cast<Tracker3dOutputPin *>(m_pFilter->GetPin(m_pin_number*2+1))->DeliverEndFlush(); if (FAILED(hr)) return hr; return CBaseInputPin::EndFlush(); } HRESULT Tracker3dInputPin::NewSegment(REFERENCE_TIME start, REFERENCE_TIME stop, double rate) { CBasePin::NewSegment(start, stop, rate); return static_cast<Tracker3dOutputPin *>(m_pFilter->GetPin(m_pin_number*2+1))->DeliverNewSegment(start, stop, rate); } Tracker3dOutputPin::Tracker3dOutputPin(int pin_number, Tracker3dFilter *filter, CCritSec *cs) : CBaseOutputPin("Tracker3dOutputPin", filter, cs, NULL, PinName(PINDIR_OUTPUT, pin_number)), m_pin_number(pin_number), m_pFilter(filter), m_refcnt(1) { } Tracker3dOutputPin::~Tracker3dOutputPin() { } STDMETHODIMP_(ULONG) Tracker3dOutputPin::NonDelegatingAddRef() { InterlockedIncrement(&m_refcnt); return CBaseOutputPin::NonDelegatingAddRef(); } STDMETHODIMP_(ULONG) Tracker3dOutputPin::NonDelegatingRelease() { if (InterlockedDecrement(&m_refcnt) == 0) { delete this; return 0; } return CBaseOutputPin::NonDelegatingRelease(); } HRESULT Tracker3dOutputPin::CheckMediaType(const CMediaType *mt) { return m_pFilter->CheckMediaType(m_pin_number, mt); } HRESULT Tracker3dOutputPin::SetMediaType(const CMediaType *mt) { CBaseOutputPin::SetMediaType(mt); return m_pFilter->SetMediaType(m_pin_number, mt); } HRESULT Tracker3dOutputPin::GetMediaType(int pos, CMediaType *mt) { return m_pFilter->GetMediaType(m_pin_number, pos, mt); } HRESULT Tracker3dOutputPin::DecideAllocator(IMemInputPin *pPin, IMemAllocator **ppAlloc) { *ppAlloc = NULL; Tracker3dInputPin *my_input_pin = static_cast<Tracker3dInputPin *>(m_pFilter->GetPin(m_pin_number*2)); IMemAllocator *alloc; HRESULT hr = my_input_pin->GetAllocator(&alloc); if (FAILED(hr)) return hr; // get downstream prop request ALLOCATOR_PROPERTIES props, request; alloc->GetProperties(&props); if (SUCCEEDED(pPin->GetAllocatorRequirements(&request))) { bool changed = false; if (request.cbAlign > props.cbAlign) props.cbAlign = request.cbAlign, changed = true; if (request.cBuffers > props.cBuffers) props.cBuffers = request.cBuffers, changed = true; if (request.cbBuffer > props.cbBuffer) props.cbBuffer = request.cbBuffer, changed = true; if (request.cbPrefix > props.cbPrefix) props.cbPrefix = request.cbPrefix, changed = true; if (changed) { ALLOCATOR_PROPERTIES actual; alloc->SetProperties(&props, &actual); } } hr = pPin->NotifyAllocator(alloc, my_input_pin->IsReadOnly()); if (FAILED(hr)) { alloc->Release(); return hr; } *ppAlloc = alloc; return NOERROR; } // Setup information const AMOVIESETUP_MEDIATYPE sudPinTypes = { &MEDIATYPE_Video, // Major type &MEDIASUBTYPE_NULL // Minor type }; const AMOVIESETUP_PIN sudpPins[] = { { L"Input", // Pins string name FALSE, // Is it rendered FALSE, // Is it an output TRUE, // Are we allowed none TRUE, // And allowed many &CLSID_NULL, // Connects to filter NULL, // Connects to pin 1, // Number of types &sudPinTypes // Pin information }, { L"Output", // Pins string name FALSE, // Is it rendered TRUE, // Is it an output TRUE, // Are we allowed none TRUE, // And allowed many &CLSID_NULL, // Connects to filter NULL, // Connects to pin 1, // Number of types &sudPinTypes // Pin information } }; const AMOVIESETUP_FILTER sudFilter = { &CLSID_Tracker3dFilter, // Filter CLSID L"3d Tracker", // String name MERIT_DO_NOT_USE, // Filter merit 2, // Number of pins sudpPins // Pin information }; // List of class IDs and creator functions for the class factory. This // provides the link between the OLE entry point in the DLL and an object // being created. The class factory will call the static CreateInstance CFactoryTemplate g_Templates[] = { { L"3d Tracker" , &CLSID_Tracker3dFilter , Tracker3dFilter::CreateInstance , NULL , &sudFilter } , { L"3d Tracker Property Page" , &CLSID_Tracker3dPropertyPage , Tracker3dPropertyPage::CreateInstance } }; int g_cTemplates = sizeof(g_Templates) / sizeof(g_Templates[0]); // // DllRegisterServer // // Handles sample registry and unregistry // STDAPI DllRegisterServer() { return AMovieDllRegisterServer2( TRUE ); } // DllRegisterServer // // DllUnregisterServer // STDAPI DllUnregisterServer() { return AMovieDllRegisterServer2( FALSE ); } // DllUnregisterServer
28.130682
130
0.594223
nzjrs
cecbf5d970405fb691fc28bfc30c0d42b0211690
13,051
hpp
C++
src/centurion/opengl.hpp
Creeperface01/centurion
e3b674c11849367a18c2d976ce94071108e1590d
[ "MIT" ]
14
2020-05-17T21:38:03.000Z
2020-11-21T00:16:25.000Z
src/centurion/opengl.hpp
Creeperface01/centurion
e3b674c11849367a18c2d976ce94071108e1590d
[ "MIT" ]
70
2020-04-26T17:08:52.000Z
2020-11-21T17:34:03.000Z
src/centurion/opengl.hpp
Creeperface01/centurion
e3b674c11849367a18c2d976ce94071108e1590d
[ "MIT" ]
null
null
null
/* * MIT License * * Copyright (c) 2019-2022 Albin Johansson * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef CENTURION_OPENGL_HPP_ #define CENTURION_OPENGL_HPP_ #ifndef CENTURION_NO_OPENGL #include <SDL.h> #include <cassert> // assert #include <memory> // unique_ptr #include <optional> // optional #include <ostream> // ostream #include <string> // string #include <string_view> // string_view #include "common.hpp" #include "detail/owner_handle_api.hpp" #include "features.hpp" #include "math.hpp" #include "texture.hpp" #include "window.hpp" namespace cen { /// \addtogroup video /// \{ /** * \defgroup opengl OpenGL * * \brief Provides utilities related to OpenGL. */ /// \addtogroup opengl /// \{ /** * \brief Represents different OpenGL attributes. */ enum class gl_attribute { red_size = SDL_GL_RED_SIZE, green_size = SDL_GL_GREEN_SIZE, blue_size = SDL_GL_BLUE_SIZE, alpha_size = SDL_GL_ALPHA_SIZE, buffer_size = SDL_GL_BUFFER_SIZE, depth_size = SDL_GL_DEPTH_SIZE, stencil_size = SDL_GL_STENCIL_SIZE, accum_red_size = SDL_GL_ACCUM_RED_SIZE, accum_green_size = SDL_GL_ACCUM_GREEN_SIZE, accum_blue_size = SDL_GL_ACCUM_BLUE_SIZE, accum_alpha_size = SDL_GL_ACCUM_ALPHA_SIZE, stereo = SDL_GL_STEREO, double_buffer = SDL_GL_DOUBLEBUFFER, accelerated_visual = SDL_GL_ACCELERATED_VISUAL, retained_backing = SDL_GL_RETAINED_BACKING, share_with_current_context = SDL_GL_SHARE_WITH_CURRENT_CONTEXT, framebuffer_srgb_capable = SDL_GL_FRAMEBUFFER_SRGB_CAPABLE, multisample_buffers = SDL_GL_MULTISAMPLEBUFFERS, multisample_samples = SDL_GL_MULTISAMPLESAMPLES, egl = SDL_GL_CONTEXT_EGL, context_flags = SDL_GL_CONTEXT_FLAGS, context_major_version = SDL_GL_CONTEXT_MAJOR_VERSION, context_minor_version = SDL_GL_CONTEXT_MINOR_VERSION, context_profile_mask = SDL_GL_CONTEXT_PROFILE_MASK, context_release_behavior = SDL_GL_CONTEXT_RELEASE_BEHAVIOR, context_reset_notification = SDL_GL_CONTEXT_RESET_NOTIFICATION, context_no_error = SDL_GL_CONTEXT_NO_ERROR }; /// \name OpenGL attribute functions /// \{ [[nodiscard]] constexpr auto to_string(const gl_attribute attr) -> std::string_view { switch (attr) { case gl_attribute::red_size: return "red_size"; case gl_attribute::green_size: return "green_size"; case gl_attribute::blue_size: return "blue_size"; case gl_attribute::alpha_size: return "alpha_size"; case gl_attribute::buffer_size: return "buffer_size"; case gl_attribute::depth_size: return "depth_size"; case gl_attribute::stencil_size: return "stencil_size"; case gl_attribute::accum_red_size: return "accum_red_size"; case gl_attribute::accum_green_size: return "accum_green_size"; case gl_attribute::accum_blue_size: return "accum_blue_size"; case gl_attribute::accum_alpha_size: return "accum_alpha_size"; case gl_attribute::stereo: return "stereo"; case gl_attribute::egl: return "egl"; case gl_attribute::context_flags: return "context_flags"; case gl_attribute::double_buffer: return "double_buffer"; case gl_attribute::accelerated_visual: return "accelerated_visual"; case gl_attribute::retained_backing: return "retained_backing"; case gl_attribute::share_with_current_context: return "share_with_current_context"; case gl_attribute::framebuffer_srgb_capable: return "framebuffer_srgb_capable"; case gl_attribute::multisample_buffers: return "multisample_buffers"; case gl_attribute::multisample_samples: return "multisample_samples"; case gl_attribute::context_major_version: return "context_major_version"; case gl_attribute::context_minor_version: return "context_minor_version"; case gl_attribute::context_profile_mask: return "context_profile_mask"; case gl_attribute::context_release_behavior: return "context_release_behavior"; case gl_attribute::context_reset_notification: return "context_reset_notification"; case gl_attribute::context_no_error: return "context_no_error"; default: throw exception{"Did not recognize OpenGL attribute!"}; } } inline auto operator<<(std::ostream& stream, const gl_attribute attr) -> std::ostream& { return stream << to_string(attr); } /// \} End of OpenGL attribute functions /** * \brief Represents different swap interval modes. */ enum class gl_swap_interval { late_immediate = -1, immediate = 0, synchronized = 1, }; /// \name OpenGL swap interval functions /// \{ [[nodiscard]] constexpr auto to_string(const gl_swap_interval interval) -> std::string_view { switch (interval) { case gl_swap_interval::immediate: return "immediate"; case gl_swap_interval::synchronized: return "synchronized"; case gl_swap_interval::late_immediate: return "late_immediate"; default: throw exception{"Did not recognize swap interval!"}; } } inline auto operator<<(std::ostream& stream, const gl_swap_interval interval) -> std::ostream& { return stream << to_string(interval); } /// \} End of OpenGL swap interva functions /** * \brief Manages the initialization and de-initialization of an OpenGL library. */ class gl_library final { public: CENTURION_DISABLE_COPY(gl_library) CENTURION_DISABLE_MOVE(gl_library) CENTURION_NODISCARD_CTOR explicit gl_library(const char* path = nullptr) { if (SDL_GL_LoadLibrary(path) == -1) { throw sdl_error{}; } } ~gl_library() noexcept { SDL_GL_UnloadLibrary(); } [[nodiscard]] auto address_of(const char* function) const noexcept // NOLINT -> void* { assert(function); return SDL_GL_GetProcAddress(function); } }; template <typename T> class basic_gl_context; using gl_context = basic_gl_context<detail::owner_tag>; ///< An owning context. using gl_context_handle = basic_gl_context<detail::handle_tag>; ///< A non-owning context. /** * \brief Represents an OpenGL context. * * \ownerhandle `gl_context`/`gl_context_handle` * * \see `gl_context` * \see `gl_context_handle` */ template <typename T> class basic_gl_context final { public: explicit basic_gl_context(maybe_owner<SDL_GLContext> context) noexcept(detail::is_handle<T>) : mContext{context} { if constexpr (detail::is_owner<T>) { if (!mContext) { throw exception{"Can't create OpenGL context from null pointer!"}; } } } template <typename U> explicit basic_gl_context(basic_window<U>& window) noexcept(detail::is_handle<T>) : mContext{SDL_GL_CreateContext(window.get())} { if constexpr (detail::is_owner<T>) { if (!mContext) { throw sdl_error{}; } } } template <typename U> auto make_current(basic_window<U>& window) -> result { assert(window.is_opengl()); return SDL_GL_MakeCurrent(window.get(), mContext.get()) == 0; } [[nodiscard]] auto get() const noexcept -> SDL_GLContext { return mContext.get(); } private: struct Deleter final { void operator()(SDL_GLContext context) noexcept { SDL_GL_DeleteContext(context); } }; std::unique_ptr<void, Deleter> mContext; }; /// \} End of group opengl /// \} End of group video /// \ingroup opengl namespace gl { /// \addtogroup video /// \{ /// \addtogroup opengl OpenGL /// \{ /** * \brief Swaps the buffers for an OpenGL window. * * \pre The window must be usable within an OpenGL context. * * \note This requires that double-buffering is supported. * * \param window the OpenGL window to swap the buffers for. */ template <typename T> void swap(basic_window<T>& window) noexcept { assert(window.is_opengl()); SDL_GL_SwapWindow(window.get()); } /** * \brief Returns the drawable size of an OpenGL window. * * \pre `window` must be an OpenGL window. * * \param window the OpenGL window that will be queried. * * \return the drawable size of the window. */ template <typename T> [[nodiscard]] auto drawable_size(const basic_window<T>& window) noexcept -> iarea { assert(window.is_opengl()); int width{}; int height{}; SDL_GL_GetDrawableSize(window.get(), &width, &height); return {width, height}; } /** * \brief Resets all OpenGL context attributes to their default values. */ inline void reset_attributes() noexcept { SDL_GL_ResetAttributes(); } /** * \brief Sets the value of an OpenGL context attribute. * * \param attr the attribute that will be set. * \param value the new value of the attribute. * * \return `success` if the attribute was set; `failure` otherwise. */ inline auto set(const gl_attribute attr, const int value) noexcept -> result { return SDL_GL_SetAttribute(static_cast<SDL_GLattr>(attr), value) == 0; } /** * \brief Returns the current value of an OpenGL context attribute. * * \param attr the attribute to query. * * \return the value of the specified attribute; an empty optional is returned if the value * could not be obtained. */ inline auto get(const gl_attribute attr) noexcept -> std::optional<int> { int value{}; if (SDL_GL_GetAttribute(static_cast<SDL_GLattr>(attr), &value) == 0) { return value; } else { return std::nullopt; } } /** * \brief Sets the swap interval strategy that will be used. * * \param interval the swap interval that will be used. * * \return `success` if the swap interval set; `failure` if it isn't supported. */ inline auto set_swap_interval(const gl_swap_interval interval) noexcept -> result { return SDL_GL_SetSwapInterval(to_underlying(interval)) == 0; } /** * \brief Returns the swap interval used by the current OpenGL context. * * \note `immediate` is returned if the swap interval cannot be determined. * * \return the current swap interval. */ [[nodiscard]] inline auto swap_interval() noexcept -> gl_swap_interval { return gl_swap_interval{SDL_GL_GetSwapInterval()}; } /** * \brief Returns a handle to the currently active OpenGL window. * * \return a potentially empty window handle. */ [[nodiscard]] inline auto get_window() noexcept -> window_handle { return window_handle{SDL_GL_GetCurrentWindow()}; } /** * \brief Returns a handle to the currently active OpenGL context. * * \return a potentially empty OpenGL context handle. */ [[nodiscard]] inline auto get_context() noexcept -> gl_context_handle { return gl_context_handle{SDL_GL_GetCurrentContext()}; } /** * \brief Indicates whether a specific extension is supported. * * \param extension the extension that will be checked. * * \return `true` if the extension is supported; `false` otherwise. */ [[nodiscard]] inline auto is_extension_supported(const char* extension) noexcept -> bool { assert(extension); return SDL_GL_ExtensionSupported(extension) == SDL_TRUE; } /// \copydoc is_extension_supported() [[nodiscard]] inline auto is_extension_supported(const std::string& extension) noexcept -> bool { return is_extension_supported(extension.c_str()); } /** * \brief Binds a texture to the current OpenGL context. * * \param texture the texture to bind. * * \return the size of the bound texture; an empty optional is returned if something goes * wrong. */ template <typename T> auto bind(basic_texture<T>& texture) noexcept -> std::optional<farea> { float width{}; float height{}; if (SDL_GL_BindTexture(texture.get(), &width, &height) == 0) { return farea{width, height}; } else { return std::nullopt; } } /** * \brief Unbinds a texture from the OpenGL context. * * \param texture the texture to unbind. * * \return `success` if the texture was unbound; `failure` otherwise. */ template <typename T> auto unbind(basic_texture<T>& texture) noexcept -> result { return SDL_GL_UnbindTexture(texture.get()) == 0; } /// \} End of group opengl /// \} End of group video } // namespace gl } // namespace cen #endif // CENTURION_NO_OPENGL #endif // CENTURION_OPENGL_HPP_
25.391051
95
0.718489
Creeperface01
cecf0b2d995a1a72bebc16cc927848ca5717c9c4
425
cc
C++
chrome/test/signaling_task.cc
meego-tablet-ux/meego-app-browser
0f4ef17bd4b399c9c990a2f6ca939099495c2b9c
[ "BSD-3-Clause" ]
1
2015-10-12T09:14:22.000Z
2015-10-12T09:14:22.000Z
chrome/test/signaling_task.cc
meego-tablet-ux/meego-app-browser
0f4ef17bd4b399c9c990a2f6ca939099495c2b9c
[ "BSD-3-Clause" ]
null
null
null
chrome/test/signaling_task.cc
meego-tablet-ux/meego-app-browser
0f4ef17bd4b399c9c990a2f6ca939099495c2b9c
[ "BSD-3-Clause" ]
1
2020-11-04T07:22:28.000Z
2020-11-04T07:22:28.000Z
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/test/signaling_task.h" #include "base/synchronization/waitable_event.h" SignalingTask::SignalingTask(base::WaitableEvent* event) : event_(event) { } SignalingTask::~SignalingTask() {} void SignalingTask::Run() { event_->Signal(); }
25
74
0.743529
meego-tablet-ux
ced507c3169c8c7c063f8361e9746cccd06d3317
2,787
cpp
C++
B2G/gecko/layout/style/nsDOMCSSValueList.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-08-31T15:24:31.000Z
2020-04-24T20:31:29.000Z
B2G/gecko/layout/style/nsDOMCSSValueList.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
null
null
null
B2G/gecko/layout/style/nsDOMCSSValueList.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-07-29T07:17:15.000Z
2020-11-04T06:55:37.000Z
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* DOM object representing lists of values in DOM computed style */ #include "nsDOMCSSValueList.h" #include "nsCOMPtr.h" #include "nsError.h" #include "nsContentUtils.h" #include "nsDOMClassInfoID.h" nsDOMCSSValueList::nsDOMCSSValueList(bool aCommaDelimited, bool aReadonly) : mCommaDelimited(aCommaDelimited), mReadonly(aReadonly) { } nsDOMCSSValueList::~nsDOMCSSValueList() { } NS_IMPL_ADDREF(nsDOMCSSValueList) NS_IMPL_RELEASE(nsDOMCSSValueList) DOMCI_DATA(CSSValueList, nsDOMCSSValueList) // QueryInterface implementation for nsDOMCSSValueList NS_INTERFACE_MAP_BEGIN(nsDOMCSSValueList) NS_INTERFACE_MAP_ENTRY(nsIDOMCSSValueList) NS_INTERFACE_MAP_ENTRY(nsIDOMCSSValue) NS_INTERFACE_MAP_ENTRY(nsISupports) NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(CSSValueList) NS_INTERFACE_MAP_END void nsDOMCSSValueList::AppendCSSValue(nsIDOMCSSValue* aValue) { mCSSValues.AppendElement(aValue); } // nsIDOMCSSValueList NS_IMETHODIMP nsDOMCSSValueList::GetLength(uint32_t* aLength) { *aLength = mCSSValues.Length(); return NS_OK; } NS_IMETHODIMP nsDOMCSSValueList::Item(uint32_t aIndex, nsIDOMCSSValue **aReturn) { NS_ENSURE_ARG_POINTER(aReturn); NS_IF_ADDREF(*aReturn = GetItemAt(aIndex)); return NS_OK; } // nsIDOMCSSValue NS_IMETHODIMP nsDOMCSSValueList::GetCssText(nsAString& aCssText) { aCssText.Truncate(); uint32_t count = mCSSValues.Length(); nsAutoString separator; if (mCommaDelimited) { separator.AssignLiteral(", "); } else { separator.Assign(PRUnichar(' ')); } nsCOMPtr<nsIDOMCSSValue> cssValue; nsAutoString tmpStr; for (uint32_t i = 0; i < count; ++i) { cssValue = mCSSValues[i]; NS_ASSERTION(cssValue, "Eek! Someone filled the value list with null CSSValues!"); if (cssValue) { cssValue->GetCssText(tmpStr); if (tmpStr.IsEmpty()) { #ifdef DEBUG_caillon NS_ERROR("Eek! An empty CSSValue! Bad!"); #endif continue; } // If this isn't the first item in the list, then // it's ok to append a separator. if (!aCssText.IsEmpty()) { aCssText.Append(separator); } aCssText.Append(tmpStr); } } return NS_OK; } NS_IMETHODIMP nsDOMCSSValueList::SetCssText(const nsAString& aCssText) { if (mReadonly) { return NS_ERROR_DOM_NO_MODIFICATION_ALLOWED_ERR; } NS_NOTYETIMPLEMENTED("Can't SetCssText yet: please write me!"); return NS_OK; } NS_IMETHODIMP nsDOMCSSValueList::GetCssValueType(uint16_t* aValueType) { NS_ENSURE_ARG_POINTER(aValueType); *aValueType = nsIDOMCSSValue::CSS_VALUE_LIST; return NS_OK; }
21.944882
87
0.739864
wilebeast
ced54dbb98e55c9638b6f9d0975021dde6d557ae
8,733
hpp
C++
stdio.hpp
recolic/rlib
4c669bb4952bd0512ec542333f7d655b10c3eeeb
[ "MIT" ]
7
2018-12-05T02:08:14.000Z
2020-07-27T03:11:19.000Z
stdio.hpp
recolic/rlib
4c669bb4952bd0512ec542333f7d655b10c3eeeb
[ "MIT" ]
4
2018-07-29T03:43:13.000Z
2020-03-26T08:08:33.000Z
stdio.hpp
recolic/rlib
4c669bb4952bd0512ec542333f7d655b10c3eeeb
[ "MIT" ]
2
2020-03-26T08:04:22.000Z
2021-08-20T03:19:28.000Z
/* * * stdio wrapper for modern c++: python like print/println/printf/printfln * print_iter println_iter * Recolic Keghart <root@recolic.net> * MIT License * */ #ifndef R_STDIO_HPP #define R_STDIO_HPP #include <rlib/require/cxx11> // Use fold expression if cxx17 is available. #include <rlib/sys/os.hpp> // Enable inline variable if cxx17 is available. #include <string> #include <iostream> #include <rlib/string.hpp> // format_string #include <type_traits> #if RLIB_OS_ID == OS_WINDOWS #define RLIB_IMPL_ENDLINE "\r\n" #elif RLIB_OS_ID == OS_MACOS #define RLIB_IMPL_ENDLINE "\r" #else #define RLIB_IMPL_ENDLINE "\n" #endif namespace rlib { namespace impl { template <typename T> struct print_wrapper { print_wrapper() = delete; print_wrapper(const T &dat) : wrapper(dat) {} const T &wrapper; friend std::ostream & operator<< (std::ostream &os, print_wrapper<T> p) { return os << p.wrapper; } }; } } namespace rlib { // print to custom stream template <typename PrintFinalT> void print(std::ostream &os, PrintFinalT reqArg); template <typename Required, typename... Optional> void print(std::ostream &os, Required reqArgs, Optional... optiArgs); template <typename... Optional> void println(std::ostream &os, Optional... optiArgs); template <> void println(std::ostream &os); template <typename Iterable, typename Printable> void print_iter(std::ostream &os, Iterable arg, Printable spliter); template <typename Iterable, typename Printable> void println_iter(std::ostream &os, Iterable arg, Printable spliter); template <typename Iterable> void print_iter(std::ostream &os, Iterable arg); template <typename Iterable> void println_iter(std::ostream &os, Iterable arg); template <typename... Args> size_t printf(std::ostream &os, const std::string &fmt, Args... args); template <typename... Args> size_t printfln(std::ostream &os, const std::string &fmt, Args... args); template <typename TargetType = std::string> inline TargetType scan(std::istream &is = std::cin) { TargetType target; is >> target; return target; } inline rlib::string scanln(std::istream &is = std::cin, char delimiter = '\n') noexcept { std::string line; std::getline(is, line, delimiter); return std::move(line); } // default for std::cout template <typename... Args> void println(Args... args); template <> void println(); template <typename... Args> void print(Args... args); template <typename... Args> size_t printf(const std::string &fmt, Args... args); template <typename... Args> size_t printfln(const std::string &fmt, Args... args); // implementations below -------------------------------- namespace impl { inline bool &enable_endl_flush() { static bool instance = true; return instance; } template <typename Iterable, typename Printable> struct _printable_iterable : private std::pair<Iterable, Printable> { using std::pair<Iterable, Printable>::pair; using _printable_iterable_tag = void; Iterable &arg() & {return std::pair<Iterable, Printable>::first;} Printable &spliter() & {return std::pair<Iterable, Printable>::second;} Iterable &&arg() && {return std::pair<Iterable, Printable>::first;} Printable &&spliter() && {return std::pair<Iterable, Printable>::second;} const Iterable &arg() const & {return std::pair<Iterable, Printable>::first;} const Printable &spliter() const & {return std::pair<Iterable, Printable>::second;} }; template <typename FirstT, typename SecondT> using FirstOf = FirstT; } // more interfaces... template <typename Iterable, typename Printable = char> auto printable_iter(Iterable &&arg, Printable spliter = ' ') -> impl::_printable_iterable<typename std::decay<Iterable>::type, Printable> { // TODO: avoid the extra copy while passing lvalue reference on constructing return value obj. return impl::_printable_iterable<typename std::decay<Iterable>::type, Printable>(std::forward<Iterable>(arg), spliter); } inline bool sync_with_stdio(bool sync = true) noexcept { return std::ios::sync_with_stdio(sync); } inline bool enable_endl_flush(bool enable = true) noexcept { return impl::enable_endl_flush() = enable; } // Implements below --------------------- template <typename CharT, typename Traits> inline std::basic_ostream<CharT, Traits>& endl(std::basic_ostream<CharT, Traits>& os) { os << RLIB_IMPL_ENDLINE; if(impl::enable_endl_flush()) os.flush(); return os; } // With custom os template <typename PrintFinalT> void print(std::ostream &os, PrintFinalT reqArg) { os << std::forward<PrintFinalT>(reqArg); } template <typename Required, typename... Optional> void print(std::ostream &os, Required reqArgs, Optional... optiArgs) { os << reqArgs << ' '; print(os, std::forward<Optional>(optiArgs) ...); } template <typename... Optional> void println(std::ostream &os, Optional... optiArgs) { print(os, std::forward<Optional>(optiArgs) ...); println(os); } template <> inline void println(std::ostream &os) { os << rlib::endl; } template <typename... Args> size_t printf(std::ostream &os, const std::string &fmt, Args... args) { std::string to_print = impl::format_string(fmt, args...); print(os, to_print); return to_print.size(); } template <typename... Args> size_t printfln(std::ostream &os, const std::string &fmt, Args... args) { size_t len = printf(os, fmt, args...); println(os); return len + 1; } // default for std::cout template <typename... Args> void println(Args... args) { return println(std::cout, std::forward<Args>(args) ...); } template <> inline void println() { return println(std::cout); } template <typename... Args> void print(Args... args) { return print(std::cout, std::forward<Args>(args) ...); } template <typename... Args> size_t printf(const std::string &fmt, Args... args) { return printf(std::cout, fmt, std::forward<Args>(args) ...); } template <typename... Args> size_t printfln(const std::string &fmt, Args... args) { return printfln(std::cout, fmt, std::forward<Args>(args) ...); } // If the stream is stringstream or ostringstream, // it will fails to match print(ostream &, args...), // and match print(args ...). It leads to an error. // Here's the fallback on such sucking substitution error. template <typename StreamType, typename... Args> void println(StreamType &os, Args... args) { using ostream_or_data = typename std::conditional<std::is_base_of<std::ostream, StreamType>::value, std::ostream &, impl::print_wrapper<StreamType>>::type; return println(static_cast<ostream_or_data>(os), std::forward<Args>(args) ...); } template <typename StreamType, typename... Args> void print(StreamType &os, Args... args) { using ostream_or_data = typename std::conditional<std::is_base_of<std::ostream, StreamType>::value, std::ostream &, impl::print_wrapper<StreamType>>::type; return print(static_cast<ostream_or_data>(os), std::forward<Args>(args) ...); } } // end namespace rlib // auto-deduct const/nonconst left/right value ref. // For C++20 std::view, it doesn't have a `begin()` method for const lvalue ref. So we have to support // passing rvalue from rlib::printable_iter() to rlib::impl::_printable_iterable to operator<< // Instead of writing 3 overloads here, let us deduce automatically. template <typename PrintableIterableT> rlib::impl::FirstOf<std::ostream&, typename std::decay<PrintableIterableT>::type::_printable_iterable_tag> operator<< (std::ostream& stream, PrintableIterableT &&p) { for(auto val : p.arg()) stream << val << p.spliter(); return stream; } // // Old version, for backup // template <typename Iterable, typename Printable> // std::ostream& operator<< (std::ostream& stream, rlib::impl::_printable_iterable<Iterable, Printable> &&p) { // for(auto val : p.arg()) // stream << val << p.spliter(); // return stream; // } #endif
36.3875
166
0.630024
recolic
ced556d24274a10ce37286ca3de032c6b4258690
1,432
cpp
C++
src/ParamsLog.cpp
quekyuyang/stitch-cpp
9158d03d4fe2b09d4672b38d0762426178cb646c
[ "MIT" ]
null
null
null
src/ParamsLog.cpp
quekyuyang/stitch-cpp
9158d03d4fe2b09d4672b38d0762426178cb646c
[ "MIT" ]
null
null
null
src/ParamsLog.cpp
quekyuyang/stitch-cpp
9158d03d4fe2b09d4672b38d0762426178cb646c
[ "MIT" ]
null
null
null
#include <vector> #include <fstream> #include "ParamsLog.hpp" #include <nlohmann/json.hpp> using json = nlohmann::json; void ParamsLogManager::addNodeData(std::vector<Node> &nodes) { for (const auto &node : nodes) { std::string ID_pair(node.getID() + "-" + node.getBestLink().getTargetID()); const cv::Mat &homo_mat = node.getBestLink().getHomoMat(); if (homo_mat.empty()) continue; std::vector<double> homo_params; if (homo_mat.isContinuous()) homo_params.assign(homo_mat.begin<double>(),homo_mat.end<double>()); else throw std::runtime_error("Homography matrix not continuous"); _params_logs[ID_pair].addHomoParams(homo_params); _params_logs[ID_pair].addNInliers(node.getBestLink().getNInliers()); } } void ParamsLogManager::saveJson(std::string filepath) { json jdata; for (const auto &entry : _params_logs) { jdata[entry.first]["params"] = entry.second.getHomoParams(); jdata[entry.first]["n_inliers"] = entry.second.getNInliers(); } std::ofstream file(filepath); file << jdata; } void ParamsLog::addHomoParams(std::vector<double> homo_params) { _homo_params_log.push_back(homo_params); } void ParamsLog::addNInliers(int n_inliers) { _n_inliers_log.push_back(n_inliers); } std::vector<std::vector<double>> ParamsLog::getHomoParams() const {return _homo_params_log;} std::vector<int> ParamsLog::getNInliers() const {return _n_inliers_log;}
27.018868
92
0.713687
quekyuyang
ced7b79c6ed690d3423fe8550ea3e244b6efa1de
1,084
cpp
C++
BZOJ/3261/code.cpp
sjj118/OI-Code
964ea6e799d14010f305c7e4aee269d860a781f7
[ "MIT" ]
null
null
null
BZOJ/3261/code.cpp
sjj118/OI-Code
964ea6e799d14010f305c7e4aee269d860a781f7
[ "MIT" ]
null
null
null
BZOJ/3261/code.cpp
sjj118/OI-Code
964ea6e799d14010f305c7e4aee269d860a781f7
[ "MIT" ]
null
null
null
#include<iostream> #include<cstdio> #define rg register #define rep(i,x,y) for(rg int i=(x);i<=(y);++i) #define per(i,x,y) for(rg int i=(x);i>=(y);--i) using namespace std; const int maxn=6e5+10,maxp=3e7; int root[maxn],n,m,xn; struct Trie{ int tot,son[maxp][2],val[maxp]; int modify(int v,int&k,int d){ int t=++tot;val[t]=val[k]+1; if(d==-1)return t; if((v>>d)&1)son[t][0]=son[k][0],son[t][1]=modify(v,son[k][1],d-1); else son[t][0]=modify(v,son[k][0],d-1),son[t][1]=son[k][1]; return t; } int query(int v,int&l,int&r,int d){ if(d==-1)return 0; int t=!((v>>d)&1); if(val[son[r][t]]-val[son[l][t]])return query(v,son[l][t],son[r][t],d-1)+(1<<d); else return query(v,son[l][!t],son[r][!t],d-1); } }T; int main(){ scanf("%d%d",&n,&m); rep(i,1,n){int x;scanf("%d",&x);root[i]=T.modify(xn,root[i-1],30);xn^=x;} rep(i,1,m){ char op;scanf("\n%c",&op); if(op=='A'){ int x;scanf("%d",&x); ++n;root[n]=T.modify(xn,root[n-1],30);xn^=x; }else{ int l,r,x;scanf("%d%d%d",&l,&r,&x); printf("%d\n",T.query(x^xn,root[l-1],root[r],30)); } } return 0; }
27.1
82
0.550738
sjj118
cedced8eb090c546fdb13af436625604296d896b
586
cpp
C++
C++/Data_Structures/sorting/bubble_sort.cpp
IUC4801/HactoberFest21
ad52dee669deba54630584435b77a6ab07dc67b2
[ "Unlicense" ]
1
2021-10-04T14:39:02.000Z
2021-10-04T14:39:02.000Z
C++/Data_Structures/sorting/bubble_sort.cpp
IUC4801/HactoberFest21
ad52dee669deba54630584435b77a6ab07dc67b2
[ "Unlicense" ]
1
2021-10-06T04:41:55.000Z
2021-10-06T04:41:55.000Z
C++/Data_Structures/sorting/bubble_sort.cpp
IUC4801/HactoberFest21
ad52dee669deba54630584435b77a6ab07dc67b2
[ "Unlicense" ]
1
2021-10-08T12:31:04.000Z
2021-10-08T12:31:04.000Z
// program to implement bubble sort #include<stdio.h> #define MAX 150 int main() { int arr[MAX]; int temp,i,j,size; printf("Enter size of array : "); scanf("%d",&size); printf("Enter %d elements\n", size); for(i=0; i<size; i++) { scanf("%d", &arr[i]); } for(i=0; i<size-1; i++) { for(j=0; j<size-i-1; j++) { if(arr[j] > arr[j+1]) { temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } printf("\nAfter applying bubble sort sorted elements are : \n"); for(i=0; i<size; i++) { printf("%d\n", arr[i]); } return 0; }
14.292683
68
0.511945
IUC4801
cedf1d3f2815230f1c11aa68733ec3f2f0a2643b
2,098
cc
C++
core/network/PiiMimeTypeMap.cc
topiolli/into
f0a47736f5c93dd32e89e7aad34152ae1afc5583
[ "BSD-3-Clause" ]
14
2015-01-19T22:14:18.000Z
2020-04-13T23:27:20.000Z
core/network/PiiMimeTypeMap.cc
topiolli/into
f0a47736f5c93dd32e89e7aad34152ae1afc5583
[ "BSD-3-Clause" ]
null
null
null
core/network/PiiMimeTypeMap.cc
topiolli/into
f0a47736f5c93dd32e89e7aad34152ae1afc5583
[ "BSD-3-Clause" ]
14
2015-01-16T05:43:15.000Z
2019-01-29T07:57:11.000Z
/* This file is part of Into. * Copyright (C) Intopii 2013. * All rights reserved. * * Licensees holding a commercial Into license may use this file in * accordance with the commercial license agreement. Please see * LICENSE.commercial for commercial licensing terms. * * Alternatively, this file may be used under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. In addition, Intopii gives you special rights * to use Into as a part of open source software projects. Please * refer to LICENSE.AGPL3 for details. */ #include "PiiMimeTypeMap.h" #include <QFile> #include <QRegExp> PiiMimeTypeMap::PiiMimeTypeMap() : d(new Data) { d->mapTypes.insert("html", "text/html"); d->mapTypes.insert("css", "text/css"); d->mapTypes.insert("js", "application/javascript"); d->mapTypes.insert("txt", "text/plain"); d->mapTypes.insert("png", "image/png"); d->mapTypes.insert("jpg", "image/jpeg"); d->mapTypes.insert("pdf", "application/pdf"); } PiiMimeTypeMap::PiiMimeTypeMap(const QString& mimeTypeFile) : d(new Data) { readMimeTypes(mimeTypeFile); } PiiMimeTypeMap::~PiiMimeTypeMap() { delete d; } void PiiMimeTypeMap::readMimeTypes(const QString& fileName) { QFile file(fileName); if (!file.open(QIODevice::ReadOnly)) return; char buffer[1024]; QRegExp reSpace("[\t \n]+"); while (file.readLine(buffer, 1024) > 0) { if (buffer[0] == '#') continue; QStringList lstParts(QString(buffer).split(reSpace, QString::SkipEmptyParts)); if (lstParts.size() < 2) continue; for (int i=1; i<lstParts.size(); ++i) d->mapTypes.insert(lstParts[i], lstParts[0]); } } QString PiiMimeTypeMap::typeForExtension(const QString& extension) const { return d->mapTypes[extension]; } QStringList PiiMimeTypeMap::extensionsForType(const QString& mimeType) const { QStringList lstResult; for (QMap<QString,QString>::const_iterator i=d->mapTypes.begin(); i != d->mapTypes.end(); ++i) if (i.value() == mimeType) lstResult << i.key(); return lstResult; }
27.605263
84
0.693518
topiolli
cee247b8ed4ea3a5e334a00a920cc167c35f4971
1,626
cpp
C++
src/knapsack/dynamic.cpp
ThermalSpan/cpp-knapsack
dcc577a3ef9f9da1f2a85400465f488d91fdd8cf
[ "MIT" ]
null
null
null
src/knapsack/dynamic.cpp
ThermalSpan/cpp-knapsack
dcc577a3ef9f9da1f2a85400465f488d91fdd8cf
[ "MIT" ]
null
null
null
src/knapsack/dynamic.cpp
ThermalSpan/cpp-knapsack
dcc577a3ef9f9da1f2a85400465f488d91fdd8cf
[ "MIT" ]
null
null
null
// // dynamic.cpp // knapsack // // Created by Russell Wilhelm Bentley on 1/26/16. // Copyright (c) 2015 Russell Wilhelm Bentley. // Distributed under the MIT license // #include <iostream> #include "dynamic.h" using namespace std; void dynamicSolve (ItemVec &vec, int capacity) { int x, y, index, doNotTake, doTake; int rowSize = capacity + 1; int columnSize = vec.size () + 1; int arraySize = columnSize * rowSize; int *sumArray = new int[arraySize]; // Here, x refers to [0, capacity] // y refers to [0, n] for (x = 0; x < rowSize; x++) { sumArray[x] = 0; } for (y = 1; y < columnSize; y++) { for (x = 0; x < rowSize; x++) { index = y * rowSize + x; if (vec[y-1].s_weight <= x) { doNotTake = sumArray[ (y-1) * rowSize + x]; doTake = sumArray[ (y-1) * rowSize + (x - vec[y-1].s_weight)] + vec[y-1].s_value; sumArray[index] = max (doNotTake, doTake); } else { sumArray[index] = sumArray[ (y-1) * rowSize + x]; } } } cout << sumArray[arraySize - 1] << endl; char *decision = (char *) malloc (vec.size () * sizeof (char) + 1); decision[vec.size ()] = '\0'; x = capacity; for (y = vec.size (); y > 0; y--) { if (sumArray[y * rowSize + x] == sumArray[ (y-1) * rowSize + x]) { decision[y-1] = '0'; } else { decision[y-1] = '1'; x -= vec[y-1].s_weight; } } string d (decision); cout << d << endl; delete (sumArray); free (decision); }
26.655738
97
0.50123
ThermalSpan
cee4def62b0375fe1890a48a8be5ce80e75f12e7
2,636
cpp
C++
lib/thornhill/src/kernel.cpp
andr3h3nriqu3s11/thornhill
ec31eb06dd914bcb7fd22ff31386b40996656d94
[ "MIT" ]
6
2021-11-06T08:42:41.000Z
2022-01-06T11:42:18.000Z
lib/thornhill/src/kernel.cpp
andr3h3nriqu3s11/thornhill
ec31eb06dd914bcb7fd22ff31386b40996656d94
[ "MIT" ]
1
2022-01-09T18:09:57.000Z
2022-01-09T18:09:57.000Z
lib/thornhill/src/kernel.cpp
andr3h3nriqu3s11/thornhill
ec31eb06dd914bcb7fd22ff31386b40996656d94
[ "MIT" ]
1
2022-01-09T18:07:42.000Z
2022-01-09T18:07:42.000Z
#include <cstring> #include <thornhill> #include "drivers/hardware/serial.hpp" using namespace std; using namespace Thornhill; namespace Thornhill::Kernel { void printChar(char c) { ThornhillSerial::writeCharacter(c); } void print(const char* message, bool appendNewline) { ThornhillSerial::write(message, appendNewline); } int vprintf(const char* fmt, va_list arg) { int length = 0; char* strPtr; char buffer[32]; char c; while ((c = *fmt++)) { if ('%' == c) { switch ((c = *fmt++)) { /* %% => print a single % symbol (escape) */ case '%': printChar('%'); length++; break; /* %c => print a character */ case 'c': printChar((char) va_arg(arg, int)); length++; break; /* %s => print a string */ case 's': strPtr = va_arg(arg, char*); print(strPtr, false); length += strlen(strPtr); break; /* %d => print number as decimal */ case 'd': itoa(buffer, va_arg(arg, int64_t), 10, 32); print(buffer, false); length += strlen(buffer); break; /* %u => print unsigned number as integer */ case 'u': uitoa(buffer, va_arg(arg, uint64_t), 10, 32); print(buffer, false); length += strlen(buffer); break; /* %x => print number as hexadecimal */ case 'x': uitoa(buffer, va_arg(arg, uint64_t), 16, 32); print(buffer, false); length += strlen(buffer); break; /* %n => print newline */ case 'n': printChar('\r'); printChar('\n'); length += 2; break; } } else { printChar(c); length++; } } return length; } void printf(const char* fmt...) { va_list arg; va_start(arg, fmt); vprintf(fmt, arg); va_end(arg); } }
28.344086
69
0.371017
andr3h3nriqu3s11
ceef16b8847785459e6d10d1411ba662812cfd15
3,488
hpp
C++
src/assembler/LinearElasticity.hpp
danielepanozzo/polyfem
34a7719c2a3874b7ecc865c28d8b3d9bbdf7d0ba
[ "MIT" ]
228
2018-11-23T19:32:42.000Z
2022-03-25T10:30:51.000Z
src/assembler/LinearElasticity.hpp
danielepanozzo/polyfem
34a7719c2a3874b7ecc865c28d8b3d9bbdf7d0ba
[ "MIT" ]
14
2019-03-11T22:44:14.000Z
2022-03-16T14:50:35.000Z
src/assembler/LinearElasticity.hpp
danielepanozzo/polyfem
34a7719c2a3874b7ecc865c28d8b3d9bbdf7d0ba
[ "MIT" ]
45
2018-12-31T02:04:57.000Z
2022-03-08T02:42:01.000Z
#pragma once #include <polyfem/Common.hpp> #include <polyfem/ElementAssemblyValues.hpp> #include <polyfem/ElementBases.hpp> #include <polyfem/ElasticityUtils.hpp> #include <polyfem/AutodiffTypes.hpp> #include <Eigen/Dense> #include <functional> //local assembler for linear elasticity namespace polyfem { class LinearElasticity { public: ///computes local stiffness matrix is R^{dim²} for bases i,j //vals stores the evaluation for that element //da contains both the quadrature weight and the change of metric in the integral Eigen::Matrix<double, Eigen::Dynamic, 1, 0, 9, 1> assemble(const ElementAssemblyValues &vals, const int i, const int j, const QuadratureVector &da) const; //neccessary for mixing linear model with non-linear collision response Eigen::MatrixXd assemble_hessian(const ElementAssemblyValues &vals, const Eigen::MatrixXd &displacement, const QuadratureVector &da) const; //compute gradient of elastic energy, as assembler Eigen::VectorXd assemble_grad(const ElementAssemblyValues &vals, const Eigen::MatrixXd &displacement, const QuadratureVector &da) const; //compute elastic energy double compute_energy(const ElementAssemblyValues &vals, const Eigen::MatrixXd &displacement, const QuadratureVector &da) const; //kernel of the pde, used in kernel problem Eigen::Matrix<AutodiffScalarGrad, Eigen::Dynamic, 1, 0, 3, 1> kernel(const int dim, const AutodiffGradPt &r) const; //uses autodiff to compute the rhs for a fabbricated solution //uses autogenerated code to compute div(sigma) //pt is the evaluation of the solution at a point Eigen::Matrix<double, Eigen::Dynamic, 1, 0, 3, 1> compute_rhs(const AutodiffHessianPt &pt) const; //compute von mises stress for an element at the local points void compute_von_mises_stresses(const int el_id, const ElementBases &bs, const ElementBases &gbs, const Eigen::MatrixXd &local_pts, const Eigen::MatrixXd &displacement, Eigen::MatrixXd &stresses) const; //compute stress tensor for an element at the local points void compute_stress_tensor(const int el_id, const ElementBases &bs, const ElementBases &gbs, const Eigen::MatrixXd &local_pts, const Eigen::MatrixXd &displacement, Eigen::MatrixXd &tensor) const; //size of the problem, this is a tensor problem so the size is the size of the mesh inline int &size() { return size_; } inline int size() const { return size_; } //inialize material parameter void set_parameters(const json &params); //initialize material param per element void init_multimaterial(const bool is_volume, const Eigen::MatrixXd &Es, const Eigen::MatrixXd &nus); //class that stores and compute lame parameters per point const LameParameters &lame_params() const { return params_; } private: int size_ = 2; //class that stores and compute lame parameters per point LameParameters params_; void assign_stress_tensor(const int el_id, const ElementBases &bs, const ElementBases &gbs, const Eigen::MatrixXd &local_pts, const Eigen::MatrixXd &displacement, const int all_size, Eigen::MatrixXd &all, const std::function<Eigen::MatrixXd(const Eigen::MatrixXd &)> &fun) const; //aux function that computes energy //double compute_energy is the same with T=double //assemble_grad is the same with T=DScalar1 and return .getGradient() template <typename T> T compute_energy_aux(const ElementAssemblyValues &vals, const Eigen::MatrixXd &displacement, const QuadratureVector &da) const; }; } // namespace polyfem
47.780822
281
0.770069
danielepanozzo
cef423c0a06783d80051447743e05e420fb46bb3
863
cpp
C++
leetcode/1094.cpp
pravinsrc/AlgorithmTraining_leetcode
72ae84e0f7f4d64dff8482d3fe7b96e32b19c9bb
[ "MIT" ]
null
null
null
leetcode/1094.cpp
pravinsrc/AlgorithmTraining_leetcode
72ae84e0f7f4d64dff8482d3fe7b96e32b19c9bb
[ "MIT" ]
null
null
null
leetcode/1094.cpp
pravinsrc/AlgorithmTraining_leetcode
72ae84e0f7f4d64dff8482d3fe7b96e32b19c9bb
[ "MIT" ]
null
null
null
#include <algorithm> #include <map> #include <vector> class Solution { public: bool carPooling(std::vector<std::vector<int>>& trips, int capacity) { std::map<int, int> pool_map{}; bool success{true}; for (const auto& trip : trips) { auto start{trip[1]}; auto end{trip[2]}; auto num{trip[0]}; pool_map[start] -= num; pool_map[end] += num; if (pool_map[start] + capacity < 0) { success = false; break; } } if(!success){ return false; } int sum{0}; for (const auto [_, num] : pool_map) { sum += num; if (num + capacity < 0) { success = false; break; } } return false; } };
21.575
71
0.432213
pravinsrc
cef7d285a9c0e707d21f972b609644e5a3683a3b
66,737
cpp
C++
test/examples/conc_queue_examples.cpp
giucamp/density
b6a9653b36ec0c37c26f879574295a56e6345a7b
[ "BSL-1.0" ]
18
2016-05-24T11:46:43.000Z
2020-11-03T17:11:27.000Z
test/examples/conc_queue_examples.cpp
giucamp/density
b6a9653b36ec0c37c26f879574295a56e6345a7b
[ "BSL-1.0" ]
13
2017-11-04T17:41:30.000Z
2018-09-05T11:32:22.000Z
test/examples/conc_queue_examples.cpp
giucamp/density
b6a9653b36ec0c37c26f879574295a56e6345a7b
[ "BSL-1.0" ]
1
2018-09-27T21:00:20.000Z
2018-09-27T21:00:20.000Z
// Copyright Giuseppe Campana (giu.campana@gmail.com) 2016-2018. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include "../test_framework/density_test_common.h" // #include "test_framework/progress.h" #include <assert.h> #include <chrono> #include <complex> #include <density/conc_heter_queue.h> #include <density/io_runtimetype_features.h> #include <iostream> #include <iterator> #include <string> // if assert expands to nothing, some local variable becomes unused #if defined(_MSC_VER) && defined(NDEBUG) #pragma warning(push) #pragma warning(disable : 4189) // local variable is initialized but not referenced #endif namespace density_tests { uint32_t compute_checksum(const void * i_data, size_t i_lenght); void conc_heterogeneous_queue_put_samples() { using namespace density; { conc_heter_queue<> queue; //! [conc_heter_queue push example 1] queue.push(12); queue.push(std::string("Hello world!!")); //! [conc_heter_queue push example 1] //! [conc_heter_queue emplace example 1] queue.emplace<int>(); queue.emplace<std::string>(12, '-'); //! [conc_heter_queue emplace example 1] { //! [conc_heter_queue start_push example 1] auto put = queue.start_push(12); put.element() += 2; put.commit(); // commits a 14 //! [conc_heter_queue start_push example 1] } { //! [conc_heter_queue start_emplace example 1] auto put = queue.start_emplace<std::string>(4, '*'); put.element() += "****"; put.commit(); // commits a "********" //! [conc_heter_queue start_emplace example 1] } } { //! [conc_heter_queue dyn_push example 1] using MyRunTimeType = runtime_type<f_default_construct, f_destroy, f_size, f_alignment>; conc_heter_queue<MyRunTimeType> queue; auto const type = MyRunTimeType::make<int>(); queue.dyn_push(type); // appends 0 //! [conc_heter_queue dyn_push example 1] } { //! [conc_heter_queue dyn_push_copy example 1] using MyRunTimeType = runtime_type<f_copy_construct, f_destroy, f_size, f_alignment>; conc_heter_queue<MyRunTimeType> queue; std::string const source("Hello world!!"); auto const type = MyRunTimeType::make<decltype(source)>(); queue.dyn_push_copy(type, &source); //! [conc_heter_queue dyn_push_copy example 1] } { //! [conc_heter_queue dyn_push_move example 1] using MyRunTimeType = runtime_type<f_move_construct, f_destroy, f_size, f_alignment>; conc_heter_queue<MyRunTimeType> queue; std::string source("Hello world!!"); auto const type = MyRunTimeType::make<decltype(source)>(); queue.dyn_push_move(type, &source); //! [conc_heter_queue dyn_push_move example 1] } { //! [conc_heter_queue start_dyn_push example 1] using MyRunTimeType = runtime_type<f_default_construct, f_destroy, f_size, f_alignment>; conc_heter_queue<MyRunTimeType> queue; auto const type = MyRunTimeType::make<int>(); auto put = queue.start_dyn_push(type); put.commit(); //! [conc_heter_queue start_dyn_push example 1] } { //! [conc_heter_queue start_dyn_push_copy example 1] using MyRunTimeType = runtime_type<f_copy_construct, f_destroy, f_size, f_alignment>; conc_heter_queue<MyRunTimeType> queue; std::string const source("Hello world!!"); auto const type = MyRunTimeType::make<decltype(source)>(); auto put = queue.start_dyn_push_copy(type, &source); put.commit(); //! [conc_heter_queue start_dyn_push_copy example 1] } { //! [conc_heter_queue start_dyn_push_move example 1] using MyRunTimeType = runtime_type<f_move_construct, f_destroy, f_size, f_alignment>; conc_heter_queue<MyRunTimeType> queue; std::string source("Hello world!!"); auto const type = MyRunTimeType::make<decltype(source)>(); auto put = queue.start_dyn_push_move(type, &source); put.commit(); //! [conc_heter_queue start_dyn_push_move example 1] } } void conc_heterogeneous_queue_put_transaction_samples() { using namespace density; { //! [conc_heter_queue put_transaction default_construct example 1] conc_heter_queue<>::put_transaction<> transaction; assert(transaction.empty()); //! [conc_heter_queue put_transaction default_construct example 1] } { //! [conc_heter_queue put_transaction copy_construct example 1] static_assert( !std::is_copy_constructible<conc_heter_queue<>::put_transaction<>>::value, ""); static_assert( !std::is_copy_constructible<conc_heter_queue<int>::put_transaction<>>::value, ""); //! [conc_heter_queue put_transaction copy_construct example 1] } { //! [conc_heter_queue put_transaction copy_assign example 1] static_assert( !std::is_copy_assignable<conc_heter_queue<>::put_transaction<>>::value, ""); static_assert( !std::is_copy_assignable<conc_heter_queue<int>::put_transaction<>>::value, ""); //! [conc_heter_queue put_transaction copy_assign example 1] } { //! [conc_heter_queue put_transaction move_construct example 1] conc_heter_queue<> queue; auto transaction1 = queue.start_push(1); // move from transaction1 to transaction2 auto transaction2(std::move(transaction1)); assert(transaction1.empty()); assert(transaction2.element() == 1); // commit transaction2 transaction2.commit(); assert(transaction2.empty()); //! [conc_heter_queue put_transaction move_construct example 1] //! [conc_heter_queue put_transaction move_construct example 2] // put_transaction<void> can be move constructed from any put_transaction<T> static_assert( std::is_constructible< conc_heter_queue<>::put_transaction<void>, conc_heter_queue<>::put_transaction<void> &&>::value, ""); static_assert( std::is_constructible< conc_heter_queue<>::put_transaction<void>, conc_heter_queue<>::put_transaction<int> &&>::value, ""); // put_transaction<T> can be move constructed only from put_transaction<T> static_assert( !std::is_constructible< conc_heter_queue<>::put_transaction<int>, conc_heter_queue<>::put_transaction<void> &&>::value, ""); static_assert( !std::is_constructible< conc_heter_queue<>::put_transaction<int>, conc_heter_queue<>::put_transaction<float> &&>::value, ""); static_assert( std::is_constructible< conc_heter_queue<>::put_transaction<int>, conc_heter_queue<>::put_transaction<int> &&>::value, ""); //! [conc_heter_queue put_transaction move_construct example 2] } { //! [conc_heter_queue put_transaction move_assign example 1] conc_heter_queue<> queue; auto transaction1 = queue.start_push(1); conc_heter_queue<>::put_transaction<> transaction2; transaction2 = std::move(transaction1); assert(transaction1.empty()); transaction2.commit(); assert(transaction2.empty()); //! [conc_heter_queue put_transaction move_assign example 1] //! [conc_heter_queue put_transaction move_assign example 2] // put_transaction<void> can be move assigned from any put_transaction<T> static_assert( std::is_assignable< conc_heter_queue<>::put_transaction<void>, conc_heter_queue<>::put_transaction<void> &&>::value, ""); static_assert( std::is_assignable< conc_heter_queue<>::put_transaction<void>, conc_heter_queue<>::put_transaction<int> &&>::value, ""); // put_transaction<T> can be move assigned only from put_transaction<T> static_assert( !std::is_assignable< conc_heter_queue<>::put_transaction<int>, conc_heter_queue<>::put_transaction<void> &&>::value, ""); static_assert( !std::is_assignable< conc_heter_queue<>::put_transaction<int>, conc_heter_queue<>::put_transaction<float> &&>::value, ""); static_assert( std::is_assignable< conc_heter_queue<>::put_transaction<int>, conc_heter_queue<>::put_transaction<int> &&>::value, ""); //! [conc_heter_queue put_transaction move_assign example 2] } { //! [conc_heter_queue put_transaction raw_allocate example 1] conc_heter_queue<> queue; struct Msg { std::chrono::high_resolution_clock::time_point m_time = std::chrono::high_resolution_clock::now(); size_t m_len = 0; void * m_data = nullptr; }; auto post_message = [&queue](const void * i_data, size_t i_len) { auto transaction = queue.start_emplace<Msg>(); transaction.element().m_len = i_len; transaction.element().m_data = transaction.raw_allocate(i_len, 1); memcpy(transaction.element().m_data, i_data, i_len); assert( !transaction .empty()); // a put transaction is not empty if it's bound to an element being put transaction.commit(); assert(transaction.empty()); // the commit makes the transaction empty }; auto const start_time = std::chrono::high_resolution_clock::now(); auto consume_all_msgs = [&queue, &start_time] { while (auto consume = queue.try_start_consume()) { auto const checksum = compute_checksum(consume.element<Msg>().m_data, consume.element<Msg>().m_len); std::cout << "Message with checksum " << checksum << " at "; std::cout << (consume.element<Msg>().m_time - start_time).count() << std::endl; consume.commit(); } }; int msg_1 = 42, msg_2 = 567; post_message(&msg_1, sizeof(msg_1)); post_message(&msg_2, sizeof(msg_2)); consume_all_msgs(); //! [conc_heter_queue put_transaction raw_allocate example 1] } { conc_heter_queue<> queue; //! [conc_heter_queue put_transaction raw_allocate_copy example 1] struct Msg { size_t m_len = 0; char * m_chars = nullptr; }; auto post_message = [&queue](const char * i_data, size_t i_len) { auto transaction = queue.start_emplace<Msg>(); transaction.element().m_len = i_len; transaction.element().m_chars = transaction.raw_allocate_copy(i_data, i_data + i_len); memcpy(transaction.element().m_chars, i_data, i_len); transaction.commit(); }; //! [conc_heter_queue put_transaction raw_allocate_copy example 1] (void)post_message; } { conc_heter_queue<> queue; //! [conc_heter_queue put_transaction raw_allocate_copy example 2] struct Msg { char * m_chars = nullptr; }; auto post_message = [&queue](const std::string & i_string) { auto transaction = queue.start_emplace<Msg>(); transaction.element().m_chars = transaction.raw_allocate_copy(i_string); transaction.commit(); }; //! [conc_heter_queue put_transaction raw_allocate_copy example 2] (void)post_message; } { conc_heter_queue<> queue; //! [conc_heter_queue put_transaction empty example 1] conc_heter_queue<>::put_transaction<> transaction; assert(transaction.empty()); transaction = queue.start_push(1); assert(!transaction.empty()); //! [conc_heter_queue put_transaction empty example 1] } { conc_heter_queue<> queue; //! [conc_heter_queue put_transaction operator_bool example 1] conc_heter_queue<>::put_transaction<> transaction; assert(!transaction); transaction = queue.start_push(1); assert(transaction); //! [conc_heter_queue put_transaction operator_bool example 1] } { //! [conc_heter_queue put_transaction cancel example 1] conc_heter_queue<> queue; // start and cancel a put assert(queue.empty()); auto put = queue.start_push(42); /* assert(queue.empty()); <- this assert would trigger an undefined behavior, because it would access the queue during a non-reentrant put transaction. */ assert(!put.empty()); put.cancel(); assert(queue.empty() && put.empty()); // start and commit a put put = queue.start_push(42); put.commit(); assert(queue.try_start_consume().element<int>() == 42); //! [conc_heter_queue put_transaction cancel example 1] } { conc_heter_queue<> queue; //! [conc_heter_queue put_transaction element_ptr example 1] int value = 42; auto put = queue.start_dyn_push_copy(runtime_type<>::make<decltype(value)>(), &value); assert(*static_cast<int *>(put.element_ptr()) == 42); std::cout << "Putting an " << put.complete_type().type_info().name() << "..." << std::endl; put.commit(); //! [conc_heter_queue put_transaction element_ptr example 1] //! [conc_heter_queue put_transaction element_ptr example 2] auto put_1 = queue.start_push(1); assert(*static_cast<int *>(put_1.element_ptr()) == 1); // this is fine assert(put_1.element() == 1); // this is better put_1.commit(); //! [conc_heter_queue put_transaction element_ptr example 2] } { conc_heter_queue<> queue; //! [conc_heter_queue put_transaction complete_type example 1] int value = 42; auto put = queue.start_dyn_push_copy(runtime_type<>::make<decltype(value)>(), &value); assert(put.complete_type().is<int>()); std::cout << "Putting an " << put.complete_type().type_info().name() << "..." << std::endl; //! [conc_heter_queue put_transaction complete_type example 1] } { conc_heter_queue<> queue; //! [conc_heter_queue put_transaction destroy example 1] queue.start_push(42); /* this transaction is destroyed without being committed, so it gets canceled automatically. */ //! [conc_heter_queue put_transaction destroy example 1] } { conc_heter_queue<> queue; //! [conc_heter_queue typed_put_transaction element example 1] int value = 42; auto untyped_put = queue.start_reentrant_dyn_push_copy(runtime_type<>::make<decltype(value)>(), &value); auto typed_put = queue.start_reentrant_push(42.); /* typed_put = std::move(untyped_put); <- this would not compile: can't assign an untyped transaction to a typed transaction */ assert(typed_put.element() == 42.); //! [conc_heter_queue typed_put_transaction element example 1] } } void conc_heterogeneous_queue_consume_operation_samples() { using namespace density; { conc_heter_queue<> queue; //! [conc_heter_queue consume_operation default_construct example 1] conc_heter_queue<>::consume_operation consume; assert(consume.empty()); //! [conc_heter_queue consume_operation default_construct example 1] } //! [conc_heter_queue consume_operation copy_construct example 1] static_assert( !std::is_copy_constructible<conc_heter_queue<>::consume_operation>::value, ""); //! [conc_heter_queue consume_operation copy_construct example 1] //! [conc_heter_queue consume_operation copy_assign example 1] static_assert(!std::is_copy_assignable<conc_heter_queue<>::consume_operation>::value, ""); //! [conc_heter_queue consume_operation copy_assign example 1] { //! [conc_heter_queue consume_operation move_construct example 1] conc_heter_queue<> queue; queue.push(42); auto consume = queue.try_start_consume(); auto consume_1 = std::move(consume); assert(consume.empty() && !consume_1.empty()); consume_1.commit(); //! [conc_heter_queue consume_operation move_construct example 1] } { //! [conc_heter_queue consume_operation move_assign example 1] conc_heter_queue<> queue; queue.push(42); queue.push(43); auto consume = queue.try_start_consume(); conc_heter_queue<>::consume_operation consume_1; consume_1 = std::move(consume); assert(consume.empty() && !consume_1.empty()); consume_1.commit(); //! [conc_heter_queue consume_operation move_assign example 1] } { //! [conc_heter_queue consume_operation destroy example 1] conc_heter_queue<> queue; queue.push(42); // this consumed is started and destroyed before being committed, so it has no observable effects queue.try_start_consume(); //! [conc_heter_queue consume_operation destroy example 1] } { //! [conc_heter_queue consume_operation empty example 1] conc_heter_queue<> queue; queue.push(42); conc_heter_queue<>::consume_operation consume; assert(consume.empty()); consume = queue.try_start_consume(); assert(!consume.empty()); //! [conc_heter_queue consume_operation empty example 1] } { //! [conc_heter_queue consume_operation operator_bool example 1] conc_heter_queue<> queue; queue.push(42); conc_heter_queue<>::consume_operation consume; assert(consume.empty() == !consume); consume = queue.try_start_consume(); assert(consume.empty() == !consume); //! [conc_heter_queue consume_operation operator_bool example 1] } { //! [conc_heter_queue consume_operation commit_nodestroy example 1] conc_heter_queue<> queue; queue.emplace<std::string>("abc"); conc_heter_queue<>::consume_operation consume = queue.try_start_consume(); consume.complete_type().destroy(consume.element_ptr()); // the string has already been destroyed. Calling commit would trigger an undefined behavior consume.commit_nodestroy(); //! [conc_heter_queue consume_operation commit_nodestroy example 1] } { //! [conc_heter_queue consume_operation cancel example 1] conc_heter_queue<> queue; queue.push(42); conc_heter_queue<>::consume_operation consume = queue.try_start_consume(); consume.cancel(); // there is still a 42 in the queue assert(queue.try_start_consume().element<int>() == 42); //! [conc_heter_queue consume_operation cancel example 1] } { //! [conc_heter_queue consume_operation complete_type example 1] conc_heter_queue<> queue; queue.push(42); conc_heter_queue<>::consume_operation consume = queue.try_start_consume(); assert(consume.complete_type().is<int>()); assert( consume.complete_type() == runtime_type<>::make<int>()); // same to the previous assert assert(consume.element<int>() == 42); consume.commit(); //! [conc_heter_queue consume_operation complete_type example 1] } { //! [conc_heter_queue consume_operation element_ptr example 1] conc_heter_queue<> queue; queue.push(42); conc_heter_queue<>::consume_operation consume = queue.try_start_consume(); ++*static_cast<int *>(consume.element_ptr()); assert(consume.element<int>() == 43); consume.commit(); //! [conc_heter_queue consume_operation element_ptr example 1] } { //! [conc_heter_queue consume_operation swap example 1] conc_heter_queue<> queue; queue.push(42); conc_heter_queue<>::consume_operation consume_1 = queue.try_start_consume(); conc_heter_queue<>::consume_operation consume_2; { using namespace std; swap(consume_1, consume_2); } assert(consume_2.complete_type().is<int>()); assert( consume_2.complete_type() == runtime_type<>::make<int>()); // same to the previous assert assert(consume_2.element<int>() == 42); consume_2.commit(); assert(queue.empty()); //! [conc_heter_queue consume_operation swap example 1] } { //! [conc_heter_queue consume_operation unaligned_element_ptr example 1] conc_heter_queue<> queue; queue.push(42); conc_heter_queue<>::consume_operation consume = queue.try_start_consume(); bool const is_overaligned = alignof(int) > conc_heter_queue<>::min_alignment; void * const unaligned_ptr = consume.unaligned_element_ptr(); int * element_ptr; if (is_overaligned) { element_ptr = static_cast<int *>(address_upper_align(unaligned_ptr, alignof(int))); } else { assert(unaligned_ptr == consume.element_ptr()); element_ptr = static_cast<int *>(unaligned_ptr); } assert(address_is_aligned(element_ptr, alignof(int))); std::cout << "An int: " << *element_ptr << std::endl; consume.commit(); //! [conc_heter_queue consume_operation unaligned_element_ptr example 1] } { //! [conc_heter_queue consume_operation element example 1] conc_heter_queue<> queue; queue.push(42); conc_heter_queue<>::consume_operation consume = queue.try_start_consume(); assert(consume.complete_type().is<int>()); std::cout << "An int: " << consume.element<int>() << std::endl; /* std::cout << "An float: " << consume.element<float>() << std::endl; this would trigger an undefined behavior, because the element is not a float */ consume.commit(); //! [conc_heter_queue consume_operation element example 1] } } void conc_heterogeneous_queue_reentrant_put_samples() { using namespace density; { conc_heter_queue<> queue; //! [conc_heter_queue reentrant_push example 1] queue.reentrant_push(12); queue.reentrant_push(std::string("Hello world!!")); //! [conc_heter_queue reentrant_push example 1] //! [conc_heter_queue reentrant_emplace example 1] queue.reentrant_emplace<int>(); queue.reentrant_emplace<std::string>(12, '-'); //! [conc_heter_queue reentrant_emplace example 1] { //! [conc_heter_queue start_reentrant_push example 1] auto put = queue.start_reentrant_push(12); put.element() += 2; put.commit(); // commits a 14 //! [conc_heter_queue start_reentrant_push example 1] } { //! [conc_heter_queue start_reentrant_emplace example 1] auto put = queue.start_reentrant_emplace<std::string>(4, '*'); put.element() += "****"; put.commit(); // commits a "********" //! [conc_heter_queue start_reentrant_emplace example 1] } } { //! [conc_heter_queue reentrant_dyn_push example 1] using MyRunTimeType = runtime_type<f_default_construct, f_destroy, f_size, f_alignment>; conc_heter_queue<MyRunTimeType> queue; auto const type = MyRunTimeType::make<int>(); queue.reentrant_dyn_push(type); // appends 0 //! [conc_heter_queue reentrant_dyn_push example 1] } { //! [conc_heter_queue reentrant_dyn_push_copy example 1] using MyRunTimeType = runtime_type<f_copy_construct, f_destroy, f_size, f_alignment>; conc_heter_queue<MyRunTimeType> queue; std::string const source("Hello world!!"); auto const type = MyRunTimeType::make<decltype(source)>(); queue.reentrant_dyn_push_copy(type, &source); //! [conc_heter_queue reentrant_dyn_push_copy example 1] } { //! [conc_heter_queue reentrant_dyn_push_move example 1] using MyRunTimeType = runtime_type<f_move_construct, f_destroy, f_size, f_alignment>; conc_heter_queue<MyRunTimeType> queue; std::string source("Hello world!!"); auto const type = MyRunTimeType::make<decltype(source)>(); queue.reentrant_dyn_push_move(type, &source); //! [conc_heter_queue reentrant_dyn_push_move example 1] } { //! [conc_heter_queue start_reentrant_dyn_push example 1] using MyRunTimeType = runtime_type<f_default_construct, f_destroy, f_size, f_alignment>; conc_heter_queue<MyRunTimeType> queue; auto const type = MyRunTimeType::make<int>(); auto put = queue.start_reentrant_dyn_push(type); put.commit(); //! [conc_heter_queue start_reentrant_dyn_push example 1] } { //! [conc_heter_queue start_reentrant_dyn_push_copy example 1] using MyRunTimeType = runtime_type<f_copy_construct, f_destroy, f_size, f_alignment>; conc_heter_queue<MyRunTimeType> queue; std::string const source("Hello world!!"); auto const type = MyRunTimeType::make<decltype(source)>(); auto put = queue.start_reentrant_dyn_push_copy(type, &source); put.commit(); //! [conc_heter_queue start_reentrant_dyn_push_copy example 1] } { //! [conc_heter_queue start_reentrant_dyn_push_move example 1] using MyRunTimeType = runtime_type<f_move_construct, f_destroy, f_size, f_alignment>; conc_heter_queue<MyRunTimeType> queue; std::string source("Hello world!!"); auto const type = MyRunTimeType::make<decltype(source)>(); auto put = queue.start_reentrant_dyn_push_move(type, &source); put.commit(); //! [conc_heter_queue start_reentrant_dyn_push_move example 1] } } void conc_heterogeneous_queue_reentrant_put_transaction_samples() { using namespace density; { //! [conc_heter_queue reentrant_put_transaction default_construct example 1] conc_heter_queue<>::reentrant_put_transaction<> transaction; assert(transaction.empty()); //! [conc_heter_queue reentrant_put_transaction default_construct example 1] } { //! [conc_heter_queue reentrant_put_transaction copy_construct example 1] static_assert( !std::is_copy_constructible<conc_heter_queue<>::reentrant_put_transaction<>>::value, ""); static_assert( !std::is_copy_constructible< conc_heter_queue<int>::reentrant_put_transaction<>>::value, ""); //! [conc_heter_queue reentrant_put_transaction copy_construct example 1] } { //! [conc_heter_queue reentrant_put_transaction copy_assign example 1] static_assert( !std::is_copy_assignable<conc_heter_queue<>::reentrant_put_transaction<>>::value, ""); static_assert( !std::is_copy_assignable<conc_heter_queue<int>::reentrant_put_transaction<>>::value, ""); //! [conc_heter_queue reentrant_put_transaction copy_assign example 1] } { //! [conc_heter_queue reentrant_put_transaction move_construct example 1] conc_heter_queue<> queue; auto transaction1 = queue.start_reentrant_push(1); // move from transaction1 to transaction2 auto transaction2(std::move(transaction1)); assert(transaction1.empty()); assert(transaction2.element() == 1); // commit transaction2 transaction2.commit(); assert(transaction2.empty()); //! [conc_heter_queue reentrant_put_transaction move_construct example 1] //! [conc_heter_queue reentrant_put_transaction move_construct example 2] // reentrant_put_transaction<void> can be move constructed from any reentrant_put_transaction<T> static_assert( std::is_constructible< conc_heter_queue<>::reentrant_put_transaction<void>, conc_heter_queue<>::reentrant_put_transaction<void> &&>::value, ""); static_assert( std::is_constructible< conc_heter_queue<>::reentrant_put_transaction<void>, conc_heter_queue<>::reentrant_put_transaction<int> &&>::value, ""); // reentrant_put_transaction<T> can be move constructed only from reentrant_put_transaction<T> static_assert( !std::is_constructible< conc_heter_queue<>::reentrant_put_transaction<int>, conc_heter_queue<>::reentrant_put_transaction<void> &&>::value, ""); static_assert( !std::is_constructible< conc_heter_queue<>::reentrant_put_transaction<int>, conc_heter_queue<>::reentrant_put_transaction<float> &&>::value, ""); static_assert( std::is_constructible< conc_heter_queue<>::reentrant_put_transaction<int>, conc_heter_queue<>::reentrant_put_transaction<int> &&>::value, ""); //! [conc_heter_queue reentrant_put_transaction move_construct example 2] } { //! [conc_heter_queue reentrant_put_transaction move_assign example 1] conc_heter_queue<> queue; auto transaction1 = queue.start_reentrant_push(1); conc_heter_queue<>::reentrant_put_transaction<> transaction2; transaction2 = queue.start_reentrant_push(1); transaction2 = std::move(transaction1); assert(transaction1.empty()); transaction2.commit(); assert(transaction2.empty()); //! [conc_heter_queue reentrant_put_transaction move_assign example 1] //! [conc_heter_queue reentrant_put_transaction move_assign example 2] // reentrant_put_transaction<void> can be move assigned from any reentrant_put_transaction<T> static_assert( std::is_assignable< conc_heter_queue<>::reentrant_put_transaction<void>, conc_heter_queue<>::reentrant_put_transaction<void> &&>::value, ""); static_assert( std::is_assignable< conc_heter_queue<>::reentrant_put_transaction<void>, conc_heter_queue<>::reentrant_put_transaction<int> &&>::value, ""); // reentrant_put_transaction<T> can be move assigned only from reentrant_put_transaction<T> static_assert( !std::is_assignable< conc_heter_queue<>::reentrant_put_transaction<int>, conc_heter_queue<>::reentrant_put_transaction<void> &&>::value, ""); static_assert( !std::is_assignable< conc_heter_queue<>::reentrant_put_transaction<int>, conc_heter_queue<>::reentrant_put_transaction<float> &&>::value, ""); static_assert( std::is_assignable< conc_heter_queue<>::reentrant_put_transaction<int>, conc_heter_queue<>::reentrant_put_transaction<int> &&>::value, ""); //! [conc_heter_queue reentrant_put_transaction move_assign example 2] } { //! [conc_heter_queue reentrant_put_transaction raw_allocate example 1] conc_heter_queue<> queue; struct Msg { std::chrono::high_resolution_clock::time_point m_time = std::chrono::high_resolution_clock::now(); size_t m_len = 0; void * m_data = nullptr; }; auto post_message = [&queue](const void * i_data, size_t i_len) { auto transaction = queue.start_reentrant_emplace<Msg>(); transaction.element().m_len = i_len; transaction.element().m_data = transaction.raw_allocate(i_len, 1); memcpy(transaction.element().m_data, i_data, i_len); assert( !transaction .empty()); // a put transaction is not empty if it's bound to an element being put transaction.commit(); assert(transaction.empty()); // the commit makes the transaction empty }; auto const start_time = std::chrono::high_resolution_clock::now(); auto consume_all_msgs = [&queue, &start_time] { while (auto consume = queue.try_start_reentrant_consume()) { auto const checksum = compute_checksum(consume.element<Msg>().m_data, consume.element<Msg>().m_len); std::cout << "Message with checksum " << checksum << " at "; std::cout << (consume.element<Msg>().m_time - start_time).count() << std::endl; consume.commit(); } }; int msg_1 = 42, msg_2 = 567; post_message(&msg_1, sizeof(msg_1)); post_message(&msg_2, sizeof(msg_2)); consume_all_msgs(); //! [conc_heter_queue reentrant_put_transaction raw_allocate example 1] } { conc_heter_queue<> queue; //! [conc_heter_queue reentrant_put_transaction raw_allocate_copy example 1] struct Msg { size_t m_len = 0; char * m_chars = nullptr; }; auto post_message = [&queue](const char * i_data, size_t i_len) { auto transaction = queue.start_reentrant_emplace<Msg>(); transaction.element().m_len = i_len; transaction.element().m_chars = transaction.raw_allocate_copy(i_data, i_data + i_len); memcpy(transaction.element().m_chars, i_data, i_len); transaction.commit(); }; //! [conc_heter_queue reentrant_put_transaction raw_allocate_copy example 1] (void)post_message; } { conc_heter_queue<> queue; //! [conc_heter_queue reentrant_put_transaction raw_allocate_copy example 2] struct Msg { char * m_chars = nullptr; }; auto post_message = [&queue](const std::string & i_string) { auto transaction = queue.start_reentrant_emplace<Msg>(); transaction.element().m_chars = transaction.raw_allocate_copy(i_string); transaction.commit(); }; //! [conc_heter_queue reentrant_put_transaction raw_allocate_copy example 2] (void)post_message; } { conc_heter_queue<> queue; //! [conc_heter_queue reentrant_put_transaction empty example 1] conc_heter_queue<>::reentrant_put_transaction<> transaction; assert(transaction.empty()); transaction = queue.start_reentrant_push(1); assert(!transaction.empty()); //! [conc_heter_queue reentrant_put_transaction empty example 1] } { conc_heter_queue<> queue; //! [conc_heter_queue reentrant_put_transaction operator_bool example 1] conc_heter_queue<>::reentrant_put_transaction<> transaction; assert(!transaction); transaction = queue.start_reentrant_push(1); assert(transaction); //! [conc_heter_queue reentrant_put_transaction operator_bool example 1] } { conc_heter_queue<> queue; //! [conc_heter_queue reentrant_put_transaction queue example 1] conc_heter_queue<>::reentrant_put_transaction<> transaction; assert(transaction.queue() == nullptr); transaction = queue.start_reentrant_push(1); assert(transaction.queue() == &queue); //! [conc_heter_queue reentrant_put_transaction queue example 1] } { //! [conc_heter_queue reentrant_put_transaction cancel example 1] conc_heter_queue<> queue; // start and cancel a put assert(queue.empty()); auto put = queue.start_reentrant_push(42); /* assert(queue.empty()); <- this assert would trigger an undefined behavior, because it would access the queue during a non-reentrant put transaction. */ assert(!put.empty()); put.cancel(); assert(queue.empty() && put.empty()); // start and commit a put put = queue.start_reentrant_push(42); put.commit(); assert(queue.try_start_reentrant_consume().element<int>() == 42); //! [conc_heter_queue reentrant_put_transaction cancel example 1] } { conc_heter_queue<> queue; //! [conc_heter_queue reentrant_put_transaction element_ptr example 1] int value = 42; auto put = queue.start_reentrant_dyn_push_copy(runtime_type<>::make<decltype(value)>(), &value); assert(*static_cast<int *>(put.element_ptr()) == 42); std::cout << "Putting an " << put.complete_type().type_info().name() << "..." << std::endl; put.commit(); //! [conc_heter_queue reentrant_put_transaction element_ptr example 1] //! [conc_heter_queue reentrant_put_transaction element_ptr example 2] auto put_1 = queue.start_reentrant_push(1); assert(*static_cast<int *>(put_1.element_ptr()) == 1); // this is fine assert(put_1.element() == 1); // this is better put_1.commit(); //! [conc_heter_queue reentrant_put_transaction element_ptr example 2] } { conc_heter_queue<> queue; //! [conc_heter_queue reentrant_put_transaction complete_type example 1] int value = 42; auto put = queue.start_reentrant_dyn_push_copy(runtime_type<>::make<decltype(value)>(), &value); assert(put.complete_type().is<int>()); std::cout << "Putting an " << put.complete_type().type_info().name() << "..." << std::endl; //! [conc_heter_queue reentrant_put_transaction complete_type example 1] } { conc_heter_queue<> queue; //! [conc_heter_queue reentrant_put_transaction destroy example 1] queue.start_reentrant_push( 42); /* this transaction is destroyed without being committed, so it gets canceled automatically. */ //! [conc_heter_queue reentrant_put_transaction destroy example 1] } { conc_heter_queue<> queue; //! [conc_heter_queue reentrant_typed_put_transaction element example 1] int value = 42; auto untyped_put = queue.start_reentrant_dyn_push_copy(runtime_type<>::make<decltype(value)>(), &value); auto typed_put = queue.start_reentrant_push(42.); /* typed_put = std::move(untyped_put); <- this would not compile: can't assign an untyped transaction to a typed transaction */ assert(typed_put.element() == 42.); //! [conc_heter_queue reentrant_typed_put_transaction element example 1] } } void conc_heterogeneous_queue_reentrant_consume_operation_samples() { using namespace density; { conc_heter_queue<> queue; //! [conc_heter_queue reentrant_consume_operation default_construct example 1] conc_heter_queue<>::reentrant_consume_operation consume; assert(consume.empty()); //! [conc_heter_queue reentrant_consume_operation default_construct example 1] } //! [conc_heter_queue reentrant_consume_operation copy_construct example 1] static_assert( !std::is_copy_constructible<conc_heter_queue<>::reentrant_consume_operation>::value, ""); //! [conc_heter_queue reentrant_consume_operation copy_construct example 1] //! [conc_heter_queue reentrant_consume_operation copy_assign example 1] static_assert( !std::is_copy_assignable<conc_heter_queue<>::reentrant_consume_operation>::value, ""); //! [conc_heter_queue reentrant_consume_operation copy_assign example 1] { //! [conc_heter_queue reentrant_consume_operation move_construct example 1] conc_heter_queue<> queue; queue.push(42); auto consume = queue.try_start_reentrant_consume(); auto consume_1 = std::move(consume); assert(consume.empty() && !consume_1.empty()); consume_1.commit(); //! [conc_heter_queue reentrant_consume_operation move_construct example 1] } { //! [conc_heter_queue reentrant_consume_operation move_assign example 1] conc_heter_queue<> queue; queue.push(42); queue.push(43); auto consume = queue.try_start_reentrant_consume(); consume.cancel(); conc_heter_queue<>::reentrant_consume_operation consume_1; consume = queue.try_start_reentrant_consume(); consume_1 = std::move(consume); assert(consume.empty()); assert(!consume_1.empty()); consume_1.commit(); //! [conc_heter_queue reentrant_consume_operation move_assign example 1] } { //! [conc_heter_queue reentrant_consume_operation destroy example 1] conc_heter_queue<> queue; queue.push(42); // this consumed is started and destroyed before being committed, so it has no observable effects queue.try_start_reentrant_consume(); //! [conc_heter_queue reentrant_consume_operation destroy example 1] } { //! [conc_heter_queue reentrant_consume_operation empty example 1] conc_heter_queue<> queue; queue.push(42); conc_heter_queue<>::reentrant_consume_operation consume; assert(consume.empty()); consume = queue.try_start_reentrant_consume(); assert(!consume.empty()); //! [conc_heter_queue reentrant_consume_operation empty example 1] } { //! [conc_heter_queue reentrant_consume_operation operator_bool example 1] conc_heter_queue<> queue; queue.push(42); conc_heter_queue<>::reentrant_consume_operation consume; assert(consume.empty() == !consume); consume = queue.try_start_reentrant_consume(); assert(consume.empty() == !consume); //! [conc_heter_queue reentrant_consume_operation operator_bool example 1] } { //! [conc_heter_queue reentrant_consume_operation queue example 1] conc_heter_queue<> queue; queue.push(42); conc_heter_queue<>::reentrant_consume_operation consume; assert(consume.empty() && !consume && consume.queue() == nullptr); consume = queue.try_start_reentrant_consume(); assert(!consume.empty() && !!consume && consume.queue() == &queue); //! [conc_heter_queue reentrant_consume_operation queue example 1] } { //! [conc_heter_queue reentrant_consume_operation commit_nodestroy example 1] conc_heter_queue<> queue; queue.emplace<std::string>("abc"); conc_heter_queue<>::reentrant_consume_operation consume = queue.try_start_reentrant_consume(); consume.complete_type().destroy(consume.element_ptr()); // the string has already been destroyed. Calling commit would trigger an undefined behavior consume.commit_nodestroy(); //! [conc_heter_queue reentrant_consume_operation commit_nodestroy example 1] } { //! [conc_heter_queue reentrant_consume_operation swap example 1] conc_heter_queue<> queue; queue.push(42); conc_heter_queue<>::reentrant_consume_operation consume_1 = queue.try_start_reentrant_consume(); conc_heter_queue<>::reentrant_consume_operation consume_2; { using namespace std; swap(consume_1, consume_2); } assert(consume_2.complete_type().is<int>()); assert( consume_2.complete_type() == runtime_type<>::make<int>()); // same to the previous assert assert(consume_2.element<int>() == 42); consume_2.commit(); assert(queue.empty()); //! [conc_heter_queue reentrant_consume_operation swap example 1] } { //! [conc_heter_queue reentrant_consume_operation cancel example 1] conc_heter_queue<> queue; queue.push(42); conc_heter_queue<>::reentrant_consume_operation consume = queue.try_start_reentrant_consume(); consume.cancel(); // there is still a 42 in the queue assert(queue.try_start_reentrant_consume().element<int>() == 42); //! [conc_heter_queue reentrant_consume_operation cancel example 1] } { //! [conc_heter_queue reentrant_consume_operation complete_type example 1] conc_heter_queue<> queue; queue.push(42); conc_heter_queue<>::reentrant_consume_operation consume = queue.try_start_reentrant_consume(); assert(consume.complete_type().is<int>()); assert( consume.complete_type() == runtime_type<>::make<int>()); // same to the previous assert consume.commit(); assert(queue.empty()); //! [conc_heter_queue reentrant_consume_operation complete_type example 1] } { //! [conc_heter_queue reentrant_consume_operation element_ptr example 1] conc_heter_queue<> queue; queue.push(42); conc_heter_queue<>::reentrant_consume_operation consume = queue.try_start_reentrant_consume(); ++*static_cast<int *>(consume.element_ptr()); assert(consume.element<int>() == 43); consume.commit(); //! [conc_heter_queue reentrant_consume_operation element_ptr example 1] } { //! [conc_heter_queue reentrant_consume_operation unaligned_element_ptr example 1] conc_heter_queue<> queue; queue.push(42); conc_heter_queue<>::reentrant_consume_operation consume = queue.try_start_reentrant_consume(); bool const is_overaligned = alignof(int) > conc_heter_queue<>::min_alignment; void * const unaligned_ptr = consume.unaligned_element_ptr(); int * element_ptr; if (is_overaligned) { element_ptr = static_cast<int *>(address_upper_align(unaligned_ptr, alignof(int))); } else { assert(unaligned_ptr == consume.element_ptr()); element_ptr = static_cast<int *>(unaligned_ptr); } assert(address_is_aligned(element_ptr, alignof(int))); std::cout << "An int: " << *element_ptr << std::endl; consume.commit(); //! [conc_heter_queue reentrant_consume_operation unaligned_element_ptr example 1] } { //! [conc_heter_queue reentrant_consume_operation element example 1] conc_heter_queue<> queue; queue.push(42); conc_heter_queue<>::reentrant_consume_operation consume = queue.try_start_reentrant_consume(); assert(consume.complete_type().is<int>()); std::cout << "An int: " << consume.element<int>() << std::endl; /* std::cout << "An float: " << consume.element<float>() << std::endl; this would trigger an undefined behavior, because the element is not a float */ consume.commit(); //! [conc_heter_queue reentrant_consume_operation element example 1] } } void conc_heterogeneous_queue_samples_1() { //! [conc_heter_queue example 3] using namespace density; /* a runtime_type is internally like a pointer to a v-table, but it can contain functions or data (like in the case of f_size and f_alignment). */ using MyRunTimeType = runtime_type< f_default_construct, f_copy_construct, f_destroy, f_size, f_alignment, f_ostream, f_istream, f_rtti>; conc_heter_queue<MyRunTimeType> queue; queue.push(4); queue.push(std::complex<double>(1., 4.)); queue.emplace<std::string>("Hello!!"); // queue.emplace<std::thread>(); - This would not compile because std::thread does not have a << operator for streams // consume all the elements while (auto consume = queue.try_start_consume()) { /* this is like: give me the function at the 6-th row in the v-table. The type f_ostream is converted to an index at compile time. */ auto const ostream_feature = consume.complete_type().get_feature<f_ostream>(); ostream_feature(std::cout, consume.element_ptr()); // this invokes the feature std::cout << "\n"; consume .commit(); // don't forget the commit, otherwise the element will remain in the queue } //! [conc_heter_queue example 3] //! [conc_heter_queue example 4] // this local function reads from std::cin an object of a given type and puts it in the queue auto ask_and_put = [&](const MyRunTimeType & i_type) { // for this we exploit the feature f_rtti that we have included in MyRunTimeType std::cout << "Enter a " << i_type.type_info().name() << std::endl; auto const istream_feature = i_type.get_feature<f_istream>(); auto put = queue.start_dyn_push(i_type); istream_feature(std::cin, put.element_ptr()); /* if an exception is thrown before the commit, the put is canceled without ever having observable side effects. */ put.commit(); }; ask_and_put(MyRunTimeType::make<int>()); ask_and_put(MyRunTimeType::make<std::string>()); //! [conc_heter_queue example 4] } void conc_heterogeneous_queue_samples(std::ostream & i_ostream) { PrintScopeDuration dur(i_ostream, "concurrent heterogeneous queue samples"); using namespace density; { //! [conc_heter_queue put example 1] conc_heter_queue<> queue; queue.push(19); // the parameter can be an l-value or an r-value queue.emplace<std::string>(8, '*'); // pushes "********" //! [conc_heter_queue put example 1] //! [conc_heter_queue example 2] auto consume = queue.try_start_consume(); int my_int = consume.element<int>(); consume.commit(); consume = queue.try_start_consume(); std::string my_string = consume.element<std::string>(); consume.commit(); //! [conc_heter_queue example 3 (void)my_int; (void)my_string; } { //! [conc_heter_queue put example 2] conc_heter_queue<> queue; struct MessageInABottle { const char * m_text = nullptr; }; auto transaction = queue.start_emplace<MessageInABottle>(); transaction.element().m_text = transaction.raw_allocate_copy("Hello world!"); transaction.commit(); //! [conc_heter_queue put example 2] //! [conc_heter_queue consume example 1] auto consume = queue.try_start_consume(); if (consume.complete_type().is<std::string>()) { std::cout << consume.element<std::string>() << std::endl; } else if (consume.complete_type().is<MessageInABottle>()) { std::cout << consume.element<MessageInABottle>().m_text << std::endl; } consume.commit(); //! [conc_heter_queue consume example 1] } { //! [conc_heter_queue default_construct example 1] conc_heter_queue<> queue; assert(queue.empty()); //! [conc_heter_queue default_construct example 1] } { //! [conc_heter_queue move_construct example 1] using MyRunTimeType = runtime_type< f_default_construct, f_copy_construct, f_destroy, f_size, f_alignment, f_equal>; conc_heter_queue<MyRunTimeType> queue; queue.push(std::string()); queue.push(std::make_pair(4., 1)); conc_heter_queue<MyRunTimeType> queue_1(std::move(queue)); assert(queue.empty()); assert(!queue_1.empty()); //! [conc_heter_queue move_construct example 1] } { //! [conc_heter_queue construct_copy_alloc example 1] default_allocator allocator; conc_heter_queue<> queue(allocator); assert(queue.empty()); //! [conc_heter_queue construct_copy_alloc example 1] } { //! [conc_heter_queue construct_move_alloc example 1] default_allocator allocator; conc_heter_queue<> queue(std::move(allocator)); assert(queue.empty()); //! [conc_heter_queue construct_move_alloc example 1] } { //! [conc_heter_queue move_assign example 1] using MyRunTimeType = runtime_type< f_default_construct, f_copy_construct, f_destroy, f_size, f_alignment, f_equal>; conc_heter_queue<MyRunTimeType> queue; queue.push(std::string()); queue.push(std::make_pair(4., 1)); conc_heter_queue<MyRunTimeType> queue_1; queue_1 = std::move(queue); assert(queue.empty()); assert(!queue_1.empty()); //! [conc_heter_queue move_assign example 1] } { //! [conc_heter_queue get_allocator example 1] conc_heter_queue<> queue; assert(queue.get_allocator() == default_allocator()); //! [conc_heter_queue get_allocator example 1] } { //! [conc_heter_queue get_allocator_ref example 1] conc_heter_queue<> queue; assert(queue.get_allocator_ref() == default_allocator()); //! [conc_heter_queue get_allocator_ref example 1] } { //! [conc_heter_queue get_allocator_ref example 2] conc_heter_queue<> queue; auto const & queue_ref = queue; assert(queue_ref.get_allocator_ref() == default_allocator()); //! [conc_heter_queue get_allocator_ref example 2] (void)queue_ref; } { //! [conc_heter_queue swap example 1] conc_heter_queue<> queue, queue_1; queue.push(1); swap(queue, queue_1); assert(queue.empty()); assert(!queue_1.empty()); //! [conc_heter_queue swap example 1] } { //! [conc_heter_queue swap example 2] conc_heter_queue<> queue, queue_1; queue.push(1); { using namespace std; swap(queue, queue_1); } assert(queue.empty()); assert(!queue_1.empty()); //! [conc_heter_queue swap example 2] } { //! [conc_heter_queue empty example 1] conc_heter_queue<> queue; assert(queue.empty()); queue.push(1); assert(!queue.empty()); //! [conc_heter_queue empty example 1] } { //! [conc_heter_queue clear example 1] conc_heter_queue<> queue; queue.push(1); queue.clear(); assert(queue.empty()); //! [conc_heter_queue clear example 1] } { //! [conc_heter_queue pop example 1] conc_heter_queue<> queue; queue.push(1); queue.push(2); queue.pop(); auto consume = queue.try_start_consume(); assert(consume.element<int>() == 2); consume.commit(); //! [conc_heter_queue pop example 1] } { //! [conc_heter_queue try_pop example 1] conc_heter_queue<> queue; bool pop_result = queue.try_pop(); assert(pop_result == false); queue.push(1); queue.push(2); pop_result = queue.try_pop(); assert(pop_result == true); auto consume = queue.try_start_consume(); assert(consume.element<int>() == 2); consume.commit(); //! [conc_heter_queue try_pop example 1] (void)pop_result; } { //! [conc_heter_queue try_start_consume example 1] conc_heter_queue<> queue; auto consume_1 = queue.try_start_consume(); assert(!consume_1); queue.push(42); auto consume_2 = queue.try_start_consume(); assert(consume_2); assert(consume_2.element<int>() == 42); consume_2.commit(); //! [conc_heter_queue try_start_consume example 1] } { //! [conc_heter_queue try_start_consume_ example 1] conc_heter_queue<> queue; conc_heter_queue<>::consume_operation consume_1; bool const bool_1 = queue.try_start_consume(consume_1); assert(!bool_1 && !consume_1); queue.push(42); conc_heter_queue<>::consume_operation consume_2; auto bool_2 = queue.try_start_consume(consume_2); assert(consume_2 && bool_2); assert(consume_2.element<int>() == 42); consume_2.commit(); //! [conc_heter_queue try_start_consume_ example 1] (void)bool_1; (void)bool_2; } { conc_heter_queue<> queue; //! [conc_heter_queue reentrant example 1] // start 3 reentrant put transactions auto put_1 = queue.start_reentrant_push(1); auto put_2 = queue.start_reentrant_emplace<std::string>("Hello world!"); double pi = 3.14; auto put_3 = queue.start_reentrant_dyn_push_copy(runtime_type<>::make<double>(), &pi); assert( queue.empty()); // the queue is still empty, because no transaction has been committed // commit and start consuming "Hello world!" put_2.commit(); auto consume2 = queue.try_start_reentrant_consume(); assert(!consume2.empty() && consume2.complete_type().is<std::string>()); // commit and start consuming 1 put_1.commit(); auto consume1 = queue.try_start_reentrant_consume(); assert(!consume1.empty() && consume1.complete_type().is<int>()); // cancel 3.14, and commit the consumes put_3.cancel(); consume1.commit(); consume2.commit(); assert(queue.empty()); //! [conc_heter_queue reentrant example 1] } { //! [conc_heter_queue reentrant_pop example 1] conc_heter_queue<> queue; queue.push(1); queue.push(2); queue.reentrant_pop(); auto consume = queue.try_start_consume(); assert(consume.element<int>() == 2); consume.commit(); //! [conc_heter_queue reentrant_pop example 1] } { //! [conc_heter_queue try_reentrant_pop example 1] conc_heter_queue<> queue; bool pop_result = queue.try_reentrant_pop(); assert(pop_result == false); queue.push(1); queue.push(2); pop_result = queue.try_reentrant_pop(); assert(pop_result == true); auto consume = queue.try_start_reentrant_consume(); assert(consume.element<int>() == 2); consume.commit(); //! [conc_heter_queue try_reentrant_pop example 1] (void)pop_result; } { //! [conc_heter_queue try_start_reentrant_consume example 1] conc_heter_queue<> queue; auto consume_1 = queue.try_start_reentrant_consume(); assert(!consume_1); queue.push(42); auto consume_2 = queue.try_start_reentrant_consume(); assert(consume_2); assert(consume_2.element<int>() == 42); consume_2.commit(); //! [conc_heter_queue try_start_reentrant_consume example 1] } { //! [conc_heter_queue try_start_reentrant_consume_ example 1] conc_heter_queue<> queue; conc_heter_queue<>::reentrant_consume_operation consume_1; bool const bool_1 = queue.try_start_reentrant_consume(consume_1); assert(!bool_1 && !consume_1); queue.push(42); conc_heter_queue<>::reentrant_consume_operation consume_2; auto bool_2 = queue.try_start_reentrant_consume(consume_2); assert(consume_2 && bool_2); assert(consume_2.element<int>() == 42); consume_2.commit(); //! [conc_heter_queue try_start_reentrant_consume_ example 1] (void)bool_1; (void)bool_2; } // this samples uses std::cout and std::cin // conc_heterogeneous_queue_samples_1(); conc_heterogeneous_queue_put_samples(); conc_heterogeneous_queue_put_transaction_samples(); conc_heterogeneous_queue_consume_operation_samples(); conc_heterogeneous_queue_reentrant_put_samples(); conc_heterogeneous_queue_reentrant_put_transaction_samples(); conc_heterogeneous_queue_reentrant_consume_operation_samples(); } } // namespace density_tests #if defined(_MSC_VER) && defined(NDEBUG) #pragma warning(pop) #endif
41.272109
125
0.574943
giucamp
300045ee0e2efaeecde3a8fb9d02197701b34471
2,962
cpp
C++
leveldb_rest.cpp
nucleati/leveldb_rest
921116a58bfed934d25b06675ed51c98fa3ea903
[ "MIT" ]
null
null
null
leveldb_rest.cpp
nucleati/leveldb_rest
921116a58bfed934d25b06675ed51c98fa3ea903
[ "MIT" ]
null
null
null
leveldb_rest.cpp
nucleati/leveldb_rest
921116a58bfed934d25b06675ed51c98fa3ea903
[ "MIT" ]
null
null
null
#include </Simple-Web-Server/client_http.hpp> #include </Simple-Web-Server/server_http.hpp> #include <future> // Added for the json-example #define BOOST_SPIRIT_THREADSAFE #include <boost/property_tree/json_parser.hpp> #include <boost/property_tree/ptree.hpp> #include <algorithm> #include <boost/filesystem.hpp> #include <fstream> #include <vector> #include <map> #ifdef HAVE_OPENSSL #include "crypto.hpp" #endif #include "config/config.hpp" #include "set_endpoints.hpp" #include "leveldb/db.h" #include "leveldb/write_batch.h" #include "leveldb/filter_policy.h" using namespace std; // Added for the json-example: using namespace boost::property_tree; using HttpServer = SimpleWeb::Server<SimpleWeb::HTTP>; using HttpClient = SimpleWeb::Client<SimpleWeb::HTTP>; int main(int argc, char** argv) { Config config; if(argc != 2) { std::cerr << "Can't start server without configuration file: " << std::endl; std::cerr << "Correct use: " << argv[0] << " configuration.json" << endl; return(-1); } else { try{ char* filename = argv[1]; config.readJson(filename); } catch(...){ throw("Something went wrong while reading configuration file."); } } HttpServer server; server.config.port = std::stoi(config.getValue("port")); std::map<std::string, leveldb::DB*> ldbs; leveldb::Options options; options.create_if_missing = true; // User/Project database for(unsigned i = 0 ; i < config.config_tree->get_child("dbs").size() ; i++){ std::string db_name = "dbs.[" + std::to_string(i) + "].db"; std::string db_mount = "dbs.[" + std::to_string(i) + "].mp"; std::string db_path = "dbs.[" + std::to_string(i) + "].path"; std::string db_name_and_path = config.getValue(db_path) + config.getValue(db_name) ; leveldb::DB* db; leveldb::Status status = leveldb::DB::Open(options, db_name_and_path, &db) ; std::cout << "Received handle from database : " << db_name_and_path << std::endl; if (false == status.ok()){ cout << "Unable to open database " << db_name_and_path << " ." << endl; cout << status.ToString() << endl; return -1; } // Set up paths for requests std::string dbm = config.getValue(db_mount); set_endpoints(server, db, dbm); } server.on_error = [](shared_ptr<HttpServer::Request> /*request*/, const SimpleWeb::error_code & /*ec*/) { // Handle errors here // Note that connection timeouts will also call this handle with ec set to SimpleWeb::errc::operation_canceled }; // Start server and receive assigned port when server is listening for requests promise<unsigned short> server_port; thread server_thread([&server, &server_port]() { // Start server server.start([&server_port](unsigned short port) { server_port.set_value(port); }); }); cout << "Server listening on port " << server_port.get_future().get() << endl << endl; server_thread.join(); }
29.62
114
0.664416
nucleati
30066a5ff92dc6432fa71d3d12d9d629e0e896bc
3,912
cpp
C++
src/cpp/server.cpp
MayaPosch/NymphMQTT
10707ba763606424ab2b81e310cb53a38fa66687
[ "BSD-3-Clause" ]
14
2019-11-15T18:19:35.000Z
2022-02-03T12:09:14.000Z
src/cpp/server.cpp
MayaPosch/NymphMQTT
10707ba763606424ab2b81e310cb53a38fa66687
[ "BSD-3-Clause" ]
null
null
null
src/cpp/server.cpp
MayaPosch/NymphMQTT
10707ba763606424ab2b81e310cb53a38fa66687
[ "BSD-3-Clause" ]
1
2020-03-20T22:45:14.000Z
2020-03-20T22:45:14.000Z
/* server.cpp - Definition of the NymphMQTT server class. Revision 0. Features: - Provides public API for NymphMQTT server. Notes: - 2021/01/03, Maya Posch */ #include "server.h" #include "dispatcher.h" #include "nymph_logger.h" #include "session.h" #include "server_connections.h" #include <Poco/Net/NetException.h> #include <Poco/NumberFormatter.h> // Static initialisations. long NmqttServer::timeout = 3000; string NmqttServer::loggerName = "NmqttServer"; Poco::Net::ServerSocket NmqttServer::ss; Poco::Net::TCPServer* NmqttServer::server; // --- CONSTRUCTOR --- NmqttServer::NmqttServer() { // } // --- DECONSTRUCTOR --- NmqttServer::~NmqttServer() { // } // --- INIT --- // Initialise the runtime. bool NmqttServer::init(std::function<void(int, std::string)> logger, int level, long timeout) { NmqttServer::timeout = timeout; setLogger(logger, level); // Set the function pointers for the command handlers. NmqttClientSocket ns; //using namespace std::placeholders; ns.connectHandler = &NmqttServer::connectHandler; //std::bind(&NmqttServer::connectHandler, this, _1); ns.pingreqHandler = &NmqttServer::pingreqHandler; //std::bind(&NmqttServer::pingreqHandler, this, _1); NmqttClientConnections::setCoreParameters(ns); // Start the dispatcher runtime. // Get the number of concurrent threads supported by the system we are running on. int numThreads = std::thread::hardware_concurrency(); // Initialise the Dispatcher with the maximum number of threads as worker count. Dispatcher::init(numThreads); return true; } // --- SET LOGGER --- // Sets the logger function to be used by the Nymph Logger class, along with the // desired maximum log level: // NYMPH_LOG_LEVEL_FATAL = 1, // NYMPH_LOG_LEVEL_CRITICAL, // NYMPH_LOG_LEVEL_ERROR, // NYMPH_LOG_LEVEL_WARNING, // NYMPH_LOG_LEVEL_NOTICE, // NYMPH_LOG_LEVEL_INFO, // NYMPH_LOG_LEVEL_DEBUG, // NYMPH_LOG_LEVEL_TRACE void NmqttServer::setLogger(std::function<void(int, std::string)> logger, int level) { NymphLogger::setLoggerFunction(logger); NymphLogger::setLogLevel((Poco::Message::Priority) level); } // --- START --- bool NmqttServer::start(int port) { try { // Create a server socket that listens on all interfaces, IPv4 and IPv6. // Assign it to the new TCPServer. ss.bind6(port, true, false); // Port, SO_REUSEADDR, IPv6-only. ss.listen(); server = new Poco::Net::TCPServer( new Poco::Net::TCPServerConnectionFactoryImpl<NmqttSession>(), ss); server->start(); } catch (Poco::Net::NetException& e) { NYMPH_LOG_ERROR("Error starting TCP server: " + e.message()); return false; } //running = true; return true; } // --- SEND MESSAGE --- // Private method for sending data to a remote broker. bool NmqttServer::sendMessage(uint64_t handle, std::string binMsg) { NmqttClientSocket* clientSocket = NmqttClientConnections::getSocket(handle); try { int ret = clientSocket->socket->sendBytes(((const void*) binMsg.c_str()), binMsg.length()); if (ret != binMsg.length()) { // Handle error. NYMPH_LOG_ERROR("Failed to send message. Not all bytes sent."); return false; } NYMPH_LOG_DEBUG("Sent " + Poco::NumberFormatter::format(ret) + " bytes."); } catch (Poco::Exception &e) { NYMPH_LOG_ERROR("Failed to send message: " + e.message()); return false; } return true; } // --- CONNECT HANDLER --- // Process connection. Return CONNACK response. void NmqttServer::connectHandler(uint64_t handle) { NmqttMessage msg(MQTT_CONNACK); sendMessage(handle, msg.serialize()); } // --- PINGREQ HANDLER --- // Reply to ping response from a client. void NmqttServer::pingreqHandler(uint64_t handle) { NmqttMessage msg(MQTT_PINGRESP); sendMessage(handle, msg.serialize()); } // --- SHUTDOWN --- // Shutdown the runtime. Close any open connections and clean up resources. bool NmqttServer::shutdown() { server->stop(); return true; }
25.23871
103
0.712168
MayaPosch
3007f8e7f05243b560d509242b738c2e8b0e31a0
26,219
cpp
C++
private/shell/ext/mydocs/src/idlist.cpp
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
11
2017-09-02T11:27:08.000Z
2022-01-02T15:25:24.000Z
private/shell/ext/mydocs/src/idlist.cpp
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
null
null
null
private/shell/ext/mydocs/src/idlist.cpp
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
14
2019-01-16T01:01:23.000Z
2022-02-20T15:54:27.000Z
/*---------------------------------------------------------------------------- / Title; / idlist.cpp / / Authors; / Rick Turner (ricktu) / / Notes; /----------------------------------------------------------------------------*/ #include "precomp.hxx" #include "stddef.h" #pragma hdrstop /*----------------------------------------------------------------------------- / IDLISTs are opaque structures, they can be stored at any aligment, ours / contain the following data. However this should not be treated as the / public version. The pack and unpack functions below are responsible for / generating this structure, use those. /----------------------------------------------------------------------------*/ #pragma pack(1) struct _myiconinfo { UINT uIndex; TCHAR szPath[1]; }; struct _myidlist { WORD cbSize; // size of the idlist DWORD dwMagic; // gaurd word DWORD dwFlags; // idlist flags DWORD dwIconOffset; // offset to icon info (present if MDIDL_HASICONINFO) DWORD dwNameOffset; // offset to name info (present if MDIDL_SPECIALITEM) DWORD dwPathOffset; // offset to path info (present if MDIDL_HASPATH) DWORD dwReserved; ITEMIDLIST idl; // shell's idlist (if present) }; #pragma pack() typedef struct _myiconinfo MYICONINFO; typedef UNALIGNED MYICONINFO* LPMYICONINFO; typedef struct _myidlist MYIDLIST; typedef UNALIGNED MYIDLIST* LPMYIDLIST; /*----------------------------------------------------------------------------- / IsIDLRootOfNameSpace / --------------------- / Given an idlist, checks to see if it is one that points to the root / our namespace (a regitem pidl w/our class id in it) / / In: / pidl = one of our pidls / / Out: / TRUE or FALSE /----------------------------------------------------------------------------*/ BOOL IsIDLRootOfNameSpace( LPITEMIDLIST pidlIN ) { LPIDREGITEM pidl = (LPIDREGITEM)pidlIN; if ( (pidl->cb == (sizeof(IDREGITEM) - sizeof(WORD))) && (pidl->bFlags == SHID_ROOT_REGITEM) && IsEqualGUID( pidl->clsid, CLSID_MyDocumentsExt) ) { return TRUE; } return FALSE; } /*----------------------------------------------------------------------------- / IsIDLFSJunction / --------------- / Given an idlist & attributes of item, checks to see if the item / is a junction point (i.e., a folder w/a desktop.ini in it). / / In: / pidl / dwAttrb / / Out: / TRUE or FALSE /----------------------------------------------------------------------------*/ BOOL IsIDLFSJunction( LPCITEMIDLIST pidlIN, DWORD dwAttrb ) { LPIDFSITEM pidl = (LPIDFSITEM)pidlIN; if ( (!(dwAttrb & SFGAO_FILESYSTEM)) || (!(dwAttrb & SFGAO_FOLDER)) || (!pidlIN) || ILIsEmpty(pidlIN) ) { return FALSE; } if ( (pidl->bFlags & (SHID_JUNCTION)) && ((pidl->bFlags & SHID_FS_DIRECTORY) || (pidl->bFlags & SHID_FS_DIRUNICODE)) ) { return TRUE; } return FALSE; } /*----------------------------------------------------------------------------- / MDGetPathFromIDL / --------------------- / Given one of our IDLIST, return the relative path to the item... / / In: / pidl = one of our pidls / pPath = buffer of where to store path / / Out: / pointer to the path (should NOT be freed) /----------------------------------------------------------------------------*/ BOOL MDGetPathFromIDL( LPITEMIDLIST pidl, LPTSTR pPath, LPTSTR pRootPath ) { LPMYIDLIST pIDL = (LPMYIDLIST)pidl; LPITEMIDLIST pidlTmp; BOOL fRes = FALSE; TCHAR szPath[ MAX_PATH ]; if (pIDL->dwMagic == MDIDL_MAGIC) { if ( (pIDL->dwFlags & MDIDL_HASNOSHELLPIDL) && (pIDL->dwFlags & MDIDL_HASPATHINFO) ) { UINT cch = MAX_PATH; if (SUCCEEDED(MDGetPathInfoFromIDL( pidl, pPath, &cch ))) return TRUE; else return FALSE; } pidlTmp = &pIDL->idl; } else { pidlTmp = pidl; } if (SHGetPathFromIDList( pidlTmp, szPath )) { if (MDIsSpecialIDL(pidl) || (!pRootPath)) { lstrcpy( pPath, szPath ); } else { LPTSTR pFileName; pFileName = PathFindFileName( szPath ); if (pRootPath && *pRootPath) { lstrcpy( pPath, pRootPath ); if (pPath[lstrlen(pPath)-1] != TEXT('\\')) { lstrcat( pPath, TEXT("\\") ); } lstrcat( pPath, pFileName ); } else { lstrcpy( pPath, pFileName ); } } fRes = TRUE; } return fRes; } /*----------------------------------------------------------------------------- / MDGetFullPathFromIDL / --------------------- / Given one of our IDLIST, return the path to the item walking down the / idlist... / / In: / pidl = one of our pidls / pPath = buffer of where to store path / / Out: / pointer to the path (should NOT be freed) /----------------------------------------------------------------------------*/ BOOL MDGetFullPathFromIDL( LPITEMIDLIST pidl, LPTSTR pPath, LPTSTR pRootPath ) { LPITEMIDLIST pidlClone, pidlTmp; LPTSTR pTmpPath = pPath, pRoot; TCHAR szNull = 0, chLast; pidlClone = ILClone( pidl ); if (pRootPath) pRoot = pRootPath; else pRoot = &szNull; if (!pidlClone) return FALSE; for ( pidlTmp = pidlClone; pidlTmp && !ILIsEmpty(pidlTmp); pidlTmp = ILGetNext( pidlTmp ) ) { LPITEMIDLIST pidlNext = ILGetNext(pidlTmp); WORD cbNext = pidlNext->mkid.cb; pidlNext->mkid.cb = 0; // get the path for this item if (!MDGetPathFromIDL( pidlTmp, pTmpPath, pRoot )) return FALSE; // if there are more items, then tack on a '\' to the end of the path if (cbNext) { for( ; (chLast = *pTmpPath) && chLast; pTmpPath++ ) ; // // only add '\' to end if it isn't already there (as is the case // with a drive --> c:\ // if (chLast != TEXT('\\')) { *pTmpPath++ = TEXT('\\'); *pTmpPath = 0; } } pidlNext->mkid.cb = cbNext; pRoot = &szNull; } ILFree( pidlClone ); return TRUE; } /*----------------------------------------------------------------------------- / _WrapSHIDL / --------------------- / Given one of the shell's IDLISTs, return it wrapped in one of our own... / / In: / pidlShell = one of the shell's pidls / / Out: / pidl (one of ours) /----------------------------------------------------------------------------*/ LPMYIDLIST _WrapSHIDL( LPITEMIDLIST pidlRoot, LPITEMIDLIST pidlShell, LPTSTR pPath ) { LPMYIDLIST pidl; LPITEMIDLIST pidlCombine; UINT cb; DWORD dw; TCHAR szPath[ MAX_PATH ]; MDTraceEnter( TRACE_IDLIST, "_WrapSHIDL" ); // MDTrace(TEXT("Incoming: pidlRoot = %08X, pidl = %08X"), pidlRoot, pidlShell ); if (pidlRoot) { pidlCombine = ILCombine( pidlRoot, pidlShell ); } else { pidlCombine = pidlShell; } cb = ILGetSize( pidlCombine ); pidl = (LPMYIDLIST)SHAlloc( cb + sizeof(MYIDLIST) ); if (pidl) { memset( pidl, 0, cb + sizeof(MYIDLIST) ); pidl->cbSize = cb + sizeof(MYIDLIST) - sizeof(WORD); pidl->dwMagic = MDIDL_MAGIC; memcpy( (LPVOID)&(pidl->idl), pidlCombine, cb ); } if (!pPath) { SHGetPathFromIDList( pidlCombine, szPath ); pPath = szPath; } // // If this item is directory, mark it is a junction... // dw = GetFileAttributes( pPath ); if (dw!=0xFFFFFFFF) { if (dw & FILE_ATTRIBUTE_DIRECTORY) { pidl->dwFlags |= MDIDL_ISJUNCTION; } } // MDTrace(TEXT("Outgoing pidl is %08X"), pidl ); MDTraceLeave(); return pidl; } /*----------------------------------------------------------------------------- / _UnWrapMDIDL / --------------------- / Given one of our IDLISTs, return a copy of the embedded shell idlist... / / In: / pidlShell = one of the shell's pidls / / Out: / pidl (one of ours) /----------------------------------------------------------------------------*/ LPITEMIDLIST _UnWrapMDIDL( LPMYIDLIST pidl ) { LPITEMIDLIST pidlOut = (LPITEMIDLIST)pidl; MDTraceEnter( TRACE_IDLIST, "_UnWrapMDIDL" ); // MDTrace(TEXT("Incoming pidl is %08X"), pidl ); if (pidl->dwMagic == MDIDL_MAGIC) { if (pidl->dwFlags & MDIDL_HASNOSHELLPIDL) { pidlOut = NULL; } else { pidlOut = &pidl->idl; } } // MDTrace(TEXT("Outgoing pidl is %08X"), pidlOut ); MDTraceLeave(); return pidlOut; } /*----------------------------------------------------------------------------- / MDCreateIDLFromPath / --------------------- / Given a pointer to filename (or UNC path), create an IDLIST from that. / that. / / In: / ppidl = receives a pointer to new IDLIST / pPath = filesystem (or UNC) path to object / / Out: / HRESULT /----------------------------------------------------------------------------*/ HRESULT MDCreateIDLFromPath( LPITEMIDLIST* ppidl, LPTSTR pPath ) { HRESULT hr = S_OK; LPMYIDLIST pidl = NULL; LPITEMIDLIST pidlShell = NULL; MDTraceEnter(TRACE_IDLIST, "MDCreateIDLFromPath"); MDTraceAssert(ppidl); MDTraceAssert(pPath); *ppidl = NULL; // incase we fail // // Get pidl from shell // hr = SHILCreateFromPath( pPath, &pidlShell, NULL ); FailGracefully( hr, "SHILCreateFromPath failed" ); // // Now wrap it... // pidl = _WrapSHIDL( NULL, pidlShell, pPath ); if (!pidl) ExitGracefully( hr, E_FAIL, "_WrapSHIDL failed" ); *ppidl = (LPITEMIDLIST)pidl; // MDTrace( TEXT("returning pidl of %08X"), pidl ); exit_gracefully: DoILFree( pidlShell ); MDTraceLeaveResult(hr); } /*----------------------------------------------------------------------------- / MDWrapShellIDList / --------------------- / Given an array of shell idlists, return an array of MyDocuments idlists / that wrap the shell's idlists. / / In: / celt = number of IDLISTs in array / rgelt = array of IDLISTs / / Out: / HRESULT /----------------------------------------------------------------------------*/ HRESULT MDWrapShellIDLists( LPITEMIDLIST pidlRoot, UINT celtIN, LPITEMIDLIST * rgeltIN, LPITEMIDLIST * rgeltOUT ) { HRESULT hr = S_OK; UINT i; MDTraceEnter( TRACE_IDLIST, "MDWrapShellIDLists" ); if (!celtIN || !rgeltIN || !rgeltOUT) ExitGracefully( hr, E_INVALIDARG, "either bad incoming or outgoing parameters" ); // // Set up prgeltOUT to hold the results... // i = 0; while( i < celtIN ) { rgeltOUT[i] = (LPITEMIDLIST)_WrapSHIDL( pidlRoot, rgeltIN[i], NULL ); if (!rgeltOUT[i]) ExitGracefully( hr, E_FAIL, "Failure to wrap an IDLIST" ); i++; } exit_gracefully: MDTraceLeaveResult(hr); } /*----------------------------------------------------------------------------- / MDUnWrapMDIDList / --------------------- / Given an array of our idlists, return an array of shell idlists. / / In: / celt = number of IDLISTs in array / rgelt = array of IDLISTs / / Out: / HRESULT /----------------------------------------------------------------------------*/ HRESULT MDUnWrapMDIDLists( UINT celtIN, LPITEMIDLIST * rgeltIN, LPITEMIDLIST * rgeltOUT ) { HRESULT hr = S_OK; UINT i; MDTraceEnter( TRACE_IDLIST, "MDUnWrapMDIDLists" ); if (!celtIN || !rgeltIN || !rgeltOUT) ExitGracefully( hr, E_INVALIDARG, "either bad incoming or outgoing parameters" ); // // Set up prgeltOUT to hold the results... // i = 0; while( i < celtIN ) { LPITEMIDLIST pidl = _UnWrapMDIDL( (LPMYIDLIST)rgeltIN[i] ); if (pidl) { rgeltOUT[i] = ILFindLastID(pidl); } else { rgeltOUT[i] = NULL; } if (!rgeltOUT[i]) ExitGracefully( hr, E_FAIL, "Failure to unwrap an IDLIST" ); i++; } exit_gracefully: MDTraceLeaveResult(hr); } /*----------------------------------------------------------------------------- / SHIDLFromMDIDL / --------------------- / If it's one of our pidls, return the embedded shell IDLIST / / In: / pidl = one of our pidls / / Out: / pidl that is shell's embedded pidl /----------------------------------------------------------------------------*/ LPITEMIDLIST SHIDLFromMDIDL( LPCITEMIDLIST pidl ) { LPITEMIDLIST pidlOut = (LPITEMIDLIST)pidl; LPMYIDLIST pIDL = (LPMYIDLIST)pidl; MDTraceEnter( TRACE_IDLIST, "SHIDLFroMDIDL" ); if ( pIDL && (pIDL->dwMagic == MDIDL_MAGIC) ) { if ( ( pIDL->dwFlags & MDIDL_HASNOSHELLPIDL ) ) { pidlOut = NULL; } else { pidlOut = &((LPMYIDLIST)pidl)->idl; } } MDTraceLeave(); return pidlOut; } /*----------------------------------------------------------------------------- / MDCreateSpecialIDL / --------------------- / Return an IDL for the Published Documents folder / / In: / pidl = one of our pidls / / Out: / pidl that is shell's embedded pidl /----------------------------------------------------------------------------*/ LPITEMIDLIST MDCreateSpecialIDL( LPTSTR pPath, LPTSTR pName, LPTSTR pIconPath, UINT uIconIndex ) { HRESULT hr = S_OK; LPMYIDLIST pidl = NULL; UINT cbSize = 0, cbName = 0, cbIconInfo = 0, cbPath = 0; DWORD dwFlags = 0; MDTraceEnter(TRACE_IDLIST, "MDCreateSpecialIDL"); MDTraceAssert(pPath); //#ifdef WINNT // DebugBreak(); //#else // _asm { // int 3; // } //#endif if ((pPath && *pPath)) { #ifdef TRY_TO_STORE_PIDL if (PathFileExists(pPath)) { // // Create a pidl // hr = MDCreateIDLFromPath( (LPITEMIDLIST *)&pidl, pPath ); FailGracefully( hr, "MDCreateIDLFromPath failed" ); } else #endif { cbPath = ((lstrlen(pPath) + 1) * sizeof(TCHAR)); dwFlags |= MDIDL_HASPATHINFO; } } dwFlags |= MDIDL_ISSPECIALITEM; if (pidl) { cbSize = ILGetSize( (LPITEMIDLIST)pidl ) + sizeof(WORD); } else { cbSize = sizeof(MYIDLIST); } // // If there's a display name, make room for it... // if (pName && *pName) { cbName = ((lstrlen(pName) + 1) * sizeof(TCHAR)); dwFlags |= MDIDL_HASNAME; } // // If there's icon information, make room for it... // if (pIconPath && *pIconPath) { // NULL terminator is already in MYICONINFO cbIconInfo = ( sizeof(MYICONINFO) + (lstrlen(pIconPath) * sizeof(TCHAR)) ); dwFlags |= MDIDL_HASICONINFO; } // // Now, combine all the info into one place... // if (cbName || cbIconInfo || cbPath) { UINT cbTotal = cbSize + cbName + cbIconInfo + cbPath; LPITEMIDLIST pidlTemp = (LPITEMIDLIST)SHAlloc( cbTotal ); if (pidlTemp) { memset( pidlTemp, 0, cbTotal ); // // Copy the old stuff and adjust the size field... // if (pidl) { pidl->dwFlags = dwFlags; cbSize -= sizeof(WORD); memcpy( (LPVOID)pidlTemp, (LPVOID)pidl, cbSize ); DoILFree( pidl ); pidlTemp->mkid.cb += sizeof(WORD); } else { ((LPMYIDLIST)pidlTemp)->dwMagic = MDIDL_MAGIC; ((LPMYIDLIST)pidlTemp)->dwFlags = (dwFlags | MDIDL_HASNOSHELLPIDL); cbSize -= sizeof(WORD); ((LPMYIDLIST)pidlTemp)->cbSize = cbSize; } pidl = (LPMYIDLIST)pidlTemp; pidl->cbSize += (cbName + cbIconInfo + cbPath); // // Now insert the new stuff... // if (cbName) { LPTSTR pTmp; pidl->dwNameOffset = cbSize; pTmp = (LPTSTR)((LPBYTE)pidl + pidl->dwNameOffset); lstrcpy( pTmp, pName ); } if (cbIconInfo) { LPMYICONINFO pii; pidl->dwIconOffset = cbSize + cbName; pii = (LPMYICONINFO)((LPBYTE)pidl + pidl->dwIconOffset); pii->uIndex = uIconIndex; lstrcpy( pii->szPath, pIconPath ); } if (cbPath) { LPTSTR pTmp; pidl->dwPathOffset = cbSize + cbName + cbIconInfo; pTmp = (LPTSTR)((LPBYTE)pidl + pidl->dwPathOffset); lstrcpy( pTmp, pPath ); } } else { DoILFree( pidl ) pidl = NULL; } } #if 0 MDTrace(TEXT("pidl->cbSize = %d"), pidl->cbSize ); MDTrace(TEXT("pidl->dwFlags = %08X"), pidl->dwFlags ); if (cbName) MDTrace(TEXT("Name is: -%s-"), (LPTSTR)((LPBYTE)pidl + pidl->dwNameOffset) ); if (cbIconInfo) { LPMYICONINFO pii = (LPMYICONINFO)((LPBYTE)pidl + pidl->dwIconOffset); MDTrace(TEXT("Icon info: %s,%d"), pii->szPath, pii->uIndex ); } MDTrace(TEXT("ILNext(pidl) is %04X"), *((WORD *)((LPBYTE)pidl + pidl->cbSize))); #endif #ifdef TRY_TO_STORE_PIDL exit_gracefully: #endif // MDTrace(TEXT("returning pidl of %08X"), pidl ); MDTraceLeave(); return (LPITEMIDLIST)pidl; } /*----------------------------------------------------------------------------- / MDIsSepcialIDL / --------------------- / Check if this pidl is a special item (ie: PUBLISHED DOCUMENTS) pidl / / In: / pidl / / Out: / TRUE or FALSE /----------------------------------------------------------------------------*/ BOOL MDIsSpecialIDL( LPITEMIDLIST pidl ) { if (pidl && ((sizeof(MYIDLIST) - sizeof(WORD)) <= (pidl->mkid).cb)) { if ( ( ((LPMYIDLIST)pidl)->dwMagic == MDIDL_MAGIC ) && ( ((LPMYIDLIST)pidl)->dwFlags & MDIDL_ISSPECIALITEM ) ) return TRUE; } return FALSE; } /*----------------------------------------------------------------------------- / MDIsJunctionIDL / --------------------- / Check if this pidl represents a junction to a folder / / In: / pidl / / Out: / TRUE or FALSE /----------------------------------------------------------------------------*/ BOOL MDIsJunctionIDL( LPITEMIDLIST pidl ) { if (pidl && ((sizeof(MYIDLIST) - sizeof(WORD)) <= (pidl->mkid).cb)) { if ( ( ((LPMYIDLIST)pidl)->dwMagic == MDIDL_MAGIC ) && ( ((LPMYIDLIST)pidl)->dwFlags & MDIDL_ISJUNCTION ) ) return TRUE; // // HACK: 0x31 is the SHITEMID flags for a folder and // 0x35 is the SHITEMID flags for a unicode folder... // if ( (((_idregitem *)pidl)->bFlags == 0x31) || (((_idregitem *)pidl)->bFlags == 0x35) ) { return TRUE; } } return FALSE; } /*----------------------------------------------------------------------------- / MDGetIconInfoFromIDL / --------------------- / Check if this pidl is a special pidl, and then returns the icon / information if present... / / In: / pidl -> pidl in question / pIconPath -> pointer to buffer to contain path (assumed to be MAX_PATH long) / pwIndex -> index of icon within pIconPath / / Out: / HRESULT /----------------------------------------------------------------------------*/ HRESULT MDGetIconInfoFromIDL( LPITEMIDLIST pidl, LPTSTR pIconPath, UINT cch, UINT * pIndex ) { HRESULT hr = S_OK; LPMYIDLIST pIDL = (LPMYIDLIST)pidl; LPMYICONINFO pii; MDTraceEnter(TRACE_IDLIST, "MDGetIconInfoFromIDL"); if (!pIconPath) ExitGracefully( hr, E_INVALIDARG, "pIconPath is invalid" ); if (!pIndex) ExitGracefully( hr, E_INVALIDARG, "pIndex is invalid" ); *pIconPath = 0; *pIndex = 0; if (!MDIsSpecialIDL(pidl)) ExitGracefully( hr, E_FAIL, "Not a special idlist" ); if (!(pIDL->dwFlags & MDIDL_HASICONINFO)) ExitGracefully( hr, E_FAIL, "No icon info to return..." ); pii = (LPMYICONINFO)( (LPBYTE)pIDL + pIDL->dwIconOffset ); lstrcpyn( pIconPath, pii->szPath, cch ); *pIndex = pii->uIndex; exit_gracefully: MDTraceLeaveResult(hr); } /*----------------------------------------------------------------------------- / MDGetNameFromIDL / --------------------- / Check if this pidl is a special pidl, and then returns the name / information if present... / / In: / pidl -> pidl in question / pName -> pointer to buffer to contain name / cchName -> size of name buffer, in characters / fFullPath -> if TRUE, then walk down the IDLIST building up a path. If / FALSE, just return the display name for the first item in the / ID List... / / / Out: / HRESULT / E_INVALIDARG --> buffer is to small, *pcch hold required size /----------------------------------------------------------------------------*/ HRESULT MDGetNameFromIDL( LPITEMIDLIST pidl, LPTSTR pName, UINT * pcch, BOOL fFullPath ) { HRESULT hr = S_OK; LPITEMIDLIST pidlTemp = pidl; LPMYIDLIST pIDL; LPTSTR pNAME; UINT cch; TCHAR szPath[ MAX_PATH ]; MDTraceEnter(TRACE_IDLIST, "MDGetNameFromIDL"); if (!pName) ExitGracefully( hr, E_FAIL, "pName is invalid" ); if (!pcch) ExitGracefully( hr, E_FAIL, "cch is invalid" ); *pName = 0; cch = *pcch; *pcch = 0; while( pidlTemp && !ILIsEmpty(pidlTemp) ) { pIDL = (LPMYIDLIST)pidlTemp; if (MDIsSpecialIDL(pidlTemp) && (pIDL->dwFlags & MDIDL_HASNAME)) { pNAME = (LPTSTR)( (LPBYTE)pIDL + pIDL->dwNameOffset ); } else { if (fFullPath) { pName = szPath; MDGetPathFromIDL( pidlTemp, szPath, NULL ); } else { ExitGracefully( hr, E_INVALIDARG, "fFullPath is FALSE and encountered a non-special IDL" ); } } if ((*pcch += (lstrlen(pNAME)+2)) <= cch) { lstrcat( pName, pNAME ); } else { hr = E_INVALIDARG; break; } pidlTemp = ILGetNext( pidlTemp ); if (pidlTemp && !ILIsEmpty( pidlTemp )) { lstrcat( pName, TEXT("\\") ); } } exit_gracefully: MDTraceLeaveResult(hr); } /*----------------------------------------------------------------------------- / MDGetPathInfoIDL / --------------------- / Check if this pidl is a special pidl, and then if it has a path stored / int he pidl, and if so, it returns that path... / / In: / pidl -> pidl in question / pName -> pointer to buffer to contain name / cchName -> size of name buffer, in characters / / Out: / HRESULT / E_INVALIDARG --> buffer is to small, *pcch hold required size /----------------------------------------------------------------------------*/ HRESULT MDGetPathInfoFromIDL( LPITEMIDLIST pidl, LPTSTR pPath, UINT * pcch ) { HRESULT hr = S_OK; LPMYIDLIST pIDL = (LPMYIDLIST)pidl; LPTSTR pPATH = NULL; UINT cch; MDTraceEnter(TRACE_IDLIST, "MDGetPathInfoIDL"); if (!pPath) ExitGracefully( hr, E_FAIL, "pName is invalid" ); if (!pcch) ExitGracefully( hr, E_FAIL, "cch is invalid" ); if (!pIDL || (!(pIDL->dwFlags & MDIDL_HASPATHINFO))) { ExitGracefully( hr, E_FAIL, "pidl is NULL or doesn't have a path!" ); } *pPath = 0; cch = *pcch; *pcch = 0; pPATH = (LPTSTR)((LPBYTE)pIDL + pIDL->dwPathOffset); if (cch < (UINT)((lstrlen(pPATH)+1))) { *pcch = (UINT)(lstrlen(pPATH)+1); ExitGracefully( hr, E_INVALIDARG, "*pcch wasn't big enough" ); } if (0==ExpandEnvironmentStrings( pPATH, pPath, cch )) { lstrcpy( pPath, pPATH ); } exit_gracefully: MDTraceLeaveResult(hr); }
25.01813
108
0.459438
King0987654
30086c6c23c601d124f5c797085d4214e774e3a8
921
cpp
C++
A_Little_Elephant_and_Rozdil.cpp
ar1936/CPP
4c76c2bf5308d8d3b6e295482e3ce4284fbeaf13
[ "MIT" ]
1
2021-04-20T13:49:56.000Z
2021-04-20T13:49:56.000Z
A_Little_Elephant_and_Rozdil.cpp
ar1936/cpp
4c76c2bf5308d8d3b6e295482e3ce4284fbeaf13
[ "MIT" ]
null
null
null
A_Little_Elephant_and_Rozdil.cpp
ar1936/cpp
4c76c2bf5308d8d3b6e295482e3ce4284fbeaf13
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #include <iomanip> using namespace std; typedef long long ll; typedef double db; #define pb push_back #define ppb pop_back #define mpll map<ll, ll> #define vll vector<ll> #define str string #define si size() #define vs vector<string> #define vc vector<char> #define sll set<ll> #define pi 3.14159265358979323846264338327 #define nope string::npos void fast(){ ios_base::sync_with_stdio(false); cin.tie(NULL); } int main() { fast(); ll n, min_time(1000000001),min_index(0),time,count(1); cin>>n; for(int i=1;i<=n;i++) { cin>>time; if(time<min_time) { min_time=time; min_index=i; count=1; } else if(min_time==time) count++; } if(count==1) cout<<min_index; else { cout<<"Still Rozdil"; } return 0; }
19.595745
59
0.560261
ar1936
3013fb6f6a50bb42007c55c626a89e05e132988d
20,028
cpp
C++
codebase/CVX_DP_ORIGINAL/cvx_clustering.cpp
JimmyLin192/ConvexLatentVariable
d81d2c465796ada22b370e76eaf22065c5823633
[ "BSD-3-Clause" ]
1
2015-03-18T00:44:26.000Z
2015-03-18T00:44:26.000Z
codebase/CVX_DP_ORIGINAL/cvx_clustering.cpp
JimmyLin192/ConvexLatentVariable
d81d2c465796ada22b370e76eaf22065c5823633
[ "BSD-3-Clause" ]
null
null
null
codebase/CVX_DP_ORIGINAL/cvx_clustering.cpp
JimmyLin192/ConvexLatentVariable
d81d2c465796ada22b370e76eaf22065c5823633
[ "BSD-3-Clause" ]
null
null
null
/*############################################################### ## MODULE: cvx_clustering.cpp ## VERSION: 1.0 ## SINCE 2014-06-14 ## AUTHOR: ## Jimmy Lin (xl5224) - JimmyLin@utexas.edu ## DESCRIPTION: ## ################################################################# ## Edited by MacVim ## Class Info auto-generated by Snippet ################################################################*/ #include "cvx_clustering.h" #include <cassert> #include "../util.h" /* algorithmic options */ #define EXACT_LINE_SEARCH // comment this to use inexact search /* dumping options */ // #define FRANK_WOLFE_DUMP // #define EXACT_LINE_SEARCH_DUMP // #define BLOCKWISE_DUMP // #define NCENTROID_DUMP // #define SPARSE_CLUSTERING_DUMP #define GROUP_LASSO_CHECK const int GROUP_LASSO_CHECK_ITER = 800; const double FRANK_WOLFE_TOL = 1e-20; typedef double (* dist_func) (Instance*, Instance*, int); const double r = 10000.0; const double EPS = 0; double first_subproblm_obj (double ** dist_mat, double ** yone, double ** zone, double ** wone, double rho, int N) { double ** temp = mat_init (N, N); double ** diffone = mat_init (N, N); mat_zeros (diffone, N, N); // sum1 = 0.5 * sum_n sum_k (w_nk * d^2_nk) -> loss mat_zeros (temp, N, N); mat_times (wone, dist_mat, temp, N, N); double sum1 = 0.5 * mat_sum (temp, N, N); // sum2 = y_1^T dot (w_1 - z) -> linear mat_zeros (temp, N, N); mat_sub (wone, zone, diffone, N, N); // temp = w_1 - z_1 mat_tdot (yone, diffone, temp, N, N); double sum2 = mat_sum (temp, N, N); // sum3 = 0.5 * rho * || w_1 - z_1 ||^2 -> quadratic mat_zeros (temp, N, N); mat_sub (wone, zone, temp, N, N); double sum3 = 0.5 * rho * mat_norm2 (temp, N, N); // sum4 = r dot (1 - sum_k w_nk) -> dummy double * temp_vec = new double [N]; mat_sum_row (wone, temp_vec, N, N); double dummy_penalty = 0.0; for (int i = 0; i < N; i ++) { dummy_penalty += r*(1 - temp_vec[i]); } double total = sum1+sum2+sum3+dummy_penalty; #ifdef FRANK_WOLFE_DUMP cout << "[Frank_wolfe] (loss, linear, quadratic, dummy, total) = (" << sum1 << ", " << sum2 << ", " << sum3 << ", " << dummy_penalty << ", " << total << ")" << endl; #endif mat_free (temp, N, N); mat_free (diffone, N, N); delete [] temp_vec; return total; } void frank_wolf (double ** dist_mat, double ** yone, double ** zone, double ** wone, double rho, int N, int K) { bool is_global_optimal_reached = false; // cout << "within frank_wolf" << endl; // This can be computed by using corner point. double ** gradient = mat_init (N, N); double ** s = mat_init (N, N); mat_zeros (gradient, N, N); #ifndef EXACT_LINE_SEARCH // int K = 300; #else // int K = 10; double ** w_minus_s = mat_init (N, N); double ** w_minus_z = mat_init (N, N); #endif int k = 0; // iteration number double gamma; // step size double penalty; double ** tempS = mat_init (N, N); //mat_zeros (wone, N, N); double sum1, sum2, sum3, sum4; // cout << "within frank_wolf: start iteration" << endl; while (k < K && !is_global_optimal_reached) { // STEP ONE: find s minimize <s, grad f> for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { gradient[i][j] = 0.5*dist_mat[i][j] + yone[i][j] + rho * (wone[i][j] - zone[i][j]) ; //- r[i]; } } mat_zeros (s, N, N); mat_min_row (gradient, s, N, N); #ifdef FRANK_WOLFE_DUMP cout << "mat_norm2 (wone, N, N): " << mat_norm2 (wone, N, N) << endl; cout << "mat_norm2 (yone, N, N): " << mat_norm2 (yone, N, N) << endl; cout << "mat_norm2 (gradient, N, N): " << mat_norm2 (gradient, N, N) << endl; cout << "mat_sum (s, N, N): " << mat_sum (s, N, N) << endl; #endif // cout << "within frank_wolf: step one finished" << endl; // STEP TWO: apply exact or inexact line search to find solution #ifndef EXACT_LINE_SEARCH // Here we use inexact line search gamma = 2.0 / (k + 2.0); #else // Here we use exact line search // gamma* = (sum1 + sum2 + sum3) / sum4, where // sum1 = 1/2 sum_n sum_k (w - s)_nk * (|| x_n - mu_k ||^2 -r) // sum2 = sum_n sum_k (w - s)_nk // sum3 = - rho * sum_n sum_k (w - z) // sum4 = sum_n sum_k rho * (s - w) mat_zeros (tempS, N, N); mat_zeros (w_minus_s, N, N); mat_zeros (w_minus_z, N, N); mat_sub (wone, s, w_minus_s, N, N); mat_sub (wone, zone, w_minus_z, N, N); // NOTE: in case of ||w_1 - s||^2 = 0, not need to optimize anymore // since incremental term = w + gamma (s - w), and whatever gamma is, // w^(k+1) = w^(k), this would be equivalent to gamma = 0 if (mat_norm2(w_minus_s, N, N) <= FRANK_WOLFE_TOL) { gamma = 0; is_global_optimal_reached = true; } else { sum1 = 0; mat_times (w_minus_s, dist_mat, tempS, N, N); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { sum1 += w_minus_s[i][j] * (dist_mat[i][j] - r); } } // sum1 = 0.5 * mat_sum (tempS, N, N) - ...; mat_zeros (tempS, N, N); mat_tdot (yone, w_minus_s, tempS, N, N); sum2 = mat_sum (tempS, N, N); mat_zeros (tempS, N, N); mat_tdot (w_minus_z, w_minus_s, tempS, N, N); sum3 = rho * mat_sum (tempS, N, N); mat_zeros (tempS, N, N); sum4 = rho * mat_norm2 (w_minus_s, N, N); // gamma should be within interval [0,1] gamma = (sum1 + sum2 + sum3) / sum4; gamma = max (gamma, 0.0); gamma = min (gamma, 1.0); #ifdef FRANK_WOLFE_DUMP cout << "mat_norm2 (w_minus_s, N, N)" << mat_norm2 (w_minus_s, N, N) << endl; cout << "mat_norm2 (w_minus_z, N, N)" << mat_norm2 (w_minus_z, N, N) << endl; #endif // cout << "within frank_wolf: step two finished" << endl; #ifdef EXACT_LINE_SEARCH_DUMP cout << "[exact line search] (sum1, sum2, sum3, sum4, gamma) = (" << sum1 << ", " << sum2 << ", " << sum3 << ", " << sum4 << ", " << gamma << ")" << endl; #endif } #endif // update the w^(k+1) mat_zeros (tempS, N, N); mat_dot (gamma, s, tempS, N, N); mat_dot (1.0-gamma, wone, wone, N, N); mat_add (wone, tempS, wone, N, N); // compute value of objective function penalty = first_subproblm_obj (dist_mat, yone, zone, wone, rho, N); // cout << "within frank_wolf: step three finished" << endl; // report the #iter and objective function /* cout << "[Frank-Wolfe] iteration: " << k << ", first_subpro_obj: " << penalty << endl; */ k ++; // cout << "within frank_wolf: next iteration" << endl; } // cout << "within frank_wolf: to free gradient" << endl; mat_free (gradient, N, N); // cout << "within frank_wolf: to free temps" << endl; mat_free (tempS, N, N); // cout << "within frank_wolf: to free s " << endl; mat_free (s, N, N); // cout << "end frank_wolf: finished! " << endl; } bool pairComparator (const std::pair<int, double>& firstElem, const std::pair<int, double>& secondElem) { // sort pairs by second element with decreasing order return firstElem.second > secondElem.second; } double second_subproblem_obj (double ** ytwo, double ** z, double ** wtwo, double rho, int N, double* lambda) { double ** temp = mat_init (N, N); double ** difftwo = mat_init (N, N); mat_zeros (difftwo, N, N); // reg = 0.5 * sum_k max_n | w_nk | -> group-lasso mat_zeros (temp, N, N); double * maxn = new double [N]; for (int i = 0; i < N; i ++) { // Ian: need initial maxn[i] = -INF; } for (int i = 0; i < N; i ++) { for (int j = 0; j < N; j ++) { if (wtwo[i][j] > maxn[j]) maxn[j] = wtwo[i][j]; } } double sumk = 0.0; for (int i = 0; i < N; i ++) { sumk += lambda[i]*maxn[i]; } double group_lasso = sumk; // sum2 = y_2^T dot (w_2 - z) -> linear mat_zeros (temp, N, N); mat_sub (wtwo, z, difftwo, N, N); mat_tdot (ytwo, difftwo, temp, N, N); double linear = mat_sum (temp, N, N); // sum3 = 0.5 * rho * || w_2 - z_2 ||^2 -> quadratic mat_zeros (temp, N, N); mat_sub (wtwo, z, temp, N, N); double quadratic = 0.5 * rho * mat_norm2 (temp, N, N); mat_free (temp, N, N); double total = group_lasso + linear + quadratic; // ouput values of each components #ifdef BLOCKWISE_DUMP cout << "[Blockwise] (group_lasso, linear, quadratic) = (" << group_lasso << ", " << linear << ", " << quadratic << ")" << endl; #endif #ifdef GROUP_LASSO_CHECK ofstream glasso_obj ("lasso_objective"); glasso_obj << "total: " << total << endl; glasso_obj << "group_lasso: " << group_lasso << endl; glasso_obj << "linear: " << linear << endl; glasso_obj << "quadratic: " << quadratic << endl; glasso_obj.close(); #endif return total; } void blockwise_closed_form (double ** ytwo, double ** ztwo, double ** wtwo, double rho, double* lambda, int N) { // STEP ONE: compute the optimal solution for truncated problem double ** wbar = mat_init (N, N); mat_zeros (wbar, N, N); mat_dot (rho, ztwo, wbar, N, N); // wbar = rho * z_2 mat_sub (wbar, ytwo, wbar, N, N); // wbar = rho * z_2 - y_2 mat_dot (1.0/rho, wbar, wbar, N, N); // wbar = (rho * z_2 - y_2) / rho // STEP TWO: find the closed-form solution for second subproblem for (int j = 0; j < N; j ++) { // 1. bifurcate the set of values vector< pair<int,double> > alpha_vec; for (int i = 0; i < N; i ++) { double value = wbar[i][j]; /*if( wbar[i][j] < 0 ){ cerr << "wbar[" << i << "][" << j << "]" << endl; exit(0); }*/ alpha_vec.push_back (make_pair(i, abs(value))); } // 2. sorting std::sort (alpha_vec.begin(), alpha_vec.end(), pairComparator); /* for (int i = 0; i < N; i ++) { if (alpha_vec[i].second != 0) cout << alpha_vec[i].second << endl; } */ // 3. find mstar int mstar = 0; // number of elements support the sky double separator; double max_term = -INF, new_term; double sum_alpha = 0.0; for (int i = 0; i < N; i ++) { sum_alpha += alpha_vec[i].second; new_term = (sum_alpha - lambda[j]) / (i + 1.0); if ( new_term > max_term ) { separator = alpha_vec[i].second; max_term = new_term; mstar = i; } } // 4. assign closed-form solution to wtwo if( max_term < 0 ){ for(int i=0;i<N;i++) wtwo[i][j] = 0.0; continue; } for (int i = 0; i < N; i ++) { // harness vector of pair double value = wbar[i][j]; if ( abs(value) >= separator ) { wtwo[i][j] = max_term; } else { // its ranking is above m*, directly inherit the wbar wtwo[i][j] = max(wbar[i][j],0.0); } } } // report the #iter and objective function /*cout << "[Blockwise] second_subproblem_obj: " << penalty << endl; cout << endl;*/ // STEP THREE: recollect temporary variable - wbar mat_free (wbar, N, N); } double overall_objective (double ** dist_mat, double* lambda, int N, double ** z) { // N is number of entities in "data", and z is N by N. // z is current valid solution (average of w_1 and w_2) double sum = 0.0; for(int i=0;i<N;i++) for(int j=0;j<N;j++) sum += z[i][j]; // cerr << "sum=" << sum/N << endl; // STEP ONE: compute // loss = sum_i sum_j z[i][j] * dist_mat[i][j] double normSum = 0.0; for (int i = 0; i < N; i ++) { for (int j = 0; j < N; j ++) { normSum += z[i][j] * dist_mat[i][j]; } } double loss = 0.5 * (normSum); cout << "loss=" << loss; // STEP TWO: compute dummy loss // sum4 = r dot (1 - sum_k w_nk) -> dummy double * temp_vec = new double [N]; mat_sum_row (z, temp_vec, N, N); double dummy_penalty=0.0; double avg=0.0; for (int i = 0; i < N; i ++) { avg += temp_vec[i]; dummy_penalty += r * max(1 - temp_vec[i], 0.0) ; } cout << ", dummy= " << dummy_penalty; // STEP THREE: compute group-lasso regularization double * maxn = new double [N]; for (int i = 0;i < N; i ++) { // Ian: need initial maxn[i] = -INF; } for (int i = 0; i < N; i ++) { for (int j = 0; j < N; j ++) { if ( fabs(z[i][j]) > maxn[j]) maxn[j] = fabs(z[i][j]); } } double sumk = 0.0; for (int i = 0; i < N; i ++) { sumk += lambda[i]*maxn[i]; } double reg = sumk; cout << ", reg=" << reg << endl; delete[] maxn; delete[] temp_vec; return loss + reg + dummy_penalty; } double noise(){ return EPS * (((double)rand()/RAND_MAX)*2.0 -1.0) ; } /* Compute the mutual distance of input instances contained within "data" */ void compute_dist_mat (vector<Instance*>& data, double ** dist_mat, int N, int D, dist_func df, bool isSym) { for (int i = 0; i < N; i ++) { for (int j = 0; j < N; j ++) { Instance * xi = data[i]; Instance * muj = data[j]; dist_mat[i][j] = df (xi, muj, D) + noise(); } } } void cvx_clustering ( double ** dist_mat, int fw_max_iter, int max_iter, int D, int N, double* lambda, double ** W) { // parameters double alpha = 0.1; double rho = 1.0; // iterative optimization double error = INF; double ** wone = mat_init (N, N); double ** wtwo = mat_init (N, N); double ** yone = mat_init (N, N); double ** ytwo = mat_init (N, N); double ** z = mat_init (N, N); double ** diffzero = mat_init (N, N); double ** diffone = mat_init (N, N); double ** difftwo = mat_init (N, N); mat_zeros (yone, N, N); mat_zeros (ytwo, N, N); mat_zeros (z, N, N); mat_zeros (diffzero, N, N); mat_zeros (diffone, N, N); mat_zeros (difftwo, N, N); int iter = 0; // Ian: usually we count up (instead of count down) while ( iter < max_iter ) { // stopping criteria #ifdef SPARSE_CLUSTERING_DUMP cout << "it is place 0 iteration #" << iter << ", going to get into frank_wolfe" << endl; #endif // STEP ONE: resolve w_1 and w_2 frank_wolf (dist_mat, yone, z, wone, rho, N, fw_max_iter); // for w_1 #ifdef SPARSE_CLUSTERING_DUMP cout << "norm2(w_1) = " << mat_norm2 (wone, N, N) << endl; #endif #ifdef GROUP_LASSO_CHECK if (iter == GROUP_LASSO_CHECK_ITER) { ofstream y2_out ("y2_input"); y2_out << mat_toString (ytwo, N, N); y2_out.close(); ofstream z2_out ("z2_input"); z2_out << mat_toString (z, N, N); z2_out.close(); } #endif blockwise_closed_form (ytwo, z, wtwo, rho, lambda, N); // for w_2 #ifdef GROUP_LASSO_CHECK if (iter == GROUP_LASSO_CHECK_ITER) { double penalty = second_subproblem_obj (ytwo, z, wtwo, rho, N, lambda); ofstream w2_out ("w2_output"); w2_out << mat_toString (wtwo, N, N); w2_out.close(); } #endif #ifdef SPARSE_CLUSTERING_DUMP cout << "norm2(w_2) = " << mat_norm2 (wtwo, N, N) << endl; #endif // STEP TWO: update z by averaging w_1 and w_2 mat_add (wone, wtwo, z, N, N); mat_dot (0.5, z, z, N, N); #ifdef SPARSE_CLUSTERING_DUMP cout << "norm2(z) = " << mat_norm2 (z, N, N) << endl; #endif // STEP THREE: update the y_1 and y_2 by w_1, w_2 and z mat_sub (wone, z, diffone, N, N); double trace_wone_minus_z = mat_norm2 (diffone, N, N); mat_dot (alpha, diffone, diffone, N, N); mat_add (yone, diffone, yone, N, N); mat_sub (wtwo, z, difftwo, N, N); //double trace_wtwo_minus_z = mat_norm2 (difftwo, N, N); mat_dot (alpha, difftwo, difftwo, N, N); mat_add (ytwo, difftwo, ytwo, N, N); // STEP FOUR: trace the objective function if (iter % 100 == 0) { error = overall_objective (dist_mat, lambda, N, z); // get current number of employed centroid #ifdef NCENTROID_DUMP int nCentroids = get_nCentroids (z, N, N); #endif cout << "[Overall] iter = " << iter << ", Overall Error: " << error #ifdef NCENTROID_DUMP << ", nCentroids: " << nCentroids #endif << endl; } iter ++; } // STEP FIVE: memory recollection mat_free (wone, N, N); mat_free (wtwo, N, N); mat_free (yone, N, N); mat_free (ytwo, N, N); mat_free (diffone, N, N); mat_free (difftwo, N, N); // STEP SIX: put converged solution to destination W mat_copy (z, W, N, N); } // entry main function int main (int argc, char ** argv) { // exception control: illustrate the usage if get input of wrong format if (argc < 6) { cerr << "Usage: cvx_clustering [dataFile] [fw_max_iter] [max_iter] [lambda] [dmatFile]" << endl; cerr << "Note: dataFile must be scaled to [0,1] in advance." << endl; exit(-1); } // parse arguments char * dataFile = argv[1]; int fw_max_iter = atoi(argv[2]); int max_iter = atoi(argv[3]); double lambda_base = atof(argv[4]); char * dmatFile = argv[5]; // vector<Instance*> data; // readFixDim (dataFile, data, FIX_DIM); // read in data int FIX_DIM; Parser parser; vector<Instance*>* pdata; vector<Instance*> data; pdata = parser.parseSVM(dataFile, FIX_DIM); data = *pdata; // vector<Instance*> data; // readFixDim (dataFile, data, FIX_DIM); // explore the data int dimensions = -1; int N = data.size(); // data size for (int i = 0; i < N; i++) { vector< pair<int,double> > * f = &(data[i]->fea); int last_index = f->size()-1; if (f->at(last_index).first > dimensions) { dimensions = f->at(last_index).first; } } assert (dimensions == FIX_DIM); int D = dimensions; cerr << "D = " << D << endl; // # features cerr << "N = " << N << endl; // # instances cerr << "lambda = " << lambda_base << endl; cerr << "r = " << r << endl; int seed = time(NULL); srand (seed); cerr << "seed = " << seed << endl; //create lambda with noise double* lambda = new double[N]; for(int i=0;i<N;i++){ lambda[i] = lambda_base + noise(); } // pre-compute distance matrix dist_func df = L2norm; double ** dist_mat = mat_init (N, N); // double ** dist_mat = mat_read (dmatFile, N, N); mat_zeros (dist_mat, N, N); compute_dist_mat (data, dist_mat, N, D, df, true); ofstream dist_mat_out ("dist_mat"); dist_mat_out << mat_toString(dist_mat, N, N); dist_mat_out.close(); // Run sparse convex clustering double ** W = mat_init (N, N); mat_zeros (W, N, N); cvx_clustering (dist_mat, fw_max_iter, max_iter, D, N, lambda, W); ofstream W_OUT("w_out"); W_OUT<< mat_toString(W, N, N); W_OUT.close(); // Output cluster output_objective(clustering_objective (dist_mat, W, N)); /* Output cluster centroids */ output_model (W, N); /* Output assignment */ output_assignment (W, data, N); /* reallocation */ mat_free (dist_mat, N, N); mat_free (W, N, N); }
33.269103
117
0.529159
JimmyLin192
30151745d9266c4dc1312469e78003bc6e110386
1,989
cpp
C++
libstarlight/source/starlight/ui/Button.cpp
mothie/libstarlight
91bd6892ccc95ccf255cad73ef659b6cf37ab4a9
[ "MIT" ]
36
2017-01-17T22:58:08.000Z
2021-12-28T00:04:52.000Z
libstarlight/source/starlight/ui/Button.cpp
mothie/libstarlight
91bd6892ccc95ccf255cad73ef659b6cf37ab4a9
[ "MIT" ]
3
2017-03-26T20:47:25.000Z
2019-12-12T01:50:02.000Z
libstarlight/source/starlight/ui/Button.cpp
mothie/libstarlight
91bd6892ccc95ccf255cad73ef659b6cf37ab4a9
[ "MIT" ]
9
2017-04-17T19:01:24.000Z
2021-12-01T18:26:01.000Z
#include "Button.h" #include "starlight/_incLib/json.hpp" #include "starlight/InputManager.h" #include "starlight/GFXManager.h" #include "starlight/ThemeManager.h" using starlight::Vector2; using starlight::Color; using starlight::gfx::Font; using starlight::InputManager; using starlight::GFXManager; using starlight::ThemeManager; using starlight::TextConfig; using starlight::ui::Button; std::function<TextConfig&()> Button::defCfg = []() -> TextConfig& { static TextConfig _tc = ThemeManager::GetMetric("/controls/button/text", TextConfig()); return _tc; }; void Button::SetText(const std::string& text) { label = text; MarkForRedraw(); } void Button::Draw() { //static auto font = ThemeManager::GetFont("default.12"); static auto idle = ThemeManager::GetAsset("controls/button.idle"); static auto press = ThemeManager::GetAsset("controls/button.press"); TextConfig& tc = style.textConfig.ROGet(); auto rect = (this->rect + GFXManager::GetOffset()).IntSnap(); if (InputManager::GetDragHandle() == this) { (style.press ? style.press : press)->Draw(rect); } else { (style.idle ? style.idle : idle)->Draw(rect); } tc.Print(rect, label); if (style.glyph) style.glyph->Draw(rect.Center(), Vector2::half, nullptr, tc.textColor); } void Button::OnTouchOn() { if (InputManager::Pressed(Keys::Touch)) { InputManager::GetDragHandle().Grab(this); MarkForRedraw(); } } void Button::OnTouchOff() { auto& drag = InputManager::GetDragHandle(); if (drag == this) drag.Release(); } void Button::OnDragStart() { // do we need to do anything here? } void Button::OnDragHold() { if (InputManager::TouchDragDist().Length() > InputManager::dragThreshold) { InputManager::GetDragHandle().PassUp(); } } void Button::OnDragRelease() { if (InputManager::Released(Keys::Touch)) { if (eOnTap) eOnTap(*this); } MarkForRedraw(); }
24.8625
92
0.659628
mothie
30154bff9150b9d07aec2c1723305bce74593c50
157,567
cxx
C++
ds/ds/src/ntdsa/src/samlogon.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
ds/ds/src/ntdsa/src/samlogon.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
ds/ds/src/ntdsa/src/samlogon.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+------------------------------------------------------------------------- // // Microsoft Windows // // Copyright (C) Microsoft Corporation, 1994 - 1999 // // File: samlogon.c // //-------------------------------------------------------------------------- /*++ Abstract: This file contains the routines for implementing SampGetMemberships which performs recursive membership retrieval. This is called by SAM when a security principal logs on. It also has routines for transitively expanding the membership list of a security prinicpal, same domain/cross domain Author: DaveStr 07-19-96 Environment: User Mode - Win32 Revision History: DaveStr 07-19-96 Created --*/ #include <NTDSpchx.h> #pragma hdrstop extern "C" { #include <ntdsa.h> #include <filtypes.h> #include <mappings.h> #include <objids.h> #include <direrr.h> #include <mdcodes.h> #include <mdlocal.h> #include <dsatools.h> #include <dsexcept.h> #include <dsevent.h> #include <debug.h> #include <drsuapi.h> #include <drserr.h> #include <anchor.h> #include <samsrvp.h> #include <fileno.h> #define FILENO FILENO_SAMLOGON #include <ntsam.h> #include <samrpc.h> #include <crypt.h> #include <ntlsa.h> #include <gcverify.h> #include <samisrv.h> #include <ntdsctr.h> #include <dsconfig.h> #include <samlogon.h> #define DEBSUB "SAMLOGON:" } // extern "C" #define MAX_TOKEN_GROUPS_COUNT (2 * LSAI_CONTEXT_SID_LIMIT) // Declare some local helper classes to manage sets of SIDs. Implementing // them as C++ classes makes them easier to replace in the future with // better performing implementations. Care is taken to allocate everything // via thread heap instead of using the global 'new' operator in order to // be consistent with the rest of the core DS code. Likewise, all // destructors are no-ops. ////////////////////////////////////////////////////////////////////////// // // // CDSNameSet - Manages a set of Values. // // In the original version this class managed a set of DSNames. // // During the course of development its utility was appreciated and // // this class was extended to manage value types of DSNAME DNT and SID // // // ////////////////////////////////////////////////////////////////////////// typedef enum _REVMEMB_VALUE_TYPE { RevMembDsName =1, RevMembDNT, RevMembSid } REVMEMB_VALUE_TYPE; class CDSNameSet { private: ULONG _cNames; // count of Values in set ( DSNAMES, dnts, or SIDS) ULONG _cMax; // count of allocated elements REVMEMB_VALUE_TYPE _valueType; // Indicates that the kind of values we are managing PVOID *_rpNames; // array of pointers, to either DSNAMES , dnts or SIDs public: // Constructor. CDSNameSet(); // Destructor. ~CDSNameSet() { NULL; } // Tell to manage internal or external names VOID SetValueType(REVMEMB_VALUE_TYPE ValueType) {_valueType = ValueType;} // Return the count of DSNAMEs currently in the set. ULONG Count() { return(_cNames); } // Retrieve a pointer to the Nth DSNAME in the set. PVOID Get(ULONG idx) { Assert(idx < _cNames); return(_rpNames[idx]); } #define DSNAME_NOT_FOUND 0xFFFFFFFF // Determine whether a DSNAME is in the set and if so, its index. ULONG Find(PVOID pDSName); // Add a DSNAME to the set. VOID Add(PVOID pDSName); // Remove the DSNAME at a given index from the set. VOID Remove(ULONG idx); // Add if the DSNAME is not already present VOID CheckDuplicateAndAdd(PVOID pDSName); // Returns the pointer to the array of DSName pointers // that represents the set of DS Names PVOID * GetArray() { return _rpNames; } // Cleans up the DSNameSet, by free-ing the array and resetting // the _cNames and _cMax fields VOID Cleanup(); }; ////////////////////////////////////////////////////////////////////////// // // // CReverseMembership - Manages the DSNAMEs in a reverse membership. // // // ////////////////////////////////////////////////////////////////////////// class CReverseMembership { private: CDSNameSet _recursed; CDSNameSet _unRecursed; public: // Constructor. CReverseMembership(){ _recursed.SetValueType(RevMembDNT); _unRecursed.SetValueType(RevMembDNT); } // Destructor. ~CReverseMembership() { _recursed.Cleanup(); _unRecursed.Cleanup(); } // Add a DSNAME to the set. VOID Add(PVOID pDSName); // Retrieve the next DSNAME which has not yet been recursively processed. PVOID NextUnrecursed(); // Retrieve the count of DSNAMEs in the reverse membership set. ULONG Count(); // Retrieve the DSNAME at a given index from the set - does not remove it. PVOID Get(ULONG idx); }; ////////////////////////////////////////////////////////////////////////// // // // CDSNameSet - Implementation // // // ////////////////////////////////////////////////////////////////////////// // Define the factor by which we will grow the PDSNAME array in a CDSNameSet // instance. Make it small for debug builds so we test boundary conditions // but big in a retail build for performance. #if DBG == 1 #define PDSNAME_INCREMENT 1 #else #define PDSNAME_INCREMENT 100 #endif int _cdecl ComparePVOIDDNT( const void *pv1, const void *pv2 ) /*++ Routine Description: Compares two DNTs that are stored in PVOID pointers Arguments: pv1 - Pointer provided by qsort or bsearch which is the value of a DNT array element. pv2 - Pointer provided by qsort or bsearch which is the value of a DNT array element. Return Value: Integer representing how much less than, equal or greater the first name is with respect to the second. --*/ { PVOID p1 = * ((PVOID * ) pv1); PVOID p2 = * ((PVOID *) pv2); ULONG u1 = PtrToUlong(p1); ULONG u2 = PtrToUlong(p2); ULONG Result; if (u1==u2) return 0; if (u1>u2) return 1; return -1; } int _cdecl ComparePSID( const void *pv1, const void *pv2 ) /*++ Routine Description: Compares two SIDs. Arguments: pv1 - Pointer provided by qsort or bsearch which is the address of a PSID array element. pv2 - Pointer provided by qsort or bsearch which is the address of a PSID array element. Return Value: Integer representing how much less than, equal or greater the first name is with respect to the second. --*/ { PSID p1 = * ((PSID *) pv1); PSID p2 = * ((PSID *) pv2); ULONG Result; if (RtlEqualSid(p1,p2)) { return 0; } if (RtlLengthSid(p1)<RtlLengthSid(p2)) { return -1; } else if (RtlLengthSid(p1) > RtlLengthSid(p2)) { return 1; } else { Result = memcmp(p1,p2,RtlLengthSid(p1)); } return Result; } int _cdecl ComparePDSNAME( const void *pv1, const void *pv2 ) /*++ Routine Description: Compares two DSNAMEs. Arguments: pv1 - Pointer provided by qsort or bsearch which is the address of a PDSNAME array element. pv2 - Pointer provided by qsort or bsearch which is the address of a PDSNAME array element. Return Value: Integer representing how much less than, equal or greater the first name is with respect to the second. --*/ { PDSNAME p1 = * ((PDSNAME *) pv1); PDSNAME p2 = * ((PDSNAME *) pv2); ULONG Result; // // if both have guids then compare guids // if (!fNullUuid(&p1->Guid) && !fNullUuid(&p2->Guid)) { return(memcmp(&p1->Guid, &p2->Guid, sizeof(GUID))); } // // At least one of the two Ds Names has a SID // // // Assert that a SID only name cannot be a security principal // in the builltin domain // Assert(!fNullUuid(&p1->Guid)||(p1->SidLen==sizeof(NT4SID))); Assert(!fNullUuid(&p2->Guid)||(p2->SidLen==sizeof(NT4SID))); // // Compare by SID // if (RtlEqualSid(&p1->Sid,&p2->Sid)) { return 0; } if (p1->SidLen<p2->SidLen) { return -1; } else if (p1->SidLen > p2->SidLen) { return 1; } else { Result = memcmp(&p1->Sid,&p2->Sid,p1->SidLen); } return Result; } CDSNameSet::CDSNameSet() { _cNames = 0; _cMax = 0; _rpNames = NULL; } ULONG CDSNameSet::Find( PVOID pDSName ) { PVOID *ppDSName = &pDSName; PVOID *pFoundName; ULONG idx; int (__cdecl *CompareFunction)(const void *, const void *) = NULL; switch(_valueType) { case RevMembDsName: CompareFunction=ComparePDSNAME; break; case RevMembDNT: CompareFunction=ComparePVOIDDNT; break; case RevMembSid: CompareFunction=ComparePSID; break; default: Assert(FALSE&&"InvalidValueType"); } pFoundName = (PVOID *) bsearch( ppDSName, _rpNames, _cNames, sizeof(PVOID), CompareFunction); if ( NULL == pFoundName ) { return(DSNAME_NOT_FOUND); } // Convert pFoundName into an array index. idx = (ULONG)(pFoundName - _rpNames); Assert(idx < _cNames); return(idx); } VOID AddToSortedList( IN PVOID *rpNames, IN OUT ULONG *pcNames, IN PVOID pDSName, IN int (__cdecl *CompareFunction)(const void *, const void *) ) /*++ Routine Description: This routine adds pDSName into the rpNames array in sorted order. This routine assumes that rpNames has enough space to grow by at least one element. The algorithm used is a binary search to locate the position that the new element should be inserted into. Arguments: rpNames -- an array of pointers with space to hold at least (*pcNames + 1) elements pcNames -- a pointer to the count of elements in rpNames. pDSName -- a pointer to an element to place into rpNames CompareFunction -- a routine to determine the sort order of rpNames Return Value: None. rpNames will be updated in place. --*/ { BOOL fFound = FALSE; ULONG n = (*pcNames); ULONG index, start, end; LONG result; // initial case, the existing array contains no elements if ((*pcNames) == 0) { rpNames[0] = pDSName; (*pcNames) = 1; return; } // locate position in array for the new element // index is the position in the array that the new element will be added. // start and end determine what range of elements are being inspected. start = 0; end = n - 1; do { // goto the middle of the range index = (start + end) / 2; result = CompareFunction(&pDSName, &(rpNames[index])); if (result < 0) { if (index == start) { // the element goes before the first element of the // left section -- we are done. fFound = TRUE; } else { // the element belongs in the left section, adjust the // end range to be just before the current position end = index-1; } } else if (result > 0 ) { if (index == end) { // the element goes after the last element of the right // section -- we are done fFound = TRUE; index = end + 1; } else{ // the element belongs in the left section, adjust the // start range to be just after the current position. start = index+1; } } else { // we found an element that is equal to the new element // insert the element right here. fFound = TRUE; } } while ( !fFound ); #if DBG Assert(index <= n); if (index == n) { // the new element is at the end of the list, therefore value must be // greater than or equal to the last element Assert(CompareFunction(&pDSName, &(rpNames[n-1])) >= 0); } else if (index == 0) { // the new element is at the front of the list, therefore its value // must be less than or equal the first element Assert(CompareFunction(&pDSName, &(rpNames[0])) <= 0); } else { Assert(n > 1); // the new element must be less or equal to the element it is replacing Assert(CompareFunction(&pDSName, &(rpNames[index])) <= 0); // the new element must be greater than or equal to the previous element Assert(CompareFunction(&pDSName, &(rpNames[index-1])) >= 0); } #endif // move the elements forward if necessary if (index < n) { memmove(&(rpNames[index+1]), &(rpNames[index]), (n-index) * sizeof(pDSName)); } // add the new element rpNames[index] = pDSName; (*pcNames)++; return; } VOID CDSNameSet::Add( PVOID pDSName ) { THSTATE *pTHS=pTHStls; PVOID *ppDSName = &pDSName; int (__cdecl *CompareFunction)(const void *, const void *) = NULL; // Caller should not add duplicates - verify. #if DBG == 1 if ( DSNAME_NOT_FOUND != Find(pDSName) ) { Assert(FALSE && "Duplicate CDSNameSet::Add"); } #endif // See if we need to (re)allocate the array of DSNAME pointers. if ( _cNames == _cMax ) { _cMax += PDSNAME_INCREMENT; if ( NULL == _rpNames ) { _rpNames = (PVOID *) THAllocEx(pTHS, _cMax * sizeof(PVOID)); } else { _rpNames = (PVOID *) THReAllocEx(pTHS, _rpNames, _cMax * sizeof(PVOID)); } } // Now add the new element and maintain a sorted array. switch(_valueType) { case RevMembDsName: CompareFunction=ComparePDSNAME; break; case RevMembDNT: CompareFunction=ComparePVOIDDNT; break; case RevMembSid: CompareFunction=ComparePSID; break; default: Assert(FALSE&&"InvalidValueType"); } AddToSortedList(_rpNames, &_cNames, pDSName, CompareFunction); } VOID CDSNameSet::Remove( ULONG idx ) { Assert(idx < _cNames); for ( ULONG i = idx; i < (_cNames-1); i++ ) { _rpNames[i] = _rpNames[i+1]; } _cNames--; // Nothing to sort since shift-down didn't perturb sort order. } VOID CDSNameSet::CheckDuplicateAndAdd( PVOID pDSName ) { if (DSNAME_NOT_FOUND==Find(pDSName)) { Add(pDSName); } return; } VOID CDSNameSet::Cleanup() { if (NULL!=_rpNames) THFree(_rpNames); _rpNames = NULL; _cMax = NULL; _cNames = NULL; } ////////////////////////////////////////////////////////////////////////// // // // CReverseMembership - Implementation // // // ////////////////////////////////////////////////////////////////////////// VOID CReverseMembership::Add( PVOID pDSName ) { // Nothing to do if we already have this DSNAME in either the recursed // or !recursed set. if ( (DSNAME_NOT_FOUND != _unRecursed.Find(pDSName)) || (DSNAME_NOT_FOUND != _recursed.Find(pDSName)) ) { return; } // Add to !recursed set of DSNAMEs. _unRecursed.Add(pDSName); } PVOID CReverseMembership::NextUnrecursed( void ) { ULONG cNames; ULONG idx; PVOID pDSName; cNames = _unRecursed.Count(); if ( 0 == cNames ) { return(NULL); } idx = --cNames; pDSName = _unRecursed.Get(idx); // Transfer DSNAME from !recursed to recursed set. _unRecursed.Remove(idx); _recursed.Add(pDSName); return(pDSName); } ULONG CReverseMembership::Count( void ) { return(_recursed.Count() + _unRecursed.Count()); } PVOID CReverseMembership::Get( ULONG idx ) { Assert(idx < Count()); if ( idx >= _recursed.Count() ) { return(_unRecursed.Get(idx - _recursed.Count())); } return(_recursed.Get(idx)); } ////////////////////////////////////////////////////////////////////////// // // // Helper functions // // // ////////////////////////////////////////////////////////////////////////// NTSTATUS SampCheckGroupTypeAndDomainLocal ( IN THSTATE *pTHS, IN ULONG SidLen, IN PSID pSid, IN DWORD NCDNT, IN DWORD GroupType, IN ATTRTYP Class, IN REVERSE_MEMBERSHIP_OPERATION_TYPE OperationType, IN ULONG LimitingNCDNT, IN PSID LimitingDomainSid, OUT BOOLEAN *pfMatch ) /*++ Given a DNT, try to look it up in the group cache. If we find it, do the check for recursive membership. Parameters: OperationType -- The type of reverse membership operation specified LimitingNCDNT -- The limiting NCDNT where the operation restricts the scope to a domain LimitingDomanSid -- The limiting DomainSid where the operation restricts the scope to a domain pfMatch -- Out parameter TRUE indicates that the current object is should enter the reverse membeship list and be followed transitively Return values STATUS_SUCCESS Other error codes to indicate resource failures --*/ { CLASSCACHE *pClassCache; NTSTATUS NtStatus = STATUS_SUCCESS; ULONG len; ULONG objectRid; NT4_GROUP_TYPE NT4GroupType; NT5_GROUP_TYPE NT5GroupType; BOOLEAN SecurityEnabled; ULONG MostBasicClass; // // Initialize return values // *pfMatch = FALSE; // // Perform the SID Check // if (0==SidLen) { // // No Sid, then no no match // return STATUS_SUCCESS; } // // Sid is present and is a valid Sid // Assert(RtlValidSid((PSID) pSid)); // // Filter out all builtin aliases, unless operation is // RevMembGetAliasMembership // objectRid = *RtlSubAuthoritySid( pSid, *RtlSubAuthorityCountSid(pSid)-1 ); if ((objectRid <= DOMAIN_ALIAS_RID_REPLICATOR) && (objectRid>=DOMAIN_ALIAS_RID_ADMINS) && (RevMembGetAliasMembership!=OperationType)) { return STATUS_SUCCESS; } // If a limiting domain SID was provided, filter SIDs // by domain. The limiting domain SID is important for // all operations except getting universal groups if (( NULL != LimitingDomainSid ) && (OperationType!=RevMembGetUniversalGroups)) { NT4SID domainSid; SampSplitNT4SID((NT4SID *)pSid, &domainSid, &objectRid); if ( !RtlEqualSid(&domainSid, LimitingDomainSid) ) { return STATUS_SUCCESS; } } // // Perform the naming context test // if ((OperationType!=RevMembGetUniversalGroups) && (NCDNT!=LimitingNCDNT)) { // // Naming Context's do not match // return STATUS_SUCCESS; } // // Read the group type // if(!GroupType) { // No GroupType. // this means that the object is probaly // not a group, so does not enter token return(STATUS_SUCCESS); } // // And the actual class id. // if ( 0 == (pClassCache = SCGetClassById(pTHS, Class)) ) { return(STATUS_INTERNAL_ERROR); } // // Derive the most basic class // MostBasicClass = SampDeriveMostBasicDsClass(Class); // // Check the group type // if (SampGroupObjectType!=SampSamObjectTypeFromDsClass(MostBasicClass)) { // // The object is not a group, so does not enter the token // return STATUS_SUCCESS; } NtStatus = SampComputeGroupType( MostBasicClass, GroupType, &NT4GroupType, &NT5GroupType, &SecurityEnabled ); if (!NT_SUCCESS(NtStatus)) { return NtStatus; } // // If the group is not security enabled, bail // if (!SecurityEnabled) { return STATUS_SUCCESS; } // // Check wether the group type is correct for the specified // operation // switch(OperationType) { case RevMembGetGroupsForUser: if (NT4GlobalGroup!=NT4GroupType) return STATUS_SUCCESS; break; case RevMembGetAliasMembership: if (NT4LocalGroup!=NT4GroupType) return STATUS_SUCCESS; break; case RevMembGetAccountGroups: case RevMembGlobalGroupsNonTransitive: if (NT5AccountGroup!=NT5GroupType) return STATUS_SUCCESS; break; case RevMembGetResourceGroups: if (NT5ResourceGroup!=NT5GroupType) return STATUS_SUCCESS; break; case RevMembGetUniversalGroups: if (NT5UniversalGroup!=NT5GroupType) return STATUS_SUCCESS; break; } // // If we got upto here, it means that we passed the filter // test. // *pfMatch = TRUE; return STATUS_SUCCESS; } NTSTATUS SampFindGroupByCache ( IN THSTATE *pTHS, IN GUID *pGuid, IN DWORD *pulDNT, IN BOOL fBaseObj, IN REVERSE_MEMBERSHIP_OPERATION_TYPE OperationType, IN ULONG LimitingNCDNT, IN PSID LimitingDomainSid, IN BOOL bNeedSidHistory, OUT BOOLEAN *pfHasSidHistory, OUT BOOLEAN *pfMatch, OUT PDSNAME *ppDSName ) /*++ Given a DNT, try to look it up in the group cache. If we find it, do the check for recursive membership. Parameters: OperationType -- The type of reverse membership operation specified LimitingNCDNT -- The limiting NCDNT where the operation restricts the scope to a domain LimitingDomanSid -- The limiting DomainSid where the operation restricts the scope to a domain pfMatch -- Out parameter TRUE indicates that the current object is should enter the reverse membeship list and be followed transitively Return values STATUS_SUCCESS Other error codes to indicate resource failures --*/ { GROUPTYPECACHERECORD GroupCacheRecord; NTSTATUS NtStatus = STATUS_SUCCESS; ULONG len; DWORD ulDNT=INVALIDDNT; // // Initialize return values // *pfMatch = FALSE; if(!pulDNT) { pulDNT = &ulDNT; } // First, see if the object is in the cache if(!GetGroupTypeCacheElement(pGuid, pulDNT, &GroupCacheRecord)) { // failed to find the object in the cache, just return return STATUS_INTERNAL_ERROR; } // Get the shortdsname that's stored in the cache. *ppDSName = (PDSNAME)THAllocEx(pTHS, DSNameSizeFromLen(0)); (*ppDSName)->structLen = DSNameSizeFromLen(0); (*ppDSName)->Guid = GroupCacheRecord.Guid; (*ppDSName)->Sid = GroupCacheRecord.Sid; (*ppDSName)->SidLen = GroupCacheRecord.SidLen; // Say that we have a sid history if we were asked for sid history and we // actually have one. That is, if the caller didn't need the sid history // checked, tell him we don't have one. *pfHasSidHistory = (bNeedSidHistory && (GroupCacheRecord.flags & GTC_FLAGS_HAS_SID_HISTORY)); if(!fBaseObj) { NtStatus = SampCheckGroupTypeAndDomainLocal ( pTHS, (*ppDSName)->SidLen, &(*ppDSName)->Sid, GroupCacheRecord.NCDNT, GroupCacheRecord.GroupType, GroupCacheRecord.Class, OperationType, LimitingNCDNT, LimitingDomainSid, pfMatch); if(!NT_SUCCESS(NtStatus)) { *pfMatch = FALSE; return NtStatus; } if(!*pfMatch) { return STATUS_SUCCESS; } } if(!(*pfHasSidHistory)) { // Don't actually need to be current in the obj table since the caller // doesn't intend to check the SID history, or he does and the Group // Type Cache says that he will find no value. So just tweak the DNT in // the DBPOS so that we get to the correct place in the link table. // NOTE!!! This is highly dangerous!!! We are lying to the DBLayer, // telling it currency is set to a specific object in the object table. // We do this so that the code to read link values will pick the DNT out // of the DBPOS, and that code doesn't actually read from the object // table, just the link table. // We're doing this extra curicular tweaking in very controlled // circumstances, when we believe that no one will use the currency in // the object table before we re-set currency to somewhere else. This // is a very likely source for bugs and unexplained behaviour later, but // doing it now will make us a LOT faster, and this code desperately // needs to be optimized. pTHS->pDB->DNT = *pulDNT; } else { DPRINT(3,"Found in the group cache, have to move anyway\n"); // // If we got up to here, it means that we passed the filter // test. Furthermore, the caller is going to check SID history, and the // cache says that one exists. Since someone is going to read from the // object, we have to actually position on the object in the DIT. // // Try to find the DNT. if(DBTryToFindDNT(pTHS->pDB,*pulDNT)) { *pfMatch = FALSE; return STATUS_INTERNAL_ERROR; } Assert(DBCheckObj(pTHS->pDB)); } return STATUS_SUCCESS; } NTSTATUS SampCheckGroupTypeAndDomain( IN THSTATE *pTHS, IN DSNAME *pDSName, IN REVERSE_MEMBERSHIP_OPERATION_TYPE OperationType, IN ULONG LimitingNCDNT, IN PSID LimitingDomainSid, OUT BOOLEAN *pfMatch ) /*++ Given the Operation type, the limiting NCDNT and the LimitingDomainSid this routine determines wether the currently positioned object is of the right type and belongs to the correct domain, and indicate whether it can enter the reverse membership list and /or be followed transitively Parameters: OperationType -- The type of reverse membership operation specified LimitingNCDNT -- The limiting NCDNT where the operation restricts the scope to a domain LimitingDomanSid -- The limiting DomainSid where the operation restricts the scope to a domain pfMatch -- Out parameter TRUE indicates that the current object is should enter the reverse membeship list and be followed transitively Return values STATUS_SUCCESS Other error codes to indicate resource failures --*/ { ULONG actualClass; ULONG actualNCDNT; ULONG actualGroupType; NTSTATUS NtStatus = STATUS_SUCCESS; // // Initialize return values // *pfMatch = FALSE; // Get the data if ( 0 != DBGetSingleValue( pTHS->pDB, FIXED_ATT_NCDNT, &actualNCDNT, sizeof(actualNCDNT), NULL) ) { return(STATUS_INTERNAL_ERROR); } if ( 0 != DBGetSingleValue( pTHS->pDB, ATT_GROUP_TYPE, &actualGroupType, sizeof(actualGroupType), NULL) ) { // Cannot read the GroupType. // this means that the object is probaly // not a group, so does not enter token return(STATUS_SUCCESS); } if ( 0 != DBGetSingleValue( pTHS->pDB, ATT_OBJECT_CLASS, &actualClass, sizeof(actualClass), NULL) ) { // Failed to Read Object Class return STATUS_INTERNAL_ERROR; } NtStatus = SampCheckGroupTypeAndDomainLocal ( pTHS, pDSName->SidLen, &pDSName->Sid, actualNCDNT, actualGroupType, actualClass, OperationType, LimitingNCDNT, LimitingDomainSid, pfMatch); if(!NT_SUCCESS(NtStatus)) { *pfMatch = FALSE; return NtStatus; } return STATUS_SUCCESS; } ULONG ulDNTDomainUsers=0; ULONG ulDNTDomainComputers=0; ULONG ulDNTDomainControllers=0; NTSTATUS SampGetPrimaryGroup( IN THSTATE *pTHS, IN DSNAME * UserName OPTIONAL, OUT PULONG pPrimaryGroupDNT) /*++ Routine Description This routine retrieves the primary group of an object. At input the database cursor is assumed to be positioned on the object. At successful return time the database cursor is positioned on the priamry group object Parameters UserName - If the User's DS Name has been specified, then grab the SID, from the user's DS Name as opposed to reading the SID again PrimaryGroupDNT - DNT of the Primary Group is returned in here If the object does not have a primary group then the return code is SUCCESS and this parameter is set to NULL Return Values STATUS_SUCCESS STATUS_UNSUCCESSFUL --*/ { NTSTATUS NtStatus = STATUS_SUCCESS; ULONG PrimaryGroupIdVal; PULONG PrimaryGroupId = &PrimaryGroupIdVal; ULONG outLen; DWORD err; ULONG ulDNTToReturn=0; *pPrimaryGroupDNT = 0; // // At this point we are positioned on the object whose // primary group Id we want to retrieve. Issue a DBGetAttVal // to retrieve the value of Primary Group Id // err=DBGetAttVal( pTHS->pDB, 1, ATT_PRIMARY_GROUP_ID, DBGETATTVAL_fCONSTANT, // DB layer should alloc sizeof(ULONG), // initial buffer size &outLen, // output buffer size (UCHAR **) &PrimaryGroupId ); if (0==err) { NT4SID SidBuffer; PSID Sid=&SidBuffer; NT4SID DomainSid; ULONG sidLen; DSNAME PrimaryGroupDN; // // Found the Primary Group Id of the user object. // Assert(sizeof(ULONG)==outLen); // // check if primary group is one of the standard groups // switch(PrimaryGroupIdVal) { case DOMAIN_GROUP_RID_USERS: if (0!=ulDNTDomainUsers) { ulDNTToReturn = ulDNTDomainUsers; break; } case DOMAIN_GROUP_RID_COMPUTERS: if (0!=ulDNTDomainComputers) { ulDNTToReturn = ulDNTDomainComputers; break; } case DOMAIN_GROUP_RID_CONTROLLERS: if (0!=ulDNTDomainControllers) { ulDNTToReturn = ulDNTDomainControllers; break; } default: if (UserName->SidLen > 0) { // // Try making use of the SID in the User DN // RtlCopyMemory(Sid,&(UserName->Sid),sizeof(NT4SID)); sidLen = RtlLengthSid(Sid); } else { // // Retrieve the User Object's SID // if (0!=DBGetAttVal( pTHS->pDB, 1, ATT_OBJECT_SID, DBGETATTVAL_fCONSTANT, // DB layer should alloc sizeof(NT4SID), // initial buffer size &sidLen, // output buffer size (UCHAR **) &Sid )) { NtStatus = STATUS_UNSUCCESSFUL; goto Error; } } Assert(RtlValidSid(Sid)); Assert(sidLen<=sizeof(NT4SID)); // // Compose the Primary group object's Sid. // This makes the assumption the the primary group // and the user are in the same domain, so only their // Rids are affected, so munge the Rid field in the Sid // *RtlSubAuthoritySid( Sid, *RtlSubAuthorityCountSid(Sid)-1) = *PrimaryGroupId; // // Construct a Sid Only name. With full support for positioning // by SID we should be able to construct a Sid only name // RtlZeroMemory(&PrimaryGroupDN, sizeof(DSNAME)); PrimaryGroupDN.SidLen = RtlLengthSid(Sid); RtlCopyMemory(&(PrimaryGroupDN.Sid), Sid, RtlLengthSid(Sid)); PrimaryGroupDN.structLen = DSNameSizeFromLen(0); // // Position using the SID only Name // err = DBFindDSName(pTHS->pDB, &PrimaryGroupDN); if (0!=err) { // // Cannot find the Primary Group // object. This is again ok, as the group could // have been deleted, and since we maintain // no consistency wrt primary group, this can // happen // NtStatus = STATUS_SUCCESS; goto Error; } // // O.k We are now postioned on the primary group // object.Update the standard DNT's if required // ulDNTToReturn = pTHS->pDB->DNT; switch(ulDNTToReturn) { case DOMAIN_GROUP_RID_USERS: ulDNTDomainUsers = ulDNTToReturn; break; case DOMAIN_GROUP_RID_COMPUTERS: ulDNTDomainComputers = ulDNTToReturn; break; case DOMAIN_GROUP_RID_CONTROLLERS: ulDNTDomainControllers = ulDNTToReturn; break; } } } else if (DB_ERR_NO_VALUE==err) { // // We cannot give the Primary Group Id. THis is // ok as the object in question does not have a // valid primary group // NtStatus = STATUS_SUCCESS; } else { // // Else we must fail the call. Cannot ever give a wrong value for // someone's token // NtStatus = STATUS_UNSUCCESSFUL; } Error: if (NT_SUCCESS(NtStatus)) { *pPrimaryGroupDNT = ulDNTToReturn; } return NtStatus; } NTSTATUS SampReadSidHistory( THSTATE * pTHS, CDSNameSet * pSidHistory ) /*++ Routine Description This Routine Reads the Sid History Off of the Currently Positioned object. This routine does not alter the cursor position. Parameters pSidHistory This is a pointer to a CDSNameSet Object. The SIDs pertaining to SID history are added to this object. Using the CDSNameSet class, allows for automatic memory allocation management, plus also automatically filters out any duplicates. This is actually a performance saver, because higher layers now need not manually check for duplicates. --*/ { ULONG dwErr=0; ULONG iTagSequence =0; ATTCACHE *pAC = NULL; ULONG outLen; PSID SidValue; // Get attribute cache entry for reverse membership. if (!(pAC = SCGetAttById(pTHS, ATT_SID_HISTORY))) { LogUnhandledError(ATT_SID_HISTORY); return STATUS_UNSUCCESSFUL; } // // Read all the values in JET. // PERFHINT: at some point see if we can do everything in 1 retrieve // column // while (0==dwErr) { dwErr = DBGetAttVal_AC( pTHS->pDB, // DBPos ++iTagSequence, // which value to get pAC, // which attribute DBGETATTVAL_fREALLOC, // DB layer should alloc 0, // initial buffer size &outLen, // output buffer size (UCHAR **) &SidValue); if (0==dwErr) { // We Successfully retrieved a Sid History value // Add it to the List. Construct a SID only DSNAME // for the SID history and add to the CReverseMembership Assert(RtlValidSid(SidValue)); Assert(RtlLengthSid(SidValue)<=sizeof(NT4SID)); pSidHistory->CheckDuplicateAndAdd(SidValue); if (pSidHistory->Count() > MAX_TOKEN_GROUPS_COUNT) { break; } } else if (DB_ERR_NO_VALUE==dwErr) { // // It's Ok to have no Sid History. // continue; } else { return STATUS_UNSUCCESSFUL; } } return STATUS_SUCCESS; } ////////////////////////////////////////////////////////////////////////// // // // SampGetMemberships - Implementation // // // ////////////////////////////////////////////////////////////////////////// extern "C" { DWORD SampFindObjectByGuid( IN THSTATE * pTHS, IN DSNAME * ObjectName, IN REVERSE_MEMBERSHIP_OPERATION_TYPE OperationType, IN BOOLEAN fBaseObject, IN BOOLEAN fUserObject, IN ULONG LimitingNCDNT, IN PSID LimitingDomainSid, IN BOOLEAN fSidHistoryRequired, OUT BOOLEAN * pfChecked, OUT BOOLEAN * pfMatch, OUT BOOLEAN * pfHasSidHistory, OUT BOOLEAN * pfMorePassesRequired ) /*++ Routine Description This routine finds the object by GUID. It first checks the group type cache for a match. If the cache lookup did not succeed it positions on the object by GUID Parameters pTHS -- The current Thread State ObjectName -- The GUID based object Name OperationType -- The reverse membership operation type fUserObject -- Indicates that the given DS name indicates a user object fBaseObject -- The base object of the search LimitingNcDNT -- Specifies the NC where we want to lookup the object in LimitingDomainSid -- The SID of the domain ( builtin/account ) that we want to lookup the object in pfChecked -- Indicates that the group type check has been performed on this object. pfMatch -- If pfChecked is true means that the group type matched pfHasSidHistory -- Wether or not a group has sid history is returned in there if the above 2 are true Return Values 0 On Success Other DB Layer error codes on failure --*/ { DWORD dwErr = 0; NTSTATUS NtStatus = STATUS_SUCCESS; // // Initialize Return Values // *pfChecked = FALSE; *pfMatch = TRUE; *pfHasSidHistory = TRUE; // // First try looking up by guid in the group type cache // No Point trying to lookup user objects // if (!fUserObject) { NtStatus = SampFindGroupByCache( pTHS, &ObjectName->Guid, NULL, fBaseObject, OperationType, LimitingNCDNT, LimitingDomainSid, fSidHistoryRequired, pfHasSidHistory, pfMatch, &ObjectName ); } if ((NT_SUCCESS(NtStatus)) && (!fUserObject)) { // Found it in the cache // // If we are looking up by guid, this is typically the object passed // in as opposed to recursing up the tree. The object passed need not // match, any criterio plus also can be a phantom ( as in the case // of cross domain memberships ). // *pfChecked = TRUE; } else { // // Try to find the DS Name. // dwErr = DBFindDSName(pTHS->pDB, ObjectName); // // If we missed a group in the cache then // then try add that to the group type cache. // if ((!dwErr) && (!fUserObject)) { GroupTypeCacheAddCacheRequest(pTHS->pDB->DNT); } } // We are finished with the current DS name *pfMorePassesRequired = FALSE; return(dwErr); } DWORD SampFindObjectByDNT( IN THSTATE * pTHS, IN ULONG ulDNT, IN REVERSE_MEMBERSHIP_OPERATION_TYPE OperationType, IN ULONG LimitingNCDNT, IN PSID LimitingDomainSid, IN BOOLEAN fSidHistoryRequired, OUT BOOLEAN * pfChecked, OUT BOOLEAN * pfMatch, OUT BOOLEAN * pfHasSidHistory, OUT BOOLEAN * pfMorePassesRequired, OUT DSNAME ** ObjectName ) /*++ Routine Description This routine finds the object by DNT. It first checks the group type cache for a match. If the cache lookup did not succeed it positions on the object by GUID Parameters pTHS -- The current Thread State ulDNT -- The DNT of the object OperationType -- The reverse membership operation type LimitingNcDNT -- Specifies the NC where we want to lookup the object in LimitingDomainSid -- The SID of the domain ( builtin/account ) that we want to lookup the object in pfChecked -- Indicates that the group type check has been performed on this object. pfMatch -- If pfChecked is true means that the group type matched pfHasSidHistory -- Wether or not a group has sid history is returned in there if the above 2 are true ObjectName -- The GUID and SID of the object are returned in this valid DS Name structure Return Values 0 On Success Other DB Layer error codes on failure --*/ { DWORD dwErr = 0; NTSTATUS NtStatus = STATUS_SUCCESS; ULONG len = 0; // // Initialize Return Values // *pfChecked = FALSE; *pfMatch = TRUE; *pfHasSidHistory = TRUE; // // Try the group type cache. // NtStatus = SampFindGroupByCache( pTHS, NULL, &ulDNT, FALSE, //fBaseObject OperationType, LimitingNCDNT, LimitingDomainSid, fSidHistoryRequired, pfHasSidHistory, pfMatch, ObjectName ); if (NT_SUCCESS(NtStatus)) { // Found the object in the cache. // Since finding by DNT is used only for objects that // were returned as part of the reverse membership list // of someone, we should always find it, and it should not // be a phantom. Assert that that matched object that has // no sid history ( common case of cache hits ) is not a // phantom. Assert(!(*pfMatch )|| !(*pfHasSidHistory) || DBCheckObj(pTHS->pDB)); *pfChecked = TRUE; } else { // // Try to find the DNT. by looking up the database // dwErr = DBTryToFindDNT(pTHS->pDB,ulDNT); // Since finding by DNT is used only for objects that // were returned as part of the reverse membership list // of someone, we should always find it, and it should not // be a phantom if (0==dwErr) { Assert(DBCheckObj(pTHS->pDB)); // // Obtain the DS Name of the Currently Positioned Object // *ObjectName = (DSNAME *)THAllocEx(pTHS,sizeof(DSNAME)); RtlZeroMemory(*ObjectName,sizeof(DSNAME)); dwErr = DBFillGuidAndSid( pTHS->pDB, *ObjectName ); (*ObjectName)->NameLen = 0; (*ObjectName)->structLen = DSNameSizeFromLen(0); } } *pfMorePassesRequired = FALSE; return(dwErr); } NTSTATUS SampFindAndAddPrimaryMembers( IN THSTATE * pTHS, IN DSNAME * GroupName, OUT CDSNameSet * pMembership ) /*++ Routine Description This routine finds and adds the set of members that are members by virtue of the primary group id property to the set of memberships. This is done by walking the primary group id index. Parameters pTHS -- The current thread state GroupName The DSNAME of the group pMembership -- The transitive membership is added to this set. Return Values STATUS_SUCCESS --*/ { NTSTATUS Status = STATUS_SUCCESS; DSNAME *pSearchRoot; FILTER filter; SEARCHARG searchArg; SEARCHRES *pSearchRes; ENTINFSEL entInfSel; ATTRVAL attrValFilter; ATTRBLOCK *pAttrBlock; ULONG i=0; RESTART *pRestart = NULL; ATTRBLOCK RequiredAttrs; NT4SID DomainSid; ULONG Rid; ULONG BuiltinDomainSid[] = {0x101,0x05000000,0x20}; Assert(NULL != pTHS); Assert(NULL != pTHS->pDB); RtlZeroMemory(&RequiredAttrs,sizeof(ATTRBLOCK)); // Find the Root Domain Object, for the specified Sid // This ensures that we find only real security prinicpals, // but not turds ( Foriegn Domain Security Principal ) and // other objects in various other domains in the G.C that might // have been created in the distant past before all the DS // stuff came together SampSplitNT4SID(&GroupName->Sid,&DomainSid,&Rid); // // If the SID is from the builtin Domain then return success. // Builtin domain contains only builtin local groups therefore // if (RtlEqualSid(&DomainSid,(PSID) &BuiltinDomainSid)) { return STATUS_SUCCESS; } if (!FindNcForSid(&DomainSid,&pSearchRoot)) { // This is a case of an FPO that is a member of some // group in the forest. The FPO by itself will not have // any members. So it is O.K to skip without returning // an error return STATUS_SUCCESS; } do { attrValFilter.valLen = sizeof(ULONG); // Rid is pointer to last subauthority in SID attrValFilter.pVal = (PUCHAR )RtlSubAuthoritySid( &GroupName->Sid, *RtlSubAuthorityCountSid(&GroupName->Sid)-1); memset(&filter, 0, sizeof(filter)); filter.choice = FILTER_CHOICE_ITEM; filter.FilterTypes.Item.choice = FI_CHOICE_EQUALITY; filter.FilterTypes.Item.FilTypes.ava.type = ATT_PRIMARY_GROUP_ID; filter.FilterTypes.Item.FilTypes.ava.Value = attrValFilter; memset(&searchArg, 0, sizeof(SEARCHARG)); InitCommarg(&searchArg.CommArg); // Search in multiples of 256 searchArg.CommArg.ulSizeLimit = 256; entInfSel.attSel = EN_ATTSET_LIST; entInfSel.AttrTypBlock = RequiredAttrs; entInfSel.infoTypes = EN_INFOTYPES_TYPES_VALS; searchArg.pObject = pSearchRoot; searchArg.choice = SE_CHOICE_WHOLE_SUBTREE; // Do not Cross NC boundaries. searchArg.bOneNC = TRUE; searchArg.pFilter = &filter; searchArg.searchAliases = FALSE; searchArg.pSelection = &entInfSel; pSearchRes = (SEARCHRES *) THAllocEx(pTHS, sizeof(SEARCHRES)); pSearchRes->CommRes.aliasDeref = FALSE; pSearchRes->PagedResult.pRestart = pRestart; SearchBody(pTHS, &searchArg, pSearchRes,0); if (pSearchRes->count>0) { ENTINFLIST * CurrentEntInf; for (CurrentEntInf = &(pSearchRes->FirstEntInf); CurrentEntInf!=NULL; CurrentEntInf=CurrentEntInf->pNextEntInf) { pMembership->CheckDuplicateAndAdd(CurrentEntInf->Entinf.pName); } } pRestart = pSearchRes->PagedResult.pRestart; } while ((NULL!=pRestart) && (pSearchRes->count>0)); return ( Status); } NTSTATUS SampGetMembersTransitive( IN THSTATE * pTHS, IN DSNAME * GroupName, OUT CDSNameSet *pMembership ) /*++ Routine Description This is the worker routine to find the transitive membership list of a group by traversing the link table. This routine does not consider the membership by virtue of the primary group id property. This is O.K for transitive membership computation as only users have a primary group id property and users are by defintion "leaves" in a membership list Parameters pTHS -- The current thread state GroupName The DSNAME of the group pMembership -- The transitive membership is added to this set. Return Values STATUS_SUCCESS STATUS_OBJECT_NAME_NOT_FOUND Other Error codes --*/ { NTSTATUS Status = STATUS_SUCCESS; CReverseMembership Membership; DWORD dwErr =0 ; ULONG ulDNT=0; BOOLEAN fBaseObject = TRUE; ATTCACHE * pAC; ULONG len; DSNAME * pDsName; BOOL bFirst; __try { // // Get an attribute cache entry for membership // if (!(pAC = SCGetAttById(pTHS, ATT_MEMBER))) { LogUnhandledError(ATT_MEMBER); Status =STATUS_UNSUCCESSFUL; __leave; } while(fBaseObject || (0!=ulDNT)) { CLASSCACHE *pClassCache; ULONG iClass; BOOL FindPrimaryMembers = FALSE; // // Position on the object locally // if (!fBaseObject) { dwErr = DBTryToFindDNT(pTHS->pDB,ulDNT); if (0!=dwErr) { Status = STATUS_UNSUCCESSFUL; __leave; } // // Get the DSNAME corresponding to this object // dwErr = DBGetAttVal(pTHS->pDB, 1, ATT_OBJ_DIST_NAME, DBGETATTVAL_fSHORTNAME, 0, &len, (PUCHAR *)&pDsName ); if (DB_ERR_NO_VALUE==dwErr) { // // This could be because the object we are // positioned right now might be a phantom. In that // case, we neither need to modify the object, nor need // to follow it transitively. Therefore start again with // the next object // dwErr = 0; goto NextObject; } else if (0!=dwErr) { Status = STATUS_UNSUCCESSFUL; __leave; } // // Add it to the list being returned // pMembership->CheckDuplicateAndAdd(pDsName); } else { dwErr = DBFindDSName(pTHS->pDB,GroupName); if ((DIRERR_OBJ_NOT_FOUND==dwErr) || (DIRERR_NOT_AN_OBJECT==dwErr)) { // // if the object was not found, or was a phantom, then return // an NtStatus code that indicates that the object was not // found // Status = STATUS_OBJECT_NAME_NOT_FOUND; __leave; } else if (0!=dwErr) { Status = STATUS_UNSUCCESSFUL; __leave; } pDsName = GroupName; } // // determine whether the current object is a group account or not. // if ( 0 != SampDetermineObjectClass(pTHS, &pClassCache) ) { Status = STATUS_UNSUCCESSFUL; __leave; } if ( SampSamClassReferenced(pClassCache, &iClass) && (ClassMappingTable[iClass].SamObjectType == SampGroupObjectType || ClassMappingTable[iClass].SamObjectType == SampAliasObjectType) ) { FindPrimaryMembers = TRUE; } // // Recurse through all the objects in the membership // list of the group // bFirst = TRUE; while ( TRUE ) { PULONG pNextDNT=NULL; ULONG ulNextDNT; dwErr = DBGetNextLinkValForLogon( pTHS->pDB, bFirst, pAC, &ulNextDNT ); if ( DB_ERR_NO_VALUE == dwErr ) { // No more values. break; } else if ( 0 != dwErr ) { Status =STATUS_INSUFFICIENT_RESOURCES; __leave; } bFirst = FALSE; // // We are casting a 32 bit unsigned integer to a pointer // The assumption here is that the pointer type is // always equal or bigger ( in terms of bits ) // Membership.Add((PVOID)(ULONG_PTR)ulNextDNT); } // // Add the membership by virtue of the primary // group id property. No need to follow this // transitively // only do so for group object // if ( FindPrimaryMembers ) { Status = SampFindAndAddPrimaryMembers( pTHS, pDsName, pMembership ); if (!NT_SUCCESS(Status)) { __leave; } } NextObject: // // For Sundown the Assumption here is that DNT will always be // a 32 bit value and so truncating and losing the upper few // bits is O.K // ulDNT = PtrToUlong(Membership.NextUnrecursed()); pDsName = NULL; fBaseObject = FALSE; } // while ( 0!=ulDNT ) } __finally { } return Status; } NTSTATUS SampGetMembershipsActual( IN THSTATE *pTHS, IN DSNAME *pObjName, IN BOOLEAN fUserObject, IN OPTIONAL DSNAME *pLimitingDomain, IN REVERSE_MEMBERSHIP_OPERATION_TYPE OperationType, IN OUT CDSNameSet *pReverseMembership, IN OUT CDSNameSet *pSidHistory OPTIONAL ) /*++ Routine Description: Derives the transitive reverse membership of an object local to this machine. This is the worker routine for reverse membership derivation Arguments: pObjName - pointer to DSNAME of the object whose reverse membership is desired. fUserObject - Set to true if the object specified in pObjName is a user object. This information is used to optimize lookups/fills in the group type cache. Note Getting this flag wrong, only results in a small performance penalty, does not cause any incorrect operation. pLimitingDomain - optional pointer to the DSNAME of a domain ( or builtin domain to filter results on ie groups not from this domain are neither returned nor followed transitively. OperationType -- Indicates the type of group membership evaluation we need to perform. Valid values are RevMembGetGroupsForUsers -- Gets the non transitive ( one level) membership, of an object in groups confined to the same domain ( specified by pLimitingDomain. Will filter out builtin groups. RevMembGetAliasMembership -- Gets the non transitive ( one level) membership of an object in local groups confined to the same domain ( specified by limiting domain SID and limiting naming context ). RevMembGetUniversalGroups -- Gets the transitive reverse membership in all universal groups, without regard to any restrictions. Will filter out builtin groups. The pLimitingDomain Parameter should not be specified RevMembGetAccountGroups -- Gets the transitive reverse membership in all account groups, in the domain specified by pLimitingDomain. Will filter out builtin groups. RevMembGetResourceGroups -- Gets the transitive reverse membership in all resource groups in the domain specified by pLimitingDomain. Will filter out builtin groups GroupMembersTransitive -- Gets the transitive membership list in the specified set of groups. SID history and attributes are not returned and are ignored if this value is specified for the operation type RevMembGlobalGroupsNonTransitive -- Gets the list of global groups, but does not do the transitive closure of these groups pReverseMembership -- This is a pointer to a DS Name set to which the filtered membership is added. Using DSName sets as parameters simplifies the implementation of routines that get the membership of multiple security principals, as this class has all the logic to filter duplicates. pSidHistory -- This is a pointer to a DS Name set to which the SID history is added. Return Value: STATUS_SUCCESS on success. STATUS_INSUFFICIENT_RESOURCES on a resource failure STATUS_TOO_MANY_CONTEXT_IDS if the number of groups is greater than what can be fit in a token. --*/ { ATTCACHE *pAC; DWORD dwErr; INT iErr; BOOLEAN bFirst; PDSNAME pDSName = pObjName; CReverseMembership revMemb; NTSTATUS status = STATUS_SUCCESS; BOOLEAN fMatch; BOOLEAN fHasSidHistory; ULONG dwException, ulErrorCode, ul2; PVOID dwEA; ULONG i; ULONG LimitingNCDNT; PSID LimitingDomainSid; BOOLEAN fBaseObject = TRUE; BOOLEAN fTransitiveClosure; BOOLEAN fChecked = FALSE; BOOLEAN fFirstTimeUserObject = FALSE; ULONG ulDNT=0; __try { // // pLimiting domain should be specified if and only if // op type is not RevMembGetUniversalGroups or GroupMembersTransitive // Assert((OperationType==RevMembGetUniversalGroups) ||(OperationType==GroupMembersTransitive) ||(NULL!=pLimitingDomain)); Assert((OperationType!=RevMembGetUniversalGroups)||(NULL==pLimitingDomain)); // // Return data will be allocated off the thread heap, so insure // we're within the context of a DS transaction. Assert(SampExistsDsTransaction()); // // Caller better specify pObjName // Assert(NULL!=pObjName); // // If the transitive membership list is specified then compute that and leave // if (GroupMembersTransitive==OperationType) { status = SampGetMembersTransitive( pTHS, pObjName, pReverseMembership ); goto ExitTry; } // // Compute whether we need transitive closure // fTransitiveClosure = ((OperationType!=RevMembGetGroupsForUser ) && (OperationType!=RevMembGetAliasMembership) && (OperationType!=RevMembGlobalGroupsNonTransitive)); if ( fTransitiveClosure ) { INC( pcMemberEvalTransitive ); // // Update counters for various transitive cases // switch ( OperationType ) { case RevMembGetUniversalGroups: INC( pcMemberEvalUniversal ); break; case RevMembGetAccountGroups: INC( pcMemberEvalAccount ); break; case RevMembGetResourceGroups: INC( pcMemberEvalResource ); break; } } else { INC( pcMemberEvalNonTransitive ); } // // Get attribute cache entry for reverse membership. // if (!(pAC = SCGetAttById(pTHS, ATT_IS_MEMBER_OF_DL))) { LogUnhandledError(ATT_IS_MEMBER_OF_DL); status =STATUS_UNSUCCESSFUL; goto ExitTry; } // // If a Limiting Domain is specified, the limiting domain test is (theoretically) // applied in the following manner ( note limiting domain can be a builtin domain ) // 1. Get an NCDNT value, such that a group with that NCDNT value will // may fall within the domain and groups with different NCDNT value will // definately fall outside that domain. If the domain object specfied // is an NC head this corresponds to the case of a "normal" domain use // the DNT of the domain as the NCDNT value. Otherwise assume it is a // builtin domain. // // 2. Get the Domain SID from the specified DSNAME and throw away groups which // do not have the domain prefix equal to the domain SID. // // Product1 however does not have multiple hosted domain support. Therefore it is // safe to assume that the limiting domain that is passed in always either the // authoritative domain for the domain controller , or its corresponding builtin // domain. if (ARGUMENT_PRESENT(pLimitingDomain)) { Assert(pLimitingDomain->SidLen>0); LimitingDomainSid = &pLimitingDomain->Sid; Assert(RtlValidSid(LimitingDomainSid)); Assert(NULL!=gAnchor.pDomainDN); // Assert((NameMatched(gAnchor.pDomainDN,pLimitingDomain)) // ||(IsBuiltinDomainSid(LimitingDomainSid))); LimitingNCDNT = gAnchor.ulDNTDomain; } else { LimitingDomainSid = NULL; LimitingNCDNT = 0; } // // Loop getting reverse memberships until we're done. // while (fBaseObject || (0!=ulDNT)) { DWORD iObject=0; BOOLEAN fSearchBySid = FALSE; BOOLEAN fSearchByDNT = FALSE; BOOLEAN fMorePassesOverCurrentName = TRUE; ULONG TotalCount = 0; fSearchBySid = (NULL!=pDSName)&&(fNullUuid( &pDSName->Guid ))&&(0==pDSName->NameLen) &&(pDSName->SidLen>0)&&(RtlValidSid(&(pDSName->Sid))); fSearchByDNT = (NULL==pDSName); while(fMorePassesOverCurrentName) { // // Position database to the name. // // SampGetMemberships accepts several types of Names // // 1. Standard DS Name , with either the GUID or Name Filled in. In this // case SampGetMemberships uses DBFindDSName to position on the object. // Only a single pass is made over the name // // 2. A Sid Only DSName, with no GUID and String name Filled in. In this case // this routine Uses DBFindObjectWithSid to position on the object. // Multiple passes are made , each type with a different sequence number // to find all occurrences of Object's with the given SID. Note on a G.C // several object's may co-exist with the same Sid, but on different // naming context. A simple case is the builtin groups. A more complex case // is (former)NT4 security prinicipals being members of DS groups. ( FPO's // and regular objects for the same security principals ). // // // 3. It is possible that the DS name is that of a phantom // object in the DIT. This happens during an AliasMembership expansion, or // a resource group expansion, where a cross domain member's reverse membership // is being expanded. // // 4. The name is simpy a DNT. This happens when recursing up, as for performance // reasons it is more efficient to keep the identity of the object as a DNT. // // Also since DBFindDsName and DBFIndObjectWithSid can throw exceptions, // they are enclosed within a exception handler // // assume the object has not been checked in the group type cache fChecked = FALSE; // Assume object will match any limited group constraints fMatch = TRUE; // Assume a sid history fHasSidHistory = TRUE; __try { if (fSearchByDNT) { // // Base object Cannot be a DNT // Assert(!fBaseObject); // // Lookup the object by DNT // dwErr = SampFindObjectByDNT( pTHS, ulDNT, OperationType, LimitingNCDNT, LimitingDomainSid, ARGUMENT_PRESENT(pSidHistory), &fChecked, &fMatch, &fHasSidHistory, &fMorePassesOverCurrentName, &pDSName ); } else if (fSearchBySid) { dwErr = DBFindObjectWithSid(pTHS->pDB, pDSName,iObject++); // We have not yet found all occurences of object's with the given // Sid. Therefore do not as yet mark this ds Name as finished. Down // below when we examing the error code, we will decide whether more // passes are needed or not. } else { // // Search By GUID // dwErr = SampFindObjectByGuid( pTHS, pDSName, OperationType, fBaseObject, (fBaseObject) && (fUserObject), LimitingNCDNT, LimitingDomainSid, ARGUMENT_PRESENT(pSidHistory), &fChecked, &fMatch, &fHasSidHistory, &fMorePassesOverCurrentName ); } switch(dwErr) { case 0: // Success break; case DIRERR_NOT_AN_OBJECT: if (fBaseObject) { // Positioning on Phantom is OK for base Object dwErr=0; } else { // // While recursing up we should never position // on a phantom. This is because // Membership "travels" with the group, not the member. // Therefore the reverse membership property points only // to memberships in groups in naming contexts on this // machine. Thus returned name is real, not a phantom. // Assert(FALSE && "Positioned on a Phantom while recursing up"); status = STATUS_INTERNAL_ERROR; goto ExitTry; } break; case DIRERR_OBJ_NOT_FOUND: if (fSearchBySid) { // If we are Searching By Sid its Ok to not find the // object. Skip the object and attempt processing the // next object dwErr=0; // We are finished with the current DS name // as all occurances of the object(s) with the given SID // have been processed. // We are not positioned on any object at this time. We must // go get the next DS Name to process. So exit this loop. fMorePassesOverCurrentName=FALSE; continue; } else { status = STATUS_OBJECT_NAME_NOT_FOUND; goto ExitTry; } break; default: status = STATUS_INSUFFICIENT_RESOURCES; goto ExitTry; } } __except (HandleMostExceptions(GetExceptionCode())) { // bail on exception. Most likely cause of an exception // is a resource failure. So set error code as // STATUS_INSUFFICINET_RESOURCES status = STATUS_INSUFFICIENT_RESOURCES; goto ExitTry; } // // If We are here we have a DSName for the current object // Assert(NULL!=pDSName); // // If the specified object is not the base object specified then // apply the filter test // if (!fBaseObject) { // // If the object registered a group type cache hit, then the lookup // itself has done the filter test for the match. Therefore there is // no need to perform a (slow) match test again. In thos cases the // fChecked flag is set. // if(!fChecked) { // // Now depending upon the operation requested evaluate // the filter. We are positioned on the object right now // and can get some properties on a demand basis. Further // we know that the object is not the base object // status = SampCheckGroupTypeAndDomain( pTHS, pDSName, OperationType, LimitingNCDNT, LimitingDomainSid, &fMatch ); if (!NT_SUCCESS(status)) { goto ExitTry; } } if (!fMatch) { // // Our Filter Indicates that we need not consider this // object for further reverse membership processing, // (either adding to the list ) or following up transtively. // Therefore move on to the next object // continue; } // // Since this is not the base object add this to the reverse membership // list to be returned // pReverseMembership->CheckDuplicateAndAdd(pDSName); } // // Read The Sid History If required. // The SID history is added in , in general only for objects that are retrieved as part of this // routine. The one exception to the rule is for the case of the user object that is passed in first // around for evaluation. // fFirstTimeUserObject = fBaseObject && ((OperationType == RevMembGetAccountGroups ) || (OperationType==RevMembGetGroupsForUser)); if (ARGUMENT_PRESENT(pSidHistory) && fHasSidHistory && ( !fBaseObject || fFirstTimeUserObject)) { // // Caller Wanted Sid History // status = SampReadSidHistory(pTHS, pSidHistory); if (!NT_SUCCESS(status)) goto ExitTry; } // // for performance consideration (to prevent/recovery from the Deny of Service Attack) // stop group expansion if reached the limit // see windows bug 452255 for more detail. // TotalCount = pReverseMembership->Count(); if (ARGUMENT_PRESENT(pSidHistory)) { TotalCount += pSidHistory->Count(); } if (TotalCount > MAX_TOKEN_GROUPS_COUNT) { goto ExitTry; } // This object satisfies all filter criterions, therefore we should // follow the object. Call DBGetAttVal_AC multiple times to get all the values // in the reverse membership, and add it to the list to be // examined. We will always follow the object if transitive closure is specified // or if it is the base object, whose reverse membership we need to compute bFirst = TRUE; while ( fBaseObject || fTransitiveClosure ) { PULONG pNextDNT=NULL; ULONG ulNextDNT; dwErr = DBGetNextLinkValForLogon( pTHS->pDB, bFirst, pAC, &ulNextDNT ); if ( DB_ERR_NO_VALUE == dwErr ) { // No more values. break; } else if ( 0 != dwErr ) { status =STATUS_INSUFFICIENT_RESOURCES; goto ExitTry; } bFirst = FALSE; // // We are casting a 32 bit unsigned integer to a pointer // The assumption here is that the pointer type is // always equal or bigger ( in terms of bits ) // revMemb.Add((PVOID)(ULONG_PTR)ulNextDNT); } // // The primary group for users is not stored explicity, but rather in // the primary group id property implicitly. Merge this into the reverse // memberships. Note further that SampGetPrimaryGroup will alter cursor // positioning. Therefore this should be the last element in the group // // Note: if fChecked is true at this point along with fBase object then // this means that the base object was also successfully looked up using // the GUID in the group type cache. Since groups have no notion of primary // group ID we should not need too call SampGetPrimaryGroup to get the primary // group of the object. // // // Note that the PrimaryGroup can be a universal group. If so, // only return this membership when the retrieving the // UniversalGroups. If the PrimaryGroup is a universal group // and AccountGroups are being requested, then the // PrimaryGroup will be rejected when the "type" of the group // is determined above. // if ((fBaseObject) && (!fChecked) && ((RevMembGetGroupsForUser==OperationType) ||(RevMembGetAccountGroups==OperationType) ||(RevMembGetUniversalGroups==OperationType) ||(RevMembGlobalGroupsNonTransitive==OperationType))) { ULONG PrimaryGroupDNT = 0; status = SampGetPrimaryGroup(pTHS, pDSName, &PrimaryGroupDNT); if (!NT_SUCCESS(status)) goto ExitTry; if (0!=PrimaryGroupDNT) revMemb.Add((PVOID)(ULONG_PTR)PrimaryGroupDNT); } } // Time to recurse. Get the next unrecursed value from UnrecursedSet, // position at it in the database, and return to the top of the // loop. Quit if there are no more unrecursed values. // // For Sundown the Assumption here is that DNT will always be // a 32 bit value and so truncating and losing the upper few // bits is O.K // ulDNT = PtrToUlong(revMemb.NextUnrecursed()); pDSName = NULL; fBaseObject = FALSE; } // while ( NULL != pulDNT ) status = STATUS_SUCCESS; ExitTry: ; } __except(GetExceptionData(GetExceptionInformation(), &dwException, &dwEA, &ulErrorCode, &ul2)) { HandleDirExceptions(dwException, ulErrorCode, ul2); status = STATUS_UNSUCCESSFUL; } return(status); } NTSTATUS SampGetMemberships( IN PDSNAME *rgObjNames, IN ULONG cObjNames, IN OPTIONAL DSNAME *pLimitingDomain, IN REVERSE_MEMBERSHIP_OPERATION_TYPE OperationType, OUT ULONG *pcDsNames, IN OUT PDSNAME **prpDsNames, IN OUT PULONG *Attributes OPTIONAL, IN OUT PULONG pcSidHistory OPTIONAL, IN OUT PSID **rgSidHistory OPTIONAL ) /*++ Routine Description: Derives the transitive reverse membership of an object local to this machine. This is the main reverse membership derivation routine for SAM. This routine will call SampGetMembershipsActual to perform most of the operations Arguments: rgObjNames pointer to an array of DS Name pointers. Each DS Name represents a security prinicipal whose reverse membership we desire cObjNames Count, specifies the number of DS Names in rgObjNames pLimitingDomain - optional pointer to the DSNAME of a domain ( or builtin domain to filter results on ie groups not from this domain are neither returned nor followed transitively. OperationType -- Indicates the type of group membership evaluation we need to perform. Valid values are RevMembGetGroupsForUsers -- Gets the non transitive ( one level) membership, of an object in groups confined to the same domain ( specified by pLimitingDomain. Will filter out builtin groups. RevMembGetAliasMembership -- Gets the non transitive ( one level) membership of an object in local groups confined to the same domain ( specified by limiting domain SID and limiting naming context ). RevMembGetUniversalGroups -- Gets the transitive reverse membership in all universal groups, without regard to any restrictions. Will filter out builtin groups. The pLimitingDomain Parameter should not be specified RevMembGetAccountGroups -- Gets the transitive reverse membership in all account groups, in the domain specified by pLimitingDomain. Will filter out builtin groups. RevMembGetResourceGroups -- Gets the transitive reverse membership in all resource groups in the domain specified by pLimitingDomain. Will filter out builtin groups GetGroupMembersTransitive -- Gets the transitive direct membership in the group based on the information in the direct database. Information about the primary group is also merged in. SID history values and attributes are not returned as part of this call. pcSid - pointer to ULONG which contains SID count on return. prpDsNames - pointer to array of DSname pointers which is allocated and filled in on return. Note Security Code Requires Sids. DsNames structure contains the SID plus the full object Name. The Advantage of returning DS Names is that the second phase of the logon need not come back to resolve the Sids back into DS Names. Resolving them again may cause a potential trip to the G.C again. To avoid this it is best to return DS Names. If second phase needs to run, it can directly use the results fr Attributes - OPTIONAL parameter, which is used to query the Attributes corresponding to the group memberhip . In NT4 and NT5 SAM this is wired to SE_GROUP_MANDATORY | SE_GROUP_ENABLED_BY_DEFAULT | SE_GROUP_ENABLED pcSidHistory OPTIONAL parameter, the count of returned Sids due to the SID history property is returned in here, rgSidHistory Array of Sids in the Sid Historuy Return Value: STATUS_SUCCESS on success. STATUS_INSUFFICIENT_RESOURCES on a resource failure STATUS_TOO_MANY_CONTEXT_IDS if the number of groups is greater than what can be fit in a token. --*/ { THSTATE *pTHS=pTHStls; NTSTATUS status = STATUS_SUCCESS; CDSNameSet ReverseMembership; // External format DSNames CDSNameSet SidHistory; // External format DSNames ULONG dwException, ulErrorCode, ul2; PVOID dwEA; ULONG i; __try { // // Init return values. // *pcDsNames = 0; *prpDsNames = NULL; if (ARGUMENT_PRESENT(pcSidHistory)) *pcSidHistory = 0; if (ARGUMENT_PRESENT(rgSidHistory)) *rgSidHistory = NULL; // // Check for valid operation types // if ((OperationType!=RevMembGetGroupsForUser) && (OperationType!=RevMembGetAliasMembership) && (OperationType!=RevMembGetUniversalGroups) && (OperationType!=RevMembGetAccountGroups) && (OperationType!=RevMembGlobalGroupsNonTransitive)&& (OperationType!=RevMembGetResourceGroups) && (OperationType!=GroupMembersTransitive)) { return(STATUS_INVALID_PARAMETER); } // // Init the classes // ReverseMembership.SetValueType(RevMembDsName); SidHistory.SetValueType(RevMembSid); // // Iterate through each of the objects passed in // for (i=0;i<cObjNames;i++) { if (NULL==rgObjNames[i]) { // // if a NULL was passed in, then simply ignore // This allows sam to simply call resolve Sids, // and pass the entire set of DS names down to // evaluate for reverse memberships // continue; } status = SampGetMembershipsActual( pTHS, rgObjNames[i], (0==i)?TRUE:FALSE, // fUserObject. SAM has this contract with // the DS that in passing an array of DSNAMES // to evaluate the reverse membership of an object // at logon time the user object will be first object // in the list. At other times, notably ACL conversion // this need not be true, but then we can take a peformance // penalty. pLimitingDomain, OperationType, &ReverseMembership, ARGUMENT_PRESENT(rgSidHistory)?&SidHistory:NULL ); if (STATUS_OBJECT_NAME_NOT_FOUND==status) { if ((RevMembGetGroupsForUser!=OperationType) && (RevMembGetAccountGroups!=OperationType) && (RevMembGlobalGroupsNonTransitive!=OperationType)) { // // If the object name was not found, its probaly O.K. // just that the DS Name is not a member of anything // and probably represents a security prinicipal in a // different domain // status = STATUS_SUCCESS; THClearErrors(); continue; } else { // // This is a fatal error in a get groups for user or // get account group membership. This is because SAM // in this case typically evaluating the reverse membership // of a user or a group, that it has verified that it exists // break; } } } if (NT_SUCCESS(status)) { // // Call Succeeded, transfer parameters in the form that caller // wants // *pcDsNames = ReverseMembership.Count(); if (0!=*pcDsNames) { *prpDsNames = (PDSNAME *)ReverseMembership.GetArray(); } if (ARGUMENT_PRESENT(rgSidHistory) && ARGUMENT_PRESENT(pcSidHistory)) { *pcSidHistory = SidHistory.Count(); if (0!=*pcSidHistory) { *rgSidHistory = SidHistory.GetArray(); } } } // We may have allocated and assigned to *prDsnames, but never filled // in any return data due to class filtering. Null out the return // pointer in this case just to be safe. if ( 0 == *pcDsNames ) { *prpDsNames = NULL; } // // If Attributes were asked for then // if (ARGUMENT_PRESENT(Attributes)) { *Attributes = NULL; if (*pcDsNames>0) { *Attributes = (ULONG *)THAllocEx(pTHS, *pcDsNames * sizeof(ULONG)); for (i=0;i<*pcDsNames;i++) { (*Attributes)[i]=SE_GROUP_MANDATORY | SE_GROUP_ENABLED_BY_DEFAULT | SE_GROUP_ENABLED; } } } } __except(GetExceptionData(GetExceptionInformation(), &dwException, &dwEA, &ulErrorCode, &ul2)) { HandleDirExceptions(dwException, ulErrorCode, ul2); status = STATUS_UNSUCCESSFUL; } return(status); } NTSTATUS SampGetMembershipsFromGC( IN PDSNAME *rgObjNames, IN ULONG cObjNames, IN OPTIONAL DSNAME *pLimitingDomain, IN REVERSE_MEMBERSHIP_OPERATION_TYPE OperationType, OUT PULONG pcDsNames, OUT PDSNAME **rpDsNames, OUT PULONG *pAttributes OPTIONAL, OUT PULONG pcSidHistory OPTIONAL, OUT PSID **rgSidHistory OPTIONAL ) /*++ Routine Description: This routine computes the reverse membership of an object at the G.C. Parameters: Same as SampGetMemberships Return Values STATUS_SUCCESS Upon A Successful Evaluation STATUS_NO_SUCH_DOMAIN If a G.C did not exist or could not be contacted STATUS_UNSUCCESSFUL Otherwise --*/ { NTSTATUS NtStatus = STATUS_SUCCESS; ULONG dwErr=0; NTSTATUS ActualNtStatus = STATUS_SUCCESS; THSTATE *pTHS=pTHStls; Assert(NULL!=pTHS); Assert(!SampExistsDsTransaction()); __try { // // Make the Reverse Membership call on the G.C // dwErr = I_DRSGetMembershipsFindGC( pTHS, NULL, NULL, ARGUMENT_PRESENT(pAttributes) ? DRS_REVMEMB_FLAG_GET_ATTRIBUTES : 0, rgObjNames, cObjNames, pLimitingDomain, OperationType, (DWORD *)&ActualNtStatus, pcDsNames, rpDsNames, pAttributes, pcSidHistory, rgSidHistory, FIND_DC_USE_CACHED_FAILURES | FIND_DC_USE_FORCE_ON_CACHE_FAIL ); if ((0!=dwErr) && (NT_SUCCESS(ActualNtStatus))) { // // The Failure is an RPC Failure // set an appropriate error code // NtStatus = STATUS_DS_GC_NOT_AVAILABLE; } else { NtStatus = ActualNtStatus; } } __except(HandleMostExceptions(GetExceptionCode())) { // // Whack error code to insufficient resources. // Exceptions will typically take place under those conditions // NtStatus = STATUS_INSUFFICIENT_RESOURCES; } return NtStatus; } BOOL SampAmIGC() /*++ Tells SAM wether we are a G.C --*/ { return(gAnchor.fAmGC || gAnchor.fAmVirtualGC); } // // Table of well known accounts (account domain / builtin domain) // // The system will automatically apply the same security descriptor // of AdminSDHolder object on each every entry in the following table // if BOOLEAN fExcludeMembers is TRUE, we will not apply the secure SD // on members of the groups. Otherwise, include all transitive members // of each group. // // typedef struct _SAMP_SECURE_ADMIN_TABLE { ULONG Rid; BOOLEAN fExcludeMembers; } SAMP_SECURE_ADMIN_TABLE, *PSAMP_SECURE_ADMIN_TABLE; SAMP_SECURE_ADMIN_TABLE BuiltinDomainSecureAdminTable[] = { { DOMAIN_ALIAS_RID_ADMINS, FALSE }, { DOMAIN_ALIAS_RID_ACCOUNT_OPS, FALSE }, { DOMAIN_ALIAS_RID_SYSTEM_OPS, FALSE }, { DOMAIN_ALIAS_RID_PRINT_OPS, FALSE }, { DOMAIN_ALIAS_RID_BACKUP_OPS, FALSE }, { DOMAIN_ALIAS_RID_REPLICATOR, FALSE } }; SAMP_SECURE_ADMIN_TABLE AccountDomainSecureAdminTable[] = { { DOMAIN_USER_RID_ADMIN, FALSE }, { DOMAIN_USER_RID_KRBTGT, FALSE }, { DOMAIN_GROUP_RID_ADMINS, FALSE }, { DOMAIN_GROUP_RID_SCHEMA_ADMINS, FALSE }, { DOMAIN_GROUP_RID_ENTERPRISE_ADMINS, FALSE }, { DOMAIN_GROUP_RID_CONTROLLERS, TRUE } }; NTSTATUS SampFilterWellKnownAccounts( IN THSTATE *pTHS, IN SEARCHRES *BuiltinDomainSearchRes, IN SEARCHRES *AccountDomainSearchRes, OUT ULONG *CountOfBuiltinLocalGroups, OUT PDSNAME **BuiltinLocalGroups, OUT ULONG *CountOfDomainLocalGroups, OUT PDSNAME **DomainLocalGroups, OUT ULONG *CountOfDomainGlobalGroups, OUT PDSNAME **DomainGlobalGroups, OUT ULONG *CountOfDomainUniversalGroups, OUT PDSNAME **DomainUniversalGroups, OUT ULONG *CountOfDomainUsers, OUT PDSNAME **DomainUsers, OUT ULONG *CountOfExclusiveGroups, OUT PDSNAME **ExclusiveGroups ) /*++ Routine Description This routines walks through all well known accounts, find out users and groups which should be protected using the special ACL, and groups them to following 5 categories: 1. Builtin Domain Local Group 2. Account Domain Local Group 3. Account Domain Global Group 4. Account Domain Universal Group 5. Account Domain Users Parameters: Return Values: STATUS_SUCCESS - succeed. This is the only return code so far. --*/ { NTSTATUS NtStatus = STATUS_SUCCESS; CDSNameSet BuiltinLocalList; CDSNameSet DomainLocalList; CDSNameSet DomainGlobalList; CDSNameSet DomainUniversalList; CDSNameSet DomainUserList; CDSNameSet ExclusiveGroupList; ENTINFLIST *CurrentEntInf; NT4SID DomainSid; ULONG ObjectRid = 0; ULONG GroupType = 0; ULONG i; BOOLEAN fIgnore = TRUE; // // init return values // *CountOfBuiltinLocalGroups = 0; *BuiltinLocalGroups = NULL; *CountOfDomainLocalGroups = 0; *DomainLocalGroups = NULL; *CountOfDomainGlobalGroups = 0; *DomainGlobalGroups = NULL; *CountOfDomainUniversalGroups = 0; *DomainUniversalGroups = NULL; *CountOfDomainUsers = 0; *DomainUsers = NULL; *CountOfExclusiveGroups = 0; *ExclusiveGroups = NULL; // // initialize local varibles // BuiltinLocalList.SetValueType( RevMembDsName ); DomainLocalList.SetValueType( RevMembDsName ); DomainGlobalList.SetValueType( RevMembDsName ); DomainUniversalList.SetValueType( RevMembDsName ); DomainUserList.SetValueType( RevMembDsName ); ExclusiveGroupList.SetValueType( RevMembDsName ); if (BuiltinDomainSearchRes->count > 0) { // // walk through Builtin Domain well known accounts // for (CurrentEntInf = &(BuiltinDomainSearchRes->FirstEntInf); CurrentEntInf != NULL; CurrentEntInf = CurrentEntInf->pNextEntInf) { // // get well known account RID // SampSplitNT4SID(&(CurrentEntInf->Entinf.pName->Sid), &DomainSid, &ObjectRid ); // // compare the objectRid against the Builtin Domain table // fIgnore = TRUE; for (i = 0; i < ARRAY_COUNT(BuiltinDomainSecureAdminTable); i++) { if (ObjectRid == BuiltinDomainSecureAdminTable[i].Rid) { // RID matches, protect this account fIgnore = FALSE; break; } } if ( !fIgnore ) { if (BuiltinDomainSecureAdminTable[i].fExcludeMembers) { // // protect this group itself only, (don't apply secure SD // onto any member of this group) // ExclusiveGroupList.Add( CurrentEntInf->Entinf.pName ); } else { // // add this account to Builtin LocalGroup List // BuiltinLocalList.Add( CurrentEntInf->Entinf.pName ); } } } } if (AccountDomainSearchRes->count > 0) { // // Now walk through Account Domain well known accounts // for (CurrentEntInf = &(AccountDomainSearchRes->FirstEntInf); CurrentEntInf != NULL; CurrentEntInf = CurrentEntInf->pNextEntInf) { // // get well known account RID // SampSplitNT4SID(&(CurrentEntInf->Entinf.pName->Sid), &DomainSid, &ObjectRid ); // // compare the objectRid against secure admin table // fIgnore = TRUE; for (i = 0; i < ARRAY_COUNT(AccountDomainSecureAdminTable); i++) { if (ObjectRid == AccountDomainSecureAdminTable[i].Rid) { // RID matches, protect this account fIgnore = FALSE; break; } } // // get object GroupType, then add it to corresponding List // if ( !fIgnore ) { if (AccountDomainSecureAdminTable[i].fExcludeMembers) { ExclusiveGroupList.Add( CurrentEntInf->Entinf.pName ); } else { if ((1 == CurrentEntInf->Entinf.AttrBlock.attrCount) && (ATT_GROUP_TYPE == CurrentEntInf->Entinf.AttrBlock.pAttr->attrTyp) && (1 == CurrentEntInf->Entinf.AttrBlock.pAttr->AttrVal.valCount) && (sizeof(ULONG) == CurrentEntInf->Entinf.AttrBlock.pAttr->AttrVal.pAVal[0].valLen) ) { // this is a group GroupType = *((ULONG *)CurrentEntInf->Entinf.AttrBlock.pAttr->AttrVal.pAVal[0].pVal); if (GroupType & GROUP_TYPE_SECURITY_ENABLED) { if (GroupType & GROUP_TYPE_RESOURCE_GROUP) { DomainLocalList.Add( CurrentEntInf->Entinf.pName ); } else if (GroupType & GROUP_TYPE_ACCOUNT_GROUP) { DomainGlobalList.Add( CurrentEntInf->Entinf.pName ); } else if (GroupType & GROUP_TYPE_UNIVERSAL_GROUP) { DomainUniversalList.Add( CurrentEntInf->Entinf.pName ); } } } else { // this is a user DomainUserList.Add( CurrentEntInf->Entinf.pName ); } } } } } // // set return value // *CountOfBuiltinLocalGroups = BuiltinLocalList.Count(); if (0 != *CountOfBuiltinLocalGroups) { *BuiltinLocalGroups = (PDSNAME *)BuiltinLocalList.GetArray(); } *CountOfDomainLocalGroups = DomainLocalList.Count(); if (0 != *CountOfDomainLocalGroups) { *DomainLocalGroups = (PDSNAME *)DomainLocalList.GetArray(); } *CountOfDomainGlobalGroups = DomainGlobalList.Count(); if (0 != *CountOfDomainGlobalGroups) { *DomainGlobalGroups = (PDSNAME *)DomainGlobalList.GetArray(); } *CountOfDomainUniversalGroups = DomainUniversalList.Count(); if (0 != *CountOfDomainUniversalGroups) { *DomainUniversalGroups = (PDSNAME *)DomainUniversalList.GetArray(); } *CountOfDomainUsers = DomainUserList.Count(); if (0 != *CountOfDomainUsers) { *DomainUsers = (PDSNAME *)DomainUserList.GetArray(); } *CountOfExclusiveGroups = ExclusiveGroupList.Count(); if (0 != *CountOfExclusiveGroups) { *ExclusiveGroups = (PDSNAME *)ExclusiveGroupList.GetArray(); } return( NtStatus ); } NTSTATUS SampBuildAdministratorsSet( IN THSTATE *pTHS, IN ULONG CountOfBuiltinLocalGroups, IN PDSNAME *BuiltinLocalGroups, IN ULONG CountOfDomainLocalGroups, IN PDSNAME *DomainLocalGroups, IN ULONG CountOfDomainGlobalGroups, IN PDSNAME *DomainGlobalGroups, IN ULONG CountOfDomainUniversalGroups, IN PDSNAME *DomainUniversalGroups, IN DSNAME * EnterpriseAdminsDsName, IN DSNAME * SchemaAdminsDsName, OUT PULONG pcCountOfMembers, OUT PDSNAME **prpMembers ) /*++ Routine Description This routine builds the set of members in all well known groups Parameters pcCountOfMembers -- The count of members is returned in here ppMembers -- The list of members is returned in here Return Values STATUS_SUCCESS Other Error Codes --*/ { NTSTATUS Status = STATUS_SUCCESS; PDSNAME *pBuiltinLocalGroupsList = NULL; PDSNAME *pDomainGlobalGroupsList = NULL; PDSNAME *pDomainLocalGroupsList = NULL; PDSNAME *pDomainUniversalGroupsList = NULL; PDSNAME *pGcEvaluationList = NULL; PDSNAME *pLocalEvaluationList = NULL; PDSNAME *pFinalLocalEvaluationList = NULL; ULONG cBuiltinLocalGroupsList = 0; ULONG cDomainGlobalGroupsList = 0; ULONG cDomainLocalGroupsList = 0; ULONG cDomainUniversalGroupsList = 0; ULONG cGcEvaluationList = 0; ULONG cLocalEvaluationList =0; ULONG cFinalLocalEvaluationList =0; CDSNameSet GCEvaluationSet; CDSNameSet FinalAdminList; ULONG i=0; __try { // // Initialize return values // *pcCountOfMembers =0; *prpMembers = NULL; FinalAdminList.SetValueType(RevMembDsName); GCEvaluationSet.SetValueType(RevMembDsName); // // Begin a transaction // DBOpen(&pTHS->pDB); // // Evaluate the transitive membership in domain global groups locally // if ( CountOfDomainGlobalGroups ) { Status = SampGetMemberships( DomainGlobalGroups, CountOfDomainGlobalGroups, NULL, GroupMembersTransitive, &cDomainGlobalGroupsList, &pDomainGlobalGroupsList, NULL, NULL, NULL ); if (!NT_SUCCESS(Status)) { __leave; } } // // Evaluate the transitive membership in domain local groups locally // if ( CountOfDomainLocalGroups ) { Status = SampGetMemberships( DomainLocalGroups, CountOfDomainLocalGroups, NULL, GroupMembersTransitive, &cDomainLocalGroupsList, &pDomainLocalGroupsList, NULL, NULL, NULL ); if (!NT_SUCCESS(Status)) { __leave; } } // // Evaluate the transitive membership in domain universal groups locally // if ( CountOfDomainUniversalGroups ) { Status = SampGetMemberships( DomainUniversalGroups, CountOfDomainUniversalGroups, NULL, GroupMembersTransitive, &cDomainUniversalGroupsList, &pDomainUniversalGroupsList, NULL, NULL, NULL ); if (!NT_SUCCESS(Status)) { __leave; } } // // Evaluate the transitive membership in all Builtin Local Group locally // if ( CountOfBuiltinLocalGroups ) { Status = SampGetMemberships( BuiltinLocalGroups, CountOfBuiltinLocalGroups, NULL, GroupMembersTransitive, &cBuiltinLocalGroupsList, &pBuiltinLocalGroupsList, NULL, NULL, NULL ); if (!NT_SUCCESS(Status)) { __leave; } } // // Commit the transaction but keep the thread state as we prepare to go off machine // DBClose(pTHS->pDB,TRUE); // // Evaluate memberships of following sets at G.C. // // 1. account domain local groups // 2. members of account domain local groups // 3. account domain universal groups // 4. members of account domain universal groups // 5. members of builtin local groups // 6. enterprise admins and schema admins // // Note: Do NOT send // account domain global groups or // builtin domain local groups // to G.C. // // 1. account domain local groups for (i = 0; i < CountOfDomainLocalGroups; i++) { GCEvaluationSet.CheckDuplicateAndAdd( DomainLocalGroups[i] ); } // 2. members of account domain local groups for (i = 0; i < cDomainLocalGroupsList; i++) { GCEvaluationSet.CheckDuplicateAndAdd( pDomainLocalGroupsList[i] ); } // 3. account domain universal groups for (i = 0; i < CountOfDomainUniversalGroups; i++) { GCEvaluationSet.CheckDuplicateAndAdd( DomainUniversalGroups[i] ); } // 4. members of account domain universal groups for (i = 0; i < cDomainUniversalGroupsList; i++) { GCEvaluationSet.CheckDuplicateAndAdd( pDomainUniversalGroupsList[i] ); } // 5. members of builtin local groups for (i = 0; i < cBuiltinLocalGroupsList; i++) { GCEvaluationSet.CheckDuplicateAndAdd( pBuiltinLocalGroupsList[i] ); } // 6. enterprise admins and schema admins GCEvaluationSet.CheckDuplicateAndAdd(EnterpriseAdminsDsName); GCEvaluationSet.CheckDuplicateAndAdd(SchemaAdminsDsName); cGcEvaluationList = GCEvaluationSet.Count(); if (0 != cGcEvaluationList) { pGcEvaluationList = (PDSNAME *) GCEvaluationSet.GetArray(); } Status = SampGetMembershipsFromGC( pGcEvaluationList, cGcEvaluationList, NULL, GroupMembersTransitive, &cLocalEvaluationList, &pLocalEvaluationList, NULL, NULL, NULL ); if (!NT_SUCCESS(Status)) { __leave; } // // Begin Transaction again to process locally // DBOpen(&pTHS->pDB); // // Evaluate the results of the above evaluation locally // Status = SampGetMemberships( pLocalEvaluationList, cLocalEvaluationList, NULL, GroupMembersTransitive, &cFinalLocalEvaluationList, &pFinalLocalEvaluationList, NULL, NULL, NULL ); if (!NT_SUCCESS(Status)) { __leave; } // // Compose the final set, by utilizing the CDSNAMESET's check duplicate and add function. // // 1. Account Domain Global Groups // 2. Account Domain Local Groups // 3. Account Domain Univesal Groups // 4. members of Account Domain Global Groups // 5. members of Account Domain Local Groups // 6. members of Account Domain Universal Groups // 7. members of Builtin Domain Local Groups // 8. result coming from G.C. evaluation // 9. result of the local evaluation on the GC list // 10. Enterprise / Schema Administrators Groups // // // 1. Account Domain Global Groups // for (i = 0; i < CountOfDomainGlobalGroups; i++) { FinalAdminList.CheckDuplicateAndAdd( DomainGlobalGroups[i] ); } // // 2. Account Domain Local Groups // for (i = 0; i < CountOfDomainLocalGroups; i++) { FinalAdminList.CheckDuplicateAndAdd( DomainLocalGroups[i] ); } // // 3. Account Domain Univesal Groups // for (i = 0; i < CountOfDomainUniversalGroups; i++) { FinalAdminList.CheckDuplicateAndAdd( DomainUniversalGroups[i] ); } // // 4. members of Account Domain Global Groups // for (i=0; i<cDomainGlobalGroupsList; i++) { FinalAdminList.CheckDuplicateAndAdd( pDomainGlobalGroupsList[i] ); } // // 5. members of Account Domain Local Groups // for (i=0; i<cDomainLocalGroupsList; i++) { FinalAdminList.CheckDuplicateAndAdd( pDomainLocalGroupsList[i] ); } // // 6. members of Account Domain Universal Groups // for (i=0; i<cDomainUniversalGroupsList; i++) { FinalAdminList.CheckDuplicateAndAdd( pDomainUniversalGroupsList[i] ); } // // 7. members of Builtin Domain Local Groups // for (i=0; i<cBuiltinLocalGroupsList; i++) { FinalAdminList.CheckDuplicateAndAdd( pBuiltinLocalGroupsList[i] ); } // // Add the set returned from the G.C // 8. result coming from G.C. evaluation // for (i=0; i<cLocalEvaluationList; i++) { FinalAdminList.CheckDuplicateAndAdd( pLocalEvaluationList[i] ); } // // Add the locally evaluated set of the set returned from the G.C // 9. result of the local evaluation on the GC list // for (i=0; i<cFinalLocalEvaluationList; i++) { FinalAdminList.CheckDuplicateAndAdd( pFinalLocalEvaluationList[i] ); } // // 10. Add Enterprise / Schema Administrators Groups // FinalAdminList.CheckDuplicateAndAdd(EnterpriseAdminsDsName); FinalAdminList.CheckDuplicateAndAdd(SchemaAdminsDsName); // // Get the final list of members // *pcCountOfMembers = FinalAdminList.Count(); if (0!=*pcCountOfMembers) { *prpMembers = (PDSNAME *)FinalAdminList.GetArray(); } } __finally { // // Commit the transaction, but keep the thread state // if (NULL!=pTHS->pDB) { DBClose(pTHS->pDB,TRUE); } } return (Status); } NTSTATUS SampGetGroupsForToken( IN DSNAME * pObjName, IN ULONG Flags, OUT ULONG *pcSids, OUT PSID **prpSids ) /*++ Routine Description: This functions evaluates the full reverse membership, as in a logon. No Open Transactions Must Exist if GC membership query is desired. Depending upon circumstances this routine may begin a Read Transaction. Caller must be capable of handling this. If caller wants control of transaction type and does not want to go to the G.C then the caller can open appropriate transaction prior to calling this routine. Parameters: pObjName -- Security Principal Whose Reverse Membership is desired. Flags -- Control the operation of the Routine. Currently defined flags are as follows SAM_GET_MEMBERSHIPS_NO_GC -- If specified this routine will not go to the G.C . All Operations are local. SAM_GET_MEMBERSHIPS_TWO_PHASE -- Does both Phase 1 and Phase 2 of Reverse membership Evaluation , as in the construction of a Logon Token for this DC. pcSids -- The count of Sids Returned prpSids -- A pointer to an array of pointers to Sids is returned in here. Return Values STATUS_SUCCESS - On SuccessFul Completion STATUS_DS_MEMBERSHIP_EVALUATED_LOCALLY - If We could not contact G.C and evaluated locally instead STATUS_DS_GC_NOT_AVAILABLE - If we could not find a G.C and could not evaluate locally. --*/ { THSTATE *pTHS=pTHStls; NTSTATUS NtStatus = STATUS_SUCCESS; BOOLEAN fPartialMemberships=FALSE; DSNAME *BuiltinDomainObject=NULL; PDSNAME * Phase1DsNames=NULL, * Phase2DsNames=NULL, * Phase3DsNames=NULL, * Phase4DsNames=NULL, * TempDsNames0=NULL, * TempDsNames1=NULL, * TempDsNames2=NULL, * TempDsNames3=NULL, * ReturnedDsNames; ULONG cPhase1DsNames=0, cPhase2DsNames=0, cPhase3DsNames=0, cPhase4DsNames=0, cTempDsNames0=0, cTempDsNames1=0, cTempDsNames2=0, cTempDsNames3=0, TotalDsNames=0; ULONG cSidHistory1=0,cSidHistory2=0,cSidHistory3=0; PSID *rgSidHistory1=NULL,*rgSidHistory2=NULL,*rgSidHistory3=NULL; ULONG dsErr = 0; ULONG i,j; BOOLEAN fMixedDomain = ((Flags & SAM_GET_MEMBERSHIPS_MIXED_DOMAIN)!=0); BOOL fCommit = FALSE; ULONG BuiltinDomainSid[] = {0x101,0x05000000,0x20}; ULONG Size; AUG_MEMBERSHIPS *pAccountMemberships = NULL; AUG_MEMBERSHIPS *pUniversalMemberships = NULL; // // This macro collects all names into a stack array, that is alloca'd // so that this can be passed onto SampGetMemberships for the next phase // of logon evaluation. // #define COLLECT_NAMES(p1,c1,p2,c2,pt,ct)\ {\ ct=0;\ pt = (DSNAME**)THAlloc((c1+c2)*sizeof(PDSNAME));\ if (pt)\ {\ RtlZeroMemory(pt, (c1+c2)*sizeof(PDSNAME));\ if (c1)\ RtlCopyMemory(pt+ct,p1,c1*sizeof(PDSNAME));\ ct+=c1;\ if (c2)\ RtlCopyMemory(pt+ct,p2,c2*sizeof(PDSNAME));\ ct+=c2;\ }\ } // // initialize return value first // *prpSids = NULL; *pcSids = 0; _try { // // This routine assumes an open transaction // Assert(pTHS->pDB != NULL); NtStatus = GetAccountAndUniversalMemberships(pTHS, Flags, NULL, NULL, 1, &pObjName, FALSE, // not the refresh task &pAccountMemberships, &pUniversalMemberships); if (!NT_SUCCESS(NtStatus)) { goto Error; } // Account memberships should always be returned cPhase1DsNames = pAccountMemberships[0].MembershipCount; Phase1DsNames = pAccountMemberships[0].Memberships; cSidHistory1 = pAccountMemberships[0].SidHistoryCount; rgSidHistory1 = pAccountMemberships[0].SidHistory; cPhase2DsNames = pUniversalMemberships[0].MembershipCount; Phase2DsNames = pUniversalMemberships[0].Memberships; cSidHistory2 = pUniversalMemberships[0].SidHistoryCount; rgSidHistory2 = pUniversalMemberships[0].SidHistory; fPartialMemberships = (pUniversalMemberships[0].Flags & AUG_PARTIAL_MEMBERSHIP_ONLY) ? TRUE : FALSE; if (Flags & SAM_GET_MEMBERSHIPS_TWO_PHASE) { // // Two phase flag is specified only by callers within SAM, // like ACL conversion or check for sensitive groups, that // should not result in a call to the G.C. Therefore a DS // transaction should exist at this point in time // Assert(pTHS->pDB != NULL); if (!NT_SUCCESS(NtStatus)) goto Error; // // Again remember to merge in the base object itself // into this. // COLLECT_NAMES(&pObjName,1,Phase1DsNames,cPhase1DsNames,TempDsNames1,cTempDsNames1) if (NULL == TempDsNames1) { NtStatus = STATUS_NO_MEMORY; goto Error; } // // Combine the reverse memberships from the account and universal // group evaluation into one big buffer, containing both. Note the // big buffer will not have any duplicates, as one buffer is account // groups and the other contains universal groups. // COLLECT_NAMES( TempDsNames1, cTempDsNames1, Phase2DsNames, cPhase2DsNames, TempDsNames2, cTempDsNames2 ); if (NULL == TempDsNames2) { NtStatus = STATUS_NO_MEMORY; goto Error; } // // Get the resource group membership of all these groups. // NtStatus = SampGetMemberships( TempDsNames2, cTempDsNames2, gAnchor.pDomainDN, RevMembGetResourceGroups, &cPhase3DsNames, &Phase3DsNames, NULL, &cSidHistory3, &rgSidHistory3 ); if (!NT_SUCCESS(NtStatus)) goto Error; // // Again collect all the names // COLLECT_NAMES( Phase3DsNames, cPhase3DsNames, TempDsNames2, cTempDsNames2, TempDsNames3, cTempDsNames3 ); if (NULL == TempDsNames3) { NtStatus = STATUS_NO_MEMORY; goto Error; } // // Get the reverse membership in the builtin domain for // all the objects that the object is a transitive reverse- // member of // Size = DSNameSizeFromLen(0); BuiltinDomainObject = (DSNAME*) THAllocEx(pTHS,Size); BuiltinDomainObject->structLen = Size; BuiltinDomainObject->SidLen = RtlLengthSid(BuiltinDomainSid); RtlCopySid(sizeof(BuiltinDomainObject->Sid), (PSID)&BuiltinDomainObject->Sid, BuiltinDomainSid); NtStatus = SampGetMemberships( TempDsNames3, cTempDsNames3, BuiltinDomainObject, RevMembGetAliasMembership, &cPhase4DsNames, &Phase4DsNames, NULL, NULL, NULL ); THFreeEx(pTHS,BuiltinDomainObject); if (!NT_SUCCESS(NtStatus)) goto Error; TotalDsNames = cPhase3DsNames; ReturnedDsNames = Phase3DsNames; } TotalDsNames = cPhase1DsNames+cPhase2DsNames+cPhase3DsNames+cPhase4DsNames; // // Alloc Memory for Returning the reverse membership. If TWO_PHASE // logon was requested then alloc Max token size amount of memory. // *prpSids = (VOID**)THAllocEx(pTHS, (TotalDsNames + cSidHistory1 + cSidHistory2 + cSidHistory3) * sizeof(PSID) ); if (NULL==*prpSids) { NtStatus = STATUS_INSUFFICIENT_RESOURCES; goto Error; } // // Copy In the SIDS for all the DS Names that we obtained. // Note we need not check for duplicates because // *pcSids=0; for (i=0;i<cPhase1DsNames;i++) { Assert(Phase1DsNames[i]->SidLen > 0); (*prpSids)[i+*pcSids] = &(Phase1DsNames[i]->Sid); } *pcSids+=cPhase1DsNames; for (i=0;i<cPhase2DsNames;i++) { Assert(Phase2DsNames[i]->SidLen > 0); (*prpSids)[i+*pcSids] = &(Phase2DsNames[i]->Sid); } *pcSids+=cPhase2DsNames; for (i=0;i<cPhase3DsNames;i++) { Assert(Phase3DsNames[i]->SidLen > 0); (*prpSids)[i+*pcSids] = &(Phase3DsNames[i]->Sid); } *pcSids+=cPhase3DsNames; for (i=0;i<cPhase4DsNames;i++) { Assert(Phase4DsNames[i]->SidLen > 0); (*prpSids)[i+*pcSids] = &(Phase4DsNames[i]->Sid); } *pcSids+=cPhase4DsNames; // // Merge In the Sid History // for (i=0;i<cSidHistory1;i++) { (*prpSids)[(*pcSids)++] = rgSidHistory1[i]; } for (i=0;i<cSidHistory2;i++) { (*prpSids)[(*pcSids)++] = rgSidHistory2[i]; } for (i=0;i<cSidHistory3;i++) { (*prpSids)[(*pcSids)++] = rgSidHistory3[i]; } } __except(HandleMostExceptions(GetExceptionCode())) { // Whack error code to insufficient resources. // Exceptions will typically take place under those conditions NtStatus = STATUS_INSUFFICIENT_RESOURCES; } // // The Transaction should be kept open, for further processing // by SAM // Error: if (TempDsNames0) { THFreeEx(pTHS, TempDsNames0); TempDsNames0 = NULL; } if (TempDsNames1) { THFreeEx(pTHS, TempDsNames1); TempDsNames1 = NULL; } if (TempDsNames2) { THFreeEx(pTHS, TempDsNames2); TempDsNames2 = NULL; } if (TempDsNames3) { THFreeEx(pTHS, TempDsNames3); TempDsNames3 = NULL; } if (!NT_SUCCESS(NtStatus)) { if (NULL!=*prpSids) { THFreeEx(pTHS, *prpSids); *prpSids = NULL; *pcSids = 0; } } // // Return STATUS_DS_MEMBERSHIP_EVALUATED_LOCALLY, if we could not contact the G.C and // evaluated memberships locally // if (fPartialMemberships && (NT_SUCCESS(NtStatus))) NtStatus = STATUS_DS_MEMBERSHIP_EVALUATED_LOCALLY; return NtStatus; } NTSTATUS GetAccountMemberships( IN THSTATE *pTHS, IN ULONG Flags, IN ULONG Count, IN DSNAME **Users, OUT AUG_MEMBERSHIPS* pAccountMemberships ) /*++ Routine Description: This routine obtains the account group memberships for Users. Parameters: pTHS -- thread state Flags -- flags for SampGetGroupsForToken Count -- number of elements in Users Users -- an array of users in dsname format ppAccountMemberships -- the account memberships of Users Return Values STATUS_SUCCESS, a resource error otherwise. --*/ { NTSTATUS NtStatus = STATUS_SUCCESS; ULONG i; BOOLEAN fMixedDomain = ((Flags & SAM_GET_MEMBERSHIPS_MIXED_DOMAIN)!=0); for (i = 0; (i < Count) && NT_SUCCESS(NtStatus); i++) { // // Call SampGetMemberships // NtStatus = SampGetMemberships( &Users[i], 1, gAnchor.pDomainDN, fMixedDomain?RevMembGetGroupsForUser:RevMembGetAccountGroups, &pAccountMemberships[i].MembershipCount, &pAccountMemberships[i].Memberships, NULL, &pAccountMemberships[i].SidHistoryCount, &pAccountMemberships[i].SidHistory ); } return NtStatus; } NTSTATUS GetUniversalMembershipsBatching( IN THSTATE *pTHS, IN ULONG Flags, IN LPWSTR PreferredGc, IN LPWSTR PreferredGcDomain, IN ULONG Count, IN DSNAME **Users, IN AUG_MEMBERSHIPS* AccountMemberships, OUT AUG_MEMBERSHIPS* UniversalMemberships ) /*++ Routine Description: This routine gets the universal group memberships for Users by calling I_DRSGetMemberships2, which allows for multiple users to passed in. N.B. This routine assumes that a GC is passed in. Support for FindGC has not been added. Parameters: pTHS -- thread state Flags -- same as SamIGetUserLogonInformation PreferredGc -- string name of GC to contact, should be DNS form PreferredGcDomain -- the domain that PreferredGc is in. Needed for SPN creation Count -- the number of Users Users -- the users for whom to obtain the group memberhship AccountMemberships -- the account memberships and sid histories of Users UniversalMemberships -- the universal memberships and sid histories obtained for Users Return Values STATUS_SUCCESS, STATUS_DS_GC_NOT_AVAILABLE nt resource errors otherwise. --*/ { NTSTATUS NtStatus = STATUS_SUCCESS; DWORD err; DRS_MSG_GETMEMBERSHIPS2_REQ Req; DRS_MSG_GETMEMBERSHIPS2_REPLY Reply; ULONG ReplyVersion; ULONG i; memset(&Req, 0, sizeof(Req)); memset(&Reply, 0, sizeof(Reply)); Assert(NULL != PreferredGc); Assert(NULL != PreferredGcDomain); err = I_DRSIsExtSupported(pTHS, PreferredGc, DRS_EXT_GETMEMBERSHIPS2); if (err) { return STATUS_NOT_SUPPORTED; } // // Setup the request // Req.V1.Count = Count; Req.V1.Requests = (DRS_MSG_REVMEMB_REQ_V1*) THAllocEx(pTHS, Count * sizeof(*Req.V1.Requests)); for ( i = 0; i < Count; i++ ) { COLLECT_NAMES(&Users[i], 1, AccountMemberships[i].Memberships, AccountMemberships[i].MembershipCount, Req.V1.Requests[i].ppDsNames, Req.V1.Requests[i].cDsNames) Req.V1.Requests[i].dwFlags = 0; Req.V1.Requests[i].OperationType = RevMembGetUniversalGroups; Req.V1.Requests[i].pLimitingDomain = NULL; } // // Make the call // err = I_DRSGetMemberships2(pTHS, PreferredGc, PreferredGcDomain, 1, &Req, &ReplyVersion, &Reply); if (err) { // BUGBUG -- Reliability -- more error handling? goto Error; } Assert(ReplyVersion == 1); // // Unpackage the request // for ( i = 0; i < Count; i++ ) { if (ERROR_SUCCESS == Reply.V1.Replies[i].errCode ) { UniversalMemberships[i].MembershipCount = Reply.V1.Replies[i].cDsNames; UniversalMemberships[i].Memberships = Reply.V1.Replies[i].ppDsNames; UniversalMemberships[i].Attributes = Reply.V1.Replies[i].pAttributes; UniversalMemberships[i].SidHistoryCount = Reply.V1.Replies[i].cSidHistory; UniversalMemberships[i].SidHistory = (PSID*)Reply.V1.Replies[i].ppSidHistory; } else { UniversalMemberships[i].Flags |= AUG_PARTIAL_MEMBERSHIP_ONLY; } } Error: if (err) { for ( i = 0; i < Count; i++) { UniversalMemberships[i].Flags |= AUG_PARTIAL_MEMBERSHIP_ONLY; } NtStatus = STATUS_DS_GC_NOT_AVAILABLE; } // // Free the request // if (Req.V1.Requests) { for (i = 0; i < Count; i++) { if (Req.V1.Requests[i].ppDsNames) { THFreeEx(pTHS, Req.V1.Requests[i].ppDsNames); } } THFreeEx(pTHS, Req.V1.Requests); } return NtStatus; } NTSTATUS GetUniversalMembershipsSequential( IN THSTATE *pTHS, IN ULONG Flags, IN LPWSTR PreferredGc OPTIONAL, IN LPWSTR PreferredGcDomain OPTIONAL, IN ULONG Count, IN DSNAME **Users, OUT AUG_MEMBERSHIPS* pAccountMemberships, OUT AUG_MEMBERSHIPS* pUniversalMemberships ) /*++ Routine Description: This routine gets the universal group memberships 'sequentially' by calling I_DRSGetMemberships for each user individually. Parameters: pTHS -- thread state Flags -- same as SamIGetUserLogonInformation PreferredGc -- string name of GC to contact, should be DNS form PreferredGcDomain -- the domain that PreferredGc is in. Needed for SPN creation Count -- the number of Users Users -- the users for whom to obtain the group memberhship AccountMemberships -- the account memberships and sid histories of Users UniversalMemberships -- the universal memberships and sid histories obtained for Users Return Values STATUS_SUCCESS, STATUS_DS_GC_NOT_AVAILABLE nt resource errors otherwise. --*/ { NTSTATUS NtStatus = STATUS_SUCCESS; ULONG i; DWORD err; NTSTATUS ActualNtStatus = STATUS_SUCCESS; DSNAME **TempDsNames = NULL; ULONG cTempDsNames = 0; Assert(NULL == PreferredGc || NULL != PreferredGcDomain); for ( i = 0; i < Count; i++ ) { // Merge in the user name COLLECT_NAMES(&Users[i], 1, pAccountMemberships->Memberships, pAccountMemberships->MembershipCount, TempDsNames, cTempDsNames); // // Make the Reverse Membership call on the G.C // err = I_DRSGetMembershipsFindGC( pTHS, PreferredGc, PreferredGcDomain, 0, // don't get attributes for universal memberships TempDsNames, cTempDsNames, NULL, // no limiting domain RevMembGetUniversalGroups, (DWORD *)&ActualNtStatus, &pUniversalMemberships[i].MembershipCount, &pUniversalMemberships[i].Memberships, &pUniversalMemberships[i].Attributes, &pUniversalMemberships[i].SidHistoryCount, &pUniversalMemberships[i].SidHistory, FIND_DC_USE_CACHED_FAILURES | FIND_DC_USE_FORCE_ON_CACHE_FAIL ); if (err && (NT_SUCCESS(ActualNtStatus))) { // // The Failure is an RPC Failure // set an appropriate error code // NtStatus = STATUS_DS_GC_NOT_AVAILABLE; } else { NtStatus = ActualNtStatus; } } return NtStatus; } NTSTATUS GetUniversalMemberships( IN THSTATE *pTHS, IN ULONG Flags, IN LPWSTR PreferredGc OPTIONAL, IN LPWSTR PreferredGcDomain OPTIONAL, IN ULONG Count, IN DSNAME **Users, IN AUG_MEMBERSHIPS* AccountMemberships, OUT AUG_MEMBERSHIPS* UniversalMemberships ) /*++ Routine Description: This routine obtains the universal group memberships for Users. If the batching method is available (new for Whistler) then it will be used; otherwise the downlevel method of making a network per user is used. Parameters: pTHS -- thread state Flags -- same as SamIGetUserLogonInformation PreferredGc -- string name of GC to contact, should be DNS form PreferredGcDomain -- the domain that PreferredGc is in. Needed for SPN creation Count -- the number of Users Users -- the users for whom to obtain the group memberhship AccountMemberships -- the account memberships and sid histories of Users UniversalMemberships -- the universal memberships and sid histories obtained for Users Return Values STATUS_SUCCESS, STATUS_DS_GC_NOT_AVAILABLE nt resource errors otherwise. --*/ { NTSTATUS NtStatus = STATUS_SUCCESS; BOOL fUseSequentialMethod = TRUE; ULONG i; // // First check if we need to go off machine // if ((SampAmIGC())||(Flags & SAM_GET_MEMBERSHIPS_NO_GC)) { // // We are the GC ourselves or have been instructed to not go to the // GC. Therefore obtain reverse memberships locally // for (i = 0; (i < Count) && NT_SUCCESS(NtStatus); i++) { DSNAME **TempDsNames = NULL; ULONG cTempDsNames = 0; // Merge in the user name COLLECT_NAMES(&Users[i], 1, AccountMemberships->Memberships, AccountMemberships->MembershipCount, TempDsNames, cTempDsNames); NtStatus = SampGetMemberships(TempDsNames, cTempDsNames, NULL, RevMembGetUniversalGroups, &UniversalMemberships[i].MembershipCount, &UniversalMemberships[i].Memberships, NULL, &UniversalMemberships[i].SidHistoryCount, &UniversalMemberships[i].SidHistory); THFreeEx(pTHS, TempDsNames); } // We are done goto Cleanup; } // // We are going off machine -- end the current transaction // if (Flags & SAM_PRESERVE_DBPOS) { // // We're being called by DS code that expects to have the same // DBPOS when the call completes. // DBTransOut(pTHS->pDB, TRUE, FALSE); } else { DBClose(pTHS->pDB, TRUE); } if ( PreferredGc && (Count > 1) ) { fUseSequentialMethod = FALSE; // // GetUniversalMembershipsBatching doesn't support FindGCInfo // currently // // // Call into GetUniversalMembershipsBatching // NtStatus = GetUniversalMembershipsBatching(pTHS, Flags, PreferredGc, PreferredGcDomain, Count, Users, AccountMemberships, UniversalMemberships); if (STATUS_NOT_SUPPORTED == NtStatus) { fUseSequentialMethod = TRUE; } } if (fUseSequentialMethod) { // // Call into GetUniversalMembershipsSequential // NtStatus = GetUniversalMembershipsSequential(pTHS, Flags, PreferredGc, PreferredGcDomain, Count, Users, AccountMemberships, UniversalMemberships); } if (Flags & SAM_PRESERVE_DBPOS) { // // DS code expects to still have an open transaction so open a new one. // DBTransIn(pTHS->pDB); } Cleanup: if ( STATUS_DS_GC_NOT_AVAILABLE == NtStatus ) { // Set the partial information for (i = 0; i < Count; i++) { freeAUGMemberships(pTHS, &UniversalMemberships[i]); memset(&UniversalMemberships[i], 0, sizeof(AUG_MEMBERSHIPS)); UniversalMemberships[i].Flags |= AUG_PARTIAL_MEMBERSHIP_ONLY; } NtStatus = STATUS_SUCCESS; } return NtStatus; } NTSTATUS GetAccountAndUniversalMembershipsWorker( IN THSTATE *pTHS, IN ULONG Flags, IN LPWSTR PreferredGc OPTIONAL, IN LPWSTR PreferredGcDomain OPTIONAL, IN ULONG Count, IN DSNAME **Users, OUT AUG_MEMBERSHIPS **ppAccountMemberships, OUT AUG_MEMBERSHIPS **ppUniversalMemberships ) /*++ Routine Description: This routine performs the work obtaining the group memberships from the local directory as well as remotely for the universal groups if necessary. pTHS -- thread state Flags -- same as SamIGetUserLogonInformation PreferredGc -- string name of GC to contact, should be DNS form PreferredGcDomain -- the domain that PreferredGc is in. Needed for SPN creation Count -- the number of Users Users -- the users for whom to obtain the group memberhship AccountMemberships -- the account memberships and sid histories obtained for Users UniversalMemberships -- the universal memberships and sid histories obtained for Users Return Values STATUS_SUCCESS, nt resource errors otherwise. --*/ { NTSTATUS NtStatus = STATUS_SUCCESS; AUG_MEMBERSHIPS *accountMemberships = NULL; AUG_MEMBERSHIPS *universalMemberships = NULL; // Allocate the space for the UniversalMemberships accountMemberships = (AUG_MEMBERSHIPS*)THAllocEx(pTHS, Count * sizeof(AUG_MEMBERSHIPS)); universalMemberships = (AUG_MEMBERSHIPS*)THAllocEx(pTHS, Count * sizeof(AUG_MEMBERSHIPS)); NtStatus = GetAccountMemberships(pTHS, Flags, Count, Users, accountMemberships); if (!NT_SUCCESS(NtStatus)) { goto Cleanup; } if (Flags & SAM_GET_MEMBERSHIPS_MIXED_DOMAIN) { // // No universal memberships // Assert(Count == 1); universalMemberships[0].MembershipCount = 0; universalMemberships[0].SidHistoryCount = 0; } else { NtStatus = GetUniversalMemberships(pTHS, Flags, PreferredGc, PreferredGcDomain, Count, Users, accountMemberships, universalMemberships); } if (!NT_SUCCESS(NtStatus)) { goto Cleanup; } // // Return the OUT parameters // *ppAccountMemberships = accountMemberships; *ppUniversalMemberships = universalMemberships; accountMemberships = NULL; universalMemberships = NULL; Cleanup: if (accountMemberships) { freeAUGMemberships(pTHS, accountMemberships); THFreeEx(pTHS, accountMemberships); } if (universalMemberships) { freeAUGMemberships(pTHS, universalMemberships); THFreeEx(pTHS, universalMemberships); } return NtStatus; } NTSTATUS GetAccountAndUniversalMemberships( IN THSTATE *pTHS, IN ULONG Flags, IN LPWSTR PreferredGc OPTIONAL, IN LPWSTR PreferredGcDomain OPTIONAL, IN ULONG Count, IN DSNAME **Users, IN BOOL fRefreshTask, OUT AUG_MEMBERSHIPS **ppAccountMemberships OPTIONAL, OUT AUG_MEMBERSHIPS **ppUniversalMemberships OPTIONAL ) /*++ Routine Description: This routine obtains the account and universal memberships of a set of users. It may involve performing a network call to obtain the universal memberships, thus any open transaction will be closed. If caching is enabled, then values from the cache will be used. Parameters: pTHS -- thread state Flags -- same as SamIGetUserLogonInformation PreferredGc -- string name of GC to contact, should be DNS form PreferredGcDomain -- the domain that PreferredGc is in. Needed for SPN creation Count -- the number of Users Users -- the users for whom to obtain the group memberhship RefreshTask -- TRUE if the caller is the group refresh task; FALSE otherwise AccountMemberships -- the account memberships and sid histories of Users UniversalMemberships -- the universal memberships and sid histories obtained for Users Return Values STATUS_SUCCESS, nt resource errors otherwise. --*/ { NTSTATUS NtStatus = STATUS_SUCCESS; ULONG i; AUG_MEMBERSHIPS *pUniversalMemberships = NULL; AUG_MEMBERSHIPS *pAccountMemberships = NULL; BOOL fDontUseCache; fDontUseCache = (Flags & SAM_GET_MEMBERSHIPS_NO_GC) || (Flags & SAM_GET_MEMBERSHIPS_MIXED_DOMAIN); // // Check cache // if ( !fDontUseCache && !fRefreshTask && isGroupCachingEnabled() && (1 == Count) ) { // // Currently don't support cases where some users have caches // and other's don't. // NtStatus = GetMembershipsFromCache(Users[0], &pAccountMemberships, &pUniversalMemberships); if (NT_SUCCESS(NtStatus)) { DPRINT1(3, "Cache successful for user %ws\n", Users[0]->StringName); // Done *ppAccountMemberships = pAccountMemberships; *ppUniversalMemberships = pUniversalMemberships; return NtStatus; } else if (STATUS_DS_NO_ATTRIBUTE_OR_VALUE != NtStatus) { DPRINT1(3, "Cache failed for user %ws\n", Users[0]->StringName); goto Cleanup; } // // In this case the cache didn't help because of the known error // STATUS_DS_NO_ATTRIBUTE_OR_VALUE, continue on to perform // the work of getting the memberships // } // // Perform a full group expansion // NtStatus = GetAccountAndUniversalMembershipsWorker(pTHS, Flags, PreferredGc, PreferredGcDomain, Count, Users, &pAccountMemberships, &pUniversalMemberships); if ( !fDontUseCache && isGroupCachingEnabled() && NT_SUCCESS(NtStatus) ) { // // Cache the results // for ( i = 0; i < Count; i++) { if (!((pUniversalMemberships)[i].Flags & AUG_PARTIAL_MEMBERSHIP_ONLY)) { NTSTATUS IgnoreStatus; IgnoreStatus = CacheMemberships(Users[i], &(pAccountMemberships)[i], &(pUniversalMemberships)[i]); if (NT_SUCCESS(IgnoreStatus)) { DPRINT1(3, "Cache save successful for user %ws\n", Users[i]->StringName); } else { DPRINT2(3, "Cache save failed for user %ws (0x%x)\n", Users[i]->StringName, IgnoreStatus); } } } } Cleanup: if (NT_SUCCESS(NtStatus)) { if (ppAccountMemberships) { *ppAccountMemberships = pAccountMemberships; pAccountMemberships = NULL; } if (ppUniversalMemberships) { *ppUniversalMemberships = pUniversalMemberships; pUniversalMemberships = NULL; } } if (pAccountMemberships) { freeAUGMemberships(pTHS, pAccountMemberships); THFreeEx(pTHS, pAccountMemberships); } if (pUniversalMemberships) { freeAUGMemberships(pTHS, pUniversalMemberships); THFreeEx(pTHS, pUniversalMemberships); } return NtStatus; } } //extern "C"
30.643135
117
0.501368
npocmaka
30188d28702d70d3aaf829bc7ee178ce28093cc4
641
cpp
C++
03-Making Decisions/Program_4-23.cpp
ringosimonchen0820/How-to-C--
69b0310e6aeab25a7e2eed41e4d6cff85a034e00
[ "MIT" ]
null
null
null
03-Making Decisions/Program_4-23.cpp
ringosimonchen0820/How-to-C--
69b0310e6aeab25a7e2eed41e4d6cff85a034e00
[ "MIT" ]
1
2020-10-11T18:39:08.000Z
2020-10-11T18:39:17.000Z
03-Making Decisions/Program_4-23.cpp
ringosimonchen0820/How-to-C--
69b0310e6aeab25a7e2eed41e4d6cff85a034e00
[ "MIT" ]
2
2020-10-12T20:33:32.000Z
2020-10-12T20:34:00.000Z
// The switch statement in this program tells the user something // he or she already knows: the data just entered! #include <iostream> using namespace std; int main() { char choice; cout << "Enter A, B, or C: "; cin >> choice; switch (choice) { case 'A' : cout << "You entered A.\n"; break; case 'B' : cout << "You entered B.\n"; break; case 'C' : cout << "You entered C.\n"; break; default : cout << "You did not enter A, B, or C!\n"; //? The default section does not need a break statement } return 0; }
22.892857
65
0.517941
ringosimonchen0820
301e8aa973d8eae4d8bbf4b693e39389f51ac7b7
4,695
cpp
C++
training/src/compiler/training/base/layers/parameters/trainable/Convolution1DParams.cpp
steelONIONknight/bolt
9bd3d08f2abb14435ca3ad0179889e48fa7e9b47
[ "MIT" ]
null
null
null
training/src/compiler/training/base/layers/parameters/trainable/Convolution1DParams.cpp
steelONIONknight/bolt
9bd3d08f2abb14435ca3ad0179889e48fa7e9b47
[ "MIT" ]
null
null
null
training/src/compiler/training/base/layers/parameters/trainable/Convolution1DParams.cpp
steelONIONknight/bolt
9bd3d08f2abb14435ca3ad0179889e48fa7e9b47
[ "MIT" ]
null
null
null
// Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #include "Convolution1DParams.h" namespace raul { Convolution1DParams::Convolution1DParams(const BasicParams& params, size_t paramKernelSize, size_t paramOutChannel, size_t paramStride, size_t paramPadding, size_t paramDilation, size_t paramGroups, bool paramBias, bool paramQuantizeWeights, bool paramTFStyle, bool paramFrozen) : TrainableParams(params, paramFrozen) , kernelSize(paramKernelSize) , kernelsCount(paramOutChannel) , stride(paramStride) , padding(paramPadding) , dilation(paramDilation) , groups(paramGroups) , useBias(paramBias) , quantizeWeights(paramQuantizeWeights) , tfStyle(paramTFStyle) { } Convolution1DParams::Convolution1DParams(const Name& input, const Name& output, const Name& sharedLayer, size_t paramKernelSize, size_t paramOutChannel, size_t paramStride, size_t paramPadding, size_t paramDilation, size_t paramGroups, bool paramBias, bool paramQuantizeWeights, bool paramTFStyle, bool paramFrozen) : TrainableParams({ input }, { output }, sharedLayer, paramFrozen) , kernelSize(paramKernelSize) , kernelsCount(paramOutChannel) , stride(paramStride) , padding(paramPadding) , dilation(paramDilation) , groups(paramGroups) , useBias(paramBias) , quantizeWeights(paramQuantizeWeights) , tfStyle(paramTFStyle) { } Convolution1DParams::Convolution1DParams(const Name& input, const Name& output, size_t kernelSize, size_t outChannel, size_t stride, size_t padding, size_t dilation, size_t groups, bool bias, bool quantizeWeights, bool tfStyle, bool paramFrozen) : Convolution1DParams({ { input }, { output } }, kernelSize, outChannel, stride, padding, dilation, groups, bias, quantizeWeights, tfStyle, paramFrozen) { } void Convolution1DParams::print(std::ostream& stream) const { BasicParams::print(stream); stream << " kernel_size: " << kernelSize << ", out_channels: " << kernelsCount << ", stride: " << stride << ", padding: " << padding << ", dilation: " << dilation; stream << ", groups: " << groups << ", bias: " << (useBias ? "true" : "false") << ", quantized weights: " << (quantizeWeights ? "true" : "false") << ", TF style: " << (tfStyle ? "true" : "false"); } } // namespace raul
50.483871
200
0.531629
steelONIONknight
302809c717e7dba0037e3b21afb8d20faf67d385
23,420
cpp
C++
dbswznm/WznmAMMachineMakefile.cpp
mpsitech/wznm-WhizniumSBE
4911d561b28392d485c46e98fb915168d82b3824
[ "MIT" ]
3
2020-09-20T16:24:48.000Z
2021-12-01T19:44:51.000Z
dbswznm/WznmAMMachineMakefile.cpp
mpsitech/wznm-WhizniumSBE
4911d561b28392d485c46e98fb915168d82b3824
[ "MIT" ]
null
null
null
dbswznm/WznmAMMachineMakefile.cpp
mpsitech/wznm-WhizniumSBE
4911d561b28392d485c46e98fb915168d82b3824
[ "MIT" ]
null
null
null
/** * \file WznmAMMachineMakefile.cpp * database access for table TblWznmAMMachineMakefile (implementation) * \copyright (C) 2016-2020 MPSI Technologies GmbH * \author Alexander Wirthmueller (auto-generation) * \date created: 5 Dec 2020 */ // IP header --- ABOVE #include "WznmAMMachineMakefile.h" using namespace std; using namespace Sbecore; /****************************************************************************** class WznmAMMachineMakefile ******************************************************************************/ WznmAMMachineMakefile::WznmAMMachineMakefile( const ubigint ref , const ubigint refWznmMMachine , const string x1SrefKTag , const string Val ) { this->ref = ref; this->refWznmMMachine = refWznmMMachine; this->x1SrefKTag = x1SrefKTag; this->Val = Val; }; bool WznmAMMachineMakefile::operator==( const WznmAMMachineMakefile& comp ) { return false; }; bool WznmAMMachineMakefile::operator!=( const WznmAMMachineMakefile& comp ) { return(!operator==(comp)); }; /****************************************************************************** class ListWznmAMMachineMakefile ******************************************************************************/ ListWznmAMMachineMakefile::ListWznmAMMachineMakefile() { }; ListWznmAMMachineMakefile::ListWznmAMMachineMakefile( const ListWznmAMMachineMakefile& src ) { nodes.resize(src.nodes.size(), NULL); for (unsigned int i = 0; i < nodes.size(); i++) nodes[i] = new WznmAMMachineMakefile(*(src.nodes[i])); }; ListWznmAMMachineMakefile::~ListWznmAMMachineMakefile() { clear(); }; void ListWznmAMMachineMakefile::clear() { for (unsigned int i = 0; i < nodes.size(); i++) if (nodes[i]) delete nodes[i]; nodes.resize(0); }; unsigned int ListWznmAMMachineMakefile::size() const { return(nodes.size()); }; void ListWznmAMMachineMakefile::append( WznmAMMachineMakefile* rec ) { nodes.push_back(rec); }; WznmAMMachineMakefile* ListWznmAMMachineMakefile::operator[]( const uint ix ) { WznmAMMachineMakefile* retval = NULL; if (ix < size()) retval = nodes[ix]; return retval; }; ListWznmAMMachineMakefile& ListWznmAMMachineMakefile::operator=( const ListWznmAMMachineMakefile& src ) { WznmAMMachineMakefile* rec; if (&src != this) { clear(); for (unsigned int i = 0; i < src.size(); i++) { rec = new WznmAMMachineMakefile(*(src.nodes[i])); nodes.push_back(rec); }; }; return(*this); }; bool ListWznmAMMachineMakefile::operator==( const ListWznmAMMachineMakefile& comp ) { bool retval; retval = (size() == comp.size()); if (retval) { for (unsigned int i = 0; i < size(); i++) { retval = ( *(nodes[i]) == *(comp.nodes[i]) ); if (!retval) break; }; }; return retval; }; bool ListWznmAMMachineMakefile::operator!=( const ListWznmAMMachineMakefile& comp ) { return(!operator==(comp)); }; /****************************************************************************** class TblWznmAMMachineMakefile ******************************************************************************/ TblWznmAMMachineMakefile::TblWznmAMMachineMakefile() { }; TblWznmAMMachineMakefile::~TblWznmAMMachineMakefile() { }; bool TblWznmAMMachineMakefile::loadRecBySQL( const string& sqlstr , WznmAMMachineMakefile** rec ) { return false; }; ubigint TblWznmAMMachineMakefile::loadRstBySQL( const string& sqlstr , const bool append , ListWznmAMMachineMakefile& rst ) { return 0; }; ubigint TblWznmAMMachineMakefile::insertRec( WznmAMMachineMakefile* rec ) { return 0; }; ubigint TblWznmAMMachineMakefile::insertNewRec( WznmAMMachineMakefile** rec , const ubigint refWznmMMachine , const string x1SrefKTag , const string Val ) { ubigint retval = 0; WznmAMMachineMakefile* _rec = NULL; _rec = new WznmAMMachineMakefile(0, refWznmMMachine, x1SrefKTag, Val); insertRec(_rec); retval = _rec->ref; if (rec == NULL) delete _rec; else *rec = _rec; return retval; }; ubigint TblWznmAMMachineMakefile::appendNewRecToRst( ListWznmAMMachineMakefile& rst , WznmAMMachineMakefile** rec , const ubigint refWznmMMachine , const string x1SrefKTag , const string Val ) { ubigint retval = 0; WznmAMMachineMakefile* _rec = NULL; retval = insertNewRec(&_rec, refWznmMMachine, x1SrefKTag, Val); rst.nodes.push_back(_rec); if (rec != NULL) *rec = _rec; return retval; }; void TblWznmAMMachineMakefile::insertRst( ListWznmAMMachineMakefile& rst , bool transact ) { }; void TblWznmAMMachineMakefile::updateRec( WznmAMMachineMakefile* rec ) { }; void TblWznmAMMachineMakefile::updateRst( ListWznmAMMachineMakefile& rst , bool transact ) { }; void TblWznmAMMachineMakefile::removeRecByRef( ubigint ref ) { }; bool TblWznmAMMachineMakefile::loadRecByRef( ubigint ref , WznmAMMachineMakefile** rec ) { return false; }; ubigint TblWznmAMMachineMakefile::loadRefsByMch( ubigint refWznmMMachine , const bool append , vector<ubigint>& refs ) { return 0; }; ubigint TblWznmAMMachineMakefile::loadRstByMch( ubigint refWznmMMachine , const bool append , ListWznmAMMachineMakefile& rst ) { return 0; }; bool TblWznmAMMachineMakefile::loadValByMchTag( ubigint refWznmMMachine , string x1SrefKTag , string& Val ) { return false; }; ubigint TblWznmAMMachineMakefile::loadRstByRefs( vector<ubigint>& refs , const bool append , ListWznmAMMachineMakefile& rst ) { ubigint numload = 0; WznmAMMachineMakefile* rec = NULL; if (!append) rst.clear(); for (unsigned int i = 0; i < refs.size(); i++) if (loadRecByRef(refs[i], &rec)) { rst.nodes.push_back(rec); numload++; }; return numload; }; #if defined(SBECORE_MAR) || defined(SBECORE_MY) /****************************************************************************** class MyTblWznmAMMachineMakefile ******************************************************************************/ MyTblWznmAMMachineMakefile::MyTblWznmAMMachineMakefile() : TblWznmAMMachineMakefile() , MyTable() { stmtInsertRec = NULL; stmtUpdateRec = NULL; stmtRemoveRecByRef = NULL; }; MyTblWznmAMMachineMakefile::~MyTblWznmAMMachineMakefile() { if (stmtInsertRec) delete(stmtInsertRec); if (stmtUpdateRec) delete(stmtUpdateRec); if (stmtRemoveRecByRef) delete(stmtRemoveRecByRef); }; void MyTblWznmAMMachineMakefile::initStatements() { stmtInsertRec = createStatement("INSERT INTO TblWznmAMMachineMakefile (refWznmMMachine, x1SrefKTag, Val) VALUES (?,?,?)", false); stmtUpdateRec = createStatement("UPDATE TblWznmAMMachineMakefile SET refWznmMMachine = ?, x1SrefKTag = ?, Val = ? WHERE ref = ?", false); stmtRemoveRecByRef = createStatement("DELETE FROM TblWznmAMMachineMakefile WHERE ref = ?", false); }; bool MyTblWznmAMMachineMakefile::loadRecBySQL( const string& sqlstr , WznmAMMachineMakefile** rec ) { MYSQL_RES* dbresult; MYSQL_ROW dbrow; WznmAMMachineMakefile* _rec = NULL; bool retval = false; if (mysql_real_query(dbs, sqlstr.c_str(), sqlstr.length())) { string dbms = "MyTblWznmAMMachineMakefile::loadRecBySQL() / " + string(mysql_error(dbs)); throw SbeException(SbeException::DBS_QUERY, {{"dbms",dbms}, {"sql",sqlstr}}); }; dbresult = mysql_store_result(dbs); if (!dbresult) { string dbms = "MyTblWznmAMMachineMakefile::loadRecBySQL() / store result / " + string(mysql_error(dbs)); throw SbeException(SbeException::DBS_QUERY, {{"dbms",dbms}, {"sql",sqlstr}}); }; if (mysql_num_rows(dbresult) == 1) { dbrow = mysql_fetch_row(dbresult); unsigned long* dblengths = mysql_fetch_lengths(dbresult); _rec = new WznmAMMachineMakefile(); if (dbrow[0]) _rec->ref = atoll((char*) dbrow[0]); else _rec->ref = 0; if (dbrow[1]) _rec->refWznmMMachine = atoll((char*) dbrow[1]); else _rec->refWznmMMachine = 0; if (dbrow[2]) _rec->x1SrefKTag.assign(dbrow[2], dblengths[2]); else _rec->x1SrefKTag = ""; if (dbrow[3]) _rec->Val.assign(dbrow[3], dblengths[3]); else _rec->Val = ""; retval = true; }; mysql_free_result(dbresult); *rec = _rec; return retval; }; ubigint MyTblWznmAMMachineMakefile::loadRstBySQL( const string& sqlstr , const bool append , ListWznmAMMachineMakefile& rst ) { MYSQL_RES* dbresult; MYSQL_ROW dbrow; ubigint numrow; ubigint numread = 0; WznmAMMachineMakefile* rec; if (!append) rst.clear(); if (mysql_real_query(dbs, sqlstr.c_str(), sqlstr.length())) { string dbms = "MyTblWznmAMMachineMakefile::loadRstBySQL() / " + string(mysql_error(dbs)); throw SbeException(SbeException::DBS_QUERY, {{"dbms",dbms}, {"sql",sqlstr}}); }; dbresult = mysql_store_result(dbs); if (!dbresult) { string dbms = "MyTblWznmAMMachineMakefile::loadRstBySQL() / store result / " + string(mysql_error(dbs)); throw SbeException(SbeException::DBS_QUERY, {{"dbms",dbms}, {"sql",sqlstr}}); }; numrow = mysql_num_rows(dbresult); if (numrow > 0) { rst.nodes.reserve(rst.nodes.size() + numrow); while (numread < numrow) { dbrow = mysql_fetch_row(dbresult); unsigned long* dblengths = mysql_fetch_lengths(dbresult); rec = new WznmAMMachineMakefile(); if (dbrow[0]) rec->ref = atoll((char*) dbrow[0]); else rec->ref = 0; if (dbrow[1]) rec->refWznmMMachine = atoll((char*) dbrow[1]); else rec->refWznmMMachine = 0; if (dbrow[2]) rec->x1SrefKTag.assign(dbrow[2], dblengths[2]); else rec->x1SrefKTag = ""; if (dbrow[3]) rec->Val.assign(dbrow[3], dblengths[3]); else rec->Val = ""; rst.nodes.push_back(rec); numread++; }; }; mysql_free_result(dbresult); return(numread); }; ubigint MyTblWznmAMMachineMakefile::insertRec( WznmAMMachineMakefile* rec ) { unsigned long l[3]; my_bool n[3]; my_bool e[3]; l[1] = rec->x1SrefKTag.length(); l[2] = rec->Val.length(); MYSQL_BIND bind[] = { bindUbigint(&rec->refWznmMMachine,&(l[0]),&(n[0]),&(e[0])), bindCstring((char*) (rec->x1SrefKTag.c_str()),&(l[1]),&(n[1]),&(e[1])), bindCstring((char*) (rec->Val.c_str()),&(l[2]),&(n[2]),&(e[2])) }; if (mysql_stmt_bind_param(stmtInsertRec, bind)) { string dbms = "MyTblWznmAMMachineMakefile::insertRec() / bind / " + string(mysql_error(dbs)); throw SbeException(SbeException::DBS_STMTEXEC, {{"dbms",dbms}}); }; if (mysql_stmt_execute(stmtInsertRec)) { string dbms = "MyTblWznmAMMachineMakefile::insertRec() / " + string(mysql_error(dbs)); throw SbeException(SbeException::DBS_STMTEXEC, {{"dbms",dbms}}); }; rec->ref = mysql_stmt_insert_id(stmtInsertRec); return rec->ref; }; void MyTblWznmAMMachineMakefile::insertRst( ListWznmAMMachineMakefile& rst , bool transact ) { if (transact) begin(); for (unsigned int i = 0; i < rst.nodes.size(); i++) insertRec(rst.nodes[i]); if (transact) if (!commit()) for (unsigned int i=0;i<rst.nodes.size();i++) insertRec(rst.nodes[i]); }; void MyTblWznmAMMachineMakefile::updateRec( WznmAMMachineMakefile* rec ) { unsigned long l[4]; my_bool n[4]; my_bool e[4]; l[1] = rec->x1SrefKTag.length(); l[2] = rec->Val.length(); MYSQL_BIND bind[] = { bindUbigint(&rec->refWznmMMachine,&(l[0]),&(n[0]),&(e[0])), bindCstring((char*) (rec->x1SrefKTag.c_str()),&(l[1]),&(n[1]),&(e[1])), bindCstring((char*) (rec->Val.c_str()),&(l[2]),&(n[2]),&(e[2])), bindUbigint(&rec->ref,&(l[3]),&(n[3]),&(e[3])) }; if (mysql_stmt_bind_param(stmtUpdateRec, bind)) { string dbms = "MyTblWznmAMMachineMakefile::updateRec() / bind / " + string(mysql_error(dbs)); throw SbeException(SbeException::DBS_STMTEXEC, {{"dbms",dbms}}); }; if (mysql_stmt_execute(stmtUpdateRec)) { string dbms = "MyTblWznmAMMachineMakefile::updateRec() / " + string(mysql_error(dbs)); throw SbeException(SbeException::DBS_STMTEXEC, {{"dbms",dbms}}); }; }; void MyTblWznmAMMachineMakefile::updateRst( ListWznmAMMachineMakefile& rst , bool transact ) { if (transact) begin(); for (unsigned int i = 0; i < rst.nodes.size(); i++) updateRec(rst.nodes[i]); if (transact) if (!commit()) for (unsigned int i = 0; i < rst.nodes.size(); i++) updateRec(rst.nodes[i]); }; void MyTblWznmAMMachineMakefile::removeRecByRef( ubigint ref ) { unsigned long l; my_bool n; my_bool e; MYSQL_BIND bind = bindUbigint(&ref,&l,&n,&e); if (mysql_stmt_bind_param(stmtRemoveRecByRef, &bind)) { string dbms = "MyTblWznmAMMachineMakefile::removeRecByRef() / bind / " + string(mysql_error(dbs)); throw SbeException(SbeException::DBS_STMTEXEC, {{"dbms",dbms}}); }; if (mysql_stmt_execute(stmtRemoveRecByRef)) { string dbms = "MyTblWznmAMMachineMakefile::removeRecByRef() / " + string(mysql_error(dbs)); throw SbeException(SbeException::DBS_STMTEXEC, {{"dbms",dbms}}); }; }; bool MyTblWznmAMMachineMakefile::loadRecByRef( ubigint ref , WznmAMMachineMakefile** rec ) { if (ref == 0) { *rec = NULL; return false; }; return loadRecBySQL("SELECT * FROM TblWznmAMMachineMakefile WHERE ref = " + to_string(ref), rec); }; ubigint MyTblWznmAMMachineMakefile::loadRefsByMch( ubigint refWznmMMachine , const bool append , vector<ubigint>& refs ) { return loadRefsBySQL("SELECT ref FROM TblWznmAMMachineMakefile WHERE refWznmMMachine = " + to_string(refWznmMMachine) + "", append, refs); }; ubigint MyTblWznmAMMachineMakefile::loadRstByMch( ubigint refWznmMMachine , const bool append , ListWznmAMMachineMakefile& rst ) { return loadRstBySQL("SELECT ref, refWznmMMachine, x1SrefKTag, Val FROM TblWznmAMMachineMakefile WHERE refWznmMMachine = " + to_string(refWznmMMachine) + " ORDER BY x1SrefKTag ASC", append, rst); }; bool MyTblWznmAMMachineMakefile::loadValByMchTag( ubigint refWznmMMachine , string x1SrefKTag , string& Val ) { return loadStringBySQL("SELECT Val FROM TblWznmAMMachineMakefile WHERE refWznmMMachine = " + to_string(refWznmMMachine) + " AND x1SrefKTag = '" + x1SrefKTag + "'", Val); }; #endif #if defined(SBECORE_PG) /****************************************************************************** class PgTblWznmAMMachineMakefile ******************************************************************************/ PgTblWznmAMMachineMakefile::PgTblWznmAMMachineMakefile() : TblWznmAMMachineMakefile() , PgTable() { }; PgTblWznmAMMachineMakefile::~PgTblWznmAMMachineMakefile() { // TODO: run SQL DEALLOCATE to free prepared statements }; void PgTblWznmAMMachineMakefile::initStatements() { createStatement("TblWznmAMMachineMakefile_insertRec", "INSERT INTO TblWznmAMMachineMakefile (refWznmMMachine, x1SrefKTag, Val) VALUES ($1,$2,$3) RETURNING ref", 3); createStatement("TblWznmAMMachineMakefile_updateRec", "UPDATE TblWznmAMMachineMakefile SET refWznmMMachine = $1, x1SrefKTag = $2, Val = $3 WHERE ref = $4", 4); createStatement("TblWznmAMMachineMakefile_removeRecByRef", "DELETE FROM TblWznmAMMachineMakefile WHERE ref = $1", 1); createStatement("TblWznmAMMachineMakefile_loadRecByRef", "SELECT ref, refWznmMMachine, x1SrefKTag, Val FROM TblWznmAMMachineMakefile WHERE ref = $1", 1); createStatement("TblWznmAMMachineMakefile_loadRefsByMch", "SELECT ref FROM TblWznmAMMachineMakefile WHERE refWznmMMachine = $1", 1); createStatement("TblWznmAMMachineMakefile_loadRstByMch", "SELECT ref, refWznmMMachine, x1SrefKTag, Val FROM TblWznmAMMachineMakefile WHERE refWznmMMachine = $1 ORDER BY x1SrefKTag ASC", 1); createStatement("TblWznmAMMachineMakefile_loadValByMchTag", "SELECT Val FROM TblWznmAMMachineMakefile WHERE refWznmMMachine = $1 AND x1SrefKTag = $2", 2); }; bool PgTblWznmAMMachineMakefile::loadRec( PGresult* res , WznmAMMachineMakefile** rec ) { char* ptr; WznmAMMachineMakefile* _rec = NULL; bool retval = false; if (PQntuples(res) == 1) { _rec = new WznmAMMachineMakefile(); int fnum[] = { PQfnumber(res, "ref"), PQfnumber(res, "refwznmmmachine"), PQfnumber(res, "x1srefktag"), PQfnumber(res, "val") }; ptr = PQgetvalue(res, 0, fnum[0]); _rec->ref = atoll(ptr); ptr = PQgetvalue(res, 0, fnum[1]); _rec->refWznmMMachine = atoll(ptr); ptr = PQgetvalue(res, 0, fnum[2]); _rec->x1SrefKTag.assign(ptr, PQgetlength(res, 0, fnum[2])); ptr = PQgetvalue(res, 0, fnum[3]); _rec->Val.assign(ptr, PQgetlength(res, 0, fnum[3])); retval = true; }; PQclear(res); *rec = _rec; return retval; }; ubigint PgTblWznmAMMachineMakefile::loadRst( PGresult* res , const bool append , ListWznmAMMachineMakefile& rst ) { ubigint numrow; ubigint numread = 0; char* ptr; WznmAMMachineMakefile* rec; if (!append) rst.clear(); numrow = PQntuples(res); if (numrow > 0) { rst.nodes.reserve(rst.nodes.size() + numrow); int fnum[] = { PQfnumber(res, "ref"), PQfnumber(res, "refwznmmmachine"), PQfnumber(res, "x1srefktag"), PQfnumber(res, "val") }; while (numread < numrow) { rec = new WznmAMMachineMakefile(); ptr = PQgetvalue(res, numread, fnum[0]); rec->ref = atoll(ptr); ptr = PQgetvalue(res, numread, fnum[1]); rec->refWznmMMachine = atoll(ptr); ptr = PQgetvalue(res, numread, fnum[2]); rec->x1SrefKTag.assign(ptr, PQgetlength(res, numread, fnum[2])); ptr = PQgetvalue(res, numread, fnum[3]); rec->Val.assign(ptr, PQgetlength(res, numread, fnum[3])); rst.nodes.push_back(rec); numread++; }; }; PQclear(res); return numread; }; bool PgTblWznmAMMachineMakefile::loadRecByStmt( const string& srefStmt , const unsigned int N , const char** vals , const int* l , const int* f , WznmAMMachineMakefile** rec ) { PGresult* res; res = PQexecPrepared(dbs, srefStmt.c_str(), N, vals, l, f, 0); if (PQresultStatus(res) != PGRES_TUPLES_OK) { string dbms = "PgTblWznmAMMachineMakefile::loadRecByStmt(" + srefStmt + ") / " + string(PQerrorMessage(dbs)); throw SbeException(SbeException::DBS_STMTEXEC, {{"dbms",dbms}}); }; return loadRec(res, rec); }; ubigint PgTblWznmAMMachineMakefile::loadRstByStmt( const string& srefStmt , const unsigned int N , const char** vals , const int* l , const int* f , const bool append , ListWznmAMMachineMakefile& rst ) { PGresult* res; res = PQexecPrepared(dbs, srefStmt.c_str(), N, vals, l, f, 0); if (PQresultStatus(res) != PGRES_TUPLES_OK) { string dbms = "PgTblWznmAMMachineMakefile::loadRstByStmt(" + srefStmt + ") / " + string(PQerrorMessage(dbs)); throw SbeException(SbeException::DBS_STMTEXEC, {{"dbms",dbms}}); }; return loadRst(res, append, rst); }; bool PgTblWznmAMMachineMakefile::loadRecBySQL( const string& sqlstr , WznmAMMachineMakefile** rec ) { PGresult* res; res = PQexec(dbs, sqlstr.c_str()); if (PQresultStatus(res) != PGRES_TUPLES_OK) { string dbms = "PgTblWznmAMMachineMakefile::loadRecBySQL() / " + string(PQerrorMessage(dbs)); throw SbeException(SbeException::DBS_QUERY, {{"dbms",dbms}, {"sql",sqlstr}}); }; return loadRec(res, rec); }; ubigint PgTblWznmAMMachineMakefile::loadRstBySQL( const string& sqlstr , const bool append , ListWznmAMMachineMakefile& rst ) { PGresult* res; res = PQexec(dbs, sqlstr.c_str()); if (PQresultStatus(res) != PGRES_TUPLES_OK) { string dbms = "PgTblWznmAMMachineMakefile::loadRstBySQL() / " + string(PQerrorMessage(dbs)); throw SbeException(SbeException::DBS_QUERY, {{"dbms",dbms}, {"sql",sqlstr}}); }; return loadRst(res, append, rst); }; ubigint PgTblWznmAMMachineMakefile::insertRec( WznmAMMachineMakefile* rec ) { PGresult* res; char* ptr; ubigint _refWznmMMachine = htonl64(rec->refWznmMMachine); const char* vals[] = { (char*) &_refWznmMMachine, rec->x1SrefKTag.c_str(), rec->Val.c_str() }; const int l[] = { sizeof(ubigint), 0, 0 }; const int f[] = {1, 0, 0}; res = PQexecPrepared(dbs, "TblWznmAMMachineMakefile_insertRec", 3, vals, l, f, 0); if (PQresultStatus(res) != PGRES_TUPLES_OK) { string dbms = "PgTblWznmAMMachineMakefile::insertRec() / " + string(PQerrorMessage(dbs)); throw SbeException(SbeException::DBS_STMTEXEC, {{"dbms",dbms}}); }; ptr = PQgetvalue(res, 0, 0); rec->ref = atoll(ptr); PQclear(res); return rec->ref; }; void PgTblWznmAMMachineMakefile::insertRst( ListWznmAMMachineMakefile& rst , bool transact ) { if (transact) begin(); for (unsigned int i = 0; i < rst.nodes.size(); i++) insertRec(rst.nodes[i]); if (transact) if (!commit()) for (unsigned int i = 0; i < rst.nodes.size(); i++) insertRec(rst.nodes[i]); }; void PgTblWznmAMMachineMakefile::updateRec( WznmAMMachineMakefile* rec ) { PGresult* res; ubigint _refWznmMMachine = htonl64(rec->refWznmMMachine); ubigint _ref = htonl64(rec->ref); const char* vals[] = { (char*) &_refWznmMMachine, rec->x1SrefKTag.c_str(), rec->Val.c_str(), (char*) &_ref }; const int l[] = { sizeof(ubigint), 0, 0, sizeof(ubigint) }; const int f[] = {1, 0, 0, 1}; res = PQexecPrepared(dbs, "TblWznmAMMachineMakefile_updateRec", 4, vals, l, f, 0); if (PQresultStatus(res) != PGRES_COMMAND_OK) { string dbms = "PgTblWznmAMMachineMakefile::updateRec() / " + string(PQerrorMessage(dbs)); throw SbeException(SbeException::DBS_STMTEXEC, {{"dbms",dbms}}); }; PQclear(res); }; void PgTblWznmAMMachineMakefile::updateRst( ListWznmAMMachineMakefile& rst , bool transact ) { if (transact) begin(); for (unsigned int i = 0; i < rst.nodes.size(); i++) updateRec(rst.nodes[i]); if (transact) if (!commit()) for (unsigned int i = 0; i < rst.nodes.size(); i++) updateRec(rst.nodes[i]); }; void PgTblWznmAMMachineMakefile::removeRecByRef( ubigint ref ) { PGresult* res; ubigint _ref = htonl64(ref); const char* vals[] = { (char*) &_ref }; const int l[] = { sizeof(ubigint) }; const int f[] = {1}; res = PQexecPrepared(dbs, "TblWznmAMMachineMakefile_removeRecByRef", 1, vals, l, f, 0); if (PQresultStatus(res) != PGRES_COMMAND_OK) { string dbms = "PgTblWznmAMMachineMakefile::removeRecByRef() / " + string(PQerrorMessage(dbs)); throw SbeException(SbeException::DBS_STMTEXEC, {{"dbms",dbms}}); }; PQclear(res); }; bool PgTblWznmAMMachineMakefile::loadRecByRef( ubigint ref , WznmAMMachineMakefile** rec ) { if (ref == 0) { *rec = NULL; return false; }; ubigint _ref = htonl64(ref); const char* vals[] = { (char*) &_ref }; const int l[] = { sizeof(ubigint) }; const int f[] = {1}; return loadRecByStmt("TblWznmAMMachineMakefile_loadRecByRef", 1, vals, l, f, rec); }; ubigint PgTblWznmAMMachineMakefile::loadRefsByMch( ubigint refWznmMMachine , const bool append , vector<ubigint>& refs ) { ubigint _refWznmMMachine = htonl64(refWznmMMachine); const char* vals[] = { (char*) &_refWznmMMachine }; const int l[] = { sizeof(ubigint) }; const int f[] = {1}; return loadRefsByStmt("TblWznmAMMachineMakefile_loadRefsByMch", 1, vals, l, f, append, refs); }; ubigint PgTblWznmAMMachineMakefile::loadRstByMch( ubigint refWznmMMachine , const bool append , ListWznmAMMachineMakefile& rst ) { ubigint _refWznmMMachine = htonl64(refWznmMMachine); const char* vals[] = { (char*) &_refWznmMMachine }; const int l[] = { sizeof(ubigint) }; const int f[] = {1}; return loadRstByStmt("TblWznmAMMachineMakefile_loadRstByMch", 1, vals, l, f, append, rst); }; bool PgTblWznmAMMachineMakefile::loadValByMchTag( ubigint refWznmMMachine , string x1SrefKTag , string& Val ) { ubigint _refWznmMMachine = htonl64(refWznmMMachine); const char* vals[] = { (char*) &_refWznmMMachine, x1SrefKTag.c_str() }; const int l[] = { sizeof(ubigint), 0 }; const int f[] = {1,0}; return loadStringByStmt("TblWznmAMMachineMakefile_loadValByMchTag", 2, vals, l, f, Val); }; #endif
27.012687
195
0.675491
mpsitech
6f72df799e5a12e1e05ecad1356ee41387923580
1,327
cpp
C++
src/population/reproducer/PassionateReproducer.cpp
jansvoboda11/gram
62e5b525ea648b4d452cb2153bcca90dfbee9de5
[ "MIT" ]
7
2017-05-03T11:47:42.000Z
2021-10-12T02:46:16.000Z
src/population/reproducer/PassionateReproducer.cpp
jansvoboda11/gram
62e5b525ea648b4d452cb2153bcca90dfbee9de5
[ "MIT" ]
3
2021-02-22T19:14:05.000Z
2021-06-14T20:36:47.000Z
src/population/reproducer/PassionateReproducer.cpp
jansvoboda11/gram
62e5b525ea648b4d452cb2153bcca90dfbee9de5
[ "MIT" ]
2
2020-01-29T05:37:00.000Z
2022-01-17T06:03:48.000Z
#include "gram/population/reproducer/PassionateReproducer.h" #include <algorithm> #include <memory> #include "gram/individual/Individual.h" #include "gram/operator/crossover/Crossover.h" #include "gram/operator/mutation/Mutation.h" #include "gram/operator/selector/IndividualSelector.h" #include "gram/population/Individuals.h" #include "gram/population/reproducer/Reproducer.h" using namespace gram; using namespace std; PassionateReproducer::PassionateReproducer(unique_ptr<IndividualSelector> selector, unique_ptr<Crossover> crossover, unique_ptr<Mutation> mutation) : selector(move(selector)), crossover(move(crossover)), mutation(move(mutation)) { // } Individuals PassionateReproducer::reproduce(Individuals& individuals) { unsigned long size = individuals.size(); Individuals children; children.reserve(size); for (unsigned long i = 0; i < size; i++) { Individual child = createChild(individuals); children.addIndividual(child); } return children; } Individual PassionateReproducer::createChild(Individuals& individuals) { Individual& parent1 = selector->select(individuals); Individual& parent2 = selector->select(individuals); Individual child = parent1.mateWith(parent2, *crossover); child.mutate(*mutation); return child; }
28.234043
116
0.74529
jansvoboda11
6f807d0caccd5ee9fa9f6be4d17bcabca111da1b
15,170
cpp
C++
demos/fractal/fractal_demo.cpp
a-n-t-h-o-n-y/MCurses
c9184a0fefbdc4eb9a044f815ee2270e6b8f202c
[ "MIT" ]
284
2017-11-07T10:06:48.000Z
2021-01-12T15:32:51.000Z
demos/fractal/fractal_demo.cpp
a-n-t-h-o-n-y/MCurses
c9184a0fefbdc4eb9a044f815ee2270e6b8f202c
[ "MIT" ]
38
2018-01-14T12:34:54.000Z
2020-09-26T15:32:43.000Z
demos/fractal/fractal_demo.cpp
a-n-t-h-o-n-y/MCurses
c9184a0fefbdc4eb9a044f815ee2270e6b8f202c
[ "MIT" ]
31
2017-11-30T11:22:21.000Z
2020-11-03T05:27:47.000Z
#include "fractal_demo.hpp" #include <cassert> #include <cmath> #include <future> #include <thread> #include <utility> #include <vector> #include <termox/termox.hpp> #include "float_t.hpp" #include "julia.hpp" #include "mandelbrot.hpp" namespace { using fractal::Float_t; auto constexpr zoom_scale = 0.05; auto constexpr default_boundary = ox::Boundary<Float_t>{-2, 2, 2, -2}; using ox::Color; using ox::RGB; /// Fractal colors start at color 16. auto const custom_palette = ox::Palette{ {Color::Background, RGB{000000}}, {Color::Foreground, RGB{0xFFFFFF}}, {Color{16}, RGB{0x02044e}}, {Color{17}, RGB{0x180450}}, {Color{18}, RGB{0x270252}}, {Color{19}, RGB{0x330154}}, {Color{20}, RGB{0x3e0055}}, {Color{21}, RGB{0x480056}}, {Color{22}, RGB{0x520057}}, {Color{23}, RGB{0x5c0058}}, {Color{24}, RGB{0x650058}}, {Color{25}, RGB{0x6e0058}}, {Color{26}, RGB{0x770058}}, {Color{27}, RGB{0x800058}}, {Color{28}, RGB{0x880057}}, {Color{29}, RGB{0x900056}}, {Color{30}, RGB{0x980455}}, {Color{31}, RGB{0x9f0d54}}, {Color{32}, RGB{0xa71553}}, {Color{33}, RGB{0xad1c52}}, {Color{34}, RGB{0xb42350}}, {Color{35}, RGB{0xba2b4e}}, {Color{36}, RGB{0xc0324d}}, {Color{37}, RGB{0xc6394b}}, {Color{38}, RGB{0xcb4049}}, {Color{39}, RGB{0xd04847}}, {Color{40}, RGB{0xd54f45}}, {Color{41}, RGB{0xd95644}}, {Color{42}, RGB{0xdd5e42}}, {Color{43}, RGB{0xe06640}}, {Color{44}, RGB{0xe36d3e}}, {Color{45}, RGB{0xe6753d}}, {Color{46}, RGB{0xe87d3b}}, {Color{47}, RGB{0xea853a}}, {Color{48}, RGB{0xec8d39}}, {Color{49}, RGB{0xed9438}}, {Color{50}, RGB{0xee9c38}}, {Color{51}, RGB{0xefa439}}, {Color{52}, RGB{0xefac3a}}, {Color{53}, RGB{0xefb43b}}, {Color{54}, RGB{0xefbc3e}}, {Color{55}, RGB{0xeec441}}, {Color{56}, RGB{0xefbc3e}}, {Color{57}, RGB{0xefb43b}}, {Color{58}, RGB{0xefac3a}}, {Color{59}, RGB{0xefa439}}, {Color{60}, RGB{0xee9c38}}, {Color{61}, RGB{0xed9438}}, {Color{62}, RGB{0xec8d39}}, {Color{63}, RGB{0xea853a}}, {Color{64}, RGB{0xe87d3b}}, {Color{65}, RGB{0xe6753d}}, {Color{66}, RGB{0xe36d3e}}, {Color{67}, RGB{0xe06640}}, {Color{68}, RGB{0xdd5e42}}, {Color{69}, RGB{0xd95644}}, {Color{70}, RGB{0xd54f45}}, {Color{71}, RGB{0xd04847}}, {Color{72}, RGB{0xcb4049}}, {Color{73}, RGB{0xc6394b}}, {Color{74}, RGB{0xc0324d}}, {Color{75}, RGB{0xba2b4e}}, {Color{76}, RGB{0xb42350}}, {Color{77}, RGB{0xad1c52}}, {Color{78}, RGB{0xa71553}}, {Color{79}, RGB{0x9f0d54}}, {Color{80}, RGB{0x980455}}, {Color{81}, RGB{0x900056}}, {Color{82}, RGB{0x880057}}, {Color{83}, RGB{0x800058}}, {Color{84}, RGB{0x770058}}, {Color{85}, RGB{0x6e0058}}, {Color{86}, RGB{0x650058}}, {Color{87}, RGB{0x5c0058}}, {Color{88}, RGB{0x520057}}, {Color{89}, RGB{0x480056}}, {Color{90}, RGB{0x3e0055}}, {Color{91}, RGB{0x330154}}, {Color{92}, RGB{0x270252}}, {Color{93}, RGB{0x180450}}}; /// Adds the given offset in each direction to the given boundary. [[nodiscard]] auto apply_offsets(ox::Boundary<Float_t> boundary, ox::Boundary<Float_t> const& offsets) -> ox::Boundary<Float_t> { boundary.west += offsets.west; boundary.east += offsets.east; boundary.north += offsets.north; boundary.south += offsets.south; return boundary; } /// Given a fractal function for a single point, will generate a field of points template <typename Fn> [[nodiscard]] auto generate_points(ox::Boundary<Float_t> boundary, Float_t x_step, Float_t y_step, unsigned int resolution, Fn&& generator) -> std::vector<std::pair<ox::Color_graph<Float_t>::Coordinate, ox::Color>> { auto result = std::vector< std::pair<ox::Color_graph<Float_t>::Coordinate, ox::Color>>{}; auto const count = ((boundary.east - boundary.west) / x_step) * ((boundary.north - boundary.south) / y_step); result.reserve(count); for (auto x = boundary.west; x <= boundary.east; x += x_step) { for (auto y = boundary.south; y <= boundary.north; y += y_step) { result.push_back( {{x, y}, ox::Color( ((std::forward<Fn>(generator)(x, y, resolution) - 1) % (custom_palette.size() - 2)) + 16)}); } } return result; } /// Generates a field of fractal values in parallel, depending on hardward cores template <typename Fn> [[nodiscard]] auto par_generate_points(ox::Boundary<Float_t> boundary, Float_t x_step, Float_t y_step, unsigned int resolution, Fn&& generator) -> std::vector<std::pair<ox::Color_graph<Float_t>::Coordinate, ox::Color>> { auto result = std::vector< std::pair<ox::Color_graph<Float_t>::Coordinate, ox::Color>>{}; auto const count = ((boundary.east - boundary.west) / x_step) * ((boundary.north - boundary.south) / y_step); result.reserve(count); // Break Into Chunks auto const thread_count = std::thread::hardware_concurrency(); auto const chunk_distance = (boundary.east - boundary.west) / (double)thread_count; auto boundaries = std::vector<ox::Boundary<Float_t>>{}; boundaries.reserve(thread_count); for (auto i = 0uL; i < thread_count; ++i) { auto b = boundary; b.west = b.west + (i * chunk_distance); b.east = b.west + chunk_distance; boundaries.push_back(b); } // Launch Threads auto futs = std::vector<std::future<std::vector< std::pair<ox::Color_graph<Float_t>::Coordinate, ox::Color>>>>{}; futs.reserve(thread_count); for (auto const& b : boundaries) { futs.push_back(std::async(std::launch::async, [=] { return generate_points(b, x_step, y_step, resolution, generator); })); } // Wait and Concat Results for (auto& f : futs) { auto points = f.get(); result.insert(std::end(result), std::begin(points), std::end(points)); } return result; } [[nodiscard]] auto make_instructions() -> ox::Glyph_string { using ox::Trait; auto x = ox::Glyph_string{}; x.append(U"Instructions" | Trait::Bold); x.append(U"\n\n"); x.append(U"Switch between "); x.append(U"fractal types" | Trait::Bold); x.append(U" with top bar selector."); x.append(U"\n\n"); x.append(U"Zoom" | Trait::Bold); x.append(U'\n'); x.append( U" [Scroll Mouse Wheel] - Zoom in/out on point over mouse cursor.\n" U" [CTRL + Up Arrow] - Zoom in on center point.\n [CTRL + " U"Down Arrow] - Zoom out on center point."); x.append(U"\n\n"); x.append(U"Move" | Trait::Bold); x.append(U" around with the arrow keys."); x.append(U"\n\n"); x.append(U"The "); x.append(U"Julia Set" | Trait::Bold); x.append( U" can have its constant `C` modified by left mouse clicking and " U"dragging on the fractal surface."); x.append(U"\n\n"); x.append(U"Decrease terminal font size to increase fractal "); x.append(U"resolution" | Trait::Bold); x.append(U"."); x.append(U"\n\n"); x.append( U"If you zoom in far enough it will bottom out on `long double` " U"floating point resolution and will freeze with black lines across " U"the image."); return x; } } // namespace namespace fractal { Float_edit::Float_edit() { using namespace ox; *this | pipe::fixed_height(1); this->second | bg(Color::White) | fg(Color::Black); } Top_bar::Top_bar() : ox::HPair<ox::Cycle_box, ox::Toggle_button>{ {ox::Align::Center, 0, 14}, {U"Instructions", U"Fractal View"}} { using namespace ox::pipe; *this | fixed_height(1); buttons | fixed_width(14) | children() | bg(ox::Color::White) | fg(ox::Color::Black); selector.add_option(U"< Mandelbrot >").connect([this] { fractal_changed.emit(Fractal::Mandelbrot); }); selector.add_option(U"< Julia >").connect([this] { fractal_changed.emit(Fractal::Julia); }); } Instructions::Instructions() : ox::Text_view{make_instructions()} { *this | bg(ox::Color{16}) | fg(ox::Color{45}); } Fractal_demo::Fractal_demo() : ox::VPair<Top_bar, ox::SPair<ox::Color_graph<Float_t>, Instructions>>{ {}, {{{-2, 2, 2, -2}}, {}}} { using namespace ox::pipe; auto const pal = custom_palette; *this | direct_focus() | on_focus_in([=] { ox::Terminal::set_palette(pal); }) | forward_focus(graph); auto& stack = this->second; stack | active_page(0); graph | strong_focus(); top_bar.instructions_request.connect([this] { this->show_instructions(); }); top_bar.fractal_view_request.connect([this] { this->show_fractals(); }); top_bar.fractal_changed.connect([this](auto type) { fractal_type_ = type; this->reset(); }); graph.mouse_moved.connect([this](auto const& m) { if (fractal_type_ != Fractal::Julia) return; auto const b = graph.boundary(); auto const hr = ((b.east - b.west) / (double)graph.area().width); auto const vr = ((b.north - b.south) / (double)graph.area().height); julia_c_.real(b.west + (m.at.x * hr)); julia_c_.imag(b.south + (m.at.y * vr)); this->reset(); }); graph.key_pressed.connect([this](auto k) { switch (k) { case ox::Key::Arrow_right: this->increment_h_offset(+1); this->reset(); break; case ox::Key::Arrow_left: this->increment_h_offset(-1); this->reset(); break; case ox::Key::Arrow_up: this->increment_v_offset(+1); this->reset(); break; case ox::Key::Arrow_down: this->increment_v_offset(-1); this->reset(); break; default: break; } // If statements to get around switch warning, not in enum. if (k == (ox::Mod::Ctrl | ox::Key::Arrow_up)) this->zoom_in(); else if (k == (ox::Mod::Ctrl | ox::Key::Arrow_down)) this->zoom_out(); }); graph.mouse_wheel_scrolled.connect([this](auto m) { switch (m.button) { case ox::Mouse::Button::ScrollUp: this->zoom_in_at(m.at); break; case ox::Mouse::Button::ScrollDown: this->zoom_out_at(m.at); break; default: break; } }); graph | on_resize([this](auto, auto) { this->reset(); }); graph | on_enable([this] { this->reset(); }); this->reset(default_boundary); } void Fractal_demo::reset(ox::Boundary<Float_t> b) { if (graph.area().height == 0 || graph.area().width == 0) return; graph.set_boundary(b); auto const x_interval = Float_t(b.east - b.west) / (graph.area().width * 1.001); auto const y_interval = Float_t(b.north - b.south) / (graph.area().height * 2.001); auto const distance = b.east - b.west; auto const resolution = std::clamp((int)std::log(1. / distance), 1, 8) * (custom_palette.size() - 2); switch (fractal_type_) { case Fractal::Mandelbrot: graph.reset(par_generate_points(b, x_interval, y_interval, resolution, mandelbrot)); break; case Fractal::Julia: graph.reset( par_generate_points(b, x_interval, y_interval, resolution, [&](auto x, auto y, auto mi) { return julia(x, y, julia_c_, mi); })); break; } } void Fractal_demo::reset() { this->reset(apply_offsets(default_boundary, offsets_)); } void Fractal_demo::increment_h_offset(int direction) { assert(direction == 1 || direction == -1); auto constexpr fraction = (Float_t)1. / (Float_t)25.; auto const b = graph.boundary(); auto const amount = direction * (b.east - b.west) * fraction; offsets_.west += amount; offsets_.east += amount; } void Fractal_demo::increment_v_offset(int direction) { assert(direction == 1 || direction == -1); auto constexpr fraction = (Float_t)1. / (Float_t)25.; auto const b = graph.boundary(); auto const amount = direction * (b.north - b.south) * fraction; offsets_.north += amount; offsets_.south += amount; } void Fractal_demo::zoom_in() { auto const b = graph.boundary(); auto const h_distance = (b.east - b.west); auto const v_distance = (b.north - b.south); offsets_.west += h_distance * zoom_scale; offsets_.east -= h_distance * zoom_scale; offsets_.north -= v_distance * zoom_scale; offsets_.south += v_distance * zoom_scale; this->reset(); } void Fractal_demo::zoom_in_at(ox::Point p) { auto const b = graph.boundary(); // Horizontal auto const h_distance = b.east - b.west; auto const h_ratio = h_distance / graph.area().width; auto const h_coord = h_ratio * p.x; offsets_.west += h_coord * zoom_scale; offsets_.east -= (h_distance - h_coord) * zoom_scale; // Vertical auto const v_distance = b.north - b.south; auto const v_ratio = v_distance / graph.area().height; auto const v_coord = v_ratio * (graph.area().height - p.y); offsets_.south += v_coord * zoom_scale; offsets_.north -= (v_distance - v_coord) * zoom_scale; this->reset(); } void Fractal_demo::zoom_out() { auto const b = graph.boundary(); auto const h_distance = (b.east - b.west); auto const v_distance = (b.north - b.south); offsets_.west -= h_distance * zoom_scale; offsets_.east += h_distance * zoom_scale; offsets_.north += v_distance * zoom_scale; offsets_.south -= v_distance * zoom_scale; this->reset(); } void Fractal_demo::zoom_out_at(ox::Point p) { auto const b = graph.boundary(); // Horizontal auto const h_distance = b.east - b.west; auto const h_ratio = h_distance / graph.area().width; auto const h_coord = h_ratio * p.x; offsets_.west -= h_coord * zoom_scale; offsets_.east += (h_distance - h_coord) * zoom_scale; // Vertical auto const v_distance = b.north - b.south; auto const v_ratio = v_distance / graph.area().height; auto const v_coord = v_ratio * (graph.area().height - p.y); offsets_.south -= v_coord * zoom_scale; offsets_.north += (v_distance - v_coord) * zoom_scale; this->reset(); } } // namespace fractal
34.873563
80
0.572841
a-n-t-h-o-n-y
6f86e37e18f7a6957282ae6811afe60b5ced4665
7,071
cpp
C++
billing/src/v20180709/model/PayModeSummaryOverviewItem.cpp
datalliance88/tencentcloud-sdk-cpp
fbb8ea8e385620ac41b0a9ceb5abf1405b8aac8c
[ "Apache-2.0" ]
null
null
null
billing/src/v20180709/model/PayModeSummaryOverviewItem.cpp
datalliance88/tencentcloud-sdk-cpp
fbb8ea8e385620ac41b0a9ceb5abf1405b8aac8c
[ "Apache-2.0" ]
null
null
null
billing/src/v20180709/model/PayModeSummaryOverviewItem.cpp
datalliance88/tencentcloud-sdk-cpp
fbb8ea8e385620ac41b0a9ceb5abf1405b8aac8c
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/billing/v20180709/model/PayModeSummaryOverviewItem.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Billing::V20180709::Model; using namespace rapidjson; using namespace std; PayModeSummaryOverviewItem::PayModeSummaryOverviewItem() : m_payModeHasBeenSet(false), m_payModeNameHasBeenSet(false), m_realTotalCostHasBeenSet(false), m_realTotalCostRatioHasBeenSet(false), m_detailHasBeenSet(false) { } CoreInternalOutcome PayModeSummaryOverviewItem::Deserialize(const Value &value) { string requestId = ""; if (value.HasMember("PayMode") && !value["PayMode"].IsNull()) { if (!value["PayMode"].IsString()) { return CoreInternalOutcome(Error("response `PayModeSummaryOverviewItem.PayMode` IsString=false incorrectly").SetRequestId(requestId)); } m_payMode = string(value["PayMode"].GetString()); m_payModeHasBeenSet = true; } if (value.HasMember("PayModeName") && !value["PayModeName"].IsNull()) { if (!value["PayModeName"].IsString()) { return CoreInternalOutcome(Error("response `PayModeSummaryOverviewItem.PayModeName` IsString=false incorrectly").SetRequestId(requestId)); } m_payModeName = string(value["PayModeName"].GetString()); m_payModeNameHasBeenSet = true; } if (value.HasMember("RealTotalCost") && !value["RealTotalCost"].IsNull()) { if (!value["RealTotalCost"].IsString()) { return CoreInternalOutcome(Error("response `PayModeSummaryOverviewItem.RealTotalCost` IsString=false incorrectly").SetRequestId(requestId)); } m_realTotalCost = string(value["RealTotalCost"].GetString()); m_realTotalCostHasBeenSet = true; } if (value.HasMember("RealTotalCostRatio") && !value["RealTotalCostRatio"].IsNull()) { if (!value["RealTotalCostRatio"].IsString()) { return CoreInternalOutcome(Error("response `PayModeSummaryOverviewItem.RealTotalCostRatio` IsString=false incorrectly").SetRequestId(requestId)); } m_realTotalCostRatio = string(value["RealTotalCostRatio"].GetString()); m_realTotalCostRatioHasBeenSet = true; } if (value.HasMember("Detail") && !value["Detail"].IsNull()) { if (!value["Detail"].IsArray()) return CoreInternalOutcome(Error("response `PayModeSummaryOverviewItem.Detail` is not array type")); const Value &tmpValue = value["Detail"]; for (Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr) { ActionSummaryOverviewItem item; CoreInternalOutcome outcome = item.Deserialize(*itr); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_detail.push_back(item); } m_detailHasBeenSet = true; } return CoreInternalOutcome(true); } void PayModeSummaryOverviewItem::ToJsonObject(Value &value, Document::AllocatorType& allocator) const { if (m_payModeHasBeenSet) { Value iKey(kStringType); string key = "PayMode"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_payMode.c_str(), allocator).Move(), allocator); } if (m_payModeNameHasBeenSet) { Value iKey(kStringType); string key = "PayModeName"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_payModeName.c_str(), allocator).Move(), allocator); } if (m_realTotalCostHasBeenSet) { Value iKey(kStringType); string key = "RealTotalCost"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_realTotalCost.c_str(), allocator).Move(), allocator); } if (m_realTotalCostRatioHasBeenSet) { Value iKey(kStringType); string key = "RealTotalCostRatio"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_realTotalCostRatio.c_str(), allocator).Move(), allocator); } if (m_detailHasBeenSet) { Value iKey(kStringType); string key = "Detail"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(kArrayType).Move(), allocator); int i=0; for (auto itr = m_detail.begin(); itr != m_detail.end(); ++itr, ++i) { value[key.c_str()].PushBack(Value(kObjectType).Move(), allocator); (*itr).ToJsonObject(value[key.c_str()][i], allocator); } } } string PayModeSummaryOverviewItem::GetPayMode() const { return m_payMode; } void PayModeSummaryOverviewItem::SetPayMode(const string& _payMode) { m_payMode = _payMode; m_payModeHasBeenSet = true; } bool PayModeSummaryOverviewItem::PayModeHasBeenSet() const { return m_payModeHasBeenSet; } string PayModeSummaryOverviewItem::GetPayModeName() const { return m_payModeName; } void PayModeSummaryOverviewItem::SetPayModeName(const string& _payModeName) { m_payModeName = _payModeName; m_payModeNameHasBeenSet = true; } bool PayModeSummaryOverviewItem::PayModeNameHasBeenSet() const { return m_payModeNameHasBeenSet; } string PayModeSummaryOverviewItem::GetRealTotalCost() const { return m_realTotalCost; } void PayModeSummaryOverviewItem::SetRealTotalCost(const string& _realTotalCost) { m_realTotalCost = _realTotalCost; m_realTotalCostHasBeenSet = true; } bool PayModeSummaryOverviewItem::RealTotalCostHasBeenSet() const { return m_realTotalCostHasBeenSet; } string PayModeSummaryOverviewItem::GetRealTotalCostRatio() const { return m_realTotalCostRatio; } void PayModeSummaryOverviewItem::SetRealTotalCostRatio(const string& _realTotalCostRatio) { m_realTotalCostRatio = _realTotalCostRatio; m_realTotalCostRatioHasBeenSet = true; } bool PayModeSummaryOverviewItem::RealTotalCostRatioHasBeenSet() const { return m_realTotalCostRatioHasBeenSet; } vector<ActionSummaryOverviewItem> PayModeSummaryOverviewItem::GetDetail() const { return m_detail; } void PayModeSummaryOverviewItem::SetDetail(const vector<ActionSummaryOverviewItem>& _detail) { m_detail = _detail; m_detailHasBeenSet = true; } bool PayModeSummaryOverviewItem::DetailHasBeenSet() const { return m_detailHasBeenSet; }
30.089362
157
0.694103
datalliance88
6f890288d684594be9ab41a64e1ea24be9669ee1
1,681
cpp
C++
src/SLEngine.Shared/graphics/texture2D.cpp
SergioMasson/SimpleLittleEngine
10a0a43d7f4abae3574e902505b457455f0cb61b
[ "MIT" ]
null
null
null
src/SLEngine.Shared/graphics/texture2D.cpp
SergioMasson/SimpleLittleEngine
10a0a43d7f4abae3574e902505b457455f0cb61b
[ "MIT" ]
null
null
null
src/SLEngine.Shared/graphics/texture2D.cpp
SergioMasson/SimpleLittleEngine
10a0a43d7f4abae3574e902505b457455f0cb61b
[ "MIT" ]
null
null
null
#include "pch.h" #include "coreGraphics.h" #include <fstream> #include <iterator> #include <vector> #include "texture2D.h" #include "dds.h" using namespace sle; graphics::Texture2D::Texture2D(const wchar_t* filePath) { std::ifstream input(filePath, std::ios::binary); std::vector<char> bytes( (std::istreambuf_iterator<char>(input)), (std::istreambuf_iterator<char>())); input.close(); CreateDDSTextureFromMemory(graphics::g_d3dDevice.Get(), (byte*)bytes.data(), bytes.size(), m_resource.GetAddressOf(), m_resourceView.GetAddressOf()); // Once the texture view is created, create a sampler. This defines how the color // for a particular texture coordinate is determined using the relevant texture data. D3D11_SAMPLER_DESC samplerDesc; ZeroMemory(&samplerDesc, sizeof(samplerDesc)); samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;; samplerDesc.MaxAnisotropy = 0; // Specify how texture coordinates outside of the range 0..1 are resolved. samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; // Use no special MIP clamping or bias. samplerDesc.MipLODBias = 0.0f; samplerDesc.MinLOD = 0; samplerDesc.MaxLOD = D3D11_FLOAT32_MAX; // Don't use a comparison function. samplerDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; // Border address mode is not used, so this parameter is ignored. samplerDesc.BorderColor[0] = 0.0f; samplerDesc.BorderColor[1] = 0.0f; samplerDesc.BorderColor[2] = 0.0f; samplerDesc.BorderColor[3] = 0.0f; ASSERT_SUCCEEDED(graphics::g_d3dDevice->CreateSamplerState(&samplerDesc, m_samplerState.GetAddressOf())); }
32.326923
106
0.767995
SergioMasson
6f8a93d6c9b07c694e4bbc26d938cf0f89e261af
15,955
cpp
C++
api/c++/persistence/PersistenceService.cpp
AudiovisualMetadataPlatform/mico
7a4faf553859119faf1abfa15d41a7c88835136f
[ "Apache-2.0" ]
null
null
null
api/c++/persistence/PersistenceService.cpp
AudiovisualMetadataPlatform/mico
7a4faf553859119faf1abfa15d41a7c88835136f
[ "Apache-2.0" ]
null
null
null
api/c++/persistence/PersistenceService.cpp
AudiovisualMetadataPlatform/mico
7a4faf553859119faf1abfa15d41a7c88835136f
[ "Apache-2.0" ]
null
null
null
/** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <ctime> #include <iomanip> #include <cassert> #include <boost/uuid/uuid.hpp> #include <boost/uuid/uuid_io.hpp> #include <boost/uuid/uuid_generators.hpp> #include "PersistenceService.hpp" #include "SPARQLUtil.hpp" #include "FileOperations.h" #include "TimeInfo.h" #include "Logging.hpp" #include "JnippExceptionHandling.hpp" #include <anno4cpp.h> #include "ItemAnno4cpp.hpp" #ifndef ANNO4JDEPENDENCIES_PATH #define ANNO4JDEPENDENCIES_PATH "" #endif using namespace std; using namespace boost; using namespace uuids; using namespace jnipp::java::lang; using namespace jnipp::org::openrdf::idGenerator; using namespace jnipp::org::openrdf::repository::sparql; using namespace jnipp::org::openrdf::model; using namespace jnipp::org::openrdf::model::impl; using namespace jnipp::org::openrdf::repository::object; using namespace jnipp::org::openrdf::sail::memory::model; using namespace jnipp::com::github::anno4j; using namespace jnipp::eu::mico::platform::anno4j::model; using namespace jnipp::eu::mico::platform::persistence::impl; // extern references to constant SPARQL templates //SPARQL_INCLUDE(askContentItem); //SPARQL_INCLUDE(createContentItem); //SPARQL_INCLUDE(deleteContentItem); //SPARQL_INCLUDE(listContentItems); //SPARQL_INCLUDE(deleteGraph); // UUID generators static random_generator rnd_gen; //static init JNIEnv* mico::persistence::PersistenceService::m_sEnv = nullptr; JavaVM* mico::persistence::PersistenceService::m_sJvm = nullptr; namespace mico { namespace persistence { PersistenceService::PersistenceService(std::string serverAddress) : marmottaServerUrl("http://" + serverAddress + ":8080/marmotta") , contentDirectory("hdfs://" + serverAddress) , metadata("http://" + serverAddress + ":8080/marmotta") { initService(); } PersistenceService::PersistenceService(std::string serverAddress, int marmottaPort, std::string user, std::string password) : marmottaServerUrl("http://" + serverAddress + ":" + std::to_string(marmottaPort) + "/marmotta") , contentDirectory("hdfs://" + serverAddress) , metadata("http://" + serverAddress + ":" + std::to_string(marmottaPort) + "/marmotta") { initService(); } PersistenceService::PersistenceService(std::string marmottaServerUrl, std::string contentDirectory) : marmottaServerUrl(marmottaServerUrl), contentDirectory(contentDirectory), metadata(marmottaServerUrl) { initService(); } void PersistenceService::initService() { log::set_log_level(log::DEBUG); if (!m_sEnv || ! m_sJvm) { std::vector<std::string> filePatterns = {std::string(".*anno4jdependencies.*")}; std::vector<std::string> paths = {std::string(ANNO4JDEPENDENCIES_PATH),"/usr/share","/usr/local/share"}; std::map<std::string,std::string> jar_file = commons::FileOperations::findFiles(filePatterns, paths); if (jar_file.size() == 0) { throw std::runtime_error("Could not find appropriate anno4jdependencies jar."); } std::string JavaClassPath="-Djava.class.path="; JavaClassPath += jar_file[".*anno4jdependencies.*"]; //JavaClassPath += "/home/christian/mico/anno4cpp/java/anno4jdependencies/target/anno4jdependencies-2.0.0-SNAPSHOT.jar"; LOG_INFO("Loading Java dependency JAR: %s", jar_file[".*anno4jdependencies.*"].c_str()); JavaVMOption options[2]; // JVM invocation options options[0].optionString = (char *) JavaClassPath.c_str(); options[1].optionString = "-Xrs"; // this is important -> tells the JVM not to steal our system signals // options[1].optionString = "-Xdebug"; // options[2].optionString = "-Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=n"; //options[1].optionString = "-Xint"; JavaVMInitArgs vm_args; vm_args.version = JNI_VERSION_1_6; // minimum Java version vm_args.nOptions = 2; vm_args.options = options; vm_args.ignoreUnrecognized = false; jint rc = JNI_CreateJavaVM(&PersistenceService::m_sJvm, (void**)&PersistenceService::m_sEnv, &vm_args); if (rc != JNI_OK) { LOG_ERROR("Could not launch Java virtual machine."); throw std::runtime_error("Could not launch Java virtual machine."); } } LOG_INFO("JavaVM initialized"); jnipp::Env::Scope scope(PersistenceService::m_sJvm); checkJavaExceptionNoThrow(m_jniErrorMessage); jnipp::LocalRef<String> jURIString = jnipp::String::create(marmottaServerUrl); checkJavaExceptionNoThrow(m_jniErrorMessage); assert((jobject)jURIString != 0); LOG_INFO("Using Marmotta URI: %s", jURIString->std_str().c_str()); jnipp::LocalRef<IDGenerator> gen = IDGeneratorAnno4j::construct(jURIString); checkJavaExceptionNoThrow(m_jniErrorMessage); assert((jobject)gen != 0); LOG_DEBUG("IDGeneratorAnno4j created"); jnipp::LocalRef<SPARQLRepository> sparqlRepository = SPARQLRepository::construct( jnipp::String::create(marmottaServerUrl + std::string("/sparql/select")), jnipp::String::create(marmottaServerUrl + std::string("/sparql/update"))); LOG_DEBUG("SPARQLRepository created"); checkJavaExceptionNoThrow(m_jniErrorMessage); m_anno4j = Anno4j::construct(sparqlRepository, gen); checkJavaExceptionNoThrow(m_jniErrorMessage); LOG_DEBUG("anno4j object created."); } /** * Create a new item with a random URI and return it. The item should be suitable for reading and * updating and write all updates to the underlying low-level persistence layer. * * @return a handle to the newly created Item */ std::shared_ptr<model::Item> PersistenceService::createItem() { bool creation_error = false; jnipp::Env::Scope scope(PersistenceService::m_sJvm); LOG_DEBUG("PersistenceService::createItem()"); assert((jobject) m_anno4j); jnipp::LocalRef<Resource> jItemResource = m_anno4j->getIdGenerator()->generateID(jnipp::java::util::HashSet::construct()); jnipp::LocalRef<Transaction> jTransaction = m_anno4j->createTransaction(); creation_error = creation_error & checkJavaExceptionNoThrow(m_jniErrorMessage); assert((jobject) jTransaction); jTransaction->begin(); jTransaction->setAllContexts((jnipp::Ref<URI>) jItemResource); jnipp::GlobalRef<ItemMMM> jNewItemMMM = jTransaction->createObject(ItemMMM::clazz(),jItemResource); creation_error = creation_error & checkJavaExceptionNoThrow(m_jniErrorMessage); assert((jobject) jNewItemMMM); LOG_DEBUG("ItemMMM created with anno4j"); jnipp::LocalRef<jnipp::String> jDateTime = jnipp::String::create(commons::TimeInfo::getTimestamp()); assert((jobject) jDateTime); jNewItemMMM->setSerializedAt(jDateTime); creation_error = creation_error & checkJavaExceptionNoThrow(m_jniErrorMessage); LOG_DEBUG("date time object create and set"); if (!creation_error) { jTransaction->commit(); LOG_DEBUG("Transaction for ItemMMM commited"); } else { if ((jobject) jTransaction) { jTransaction->rollback(); jTransaction->close(); } } auto newItem = std::make_shared<model::ItemAnno4cpp>(jNewItemMMM, *this); LOG_INFO("ItemMMM created and Item wrapper returned"); return newItem; } /** * Return the item with the given URI if it exists. The item should be suitable for reading and * updating and write all updates to the underlying low-level persistence layer. * * @return A handle to the Item with the given URI, or null if it does not exist */ std::shared_ptr<model::Item> PersistenceService::getItem(const mico::persistence::model::URI& id) { LOG_DEBUG("PersistenceService::getItem for [%s] requested.", id.stringValue().c_str()); jnipp::Env::Scope scope(PersistenceService::m_sJvm); jnipp::LocalRef<URI> jItemURI = URIImpl::construct((jnipp::Ref<String>) jnipp::String::create(id.stringValue())); checkJavaExceptionNoThrow(m_jniErrorMessage); assert((jobject) jItemURI); jnipp::LocalRef<Transaction> jTransaction = m_anno4j->createTransaction(); checkJavaExceptionNoThrow(m_jniErrorMessage); assert((jobject) jTransaction); LOG_DEBUG("PersistenceService::getItem. Setting context [%s] to transaction.", jItemURI->toString()->std_str().c_str()); jTransaction->setAllContexts((jnipp::Ref<URI>) jItemURI); jnipp::GlobalRef<ItemMMM> jItemMMM= jTransaction->findByID(ItemMMM::clazz(), jItemURI); bool isInstance = jItemMMM->isInstanceOf(ItemMMM::clazz()); bool except = checkJavaExceptionNoThrow(m_jniErrorMessage); if (!isInstance || except) { LOG_WARN("PersistenceService::getItem - returned RDF object is NOT an instance of ItemMMM or null"); return std::shared_ptr<model::Item>(); } jnipp::LocalRef<URI> jItemURIRet = ((jnipp::Ref<RDFObject>)jItemMMM)->getResource(); LOG_DEBUG("Got item with URI [%s]", jItemURIRet->toString()->std_str().c_str()); return std::make_shared<model::ItemAnno4cpp>(jItemMMM, *this); } /** * Delete the content item with the given URI. If the content item does not exist, do nothing. */ void PersistenceService::deleteItem(const model::URI& id) { jnipp::Env::Scope scope(PersistenceService::m_sJvm); jnipp::LocalRef<URI> jItemURI = URIImpl::construct((jnipp::Ref<String>) jnipp::String::create(id.stringValue())); checkJavaExceptionNoThrow(m_jniErrorMessage); assert((jobject) jItemURI); m_anno4j->clearContext(jItemURI); LOG_DEBUG("Deleted item with id %s including all triples in the corresponding context graph", id.stringValue().c_str()); } std::vector< std::shared_ptr<model::Item> > PersistenceService::getItems() { std::vector< std::shared_ptr<model::Item> > resultVec; jnipp::Env::Scope scope(PersistenceService::m_sJvm); jnipp::LocalRef<jnipp::java::util::List> jItemsMMM = m_anno4j->findAll(ItemMMM::clazz()); checkJavaExceptionNoThrow(m_jniErrorMessage); assert((jobject) jItemsMMM); jint jNumItems = jItemsMMM->size(); checkJavaExceptionNoThrow(m_jniErrorMessage); LOG_DEBUG("Found %d items.", jNumItems); resultVec.reserve(jNumItems); for (jint idx_item; idx_item < jNumItems; ++idx_item) { jnipp::GlobalRef<ItemMMM> jItemMMM = jItemsMMM->get(idx_item); resultVec.push_back(std::make_shared<model::ItemAnno4cpp>(jItemMMM, *this)); } return resultVec; } // /** // * Return an iterator over all currently available content items. // * // * @return iterable // */ // item_iterator PersistenceService::begin() { // map<string,string> params; // params["g"] = marmottaServerUrl; // const TupleResult* r = metadata.query(SPARQL_FORMAT(listContentItems,params)); // if(r->size() > 0) { // return item_iterator(marmottaServerUrl,contentDirectory,r); // } else { // delete r; // return item_iterator(marmottaServerUrl,contentDirectory); // } // } // item_iterator PersistenceService::end() { // return item_iterator(marmottaServerUrl,contentDirectory); // } // void item_iterator::increment() { // pos = pos+1 == result->size() ? -1 : pos + 1; // }; // bool item_iterator::equal(item_iterator const& other) const { // return this->pos == other.pos; // }; // Item *item_iterator::dereference() const { // return new ContentItem(baseUrl, contentDirectory, *dynamic_cast<const URI*>( result->at(pos).at("p") ) ); // } jnipp::LocalRef<Anno4j> PersistenceService::getAnno4j() { jnipp::Env::Scope scope(m_sJvm); return m_anno4j; } std::string PersistenceService::getContentDirectory() { return contentDirectory; } void PersistenceService::checkJavaExceptionThrow() { jnipp::Env::Scope scope(m_sJvm); jnipputil::checkJavaExceptionThrow(); } void PersistenceService::checkJavaExceptionThrow(std::vector<std::string> exceptionNames) { jnipp::Env::Scope scope(m_sJvm); jnipputil::checkJavaExceptionThrow(exceptionNames); } bool PersistenceService::checkJavaExceptionNoThrow(std::string& msg) { jnipp::Env::Scope scope(m_sJvm); return jnipputil::checkJavaExceptionNoThrow(msg); } bool PersistenceService::checkJavaExceptionNoThrow(std::vector<std::string> exceptionNames, std::string& msg) { jnipp::Env::Scope scope(m_sJvm); return jnipputil::checkJavaExceptionNoThrow(exceptionNames, msg); } void PersistenceService::setContext(jnipp::Ref<ObjectConnection> con, jnipp::Ref<URI> context) { jnipp::Env::Scope scope(PersistenceService::m_sJvm); LOG_DEBUG("Setting context for object connection with object identity hash %d", System::identityHashCode(con)); checkJavaExceptionNoThrow(m_jniErrorMessage); con->setReadContexts(context); con->setInsertContext(context); con->setRemoveContexts(context); } std::string PersistenceService::getStoragePrefix(){ jnipp::Env::Scope scope(PersistenceService::m_sJvm); checkJavaExceptionNoThrow(m_jniErrorMessage); return jnipp::eu::mico::platform::persistence::model::Asset::STORAGE_SERVICE_URN_PREFIX->std_str(); } std::string PersistenceService::unmaskContentLocation(const std::string &maskedURL){ std::string urn_prefix=getStoragePrefix(); if (maskedURL.compare(0, urn_prefix.length(), urn_prefix) == 0) { return getContentDirectory() + std::string("/") + maskedURL.substr(urn_prefix.length()); } return maskedURL; } } }
36.343964
137
0.62482
AudiovisualMetadataPlatform
6f8cd43d044cfbac72e83f9a89554c2eea13fff7
2,409
hpp
C++
libs/core/include/fcppt/math/matrix/detail/determinant.hpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
libs/core/include/fcppt/math/matrix/detail/determinant.hpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
libs/core/include/fcppt/math/matrix/detail/determinant.hpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
// Copyright Carl Philipp Reh 2009 - 2018. // 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 FCPPT_MATH_MATRIX_DETAIL_DETERMINANT_HPP_INCLUDED #define FCPPT_MATH_MATRIX_DETAIL_DETERMINANT_HPP_INCLUDED #include <fcppt/literal.hpp> #include <fcppt/tag_type.hpp> #include <fcppt/use.hpp> #include <fcppt/algorithm/fold.hpp> #include <fcppt/math/int_range_count.hpp> #include <fcppt/math/size_type.hpp> #include <fcppt/math/matrix/at_r_c.hpp> #include <fcppt/math/matrix/delete_row_and_column.hpp> #include <fcppt/math/matrix/has_dim.hpp> #include <fcppt/math/matrix/index.hpp> #include <fcppt/math/matrix/object_impl.hpp> #include <fcppt/math/matrix/static.hpp> namespace fcppt { namespace math { namespace matrix { namespace detail { template< typename T, typename S > T determinant( fcppt::math::matrix::object< T, 1, 1, S > const &_matrix ) { return fcppt::math::matrix::at_r_c< 0, 0 >( _matrix ); } template< typename T, fcppt::math::size_type N, typename S > std::enable_if_t< !fcppt::math::matrix::has_dim< fcppt::math::matrix::object< T, N, N, S >, 1, 1 >::value, T > determinant( fcppt::math::matrix::object< T, N, N, S > const &_matrix ) { return fcppt::algorithm::fold( fcppt::math::int_range_count< N >{}, fcppt::literal< T >( 0 ), [ &_matrix ]( auto const _row, T const _sum ) { FCPPT_USE( _row ); typedef fcppt::tag_type< decltype( _row ) > row; T const coeff{ row::value % fcppt::literal< fcppt::math::size_type >( 2 ) == fcppt::literal< fcppt::math::size_type >( 0 ) ? fcppt::literal< T >( 1 ) : fcppt::literal< T >( -1 ) }; constexpr fcppt::math::size_type const column{ 0u }; return _sum + coeff * fcppt::math::matrix::at_r_c< row::value, column >( _matrix ) * fcppt::math::matrix::detail::determinant( fcppt::math::matrix::delete_row_and_column< row::value, column >( _matrix ) ); } ); } } } } } #endif
13.844828
61
0.576588
pmiddend
6f8d7eae3e515934fa4bd754d6f749babaaa2380
46
hpp
C++
src/boost_log_utility_manipulators.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_log_utility_manipulators.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_log_utility_manipulators.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/log/utility/manipulators.hpp>
23
45
0.804348
miathedev
6f8ecb75e93f4737e55b506c0d42046a0034f092
13,172
cpp
C++
src/core/type/typemanager.cpp
eXl-Nic/eXl
a5a0f77f47db3179365c107a184bb38b80280279
[ "MIT" ]
null
null
null
src/core/type/typemanager.cpp
eXl-Nic/eXl
a5a0f77f47db3179365c107a184bb38b80280279
[ "MIT" ]
null
null
null
src/core/type/typemanager.cpp
eXl-Nic/eXl
a5a0f77f47db3179365c107a184bb38b80280279
[ "MIT" ]
null
null
null
/* Copyright 2009-2021 Nicolas Colombe Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <core/type/typemanager.hpp> #include <core/type/tupletypestruct.hpp> #include <core/type/enumtype.hpp> #include <core/type/arraytype.hpp> #include <core/type/objectptrtype.hpp> #include <core/type/classtyperttiobject.hpp> #include <boost/lexical_cast.hpp> #include <boost/multi_index_container.hpp> #include <boost/multi_index/ordered_index.hpp> #include <boost/multi_index/member.hpp> #include <boost/multi_index/identity.hpp> #include <core/log.hpp> namespace eXl { namespace TypeManager { namespace detail { struct TypeCmpName { typedef TypeName const result_type; const TypeName operator()(const Type* iType) const { return iType->GetName(); } }; struct TypeCmpID { typedef size_t result_type; size_t operator()(TupleType* iType) const { return iType->GetTypeId(); } }; typedef boost::multi_index::multi_index_container<Type*, boost::multi_index::indexed_by< //boost::multi_index::ordered_unique<TypeCmpID>, boost::multi_index::ordered_unique<TypeCmpName>, boost::multi_index::ordered_unique<boost::multi_index::identity<Type*> > > >TypeMap; //typedef TypeMap::nth_index<0>::type TypeMap_by_ID; typedef TypeMap::nth_index<0>::type TypeMap_by_Name; typedef TypeMap::nth_index<1>::type TypeMap_by_Type; //typedef std::pair<const TupleType*,const TupleType*> ViewKey; typedef UnorderedMap<Type const*, ArrayType const*> ArrayCacheMap; typedef UnorderedMap<std::pair<Type const*, uint32_t>, ArrayType const*> SmallArrayCacheMap; struct ClassTypeEntry { Rtti const* rtti; ClassType const* classType; void SetPtrType(ObjectPtrType const* iType) { classPtrType = iType; } ObjectPtrType const* GetPtrType() const { return ((flags & 1) == 0) ? classPtrType : nullptr; } void SetHandleType(ResourceHandleType const* iType) { resHandleType = iType; flags |= 1; } ResourceHandleType const* GetHandleType() const { return ((flags & 1) == 1) ? (ResourceHandleType const*)(*((size_t*)&resHandleType) & ~1) : nullptr; } union { unsigned int flags; ObjectPtrType const* classPtrType; ResourceHandleType const* resHandleType; }; }; struct ClassCmpRtti { typedef Rtti const* result_type; result_type operator()(ClassTypeEntry const& iEntry) const { return iEntry.rtti; } }; struct ClassCmpParentRtti { typedef Rtti const* result_type; result_type operator()(ClassTypeEntry const& iEntry) const { return iEntry.rtti->GetFather(); } }; struct ClassCmpName { typedef KString const& result_type; result_type operator()(ClassTypeEntry const& iEntry) const { return iEntry.rtti->GetName(); } }; typedef boost::multi_index::multi_index_container<ClassTypeEntry, boost::multi_index::indexed_by< boost::multi_index::ordered_unique<ClassCmpRtti> ,boost::multi_index::ordered_non_unique<ClassCmpParentRtti> ,boost::multi_index::ordered_unique<ClassCmpName> > > ClassMap; typedef ClassMap::nth_index<0>::type ClassMap_by_Rtti; typedef ClassMap::nth_index<1>::type ClassMap_by_ParentRtti; typedef ClassMap::nth_index<2>::type ClassMap_by_Name; static const size_t UsrTypeFlag = size_t(1)<<(sizeof(size_t)*8-1); } struct TMData { detail::TypeMap m_TypeMap; detail::ArrayCacheMap m_ArrayMap; detail::SmallArrayCacheMap m_SmallArrayMap; detail::ClassMap m_ClassMap; void Clear() { m_TypeMap.clear(); for (auto Type : m_ArrayMap) { eXl_DELETE Type.second; } m_ArrayMap.clear(); m_ClassMap.clear(); } static TMData& Get() { static TMData s_Data; return s_Data; } }; UsrTypeReg BeginTypeRegistration(TypeName iName) { return UsrTypeReg(iName); } UsrTypeReg::UsrTypeReg(TypeName iName) : m_Name(iName) , m_Offset(0) { } UsrTypeReg& UsrTypeReg::AddField(TypeFieldName iName,Type const* iType) { if(iType!=nullptr) { List<FieldDesc>::iterator iter = m_Fields.begin(); List<FieldDesc>::iterator iterEnd = m_Fields.end(); for(;iter!=iterEnd;iter++) { if(iName==iter->GetName()) { eXl_ASSERT_MSG(iType == iter->GetType(),"Inconsistant"); return *this; } } m_Fields.push_back(FieldDesc(iName,m_Offset,iType)); m_Offset+=iType->GetSize(); } return *this; } UsrTypeReg& UsrTypeReg::AddFieldsFrom(const TupleType* iType) { if(iType==nullptr) return *this; unsigned int numFields = iType->GetNumField(); for(unsigned int i=0;i<numFields;i++) { bool nextField = false; TypeFieldName name; const Type* type = iType->GetFieldDetails(i,name); List<FieldDesc>::iterator iter = m_Fields.begin(); List<FieldDesc>::iterator iterEnd = m_Fields.end(); for(;iter!=iterEnd;iter++) { if(name==iter->GetName()) { nextField=true; break; } } if(nextField) continue; m_Fields.push_back(FieldDesc(name,m_Offset,type)); m_Offset+=iType->GetSize(); } return *this; } const TupleType* UsrTypeReg::EndRegistration() { return MakeTuple(m_Name,m_Fields,nullptr); } const TupleType* MakeTuple(TypeName iName,const List<FieldDesc>& iList,size_t* iId) { if(!iList.empty()) { size_t newId = iId==nullptr ? detail::UsrTypeFlag : *iId; TupleType* newType = TupleTypeStruct::MakeTuple(iName,iList,newId); List<FieldDesc>::const_iterator iter = iList.begin(); List<FieldDesc>::const_iterator iterEnd = iList.end(); return newType; } return nullptr; } const Type* RegisterType(Type const* iType) { if(iType == nullptr) return nullptr; eXl_ASSERT_REPAIR_RET(iType->IsCoreType() || iType->IsEnum(), nullptr); detail::TypeMap_by_Type::iterator iter = TMData::Get().m_TypeMap.get<1>().find(const_cast<Type*>(iType)); eXl_ASSERT_MSG(iter == TMData::Get().m_TypeMap.get<1>().end(),"Already registered"); if(iter!=TMData::Get().m_TypeMap.get<1>().end()) { LOG_WARNING<<"Type "<<iType->GetName()<<"already registered"<<"\n"; return *iter; } TMData::Get().m_TypeMap.insert(const_cast<Type*>(iType)); return iType; } const Type* GetCoreTypeFromName(TypeName iName) { auto const& typeMapByName = TMData::Get().m_TypeMap.get<0>(); auto iter = typeMapByName.find(iName); if (iter != typeMapByName.end()) { return *iter; } return nullptr; } Vector<Type const*> GetCoreTypes() { Vector<Type const*> coreTypes; for (auto const& entry : TMData::Get().m_TypeMap) { if (entry->IsCoreType()) { coreTypes.push_back(entry); } } return coreTypes; } TypeManager::EnumTypeReg::EnumTypeReg(TypeName iName) : m_Name(iName) { } TypeManager::EnumTypeReg& TypeManager::EnumTypeReg::AddValue(TypeEnumName iName) { for(unsigned int i = 0;i<m_Enums.size();++i) { if(m_Enums[i] == iName) { LOG_WARNING<<"Enum "<<iName<<" already exists"<<"\n"; return *this; } } m_Enums.push_back(iName); return *this; } namespace detail { EnumType const* _MakeEnumType(TypeName iName, Vector<TypeEnumName> & iVal) { //size_t newId = ++TMData::Get().m_IDGen; EnumType* newType = eXl_NEW EnumType(iName,0); newType->m_Enums.swap(iVal); Type const* res = TypeManager::RegisterType(newType); if(res == nullptr) { //TMData::Get().m_IDGen--; eXl_DELETE newType; return nullptr; } return newType; } } Type const* EnumTypeReg::EndRegistration() { if(m_Name != "" && m_Enums.size() > 0) { return detail::_MakeEnumType(m_Name,m_Enums); }else { LOG_WARNING<<"Invalid Enum definition"<<"\n"; return nullptr; } } EnumTypeReg BeginEnumTypeRegistration(TypeName iName) { return EnumTypeReg(iName); } ArrayType const* GetArrayType(Type const* iType) { if(iType != nullptr) { detail::ArrayCacheMap::iterator iter = TMData::Get().m_ArrayMap.find(iType); if(iter == TMData::Get().m_ArrayMap.end()) { return nullptr; } else { return iter->second; } } return nullptr; } void RegisterArrayType(ArrayType const* iType) { if (iType != nullptr) { eXl_ASSERT_REPAIR_RET(iType->IsCoreType(), ); detail::ArrayCacheMap::iterator iter = TMData::Get().m_ArrayMap.find(iType); if (iter == TMData::Get().m_ArrayMap.end()) { TMData::Get().m_ArrayMap.insert(std::make_pair(iType->GetElementType(), iType)); } } } ArrayType const* GetSmallArrayType(Type const* iType, uint32_t iBufferSize) { if (iType != nullptr) { detail::SmallArrayCacheMap::iterator iter = TMData::Get().m_SmallArrayMap.find(std::make_pair(iType, iBufferSize)); if (iter == TMData::Get().m_SmallArrayMap.end()) { return nullptr; } else { return iter->second; } } return nullptr; } void RegisterSmallArrayType(ArrayType const* iType, uint32_t iBufferSize) { if (iType != nullptr) { eXl_ASSERT_REPAIR_RET(iType->IsCoreType(), ); auto key = std::make_pair(iType->GetElementType(), iBufferSize); detail::SmallArrayCacheMap::iterator iter = TMData::Get().m_SmallArrayMap.find(key); if (iter == TMData::Get().m_SmallArrayMap.end()) { TMData::Get().m_SmallArrayMap.insert(std::make_pair(key, iType)); } } } Err ListDerivedClassesForRtti(Rtti const& iRtti, List<Rtti const*>& oList) { oList.clear(); List<Rtti const*> tempList; List<Rtti const*> tempList2; tempList.push_back(&iRtti); while(!tempList.empty()) { List<Rtti const*>::iterator iter = tempList.begin(); List<Rtti const*>::iterator iterEnd = tempList.end(); for(; iter != iterEnd; ++iter) { std::pair<detail::ClassMap_by_ParentRtti::iterator, detail::ClassMap_by_ParentRtti::iterator> iterRange = TMData::Get().m_ClassMap.get<1>().equal_range(*iter); detail::ClassMap_by_ParentRtti::iterator iterEntry = iterRange.first; for(; iterEntry != iterRange.second; ++iterEntry) { tempList2.push_back(iterEntry->rtti); oList.push_back(iterEntry->rtti); } } tempList.clear(); tempList.swap(tempList2); } RETURN_SUCCESS; } ResourceHandleType const* GetResourceHandleForRtti(Rtti const& iRtti) { detail::ClassMap_by_Rtti::iterator iter = TMData::Get().m_ClassMap.get<0>().find(&iRtti); if(iter != TMData::Get().m_ClassMap.get<0>().end()) { return iter->GetHandleType(); } return nullptr; } namespace detail { void _TMClear() { TMData::Get().Clear(); } } } }
29.077263
460
0.601124
eXl-Nic
6f91fe545d655a91ce5e6bbcaaff9de6252f4ed0
9,157
hpp
C++
tau/TauUtils/include/TUMaths.hpp
hyfloac/TauEngine
1559b2a6e6d1887b8ee02932fe0aa6e5b9d5652c
[ "MIT" ]
1
2020-04-22T04:07:01.000Z
2020-04-22T04:07:01.000Z
tau/TauUtils/include/TUMaths.hpp
hyfloac/TauEngine
1559b2a6e6d1887b8ee02932fe0aa6e5b9d5652c
[ "MIT" ]
null
null
null
tau/TauUtils/include/TUMaths.hpp
hyfloac/TauEngine
1559b2a6e6d1887b8ee02932fe0aa6e5b9d5652c
[ "MIT" ]
null
null
null
// ReSharper disable CppClangTidyClangDiagnosticSignCompare #pragma once #include "NumTypes.hpp" /** * Equal to pi/180. */ #define RADIANS_TO_DEGREES_CONVERTER_VAL 57.29577951308232087679815481410517 /** * Equal to 180/pi */ #define DEGREES_TO_RADIANS_CONVERTER_VAL 0.017453292519943295769236907684886 /** * Converts radians to degrees (single precision). */ #define RAD_2_DEG_F(__F) (float) ((__F) * RADIANS_TO_DEGREES_CONVERTER_VAL) /** * Converts degrees to radians (single precision). */ #define DEG_2_RAD_F(__F) (float) ((__F) * DEGREES_TO_RADIANS_CONVERTER_VAL) /** * Converts radians to degrees (double precision). */ #define RAD_2_DEG_D(__D) (double) ((__D) * RADIANS_TO_DEGREES_CONVERTER_VAL) /** * Converts degrees to radians (double precision). */ #define DEG_2_RAD_D(__D) (double) ((__D) * DEGREES_TO_RADIANS_CONVERTER_VAL) #define RAD_2_DEG(__F) RAD_2_DEG_F(__F) #define DEG_2_RAD(__F) DEG_2_RAD_F(__F) template<typename _T> [[nodiscard]] inline constexpr _T minT(const _T a, const _T b) noexcept { return a < b ? a : b; } template<typename _T> [[nodiscard]] inline constexpr _T minT(const _T a, const _T b, const _T c) noexcept { return minT(minT(a, b), c); } template<typename _T> [[nodiscard]] inline constexpr _T minT(const _T a, const _T b, const _T c, const _T d) noexcept { return minT(minT(a, b), minT(c, d)); } template<typename _T> [[nodiscard]] inline constexpr _T maxT(const _T a, const _T b) noexcept { return a > b ? a : b; } template<typename _T> [[nodiscard]] inline constexpr _T maxT(const _T a, const _T b, const _T c) noexcept { return maxT(maxT(a, b), c); } template<typename _T> [[nodiscard]] inline constexpr _T maxT(const _T a, const _T b, const _T c, const _T d) noexcept { return maxT(maxT(a, b), maxT(c, d)); } template<typename _T0, typename _T1> [[nodiscard]] inline constexpr _T0 minT(const _T0 a, const _T1 b) noexcept { return a < b ? a : b; } template<typename _T0, typename _T1, typename _T2> [[nodiscard]] inline constexpr _T0 minT(const _T0 a, const _T1 b, const _T2 c) noexcept { return minT(minT(a, b), c); } template<typename _T0, typename _T1, typename _T2, typename _T3> [[nodiscard]] inline constexpr _T0 minT(const _T0 a, const _T1 b, const _T2 c, const _T3 d) noexcept { return minT(minT(a, b), minT(c, d)); } template<typename _T0, typename _T1> [[nodiscard]] inline constexpr _T0 maxT(const _T0 a, const _T1 b) noexcept { return a > b ? a : b; } template<typename _T0, typename _T1, typename _T2> [[nodiscard]] inline constexpr _T0 maxT(const _T0 a, const _T1 b, const _T2 c) noexcept { return maxT(maxT(a, b), c); } template<typename _T0, typename _T1, typename _T2, typename _T3> [[nodiscard]] inline constexpr _T0 maxT(const _T0 a, const _T1 b, const _T2 c, const _T3 d) noexcept { return maxT(maxT(a, b), maxT(c, d)); } /** * Relative epsilon equals function. */ template<typename _T> static inline bool rEpsilonEquals(const _T x, const _T y, const _T epsilon = 1E-5) { const _T epsilonRelative = maxT(fabs(x), fabs(y)) * epsilon; return fabs(x - y) <= epsilonRelative; } /** * Absolute epsilon equals function. */ template<typename _T> static inline bool aEpsilonEquals(const _T x, const _T y, const _T epsilon = 1E-5) { return fabs(x - y) <= epsilon; } const u32 clzTab32[32] = { 0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30, 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31 }; const u32 clzTab64[64] = { 63, 0, 58, 1, 59, 47, 53, 2, 60, 39, 48, 27, 54, 33, 42, 3, 61, 51, 37, 40, 49, 18, 28, 20, 55, 30, 34, 11, 43, 14, 22, 4, 62, 57, 46, 52, 38, 26, 32, 41, 50, 36, 17, 19, 29, 10, 13, 21, 56, 45, 25, 31, 35, 16, 9, 12, 44, 24, 15, 8, 23, 7, 6, 5 }; const u32 ctzTab32[32] = { 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9 }; const u32 ctzTab64[64] = { 0, 47, 1, 56, 48, 27, 2, 60, 57, 49, 41, 37, 28, 16, 3, 61, 54, 58, 35, 52, 50, 42, 21, 44, 38, 32, 29, 23, 17, 11, 4, 62, 46, 55, 26, 59, 40, 36, 15, 53, 34, 51, 20, 43, 31, 22, 10, 45, 25, 39, 14, 33, 19, 30, 9, 24, 13, 18, 8, 12, 7, 6, 5, 63 }; template<typename _T> [[nodiscard]] constexpr inline _T _alignTo(const _T val, const _T alignment) noexcept { if(alignment == 1) { return val; } return (val + alignment) & ~(alignment - 1); } template<typename _Tv, typename _Ta> [[nodiscard]] constexpr inline _Tv _alignTo(const _Tv val, const _Ta _alignment) noexcept { const _Tv alignment = static_cast<_Tv>(_alignment); if(alignment == 1) { return val; } return (val + alignment) & ~(alignment - 1); } template<typename _T, _T _Alignment> [[nodiscard]] constexpr inline _T _alignTo(const _T val) noexcept { if(_Alignment == 1) { return val; } return (val + _Alignment) & ~(_Alignment - 1); } template<typename _Tv, typename _Ta, _Ta _Alignment> [[nodiscard]] constexpr inline _Tv _alignTo(const _Tv val) noexcept { constexpr _Tv alignment = static_cast<_Tv>(_Alignment); if(alignment == 1) { return val; } return (val + alignment) & ~(alignment - 1); } #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN #define NOMINMAX #include <Windows.h> [[nodiscard]] inline u32 _ctz(const u32 v) noexcept { unsigned long trailingZero = 0; _BitScanForward(&trailingZero, v); return trailingZero; } [[nodiscard]] inline u32 _clz(const u32 v) noexcept { unsigned long leadingZero = 0; _BitScanReverse(&leadingZero, v); return 31 - leadingZero; } [[nodiscard]] inline u64 _ctz(const u64 v) noexcept { unsigned long trailingZero = 0; _BitScanForward64(&trailingZero, v); return trailingZero; } [[nodiscard]] inline u64 _clz(const u64 v) noexcept { unsigned long leadingZero = 0; _BitScanReverse64(&leadingZero, v); return 63 - leadingZero; } [[nodiscard]] constexpr inline u32 _ctzC(const u32 v) noexcept { return ctzTab32[((v ^ (v - 1)) * 0x077CB531u) >> 27]; } [[nodiscard]] constexpr inline u32 _clzC(u32 v) noexcept { v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; return 63 - clzTab32[((v * 0x07C4ACDDu)) >> 27]; } [[nodiscard]] constexpr inline u32 _ctzC(const u64 v) noexcept { return ctzTab64[((v ^ (v - 1)) * 0x03F79D71B4CB0A89u) >> 58]; } [[nodiscard]] constexpr inline u32 _clzC(u64 v) noexcept { v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v |= v >> 32; return 63 - clzTab64[((v - (v >> 1)) * 0x07EDD5E59A4E28C2ull) >> 58]; } #else [[nodiscard]] inline u32 _ctz(const u32 v) noexcept { return __builtin_ctz(v); } [[nodiscard]] inline u32 _clz(const u32 v) noexcept { return __builtin_clz(v); } [[nodiscard]] inline u32 _ctz(const u64 v) noexcept { return __builtin_ctzll(v); } [[nodiscard]] inline u32 _clz(const u64 v) noexcept { return __builtin_clzll(v); } [[nodiscard]] constexpr inline u32 _ctzC(const u32 v) noexcept { return __builtin_ctz(v); } [[nodiscard]] constexpr inline u32 _clzC(const u32 v) noexcept { return __builtin_clz(v); } [[nodiscard]] constexpr inline u32 _ctzC(const u64 v) noexcept { return __builtin_ctzll(v); } [[nodiscard]] constexpr inline u32 _clzC(const u64 v) noexcept { return __builtin_clzll(v); } #endif #if defined(TAU_CROSS_PLATFORM) [[nodiscard]] constexpr inline u32 nextPowerOf2(u32 v) noexcept { --v; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; return v + 1; } [[nodiscard]] constexpr inline u64 nextPowerOf2(u64 v) noexcept { --v; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v |= v >> 32; return v + 1; } [[nodiscard]] constexpr inline u32 log2i(u32 value) noexcept { value |= value >> 1; value |= value >> 2; value |= value >> 4; value |= value >> 8; value |= value >> 16; return clzTab32[((value * 0x07C4ACDDu)) >> 27]; } [[nodiscard]] constexpr inline u32 log2i(u64 value) noexcept { value |= value >> 1; value |= value >> 2; value |= value >> 4; value |= value >> 8; value |= value >> 16; value |= value >> 32; return clzTab64[((value - (value >> 1)) * 0x07EDD5E59A4E28C2ull) >> 58]; } #else [[nodiscard]] constexpr inline u32 nextPowerOf2(const u32 v) noexcept { if(v == 1) { return 1; } return 1u << (32u - _clzC(v - 1u)); } [[nodiscard]] constexpr inline u64 nextPowerOf2(const u64 v) noexcept { if(v == 1) { return 1; } return 1ull << (64ull - _clzC(v - 1ull)); } [[nodiscard]] constexpr inline u32 log2i(const u32 v) noexcept { return 63 - _clzC(v); } [[nodiscard]] constexpr inline u32 log2i(const u64 v) noexcept { return 63 - _clzC(v); } #endif
28.262346
101
0.611663
hyfloac
6f934bf0f862e239e196e4ed20105ed5bcadbaf7
4,638
cpp
C++
paxos++/detail/tcp_connection.cpp
armos-db/libpaxos-cpp
31e8a3f9664e3e6563d26dbc1323457f596b8eef
[ "BSD-3-Clause" ]
54
2015-02-09T11:46:30.000Z
2021-08-13T14:08:52.000Z
paxos++/detail/tcp_connection.cpp
armos-db/libpaxos-cpp
31e8a3f9664e3e6563d26dbc1323457f596b8eef
[ "BSD-3-Clause" ]
null
null
null
paxos++/detail/tcp_connection.cpp
armos-db/libpaxos-cpp
31e8a3f9664e3e6563d26dbc1323457f596b8eef
[ "BSD-3-Clause" ]
17
2015-01-13T03:18:49.000Z
2022-03-23T02:20:57.000Z
#include <iostream> #include <functional> #include <assert.h> #include <boost/asio/write.hpp> #include <boost/asio/placeholders.hpp> #include "util/debug.hpp" #include "parser.hpp" #include "command_dispatcher.hpp" #include "tcp_connection.hpp" namespace paxos { namespace detail { tcp_connection::tcp_connection ( boost::asio::io_service & io_service) : socket_ (io_service) { } tcp_connection::~tcp_connection () { PAXOS_DEBUG ("destructing connection " << this); } /*! static */ tcp_connection_ptr tcp_connection::create ( boost::asio::io_service & io_service) { return tcp_connection_ptr ( new tcp_connection (io_service)); } void tcp_connection::close () { socket_.close (); } bool tcp_connection::is_open () const { return socket_.is_open (); } boost::asio::ip::tcp::socket & tcp_connection::socket () { return socket_; } void tcp_connection::write_command ( detail::command const & command) { parser::write_command (shared_from_this (), command); } void tcp_connection::read_command ( read_callback callback) { parser::read_command (shared_from_this (), callback); } void tcp_connection::read_command_loop ( read_callback callback) { read_command ( [this, callback] (boost::optional <enum error_code> error, command const & command) { callback (error, command); if (!error) { this->read_command_loop (callback); } }); } void tcp_connection::write ( std::string const & message) { boost::mutex::scoped_lock lock (mutex_); write_locked (message); } void tcp_connection::write_locked ( std::string const & message) { /*! The problem with Boost.Asio is that it assumes that the buffer we send to async_write () must stay alive until the callback to handle_write () has been called. Since there is no way we can guarantee that if we use the message object we get as a reference to this function, we have no alternative but to copy the data into our local buffer. But wait! What happends when write() is called when we are not yet done writing another block? In that case, we will just append that data onto the queue. The handle_write () function checks whether any data is still pending on the queue, and if so, ensures another async_write () is called. */ if (write_buffer_.empty () == true) { write_buffer_ = message; start_write_locked (); } else { write_buffer_ += message; } } void tcp_connection::start_write_locked () { PAXOS_ASSERT (write_buffer_.empty () == false); boost::asio::async_write (socket_, boost::asio::buffer (write_buffer_), std::bind (&tcp_connection::handle_write, /*! Using shared_from_this here instead of this ensures that we obtain a shared pointer to ourselves, and so when our object would go out of scope normally, it at least stays alive until this callback is called. */ shared_from_this(), std::placeholders::_1, std::placeholders::_2)); } void tcp_connection::handle_write ( boost::system::error_code const & error, size_t bytes_transferred) { if (error) { PAXOS_WARN ("an error occured while writing data: " << error.message ()); return; } boost::mutex::scoped_lock lock (mutex_); handle_write_locked (bytes_transferred); } void tcp_connection::handle_write_locked ( size_t bytes_transferred) { PAXOS_ASSERT (write_buffer_.size () >= bytes_transferred); write_buffer_ = write_buffer_.substr (bytes_transferred); /*! As discussed in the write () function, if we still have data on the buffer, ensure that data is also written. */ if (write_buffer_.empty () == false) { start_write_locked (); } } }; };
24.670213
102
0.55994
armos-db
6f958355910429a3c5ab6590c7d0f0d3ba96cfa4
276
hpp
C++
src/color.hpp
adamhutchings/chirpc
70d190fa79fa9f968b8de14ca41a8f50bae0019b
[ "MIT" ]
1
2021-06-02T13:24:13.000Z
2021-06-02T13:24:13.000Z
src/color.hpp
dekrain/chirpc
93a6230da746d1e6e16230d79b151dee0d3f4a09
[ "MIT" ]
null
null
null
src/color.hpp
dekrain/chirpc
93a6230da746d1e6e16230d79b151dee0d3f4a09
[ "MIT" ]
null
null
null
/* Command-Line coloring, currently works only on linux VT100-based terminals.. This should be overhaul, rn this is very hacky. */ #pragma once #include <iostream> enum class color { red, blue, green, yellow, }; std::string write_color(std::string, color);
16.235294
77
0.692029
adamhutchings
6f9821aac5c9809f3b37c5ad13ae5ed5bacf5b2d
529
cpp
C++
C++/product-of-the-last-k-numbers.cpp
jaiskid/LeetCode-Solutions
a8075fd69087c5463f02d74e6cea2488fdd4efd1
[ "MIT" ]
3,269
2018-10-12T01:29:40.000Z
2022-03-31T17:58:41.000Z
C++/product-of-the-last-k-numbers.cpp
jaiskid/LeetCode-Solutions
a8075fd69087c5463f02d74e6cea2488fdd4efd1
[ "MIT" ]
53
2018-12-16T22:54:20.000Z
2022-02-25T08:31:20.000Z
C++/product-of-the-last-k-numbers.cpp
jaiskid/LeetCode-Solutions
a8075fd69087c5463f02d74e6cea2488fdd4efd1
[ "MIT" ]
1,236
2018-10-12T02:51:40.000Z
2022-03-30T13:30:37.000Z
// Time: ctor: O(1) // add : O(1) // get : O(1) // Space: O(n) class ProductOfNumbers { public: ProductOfNumbers() : accu_(1, 1) { } void add(int num) { if (!num) { accu_ = {1}; return; } accu_.emplace_back(accu_.back() * num); } int getProduct(int k) { if (accu_.size() <= k) { return 0; } return accu_.back() / accu_[accu_.size() - 1 - k]; } private: vector<int> accu_; };
17.064516
58
0.42344
jaiskid
6f9c7fe902da0dc2f08f7ff3983c543facfc4bd9
1,482
hpp
C++
lib/include/hwloc/hwloc_memory_info_extractor.hpp
harryherold/sysmap
293e5f0dc22ed709c8fd5c170662e433c039eeab
[ "BSD-3-Clause" ]
1
2020-05-08T13:55:31.000Z
2020-05-08T13:55:31.000Z
lib/include/hwloc/hwloc_memory_info_extractor.hpp
harryherold/sysmap
293e5f0dc22ed709c8fd5c170662e433c039eeab
[ "BSD-3-Clause" ]
3
2020-01-16T10:30:28.000Z
2020-01-27T11:23:49.000Z
lib/include/hwloc/hwloc_memory_info_extractor.hpp
harryherold/sysmap
293e5f0dc22ed709c8fd5c170662e433c039eeab
[ "BSD-3-Clause" ]
1
2020-01-16T09:08:14.000Z
2020-01-16T09:08:14.000Z
#ifndef __SYSMAP_HWLOC_MEMORY_INFO_EXTRACTOR_HPP__ #define __SYSMAP_HWLOC_MEMORY_INFO_EXTRACTOR_HPP__ #include "../extractors/memory_info_extractor.hpp" extern "C"{ #include <hwloc.h> } namespace sysmap { namespace hwloc { /** *@class Hwloc_Memory_Info_Extractor */ struct Hwloc_Memory_Info_Extractor : extractor::Memory_Info_Extractor { static std::unique_ptr<Extractor> create() { return std::make_unique<Hwloc_Memory_Info_Extractor>(); } /** * Constructor * Initializes, sets flags and loads hwloc topology */ Hwloc_Memory_Info_Extractor(); /** * Virtual Destructor * Destroys hwloc topology */ virtual ~Hwloc_Memory_Info_Extractor(); protected: /** * Calls methods to collect information about Memory. * Overrides virtual function from the base class */ virtual data collect() override; hwloc_topology_t topology; private: static Registrar registrar; /** * Creates hwloc_obj_t and returns Memory information into the structure "result" * @param result Reference to data object, gets filled with information */ void collect_memory_info(data& result); }; }} /* closing namespace sysmap::hwloc */ #endif /* __SYSMAP_HWLOC_MEMORY_INFO_EXTRACTOR_HPP__ */
26.945455
110
0.618758
harryherold
6f9ec2aa436144b454448ab7ed43166d4df05571
2,337
cpp
C++
mptrack/MoveFXSlotDialog.cpp
ford442/openmpt
614c44fe665b0e1cce15092ecf0d069cbb3e1fe7
[ "BSD-3-Clause" ]
335
2017-02-25T16:39:27.000Z
2022-03-29T17:45:42.000Z
mptrack/MoveFXSlotDialog.cpp
ford442/openmpt
614c44fe665b0e1cce15092ecf0d069cbb3e1fe7
[ "BSD-3-Clause" ]
7
2018-02-05T18:22:38.000Z
2022-02-15T19:35:24.000Z
mptrack/MoveFXSlotDialog.cpp
ford442/openmpt
614c44fe665b0e1cce15092ecf0d069cbb3e1fe7
[ "BSD-3-Clause" ]
69
2017-04-10T00:48:09.000Z
2022-03-20T10:24:45.000Z
/* * MoveFXSlotDialog.h * ------------------ * Purpose: Implementationof OpenMPT's move plugin dialog. * Notes : (currently none) * Authors: OpenMPT Devs * The OpenMPT source code is released under the BSD license. Read LICENSE for more details. */ #include "stdafx.h" #include "Mptrack.h" #include "MoveFXSlotDialog.h" OPENMPT_NAMESPACE_BEGIN void CMoveFXSlotDialog::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_COMBO1, m_CbnEmptySlots); } CMoveFXSlotDialog::CMoveFXSlotDialog(CWnd *pParent, PLUGINDEX currentSlot, const std::vector<PLUGINDEX> &emptySlots, PLUGINDEX defaultIndex, bool clone, bool hasChain) : CDialog(CMoveFXSlotDialog::IDD, pParent), m_EmptySlots(emptySlots), m_nDefaultSlot(defaultIndex), moveChain(hasChain) { if(clone) { m_csPrompt.Format(_T("Clone plugin in slot %d to the following empty slot:"), currentSlot + 1); m_csTitle = _T("Clone To Slot..."); m_csChain = _T("&Clone follow-up plugin chain if possible"); } else { m_csPrompt.Format(_T("Move plugin in slot %d to the following empty slot:"), currentSlot + 1); m_csTitle = _T("Move To Slot..."); m_csChain = _T("&Move follow-up plugin chain if possible"); } } BOOL CMoveFXSlotDialog::OnInitDialog() { CDialog::OnInitDialog(); SetDlgItemText(IDC_STATIC1, m_csPrompt); SetDlgItemText(IDC_CHECK1, m_csChain); SetWindowText(m_csTitle); if(m_EmptySlots.empty()) { Reporting::Error("No empty plugin slots are availabe."); OnCancel(); return TRUE; } CString slotText; std::size_t defaultSlot = 0; bool foundDefault = false; for(size_t nSlot = 0; nSlot < m_EmptySlots.size(); nSlot++) { slotText.Format(_T("FX%d"), m_EmptySlots[nSlot] + 1); m_CbnEmptySlots.SetItemData(m_CbnEmptySlots.AddString(slotText), nSlot); if(m_EmptySlots[nSlot] >= m_nDefaultSlot && !foundDefault) { defaultSlot = nSlot; foundDefault = true; } } m_CbnEmptySlots.SetCurSel(static_cast<int>(defaultSlot)); GetDlgItem(IDC_CHECK1)->EnableWindow(moveChain ? TRUE : FALSE); CheckDlgButton(IDC_CHECK1, moveChain ? BST_CHECKED : BST_UNCHECKED); return TRUE; } void CMoveFXSlotDialog::OnOK() { m_nToSlot = m_CbnEmptySlots.GetItemData(m_CbnEmptySlots.GetCurSel()); moveChain = IsDlgButtonChecked(IDC_CHECK1) != BST_UNCHECKED; CDialog::OnOK(); } OPENMPT_NAMESPACE_END
25.681319
169
0.733847
ford442
6f9ffdbb067904197270bf9e6c4198a18f56a85e
493
cpp
C++
debugpoint.cpp
gberthou/PeacefulWorld
50c32b16c550799f3b7ba52b4bf8c1c66dcbdf43
[ "MIT" ]
null
null
null
debugpoint.cpp
gberthou/PeacefulWorld
50c32b16c550799f3b7ba52b4bf8c1c66dcbdf43
[ "MIT" ]
null
null
null
debugpoint.cpp
gberthou/PeacefulWorld
50c32b16c550799f3b7ba52b4bf8c1c66dcbdf43
[ "MIT" ]
null
null
null
#include "debugpoint.h" DebugPoint::DebugPoint(): model(8, 8, {1, 0, 0}) { } void DebugPoint::AddPoint(const SphericCoord &point) { points.push_back(point); } void DebugPoint::Draw(const glutils::ProgramWorld &program) { const float MAP_RADIUS = .5f; const float SCALE = .02f; for(const auto &point : points) { model.SetMatrix(transform_to_sphere_surface(MAP_RADIUS, point.theta, point.phi, 0.f, SCALE, SCALE, SCALE)); model.Draw(program); } }
19.72
115
0.661258
gberthou
6fa2d4f12b5516aaec0d7d3d08a9842cd5423925
1,309
hpp
C++
includes/Transaction.hpp
moguchev/Wallet
ddc38f49b3f563e9a68b784bf315206d21631116
[ "MIT" ]
null
null
null
includes/Transaction.hpp
moguchev/Wallet
ddc38f49b3f563e9a68b784bf315206d21631116
[ "MIT" ]
null
null
null
includes/Transaction.hpp
moguchev/Wallet
ddc38f49b3f563e9a68b784bf315206d21631116
[ "MIT" ]
null
null
null
#ifndef TRANSACTION_HPP #define TRANSACTION_HPP #include <algorithm> #include <fstream> #include <includes/Script.hpp> #include <includes/TxIn.hpp> #include <includes/TxOut.hpp> #include <string> using outputs = std::vector<TxOut>; using inputs = std::vector<TxIn>; class Transaction { public: Transaction() = default; ~Transaction() = default; Transaction(const std::string& file_name); Transaction(int32_t version, const inputs& input, const outputs& output, uint32_t lock_time); Transaction(Transaction&& other); Transaction(const Transaction& other); Transaction& operator=(Transaction&& other); Transaction& operator=(const Transaction& other); std::string get_hex_tx() const; std::vector<byte> get_byte_tx() const; void sign(const std::string& private_key_wif); bool is_signed() const; static Transaction parse(const std::string& file_name); std::vector<TxIn> get_inputs() const; std::vector<TxOut> get_outputs() const; int32_t get_version() const; uint32_t get_locktime() const; byte get_in_count() const; byte get_out_count() const; private: int32_t version_; byte tx_in_count_; inputs tx_in_; byte tx_out_count_; outputs tx_out_; uint32_t locktime_; }; #endif // TRANSACTION_HPP
18.7
57
0.70741
moguchev
6fa64d0afec87fcb3308d2df19b49776968eaa8c
699
cpp
C++
Task 1/Josephus Problem/Solution.cpp
anjali-coder/Hacktoberfest_2020
05cf51d9b791b89f93158971637ba931a3037dc5
[ "MIT" ]
74
2021-09-22T06:29:40.000Z
2022-01-20T14:46:11.000Z
Task 1/Josephus Problem/Solution.cpp
anjali-coder/Hacktoberfest_2020
05cf51d9b791b89f93158971637ba931a3037dc5
[ "MIT" ]
65
2020-10-02T11:03:42.000Z
2020-11-01T06:00:25.000Z
Task 1/Josephus Problem/Solution.cpp
anjali-coder/Hacktoberfest_2020
05cf51d9b791b89f93158971637ba931a3037dc5
[ "MIT" ]
184
2020-10-02T10:53:53.000Z
2021-08-20T12:27:04.000Z
#include<iostream> using namespace std; int jos(int n,int k) { if(n==1) return 0; else { return (jos(n-1,k)+k)%n; } } int main() { int n,k,choice; cout<<"\n\tEnter the total no of people : "; cin>>n; cout<<"\n\tEnter the k : "; cin>>k; cout<<"The numbering start form where : "; cout<<"\n\t 0.Zero"; cout<<"\n\t 1.One\n"; cin>>choice; switch(choice) { case 0: cout<<"\n\tThe person remaining is : "<<jos(n,k); break; case 1: cout<<"\n\tThe person remaining is : "<<jos(n,k)+1; break; default: cout<<"\n\tEnter valid choice : "; break; } return 0; }
21.181818
67
0.48927
anjali-coder
6fa73f82aaf4c72123eb26e2a0d5365e0d31cd44
1,764
cpp
C++
src/mixer/mixer.editableObject_PolygonDuplicate.cpp
3dhater/mixer
52dca419de53abf3b61acd020c2fc9a52bce2255
[ "libpng-2.0" ]
null
null
null
src/mixer/mixer.editableObject_PolygonDuplicate.cpp
3dhater/mixer
52dca419de53abf3b61acd020c2fc9a52bce2255
[ "libpng-2.0" ]
null
null
null
src/mixer/mixer.editableObject_PolygonDuplicate.cpp
3dhater/mixer
52dca419de53abf3b61acd020c2fc9a52bce2255
[ "libpng-2.0" ]
null
null
null
#include "mixer.sdkImpl.h" #include "mixer.application.h" #include "mixer.viewportCamera.h" #include "mixer.pluginGUIImpl.h" #include "mixer.editableObject.h" #include "containers/mixer.BST.h" #include <set> extern miApplication * g_app; void miEditableObject::PolygonDuplicate() { miArray<miPolygon*> newPolygons; newPolygons.reserve(0x1000); { miBinarySearchTree<miVertex*> newVerts; auto c = m_mesh->m_first_polygon; auto l = c->m_left; while (true) { if (c->m_flags & miPolygon::flag_isSelected) { miPolygon* newPolygon = m_allocatorPolygon->Allocate(); newPolygons.push_back(newPolygon); auto cv = c->m_verts.m_head; auto lv = cv->m_left; while (true) { miVertex* newVertex = 0; if (!newVerts.Get((uint64_t)cv->m_data.m_vertex, newVertex)) { newVertex = m_allocatorVertex->Allocate(); newVertex->m_position = cv->m_data.m_vertex->m_position; m_mesh->_add_vertex_to_list(newVertex); newVerts.Add((uint64_t)cv->m_data.m_vertex, newVertex); } newVertex->m_polygons.push_back(newPolygon); newPolygon->m_verts.push_back(miPolygon::_vertex_data(newVertex, cv->m_data.m_uv, cv->m_data.m_normal, 0)); if (cv == lv) break; cv = cv->m_right; } } if (c == l) break; c = c->m_right; } } if (!newPolygons.m_size) return; this->DeselectAll(g_app->m_editMode); for (u32 i = 0; i < newPolygons.m_size; ++i) { m_mesh->_add_polygon_to_list(newPolygons.m_data[i]); newPolygons.m_data[i]->m_flags |= miPolygon::flag_isSelected; } m_mesh->UpdateCounts(); _rebuildEdges(); this->OnSelect(g_app->m_editMode); this->UpdateAabb(); g_app->UpdateSelectionAabb(); /// g_app->_callVisualObjectOnSelect(); _rebuildEdges(); }
23.52
112
0.681406
3dhater
6fa958e87f8361094f5b5fadb9ad561a6ae1039e
1,954
hpp
C++
boiled-plates/bop-utility/Benchmark.hpp
Lokidottir/boiled-plates
2ada3a86f5ea9a12a3244f9f6de54ce8329dbe38
[ "MIT" ]
null
null
null
boiled-plates/bop-utility/Benchmark.hpp
Lokidottir/boiled-plates
2ada3a86f5ea9a12a3244f9f6de54ce8329dbe38
[ "MIT" ]
null
null
null
boiled-plates/bop-utility/Benchmark.hpp
Lokidottir/boiled-plates
2ada3a86f5ea9a12a3244f9f6de54ce8329dbe38
[ "MIT" ]
null
null
null
#ifndef BOP_BENCHMARK_HPP #define BOP_BENCHMARK_HPP #include <chrono> namespace bop { namespace util { #ifndef BOP_UTIL_DEFAULT_TYPES #define BOP_UTIL_DEFAULT_TYPES typedef double prec_type; typedef uint64_t uint_type; #endif template<typename ...params> void nothing(params&&... args) { /* Used to gauge function call time. */ } template<class T = uint_type,typename F, typename ...params> T benchmark(uint_type test_count, F function, params&&... P) { /* Returns nanoseconds taken to perform a function given the parameters. The time taken to call the function is subtracted from the result. */ //Get the time before empty function calling auto empty_funct_b = std::chrono::high_resolution_clock::now(); #ifdef BOP_BENCHMARK_KEEP_CALLTIME for (unsigned int i = 0; i < test_count; i++) { /* Call the empty function as many times as the function being benchmarked to eliminate function call time as a factor. */ nothing(P...); } #endif //Get the time after the function calling auto empty_funct_a = std::chrono::high_resolution_clock::now(); //Get the time before benchmarked function is called auto before = std::chrono::high_resolution_clock::now(); for (unsigned int i = 0; i < test_count; i++) { function(P...); } //Get the time after auto after = std::chrono::high_resolution_clock::now(); return (std::chrono::duration_cast<std::chrono::nanoseconds>((after - before) - (empty_funct_b - empty_funct_a)).count()/static_cast<T>(test_count)); } } } #endif
36.867925
161
0.562948
Lokidottir
6faa0e34657af00fdaf827230b44506650038fa7
1,767
cpp
C++
C++/form-largest-integer-with-digits-that-add-up-to-target.cpp
Akhil-Kashyap/LeetCode-Solutions
c671a588f96f4e4bbde4512727322ff9b1c8ae6a
[ "MIT" ]
3,269
2018-10-12T01:29:40.000Z
2022-03-31T17:58:41.000Z
C++/form-largest-integer-with-digits-that-add-up-to-target.cpp
Akhil-Kashyap/LeetCode-Solutions
c671a588f96f4e4bbde4512727322ff9b1c8ae6a
[ "MIT" ]
53
2018-12-16T22:54:20.000Z
2022-02-25T08:31:20.000Z
C++/form-largest-integer-with-digits-that-add-up-to-target.cpp
Akhil-Kashyap/LeetCode-Solutions
c671a588f96f4e4bbde4512727322ff9b1c8ae6a
[ "MIT" ]
1,236
2018-10-12T02:51:40.000Z
2022-03-30T13:30:37.000Z
// Time: O(t) // Space: O(t) class Solution { public: string largestNumber(vector<int>& cost, int target) { vector<int> dp(1); dp[0] = 0; for (int t = 1; t <= target; ++t) { dp.emplace_back(-1); for (int i = 0; i < 9; ++i) { if (t < cost[i] || dp[t - cost[i]] < 0) { continue; } dp[t] = max(dp[t], dp[t - cost[i]] + 1); } } if (dp[target] < 0) { return "0"; } string result; for (int i = 8; i >= 0; --i) { while (target >= cost[i] && dp[target] == dp[target - cost[i]] + 1) { target -= cost[i]; result.push_back('1' + i); } } return result; } }; // Time: O(t) // Space: O(t) class Solution2 { public: string largestNumber(vector<int>& cost, int target) { const auto& key = [](const auto& a) { return pair{accumulate(cbegin(a), cend(a), 0), a}; }; vector<vector<int>> dp = {vector<int>(9)}; for (int t = 1; t <= target; ++t) { dp.emplace_back(); for (int i = 0; i < 9; ++i) { if (t < cost[i] || dp[t - cost[i]].empty()) { continue; } auto curr = dp[t - cost[i]]; ++curr[8 - i]; if (key(curr) > key(dp[t])) { dp[t] = move(curr); } } } if (dp.back().empty()) { return "0"; } string result; for (int i = 0; i < dp.back().size(); ++i) { result += string(dp.back()[i], '1' + 8 - i); } return result; } };
27.609375
81
0.370119
Akhil-Kashyap
6fabb7217734c99c79c1b9c076e29efd63650c74
1,865
cpp
C++
Fudl/easy/solved/Equivalent Resistance, Circuit Building.cpp
AhmedMostafa7474/Codingame-Solutions
da696a095c143c5d216bc06f6689ad1c0e25d0e0
[ "MIT" ]
1
2022-03-16T08:56:31.000Z
2022-03-16T08:56:31.000Z
Fudl/easy/solved/Equivalent Resistance, Circuit Building.cpp
AhmedMostafa7474/Codingame-Solutions
da696a095c143c5d216bc06f6689ad1c0e25d0e0
[ "MIT" ]
2
2022-03-17T11:27:14.000Z
2022-03-18T07:41:00.000Z
Fudl/easy/solved/Equivalent Resistance, Circuit Building.cpp
AhmedMostafa7474/Codingame-Solutions
da696a095c143c5d216bc06f6689ad1c0e25d0e0
[ "MIT" ]
6
2022-03-13T19:56:11.000Z
2022-03-17T12:08:22.000Z
#include <ctype.h> #include <iomanip> #include <cstdio> #include <ios> #include <iostream> #include <string> #include <vector> #include <algorithm> #include <map> #include <stack> using namespace std; /** * Auto-generated code below aims at helping you parse * the standard input according to the problem statement. **/ int main() { int n; cin >> n; cin.ignore(); map<string,double> var; for (int i = 0; i < n; i++) { string name; double r; cin >> name >> r; cin.ignore(); var[name] = r; } stack<string> ch; stack<double> val; char temp = '1'; string circuit; getline(cin, circuit); for (int i = 0; i < circuit.size(); i++) { if (circuit[i] == '[' || circuit[i] == '(') ch.push(circuit.substr(i,1)); else if (isalpha(circuit[i])) { string temp = ""; while (i < circuit.size()) { temp += circuit.substr(i,1); i++; if (!isalpha(circuit[i])) { val.push(var[temp]); ch.push(temp); i--; break; } } } else if (circuit[i] == ')') { double value = 0; while (!ch.empty()) { if (ch.top() == "(") { val.push(value); ch.pop(); ch.push("a"); break; } // value += top value += val.top(); val.pop(); ch.pop(); } } else if (circuit[i] == ']') { double value = 0; while (!ch.empty()) { if (ch.top() == "[") { val.push(1/value); ch.pop(); ch.push("a"); break; } // value += 1/top value += 1/val.top(); val.pop(); ch.pop(); } } } // Write an answer using cout. DON'T FORGET THE "<< endl" // To debug: cerr << "Debug messages..." << endl; cout << fixed << setprecision(1) << val.top() << endl; }
21.193182
59
0.472386
AhmedMostafa7474
6fae2b8cf2e308aa2ec94a8d5b288b79a75abeb0
394
cc
C++
geometry/render/render_engine_vtk_factory.cc
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
2
2021-02-25T02:01:02.000Z
2021-03-17T04:52:04.000Z
geometry/render/render_engine_vtk_factory.cc
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
null
null
null
geometry/render/render_engine_vtk_factory.cc
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
1
2021-06-13T12:05:39.000Z
2021-06-13T12:05:39.000Z
#include "drake/geometry/render/render_engine_vtk_factory.h" #include "drake/geometry/render/render_engine_vtk.h" namespace drake { namespace geometry { namespace render { std::unique_ptr<RenderEngine> MakeRenderEngineVtk( const RenderEngineVtkParams& params) { return std::make_unique<RenderEngineVtk>(params); } } // namespace render } // namespace geometry } // namespace drake
23.176471
60
0.774112
RobotLocomotion
6faef9985d7c2a365462673f37a33686614a73a8
258
cpp
C++
classes/RandomUtility.cpp
dstratossong/CC3K
026c2de810a7174a001427e2b9c3499b5ef1444f
[ "Apache-2.0" ]
null
null
null
classes/RandomUtility.cpp
dstratossong/CC3K
026c2de810a7174a001427e2b9c3499b5ef1444f
[ "Apache-2.0" ]
null
null
null
classes/RandomUtility.cpp
dstratossong/CC3K
026c2de810a7174a001427e2b9c3499b5ef1444f
[ "Apache-2.0" ]
null
null
null
// // Created by glados on 4/11/15. // #include <stdlib.h> #include <iostream> #include "RandomUtility.h" int RandomUtility::get_random_integer(int range) { return rand() % range; } void RandomUtility::seed() { srand((unsigned int) time(NULL)); }
16.125
50
0.674419
dstratossong
6fb11542c6ea9c59dd65ca5c48c30dee2c65cb43
1,215
cpp
C++
KTLT_doan1/file.cpp
ipupro2/KTLTr-Project-1
1ee29823a75b9518d6cc4d0b94edebc2a46ec63c
[ "MIT" ]
null
null
null
KTLT_doan1/file.cpp
ipupro2/KTLTr-Project-1
1ee29823a75b9518d6cc4d0b94edebc2a46ec63c
[ "MIT" ]
null
null
null
KTLT_doan1/file.cpp
ipupro2/KTLTr-Project-1
1ee29823a75b9518d6cc4d0b94edebc2a46ec63c
[ "MIT" ]
null
null
null
#include "file.h" void LoadScore(saveData data[]) { ifstream inNameScore; inNameScore.open("save.sav"); if (!inNameScore) { inNameScore.close(); ofstream outNameScore; outNameScore.open("save.sav"); for (int i = 0; i < 10; i++) outNameScore << "Noname 0" << endl; outNameScore.close(); inNameScore.open("save.sav"); } for (int i = 0; i < 10; i++) { inNameScore >> data[i].name; inNameScore >> data[i].score; } inNameScore.close(); } void SaveScore(saveData data) { ifstream inNameScore; inNameScore.open("save.sav"); saveData a[10]; string t1; unsigned long t2; int i = 0; LoadScore(a); for (i = 0; i < 10; i++) if (a[i].score < data.score) { t1 = a[i].name; t2 = a[i].score; a[i].name = data.name; a[i].score = data.score; for (int j = 9; j > i + 1; j--) { a[j].name = a[j - 1].name; a[j].score = a[j - 1].score; } a[i + 1].name = t1; a[i + 1].score = t2; break; } cout << endl; inNameScore.close(); ofstream outNameScore; outNameScore.open("save.sav"); for (i = 0; i < 10; i++) { outNameScore << a[i].name << " " << a[i].score << endl; } outNameScore.close(); }
20.25
58
0.548971
ipupro2
6fb33bf4fabc61bc75f4dd6f0059b84b3f4cc796
4,765
cpp
C++
src/render/Shader.cpp
Yousazoe/Solar
349c75f7a61b1727aa0c6d581cf75124b2502a57
[ "Apache-2.0" ]
1
2021-08-07T13:02:01.000Z
2021-08-07T13:02:01.000Z
src/render/Shader.cpp
Yousazoe/Solar
349c75f7a61b1727aa0c6d581cf75124b2502a57
[ "Apache-2.0" ]
null
null
null
src/render/Shader.cpp
Yousazoe/Solar
349c75f7a61b1727aa0c6d581cf75124b2502a57
[ "Apache-2.0" ]
null
null
null
#include<render/Shader.hpp> #include<render/ShaderInstanceLoader.hpp> #include<fs/Path.hpp> #include<fs/FileSystem.hpp> #include<sstream> namespace tutorial::graphics { bool Shader::_has_shader_cachae = true; using ShaderCompiler = std::string; struct CompileStrategy { std::string version; std::string shader_type; std::string suffix; }; std::string _shader_res_path = "../../data/shaders/"; CompileStrategy vs_5_0 = { "vs_5_0", "VERTEX_SHADER", "_vs" }; CompileStrategy gs_5_0 = { "gs_5_0", "GEOMETRY_SHADER", "_gs" }; CompileStrategy ps_5_0 = { "ps_5_0", "PIXEL_SHADER", "_ps" }; CompileStrategy cs_5_0 = { "cs_5_0", "COMPUTE_SHADER", "_cs" }; inline void compile_shader( const ShaderCompiler& compiler, const fs::Path& path, const fs::Path& output_path, const CompileStrategy& strategy, const std::string& entry, const std::vector<std::string>& defines ) { static std::stringstream cmd; cmd.clear(); cmd << compiler; cmd << " /Od "; cmd << " /T " << strategy.version; cmd << " /E " << entry; // use main as default entry cmd << " /I ./ "; // pipeline closure cmd << " /I " << path.parent_path().string(); // include directory/ cmd << " /D " << strategy.shader_type; for (const auto& define : defines) { cmd << " /D " << define; } cmd << " /Fo " << output_path.string(); cmd << path.string(); system(cmd.str().c_str()); cmd.str(""); } inline auto get_output_path( const fs::Path& path, const CompileStrategy& strategy ) { auto output_directory = path.parent_path(); output_directory.concat("/fxbin/"); auto file_name = path.stem().string(); return output_directory.append( file_name + strategy.suffix + ".fxo " ); } Shader::Shader(std::string name, bool compute) noexcept : _name{ std::move(name) }, _compute{ compute } { } Shader::Shader(std::string name, std::string entry, bool compute) noexcept : _name{ std::move(name) }, _entry{ std::move(entry) }, _compute{ compute } { } void Shader::operator=(Shader&& rhs) noexcept { _name = std::move(rhs._name); _entry = std::move(rhs._entry); _option_count = rhs._option_count; _options = rhs._options; _blocks = rhs._blocks; _shader_instances = std::move(rhs._shader_instances); } auto Shader::add_block(const ShaderBlock& block) noexcept -> void { assert(block.index < 32u); _blocks[block.index].enable = true; _blocks[block.index].option_offset = _option_count; const auto& option_strings = block.option_strings; std::copy_n(option_strings.begin(), option_strings.size(), _options.begin() + _option_count); _option_count += uint8(block.option_strings.size()); } auto Shader::default() noexcept -> ShaderVersion { return ShaderVersion{ *this }; } auto Shader::fetch(uint64 version) noexcept -> const ShaderInstance& { if (_shader_instances.find(version) == _shader_instances.end()) { _shader_instances[version] = compile(version); } return _shader_instances[version]; } auto Shader::compile(uint64 version) const noexcept -> ShaderInstance { std::vector<std::string> defines = {}; for (uint32 opt = 0u; opt < 32u; ++opt) { if (version & (1 << opt)) { defines.push_back(_options[opt]); } } static std::string compiler = std::string("fxc "); //compiler += " /I " + std::string(compilerDirectory) + "FX"; auto path = _shader_res_path + _name + (_compute ? ".compute" : ".shader"); auto output_path_base = _shader_res_path + _name + "_" + std::to_string(version); if (_compute) { auto output_path_cs = get_output_path(output_path_base, cs_5_0); compile_shader(compiler, path, output_path_cs, cs_5_0, _entry, defines); return ShaderInstanceLoader::load_compute(output_path_cs); } else { auto output_path_vs = get_output_path(output_path_base, vs_5_0); auto output_path_gs = get_output_path(output_path_base, gs_5_0); auto output_path_ps = get_output_path(output_path_base, ps_5_0); if (!_has_shader_cachae || !fs::exists(fs::status(output_path_vs))) { compile_shader(compiler, path, output_path_vs, vs_5_0, _entry, defines); } if (!_has_shader_cachae || !fs::exists(fs::status(output_path_gs))) { compile_shader(compiler, path, output_path_gs, gs_5_0, _entry, defines); } if (!_has_shader_cachae || !fs::exists(fs::status(output_path_ps))) { compile_shader(compiler, path, output_path_ps, ps_5_0, _entry, defines); } return ShaderInstanceLoader::load(output_path_vs, output_path_gs, output_path_ps); } } auto ShaderVersion::set_option(uint8 block, uint8 option, bool enable) noexcept -> void { assert(block < 32u); uint8 local_option = _shader._blocks[block].option_offset + option; _options.set(local_option, enable); } }
28.878788
95
0.684995
Yousazoe
6fb57f0384bd58536feaec3aec330c5773f1e535
1,738
cpp
C++
engine/graphics/src/graphics_glfw_wrappers.cpp
hapass/defold
fd3602f27a2596a2ad62bf9a70ae9d7acda24ad8
[ "Apache-2.0" ]
1
2020-05-19T15:47:07.000Z
2020-05-19T15:47:07.000Z
engine/graphics/src/graphics_glfw_wrappers.cpp
CagdasErturk/defold
28e5eb635042d37e17cda4d33e47fce2b569cab8
[ "Apache-2.0" ]
null
null
null
engine/graphics/src/graphics_glfw_wrappers.cpp
CagdasErturk/defold
28e5eb635042d37e17cda4d33e47fce2b569cab8
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 The Defold Foundation // Licensed under the Defold License version 1.0 (the "License"); you may not use // this file except in compliance with the License. // // You may obtain a copy of the License, together with FAQs at // https://www.defold.com/license // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #include <graphics/glfw/glfw.h> #include <graphics/glfw/glfw_native.h> #include "graphics_native.h" namespace dmGraphics { #define WRAP_GLFW_NATIVE_HANDLE_CALL(return_type, func_name) return_type GetNative##func_name() { return glfwGet##func_name(); } WRAP_GLFW_NATIVE_HANDLE_CALL(id, iOSUIWindow); WRAP_GLFW_NATIVE_HANDLE_CALL(id, iOSUIView); WRAP_GLFW_NATIVE_HANDLE_CALL(id, iOSEAGLContext); WRAP_GLFW_NATIVE_HANDLE_CALL(id, OSXNSWindow); WRAP_GLFW_NATIVE_HANDLE_CALL(id, OSXNSView); WRAP_GLFW_NATIVE_HANDLE_CALL(id, OSXNSOpenGLContext); WRAP_GLFW_NATIVE_HANDLE_CALL(HWND, WindowsHWND); WRAP_GLFW_NATIVE_HANDLE_CALL(HGLRC, WindowsHGLRC); WRAP_GLFW_NATIVE_HANDLE_CALL(EGLContext, AndroidEGLContext); WRAP_GLFW_NATIVE_HANDLE_CALL(EGLSurface, AndroidEGLSurface); WRAP_GLFW_NATIVE_HANDLE_CALL(JavaVM*, AndroidJavaVM); WRAP_GLFW_NATIVE_HANDLE_CALL(jobject, AndroidActivity); WRAP_GLFW_NATIVE_HANDLE_CALL(android_app*, AndroidApp); WRAP_GLFW_NATIVE_HANDLE_CALL(Window, X11Window); WRAP_GLFW_NATIVE_HANDLE_CALL(GLXContext, X11GLXContext); #undef WRAP_GLFW_NATIVE_HANDLE_CALL }
44.564103
129
0.794016
hapass
6fb6238c77ea47bca6d5fc7ddeb3796bf917ba05
62
cpp
C++
source/romocc/core/Object.cpp
SINTEFMedtek/libromocc
65a10849401cec02fc1c9ac8b1bdebbbfc4ff1c0
[ "BSD-2-Clause" ]
2
2019-07-03T10:02:11.000Z
2020-04-20T09:01:42.000Z
source/romocc/core/Object.cpp
SINTEFMedtek/libromocc
65a10849401cec02fc1c9ac8b1bdebbbfc4ff1c0
[ "BSD-2-Clause" ]
4
2019-08-05T07:55:22.000Z
2020-05-11T11:05:59.000Z
source/romocc/core/Object.cpp
SINTEFMedtek/libromocc
65a10849401cec02fc1c9ac8b1bdebbbfc4ff1c0
[ "BSD-2-Clause" ]
1
2020-06-22T09:55:47.000Z
2020-06-22T09:55:47.000Z
// // Created by androst on 02.06.19. // #include "Object.h"
10.333333
34
0.612903
SINTEFMedtek
6fb976ab82764e96e51eca155329457c4d7d3694
2,449
cpp
C++
src/edit-row/treeview_enable_edit_next_field.cpp
rasmusbonnedal/gtk-snippets
54bd00e295c5701002bd5c9b42383d584120def0
[ "MIT" ]
1
2019-11-25T03:11:45.000Z
2019-11-25T03:11:45.000Z
src/edit-row/treeview_enable_edit_next_field.cpp
rasmusbonnedal/gtk-snippets
54bd00e295c5701002bd5c9b42383d584120def0
[ "MIT" ]
null
null
null
src/edit-row/treeview_enable_edit_next_field.cpp
rasmusbonnedal/gtk-snippets
54bd00e295c5701002bd5c9b42383d584120def0
[ "MIT" ]
1
2020-06-19T18:32:04.000Z
2020-06-19T18:32:04.000Z
// // Copyright (C) 2019 Rasmus Bonnedal // #include "treeview_enable_edit_next_field.h" namespace { void setCursorNextFieldHandler(const Glib::ustring& path_string, const Glib::ustring& new_text, Gtk::TreeViewColumn* column, Gtk::TreeViewColumn* colNext, bool nextRow) { Gtk::TreeView* treeView = column->get_tree_view(); Gtk::TreePath currpath(path_string); Gtk::TreePath nextpath(currpath); if (nextRow) { nextpath.next(); Glib::RefPtr<Gtk::ListStore> model = Glib::RefPtr<Gtk::ListStore>::cast_dynamic(treeView->get_model()); // If path.next() is not a valid row, append new row for editing if (!model->get_iter(nextpath)) { model->append(); } } // Hack to work around problem setting cursor // See: // https://github.com/bbuhler/HostsManager/commit/bfa95e32dce484b79d4dc023cb48f3249dc3ff7a // https://gitlab.com/inkscape/inkscape/merge_requests/801/diffs?commit_id=40b6f70127755d2b44597e56f5bd965083eda3f2 Glib::signal_timeout().connect_once( [treeView, currpath, column, nextpath, colNext]() { Gtk::TreePath focusPath; Gtk::TreeViewColumn* focusColumn; treeView->get_cursor(focusPath, focusColumn); if (focusPath == currpath && focusColumn == column) { treeView->set_cursor(nextpath, *colNext, true); } }, 1); } void setCursorNextField(Gtk::TreeViewColumn* column, Gtk::TreeViewColumn* colNext, bool nextRow) { Gtk::CellRendererText* crt = dynamic_cast<Gtk::CellRendererText*>(column->get_first_cell()); g_return_if_fail(crt != nullptr); crt->signal_edited().connect( sigc::bind(&setCursorNextFieldHandler, column, colNext, nextRow)); } } // namespace void enableEditNextField(const std::vector<Gtk::TreeViewColumn*>& columns) { size_t nColumn = columns.size(); g_return_if_fail(nColumn >= 2); Gtk::TreeView* treeView = columns[0]->get_tree_view(); Glib::RefPtr<Gtk::ListStore> model = Glib::RefPtr<Gtk::ListStore>::cast_dynamic(treeView->get_model()); g_return_if_fail(model); for (size_t i = 0; i < nColumn - 1; ++i) { setCursorNextField(columns[i], columns[i + 1], false); } setCursorNextField(columns[nColumn - 1], columns[0], true); }
38.265625
119
0.633728
rasmusbonnedal
6fb9b215a5d925f19e9cb756aa2b56168835071b
7,484
cpp
C++
src/main.cpp
FCS-holding/falcon-genome
bbba762ec54139392be843e9edff21766d5d7f5b
[ "Apache-2.0" ]
null
null
null
src/main.cpp
FCS-holding/falcon-genome
bbba762ec54139392be843e9edff21766d5d7f5b
[ "Apache-2.0" ]
null
null
null
src/main.cpp
FCS-holding/falcon-genome
bbba762ec54139392be843e9edff21766d5d7f5b
[ "Apache-2.0" ]
null
null
null
#include <algorithm> #include <boost/thread/lockable_adapter.hpp> #include <boost/thread/mutex.hpp> #include <iostream> #include <string> #include "fcs-genome/common.h" #include "fcs-genome/config.h" #include "fcs-genome/Executor.h" #define print_cmd_col(str1, str2) std::cout \ << " " << std::left << std::setw(16) << str1 \ << std::left << std::setw(54) << str2 \ << std::endl; int print_help() { std::cout << "Falcon Genome Analysis Toolkit " << std::endl; std::cout << "Usage: fcs-genome [command] <options>" << std::endl; std::cout << std::endl; std::cout << "Commands: " << std::endl; print_cmd_col("align", "align pair-end FASTQ files into a sorted,"); print_cmd_col(" ", "duplicates-marked BAM file"); print_cmd_col("markdup", "mark duplicates in an aligned BAM file"); print_cmd_col("bqsr", "base recalibration with GATK BaseRecalibrator"); print_cmd_col(" ", "and GATK PrintReads"); print_cmd_col("baserecal", "equivalent to GATK BaseRecalibrator"); print_cmd_col("germline", "accelerated pipeline for DNA sample (align + htc)"); print_cmd_col("printreads", "equivalent to GATK PrintReads"); print_cmd_col("htc", "variant calling with GATK HaplotypeCaller"); print_cmd_col("mutect2", "(Experimental) somatic variant calling with GATK Mutect2"); print_cmd_col("indel", "indel realignment with GATK IndelRealigner"); print_cmd_col("joint", "joint variant calling with GATK GenotypeGVCFs"); print_cmd_col("ug", "variant calling with GATK UnifiedGenotyper"); print_cmd_col("gatk", "call GATK routines"); print_cmd_col("depth", "Depth of Coverage"); print_cmd_col("vcf_filter", "Variant Filtration"); return 0; } void sigint_handler(int s){ boost::lock_guard<fcsgenome::Executor> guard(*fcsgenome::g_executor); LOG(INFO) << "Caught interrupt, cleaning up..."; if (fcsgenome::g_executor) { delete fcsgenome::g_executor; } #ifndef NDEBUG fcsgenome::remove_path(fcsgenome::conf_temp_dir); #endif } namespace fcsgenome { namespace po = boost::program_options; int align_main(int argc, char** argv, po::options_description &opt_desc); int bqsr_main(int argc, char** argv, po::options_description &opt_desc); int baserecal_main(int argc, char** argv, po::options_description &opt_desc); int germline_main(int argc, char** argv, po::options_description &opt_desc); int concat_main(int argc, char** argv, po::options_description &opt_desc); int htc_main(int argc, char** argv, po::options_description &opt_desc); int ir_main(int argc, char** argv, po::options_description &opt_desc); int joint_main(int argc, char** argv, po::options_description &opt_desc); int markdup_main(int argc, char** argv, po::options_description &opt_desc); int pr_main(int argc, char** argv, po::options_description &opt_desc); int ug_main(int argc, char** argv, po::options_description &opt_desc); int gatk_main(int argc, char** argv, po::options_description &opt_desc); int hist_main(int argc, char** argv, po::options_description &opt_desc); int mutect2_main(int argc, char** argv, po::options_description &opt_desc); int depth_main(int argc, char** argv, po::options_description &opt_desc); int variant_filtration_main(int argc, char** argv, po::options_description &opt_desc); } int main(int argc, char** argv) { using namespace fcsgenome; // Initialize Google Log google::InitGoogleLogging(argv[0]); FLAGS_logtostderr=1; if (argc < 2) { print_help(); return 1; } namespace po = boost::program_options; po::options_description opt_desc; opt_desc.add_options() ("help,h", "print help messages") ("force,f", "overwrite output files if they exist") ("extra-options,O", po::value<std::vector<std::string> >(), "extra options for the command"); //("checkpoint", "save the output of the command"); //("schedule,a", "schedule the command rather than executing it"); std::string cmd(argv[1]); // transform all cmd to lower-case std::transform(cmd.begin(), cmd.end(), cmd.begin(), ::tolower); signal(SIGINT, sigint_handler); int ret = 0; try { // load configurations init(argv, argc); std::stringstream cmd_log; for (int i = 0; i < argc; i++) { cmd_log << argv[i] << " "; } LOG(INFO) << "Arguments: " << cmd_log.str(); // run command if (cmd == "align" | cmd == "al") { align_main(argc-1, &argv[1], opt_desc); } else if (cmd == "markdup" | cmd == "md") { markdup_main(argc-1, &argv[1], opt_desc); } else if (cmd == "baserecal") { baserecal_main(argc-1, &argv[1], opt_desc); } else if (cmd == "printreads" | cmd == "pr") { pr_main(argc-1, &argv[1], opt_desc); } else if (cmd == "bqsr") { bqsr_main(argc-1, &argv[1], opt_desc); } else if (cmd == "indel" | cmd == "ir") { ir_main(argc-1, &argv[1], opt_desc); } else if (cmd == "joint") { joint_main(argc-1, &argv[1], opt_desc); } else if (cmd == "unifiedgeno" | cmd == "ug") { ug_main(argc-1, &argv[1], opt_desc); } else if (cmd == "htc") { htc_main(argc-1, &argv[1], opt_desc); } else if (cmd == "concat") { concat_main(argc-1, &argv[1], opt_desc); } else if (cmd == "gatk") { gatk_main(argc-1, &argv[1], opt_desc); } else if (cmd == "mutect2") { mutect2_main(argc-1, &argv[1], opt_desc); } else if (cmd == "depth") { depth_main(argc-1, &argv[1], opt_desc); } else if (cmd == "vcf_filter") { variant_filtration_main(argc-1, &argv[1], opt_desc); } else if (cmd == "germline") { germline_main(argc-1, &argv[1], opt_desc); } else if (cmd == "--version") { std::cout << VERSION << std::endl; } else { print_help(); throw silentExit(); } #ifdef NDEBUG // delete temp dir remove_path(conf_temp_dir); #endif } catch (helpRequest &e) { std::cerr << "'fcs-genome " << cmd; std::cerr << "' options:" << std::endl; std::cerr << opt_desc << std::endl; // delete temp dir remove_path(conf_temp_dir); ret = 0; } catch (invalidParam &e) { LOG(ERROR) << "Failed to parse arguments: " << "invalid option " << e.what(); std::cerr << "'fcs-genome " << cmd; std::cerr << "' options:" << std::endl; std::cerr << opt_desc << std::endl; ret = 1; } catch (pathEmpty &e) { LOG(ERROR) << "Failed to parse arguments: " << "option " << e.what() << " cannot be empty"; std::cerr << "'fcs-genome " << cmd; std::cerr << "' options:" << std::endl; std::cerr << opt_desc << std::endl; ret = 1; } catch (boost::program_options::error &e) { LOG(ERROR) << "Failed to parse arguments: " << e.what(); std::cerr << "'fcs-genome " << cmd; std::cerr << "' options:" << std::endl; std::cerr << opt_desc << std::endl; // delete temp dir remove_path(conf_temp_dir); ret = 2; } catch (fileNotFound &e) { LOG(ERROR) << e.what(); ret = 3; } catch (silentExit &e) { LOG(INFO) << "Exiting program"; // delete temp dir remove_path(conf_temp_dir); ret = 1; } catch (failedCommand &e) { //LOG(ERROR) << e.what(); ret = 4; } catch (std::runtime_error &e) { LOG(ERROR) << "Encountered an error: " << e.what(); LOG(ERROR) << "Please contact support@falcon-computing.com for details."; ret = -1; } return ret; }
30.92562
88
0.62186
FCS-holding
6fc0687c87e7a65c1b5259d6403a31bec8424ca8
2,115
cc
C++
band/control/border.cc
jwowillo/band
d5268232f695459914773d5c189de85a5cdfdfc5
[ "MIT" ]
null
null
null
band/control/border.cc
jwowillo/band
d5268232f695459914773d5c189de85a5cdfdfc5
[ "MIT" ]
null
null
null
band/control/border.cc
jwowillo/band
d5268232f695459914773d5c189de85a5cdfdfc5
[ "MIT" ]
null
null
null
#include "band/control/border.h" #include <cmath> #include "band/control/rectangle.h" namespace band { namespace control { void Border::SetArea(const ::band::Area& area) { area_ = area; } Dimension Border::Thickness() const { return thickness_; } void Border::SetThickness(const Dimension& thickness) { thickness_ = thickness; } ::band::Color Border::Color() const { return color_; } void Border::SetColor(const ::band::Color& color) { color_ = color; } Real Border::RealBorderThickness(const Interface& interface) const { return thickness_.unit == Unit::kPixel ? thickness_.scalar : thickness_.scalar * std::min( interface.WindowArea().width, interface.WindowArea().height); } ::band::Area Border::Area(const Interface&) const { return area_; } void Border::Update(const Point&, const Interface&) { } void Border::Display(const Point& position, Interface& interface) { Dimension thickness{}; thickness.scalar = RealBorderThickness(interface); thickness.unit = Unit::kPixel; ::band::Area area = this->Area(interface); ::band::Area horizontal_area{ .width = area.width, .height = thickness }; ::band::Area vertical_area{ .width = thickness, .height = area.height }; ::band::control::Rectangle vertical; vertical.SetColor(this->Color()); vertical.SetArea(vertical_area); ::band::control::Rectangle horizontal; horizontal.SetColor(this->Color()); horizontal.SetArea(horizontal_area); Point top_left = position; Point top_right{ .x = SubtractDimensions( AddDimensions(top_left.x, area.width, interface.WindowArea().width), thickness, interface.WindowArea().width), .y = top_left.y }; Point bottom_left{ .x = top_left.x, .y = SubtractDimensions( AddDimensions(top_left.y, area.height, interface.WindowArea().height), thickness, interface.WindowArea().height) }; vertical.Display(top_left, interface); horizontal.Display(top_left, interface); vertical.Display(top_right, interface); horizontal.Display(bottom_left, interface); } } // namespace control } // namespace band
25.178571
78
0.702128
jwowillo
6fc1200e6c8493970730ac8160e71cfede239788
1,592
cpp
C++
sem_2/course_algorithms/contest_5/B.cpp
KingCakeTheFruity/mipt
e32cfe5e53236cdd2933d8b666ca995508300f0f
[ "MIT" ]
null
null
null
sem_2/course_algorithms/contest_5/B.cpp
KingCakeTheFruity/mipt
e32cfe5e53236cdd2933d8b666ca995508300f0f
[ "MIT" ]
null
null
null
sem_2/course_algorithms/contest_5/B.cpp
KingCakeTheFruity/mipt
e32cfe5e53236cdd2933d8b666ca995508300f0f
[ "MIT" ]
null
null
null
/* Пишем Крускалу, делая вид, что что-то может быть приятнее dsu */ #include <cstdio> #include <cstdlib> #include <vector> #include <algorithm> #include <set> using std::vector; using std::reverse; using std::find; using std::set; using std::min; vector<long long> dsu; vector<long long> dsu_size; struct Pair { long long x; long long y; long long w; Pair() {} Pair(long long a, long long b, long long c): x(a), y(b), w(c) {} }; bool operator<(const Pair &a, const Pair &b) { if (a.w < b.w) { return true; } else if (a.w > b.w) { return false; } else { return a.y < b.y && a.x < b.x; } } void dsu_init(int n) { dsu.resize(n); dsu_size.resize(n); for (int i = 0; i < n; ++i) { dsu[i] = i; dsu_size[i] = 1; } } long long dsu_get(long long v) { if (dsu[v] == v) { return v; } else { return dsu[v] = dsu_get(dsu[v]); } } void dsu_unite(long long first, long long second) { first = dsu_get(first); second = dsu_get(second); if (dsu_size[first] > dsu_size[second]) { dsu[second] = first; dsu_size[first] += dsu_size[second]; } else { dsu[first] = second; dsu_size[second] += dsu_size[first]; } } int main() { long long n, m; scanf("%lld %lld", &n, &m); dsu_init(n); vector<Pair> g; for (long long i = 0; i < m; ++i) { long long a, b, x; scanf("%lld %lld %lld", &a, &b, &x); --a; --b; g.push_back({a, b, x}); } sort(g.begin(), g.end()); long long ans = 0; for (auto e : g) { if (dsu_get(e.x) != dsu_get(e.y)) { dsu_unite(e.x, e.y); ans += e.w; } } printf("%lld\n", ans); return 0; }
15.607843
61
0.568467
KingCakeTheFruity
6fc5a3f2f96a6118da72cb714d115c6548375138
3,929
hpp
C++
snmp_fetch/api/types.hpp
higherorderfunctor/snmp-fetch
c95e9f60d38901c500456dc6f07af343b36b4938
[ "CC0-1.0" ]
null
null
null
snmp_fetch/api/types.hpp
higherorderfunctor/snmp-fetch
c95e9f60d38901c500456dc6f07af343b36b4938
[ "CC0-1.0" ]
32
2019-09-19T05:25:07.000Z
2019-12-05T20:28:17.000Z
snmp_fetch/api/types.hpp
higherorderfunctor/snmp-fetch
c95e9f60d38901c500456dc6f07af343b36b4938
[ "CC0-1.0" ]
null
null
null
/** * type.hpp - Common type definitions. */ #ifndef SNMP_FETCH__TYPES_H #define SNMP_FETCH__TYPES_H #include <iostream> #include <boost/format.hpp> extern "C" { #include <net-snmp/net-snmp-config.h> #include <net-snmp/net-snmp-includes.h> } #include "utils.hpp" namespace snmp_fetch { // default values #define SNMP_FETCH__DEFAULT_RETRIES 3 #define SNMP_FETCH__DEFAULT_TIMEOUT 3 #define SNMP_FETCH__DEFAULT_MAX_ACTIVE_SESSIONS 10 #define SNMP_FETCH__DEFAULT_MAX_VAR_BINDS_PER_PDU 10 #define SNMP_FETCH__DEFAULT_MAX_BULK_REPETITIONS 10 // type aliases using host_t = std::tuple<uint64_t, std::string, std::string>; using oid_t = std::vector<uint64_t>; using oid_size_t = uint64_t; using value_size_t = uint64_t; using var_bind_size_t = std::tuple<oid_size_t, value_size_t>; using var_bind_t = std::tuple<oid_t, var_bind_size_t>; /** * async_status_t - Different statuses of an async session. */ enum async_status_t { ASYNC_IDLE = 0, ASYNC_WAITING, ASYNC_RETRY }; /** * PDU_TYPE - Constants exposed to python. */ enum PDU_TYPE { GET = SNMP_MSG_GET, NEXT= SNMP_MSG_GETNEXT, BULKGET = SNMP_MSG_GETBULK, }; /** * SnmpConfig - Pure C++ config type exposed through the to python module. */ struct SnmpConfig { ssize_t retries; ssize_t timeout; size_t max_active_sessions; size_t max_var_binds_per_pdu; size_t max_bulk_repetitions; /** * SnmpConfig - Constructor with default values. */ SnmpConfig( ssize_t retries = SNMP_FETCH__DEFAULT_RETRIES, ssize_t timeout = SNMP_FETCH__DEFAULT_TIMEOUT, size_t max_active_sessions = SNMP_FETCH__DEFAULT_MAX_ACTIVE_SESSIONS, size_t max_var_binds_per_pdu = SNMP_FETCH__DEFAULT_MAX_VAR_BINDS_PER_PDU, size_t max_bulk_repetitions = SNMP_FETCH__DEFAULT_MAX_BULK_REPETITIONS ); /** * SnmpConfig::operator== */ bool operator==(const SnmpConfig &a); /** * to_string - String method used for __str__ and __repr__ which mimics attrs. * * @return String representation of a SnmpConfig. */ std::string to_string(); }; /** * ERROR_TYPE - Constants exposed to python for identifying where an error happened. */ enum SNMP_ERROR_TYPE { SESSION_ERROR = 0, CREATE_REQUEST_PDU_ERROR, SEND_ERROR, BAD_RESPONSE_PDU_ERROR, TIMEOUT_ERROR, ASYNC_PROBE_ERROR, TRANSPORT_DISCONNECT_ERROR, CREATE_RESPONSE_PDU_ERROR, VALUE_WARNING }; /** * SnmpError - Pure C++ container for various error types exposed to python. */ struct SnmpError { SNMP_ERROR_TYPE type; host_t host; std::optional<int64_t> sys_errno; std::optional<int64_t> snmp_errno; std::optional<int64_t> err_stat; std::optional<int64_t> err_index; std::optional<oid_t> err_oid; std::optional<std::string> message; /** * SnmpError - Constructor method with default values. */ SnmpError( SNMP_ERROR_TYPE type, host_t host, std::optional<int64_t> sys_errno = {}, std::optional<int64_t> snmp_errno = {}, std::optional<int64_t> err_stat = {}, std::optional<int64_t> err_index = {}, std::optional<oid_t> err_oid = {}, std::optional<std::string> message = {} ); /** * SnmpError::operator== */ bool operator==(const SnmpError &a); /** * to_string - String method used for __str__ and __repr__ which mimics attrs. * * @return String representation of an SnmpError. */ std::string to_string(); }; /** * async_state - State wrapper for net-snmp sessions. * * Host should be left as copy as the underlying pending host list destroys the elements that * were used to build this structure. */ struct async_state { async_status_t async_status; void *session; int pdu_type; host_t host; std::vector<var_bind_t> *var_binds; std::vector<std::vector<oid_t>> next_var_binds; std::vector<std::vector<uint8_t>> *results; std::vector<SnmpError> *errors; SnmpConfig *config; }; } #endif
22.58046
94
0.71494
higherorderfunctor
6fc610be415c6d6c19d1b53b773bdf0b10c1ac3c
2,513
cpp
C++
Test/Math/Test_MathCore.cpp
XenonicDev/Red
fcd12416bdf7fe4d2372161e67edc585f75887e4
[ "MIT" ]
1
2018-01-29T02:49:05.000Z
2018-01-29T02:49:05.000Z
Test/Math/Test_MathCore.cpp
XenonicDev/Red
fcd12416bdf7fe4d2372161e67edc585f75887e4
[ "MIT" ]
26
2017-05-08T22:57:14.000Z
2018-05-15T20:55:26.000Z
Test/Math/Test_MathCore.cpp
XenonicDev/Red
fcd12416bdf7fe4d2372161e67edc585f75887e4
[ "MIT" ]
null
null
null
/* Copyright (c) 2017-2018 Andrew Depke */ #include "gtest/gtest.h" #include "../../Red/Math/MathCore.h" using namespace Red; TEST(MathCoreSuite, AbsGeneralInt) { EXPECT_EQ(3, Abs(3)); EXPECT_EQ(3, Abs(-3)); EXPECT_EQ(0, Abs(0)); } TEST(MathCoreSuite, AbsGeneralFloat) { EXPECT_FLOAT_EQ(3.0f, Abs(3.0f)); EXPECT_FLOAT_EQ(3.0f, Abs(-3.0f)); EXPECT_FLOAT_EQ(0.0f, Abs(0.0f)); } TEST(MathCoreSuite, AbsGeneralDouble) { EXPECT_EQ(3.0, Abs(3.0)); EXPECT_EQ(3.0, Abs(-3.0)); EXPECT_EQ(0.0, Abs(0.0)); } TEST(MathCoreSuite, AbsGeneralLongDouble) { EXPECT_EQ((long double)3.0, Abs((long double)3.0)); EXPECT_EQ((long double)3.0, Abs((long double)-3.0)); EXPECT_EQ((long double)0.0, Abs((long double)0.0)); } TEST(MathCoreSuite, MinGeneral) { EXPECT_EQ(3, Min(3, 3)); EXPECT_EQ(-3, Min(-3, -3)); EXPECT_EQ(-3, Min(3, -3)); EXPECT_EQ(-3, Min(-3, 3)); EXPECT_EQ(0, Min(0, 0)); } TEST(MathCoreSuite, MaxGeneral) { EXPECT_EQ(3, Max(3, 3)); EXPECT_EQ(-3, Max(-3, -3)); EXPECT_EQ(3, Max(3, -3)); EXPECT_EQ(3, Max(-3, 3)); EXPECT_EQ(0, Max(0, 0)); } TEST(MathCoreSuite, PowerGeneral) { EXPECT_EQ(64.0f, Power(4.0f, 3.0f)); EXPECT_NEAR(104.47f, Power(7.23f, 2.35f), 0.01f); EXPECT_NEAR(80890.20, Power(26.21, 3.46), 0.01); EXPECT_NEAR((long double)340439729893056.21, Power((long double)53.45, (long double)8.41), 0.4); } TEST(MathCoreSuite, PowerSpecialCases) { EXPECT_FLOAT_EQ(1.0f, Power(1.0f, 0.0f)); EXPECT_FLOAT_EQ(0.0f, Power(0.0f, 1.0f)); EXPECT_FLOAT_EQ(1.0f, Power(0.0f, 0.0f)); } TEST(MathCoreSuite, SquareRootGeneral) { EXPECT_EQ(0.0f, SquareRoot(0.0f)); EXPECT_FLOAT_EQ(3.0f, SquareRoot(9.0f)); EXPECT_NEAR(2.28, SquareRoot(5.20), 0.01); EXPECT_NEAR((long double)773.11, SquareRoot((long double)597695.0), 0.01); } TEST(MathCoreSuite, SquareRootNegative) { EXPECT_NO_THROW(SquareRoot(-1.0f)); EXPECT_NO_THROW(SquareRoot(-0.01f)); } TEST(MathCoreSuite, ModulusGeneral) { EXPECT_EQ(-5, Modulus(-5, 9)); EXPECT_FLOAT_EQ(1.8f, Modulus(9.0f, 2.4f)); EXPECT_NEAR(0.1, Modulus(5.20, 1.02), 0.01); EXPECT_NEAR((long double)170.84, Modulus((long double)597695.0, (long double)214.32), 0.01); } TEST(MathCoreSuite, ModulusSpecialCases) { EXPECT_NO_THROW(Modulus(1, 0)); EXPECT_EQ(0, Modulus(0, 1)); EXPECT_NO_THROW(Modulus(0, 0)); } TEST(MathCoreSuite, FactorialGeneral) { EXPECT_EQ(1, Factorial(0)); EXPECT_EQ(1, Factorial(1)); EXPECT_EQ(24, Factorial(4)); EXPECT_EQ(479001600, Factorial(12)); //EXPECT_EQ(243902008176640000, Factorial(20)); // Overflow Issues }
23.485981
97
0.68842
XenonicDev
6fc6e4cfb9f36f5eb8fa56104d1872f9014380dd
8,655
cpp
C++
src/server/safs/filtersafs.cpp
jvirkki/heliod
efdf2d105e342317bd092bab2d727713da546174
[ "BSD-3-Clause" ]
13
2015-10-09T05:59:20.000Z
2021-11-12T10:38:51.000Z
src/server/safs/filtersafs.cpp
JamesLinus/heliod
efdf2d105e342317bd092bab2d727713da546174
[ "BSD-3-Clause" ]
null
null
null
src/server/safs/filtersafs.cpp
JamesLinus/heliod
efdf2d105e342317bd092bab2d727713da546174
[ "BSD-3-Clause" ]
6
2016-05-23T10:53:29.000Z
2019-12-13T17:57:32.000Z
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * * THE BSD LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * filtersafs.cpp: SAFs related to NSAPI filters * * Chris Elving */ #include "base/util.h" #include "base/vs.h" #include "frame/log.h" #include "frame/object.h" #include "frame/filter.h" #include "safs/dbtsafs.h" #include "safs/filtersafs.h" // Names of the SAFs as they should appear in log messages #define INSERT_FILTER "insert-filter" #define REMOVE_FILTER "remove-filter" #define INIT_FILTER_ORDER "init-filter-order" /* ------------------------ filter_init_directive ------------------------- */ static int filter_init_directive(const directive *dir, VirtualServer *incoming, const VirtualServer *current) { // Cache a const Filter * in the pblock if possible const char *name = pblock_findkeyval(pb_key_filter, dir->param.pb); if (name) { const Filter *filter = filter_find(name); if (filter) pblock_kvinsert(pb_key_magnus_internal, (const char *)&filter, sizeof(filter), dir->param.pb); } return REQ_PROCEED; } /* ----------------------------- find_filter ------------------------------ */ static inline const Filter *find_filter(pblock *pb, Session *sn, Request *rq) { const Filter *filter; // Look for a cached const Filter * const Filter **pfilter = (const Filter **)pblock_findkeyval(pb_key_magnus_internal, pb); if (pfilter) { filter = *pfilter; PR_ASSERT(filter != NULL); return filter; } // No cached const Filter *, find the filter name const char *name = pblock_findkeyval(pb_key_filter, pb); if (!name) { log_error(LOG_MISCONFIG, pblock_findkeyval(pb_key_fn, pb), sn, rq, XP_GetAdminStr(DBT_NeedFilter)); return NULL; } // Find the const Filter * with the specified name (this is slow) filter = filter_find(name); if (!filter) { log_error(LOG_MISCONFIG, pblock_findkeyval(pb_key_fn, pb), sn, rq, XP_GetAdminStr(DBT_CantFindFilterX), name); return NULL; } return filter; } /* ---------------------------- insert_filter ----------------------------- */ int insert_filter(pblock *pb, Session *sn, Request *rq) { const Filter *filter = find_filter(pb, sn, rq); if (!filter) return REQ_ABORTED; int rv = filter_insert(sn->csd, pb, sn, rq, NULL, filter); if (rv == REQ_PROCEED) { ereport(LOG_VERBOSE, "inserted filter %s", filter_name(filter)); } else if (rv == REQ_NOACTION) { ereport(LOG_VERBOSE, "did not insert filter %s", filter_name(filter)); } else { log_error(LOG_WARN, INSERT_FILTER, sn, rq, XP_GetAdminStr(DBT_ErrorInsertingFilterX), filter_name(filter)); } return rv; } /* ---------------------------- remove_filter ----------------------------- */ int remove_filter(pblock *pb, Session *sn, Request *rq) { const Filter *filter = find_filter(pb, sn, rq); if (!filter) return REQ_ABORTED; int rv = REQ_NOACTION; if (sn->csd && sn->csd_open == 1) rv = filter_remove(sn->csd, filter); return rv; } /* ------------------------ validate_filter_order ------------------------- */ static void validate_filter_order(const Filter *filter, int order) { if (FILTER_ORDER_CLASS(filter->order) != FILTER_ORDER_CLASS(order)) { log_error(LOG_WARN, INIT_FILTER_ORDER, NULL, NULL, XP_GetAdminStr(DBT_InvalidOrderForX), filter->name); } } /* -------------------------- init_filter_order --------------------------- */ int init_filter_order(pblock *pb, Session *sn, Request *rq) { // Get the list of filters to define the filter order for char *filters = pblock_findval("filters", pb); if (!filters) { pblock_nvinsert("error", XP_GetAdminStr(DBT_NeedFilters), pb); return REQ_ABORTED; } // Parse the list of filters int order = FILTER_TOPMOST; char *lasts; char *name = util_strtok(filters, ", \t", &lasts); while (name) { Filter *filter; if (*name == '(') { // Handle filter group. The relative order of filters within the // '('- and ')'-delimited filter group doesn't matter. // Skip past the opening '(' name++; // Handle all the filters in the group int group_order = order; while (name) { if (*name) { // Remove any closing ')' from the filter name char *paren = NULL; if (name[strlen(name) - 1] == ')') { paren = &name[strlen(name) - 1]; *paren = '\0'; } // Handle a filter within the group filter = (Filter *)filter_find(name); if (filter) { if (filter->order >= order) { validate_filter_order(filter, order - 1); filter->order = order - 1; } if (filter->order < group_order) group_order = filter->order; } else { log_error(LOG_MISCONFIG, INIT_FILTER_ORDER, sn, rq, XP_GetAdminStr(DBT_CannotOrderNonexistentFilterX), name); } // Check for end of filter group if (paren) { *paren = ')'; break; } } name = util_strtok(NULL, ", \t", &lasts); } if (!name) { log_error(LOG_MISCONFIG, INIT_FILTER_ORDER, sn, rq, XP_GetAdminStr(DBT_FiltersMissingClosingParen)); } order = group_order; } else { // Handle individual filter filter = (Filter *)filter_find(name); if (filter) { if (filter->order >= order) { validate_filter_order(filter, order - 1); filter->order = order - 1; } if (filter->order < order) order = filter->order; } else { log_error(LOG_MISCONFIG, INIT_FILTER_ORDER, sn, rq, XP_GetAdminStr(DBT_CannotOrderNonexistentFilterX), name); } } // Next filter name = util_strtok(NULL, ", \t", &lasts); } return REQ_PROCEED; } /* --------------------------- filtersafs_init ---------------------------- */ PRStatus filtersafs_init(void) { // Call filter_init_vs_directive() to cache the const Filter * for each // insert-filter and remove-filter directive vs_directive_register_cb(insert_filter, filter_init_directive, 0); vs_directive_register_cb(remove_filter, filter_init_directive, 0); return PR_SUCCESS; }
33.677043
109
0.570422
jvirkki
6fd3d114bf81b64d43165668d4ca94f6e752bce5
539
cpp
C++
Pair_Inheritance/money.cpp
w1ldy0uth/OOP_VSU_labs
21a13abccb6bf267e012c6aeaea3bc2148f1eb41
[ "MIT" ]
1
2021-09-20T20:37:14.000Z
2021-09-20T20:37:14.000Z
Pair_Inheritance/money.cpp
w1ldy0uth/OOP_VSU_labs
21a13abccb6bf267e012c6aeaea3bc2148f1eb41
[ "MIT" ]
null
null
null
Pair_Inheritance/money.cpp
w1ldy0uth/OOP_VSU_labs
21a13abccb6bf267e012c6aeaea3bc2148f1eb41
[ "MIT" ]
null
null
null
#include "money.h" Money Money::operator/(int val) { Money res; int t =a * 100 + b; t /= val; res.a = t / 100; res.b = t%100; return res; } int Money::operator/(const Money& obj) { return (a*100+b)/(obj.a*100+obj.b); } void Money::norm() { if (b >= 100) { a = a + b / 100; b = b % 100; } if (b < 0) { b += 100; a -= 1; } } std::ostream& operator<<(std::ostream& out, Money obj) { out << obj.a << " руб. " << obj.b << " коп.\n"; return out; }
14.567568
54
0.445269
w1ldy0uth
6fd4f9df67eaaae02c4bad0b328741e36348eb7c
291
cpp
C++
src/agent.cpp
kaidokert/MosquitoBorneDisease
b3584f12a9c3be2907360152c04032b213f19cd1
[ "BSD-3-Clause" ]
null
null
null
src/agent.cpp
kaidokert/MosquitoBorneDisease
b3584f12a9c3be2907360152c04032b213f19cd1
[ "BSD-3-Clause" ]
8
2018-11-13T14:33:26.000Z
2018-11-23T18:01:38.000Z
src/agent.cpp
kaidokert/MosquitoBorneDisease
b3584f12a9c3be2907360152c04032b213f19cd1
[ "BSD-3-Clause" ]
2
2019-08-05T07:21:28.000Z
2019-08-23T06:24:23.000Z
/* # Sub-module containing agent functions # # This file is part of SMosMod. # Copyright (c) 2017-2018, Imperial College London # For licensing information, see the LICENSE file distributed with the SMosMod # software package. */ #include "agent.hpp" Agent::Agent(double a) : age(a) {}
22.384615
79
0.725086
kaidokert
6fd6ece4a9cbb2847937978c423e9211904afbd8
2,976
hpp
C++
apps/openmw/mwgui/inventorywindow.hpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
apps/openmw/mwgui/inventorywindow.hpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
apps/openmw/mwgui/inventorywindow.hpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
#ifndef MGUI_Inventory_H #define MGUI_Inventory_H #include "../mwrender/characterpreview.hpp" #include "windowpinnablebase.hpp" #include "widgets.hpp" #include "mode.hpp" namespace MWGui { class ItemView; class SortFilterItemModel; class TradeItemModel; class DragAndDrop; class ItemModel; class InventoryWindow : public WindowPinnableBase { public: InventoryWindow(DragAndDrop* dragAndDrop); virtual void open(); void doRenderUpdate(); /// start trading, disables item drag&drop void setTrading(bool trading); void onFrame(); void pickUpObject (MWWorld::Ptr object); MWWorld::Ptr getAvatarSelectedItem(int x, int y); void rebuildAvatar() { mPreview->rebuild(); } SortFilterItemModel* getSortFilterModel(); TradeItemModel* getTradeModel(); ItemModel* getModel(); void updateItemView(); void updatePlayer(); void useItem(const MWWorld::Ptr& ptr); void setGuiMode(GuiMode mode); private: DragAndDrop* mDragAndDrop; bool mPreviewDirty; bool mPreviewResize; int mSelectedItem; MWWorld::Ptr mPtr; MWGui::ItemView* mItemView; SortFilterItemModel* mSortModel; TradeItemModel* mTradeModel; MyGUI::Widget* mAvatar; MyGUI::ImageBox* mAvatarImage; MyGUI::TextBox* mArmorRating; Widgets::MWDynamicStat* mEncumbranceBar; MyGUI::Widget* mLeftPane; MyGUI::Widget* mRightPane; MyGUI::Button* mFilterAll; MyGUI::Button* mFilterWeapon; MyGUI::Button* mFilterApparel; MyGUI::Button* mFilterMagic; MyGUI::Button* mFilterMisc; MWWorld::Ptr mSkippedToEquip; GuiMode mGuiMode; int mLastXSize; int mLastYSize; std::auto_ptr<MWRender::InventoryPreview> mPreview; bool mTrading; void onItemSelected(int index); void onItemSelectedFromSourceModel(int index); void onBackgroundSelected(); void sellItem(MyGUI::Widget* sender, int count); void dragItem(MyGUI::Widget* sender, int count); void onWindowResize(MyGUI::Window* _sender); void onFilterChanged(MyGUI::Widget* _sender); void onAvatarClicked(MyGUI::Widget* _sender); void onPinToggled(); void onTitleDoubleClicked(); void updateEncumbranceBar(); void notifyContentChanged(); void adjustPanes(); /// Unequips mSelectedItem, if it is equipped, and then updates mSelectedItem in case it was re-stacked void ensureSelectedItemUnequipped(); }; } #endif // Inventory_H
25.878261
115
0.589718
Bodillium
6fda95da7513c71b2424519b6f8a5a6367b4cef7
3,243
cpp
C++
Acceleration/memcached/hls/sources/hashTable/memRead.cpp
pooyaww/Vivado_HLS_Samples
6dc48bded1fc577c99404fc99c5089ae7279189a
[ "BSD-3-Clause" ]
326
2016-07-06T01:50:43.000Z
2022-03-31T21:50:19.000Z
Acceleration/memcached/hls/sources/hashTable/memRead.cpp
asicguy/HLx_Examples
249406bf7718c33d10a837ddd2ee71a683d481e8
[ "BSD-3-Clause" ]
10
2017-04-05T16:02:19.000Z
2021-06-09T14:26:40.000Z
Acceleration/memcached/hls/sources/hashTable/memRead.cpp
asicguy/HLx_Examples
249406bf7718c33d10a837ddd2ee71a683d481e8
[ "BSD-3-Clause" ]
192
2016-08-31T09:15:18.000Z
2022-03-01T11:28:12.000Z
/************************************************ Copyright (c) 2016, Xilinx, 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. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.// Copyright (c) 2015 Xilinx, Inc. ************************************************/ #include "../globals.h" void memRead(stream<hashTableInternalWord> &cc2memRead, stream<internalMdWord> &cc2memReadMd, stream<memCtrlWord> &memRdCtrl, stream<hashTableInternalWord> &memRd2comp, stream<internalMdWord> &memRd2compMd) { #pragma HLS INLINE off #pragma HLS pipeline II=1 enable_flush memCtrlWord memData = {0, 0}; hashTableInternalWord inData = {0, 0, 0}; internalMdWord inDataMd = {0, 0, 0}; static enum mrState {MEMRD_IDLE, MEMRD_STREAM} memRdState; switch (memRdState) { case MEMRD_IDLE: { if (!cc2memReadMd.empty() && !cc2memRead.empty()) { cc2memReadMd.read(inDataMd); cc2memRead.read(inData); if (inDataMd.operation != 8) { //ap_uint<7> tempAddress = inDataMd.metadata.range(noOfHashTableEntries + 4, 8); ap_uint<32> tempAddress = inDataMd.metadata; memData.address.range(noOfHashTableEntries - 1, 3) = tempAddress.range(6, 0); memData.count = inDataMd.keyLength/16; if (inDataMd.keyLength > (memData.count*16)) memData.count += 2; else memData.count += 1; memRdCtrl.write(memData); } if (inDataMd.keyLength <= 16) { ap_uint<64*words2aggregate> tempData = 0; tempData.range((inDataMd.keyLength*8) - 1, 0) = inData.data.range((inDataMd.keyLength*8) - 1, 0); inData.data = tempData; } memRd2comp.write(inData); memRd2compMd.write(inDataMd); if (inData.EOP == 0) memRdState = MEMRD_STREAM; } break; } case MEMRD_STREAM: { cc2memRead.read(inData); memRd2comp.write(inData); if (inData.EOP == 1) memRdState = MEMRD_IDLE; break; } } }
39.54878
208
0.714154
pooyaww
6fdc5403627b016de97575f7b628f60fa2c16412
1,486
cpp
C++
src/ImageWriter.cpp
iaddis/milkdrop2020
9354242ccf17909be7e9ab2f140d8508030bc3b1
[ "MIT" ]
13
2021-03-07T01:57:37.000Z
2022-03-08T05:45:06.000Z
src/ImageWriter.cpp
iaddis/milkdrop2020
9354242ccf17909be7e9ab2f140d8508030bc3b1
[ "MIT" ]
1
2021-02-13T20:16:06.000Z
2021-03-22T18:42:58.000Z
src/ImageWriter.cpp
iaddis/milkdrop2020
9354242ccf17909be7e9ab2f140d8508030bc3b1
[ "MIT" ]
4
2021-03-27T03:23:31.000Z
2022-01-24T00:38:07.000Z
//#define STB_IMAGE_WRITE_STATIC #define STB_IMAGE_WRITE_IMPLEMENTATION #include "../external/stb/stb_image_write.h" #include "ImageWriter.h" #include <string> #include "path.h" bool ImageWriteToPNG(const std::string &path, const uint32_t *data, int width, int height) { int pitch = width * sizeof(data[0]); // stbi_write_force_png_filter = 0; // stbi_write_png_compression_level = 1; return stbi_write_png( path.c_str(), width, height, 4, data, pitch ) != 0; } bool ImageWriteToBMP(const std::string &path, const uint32_t *data, int width, int height) { // int pitch = width * sizeof(data[0]); return stbi_write_bmp( path.c_str(), width, height, 4, data ) != 0; } bool ImageWriteToTGA(const std::string &path, const uint32_t *data, int width, int height) { return stbi_write_tga( path.c_str(), width, height, 4, data ) != 0; } bool ImageWriteToHDR(const std::string &path, const float *data, int width, int height) { return stbi_write_hdr( path.c_str(), width, height, 4, data ) != 0; } bool ImageWriteToFile(const std::string &path, const uint32_t *data, int width, int height) { std::string ext = PathGetExtensionLower(path); if (ext == ".tga") { return ImageWriteToTGA(path, data, width, height); } if (ext == ".png") { return ImageWriteToPNG(path, data, width, height); } if (ext == ".bmp") { return ImageWriteToBMP(path, data, width, height); } return false; }
24.766667
91
0.662853
iaddis
6fe23e0207021da283b5b2934bcc1f0f5b52de59
988
cpp
C++
src/vnx_keyvalue_server.cpp
madMAx43v3r/vnx-keyvalue
dbb28a2494c12741ba6ce14c579bc5973981d5ac
[ "MIT" ]
1
2021-09-11T04:07:29.000Z
2021-09-11T04:07:29.000Z
src/vnx_keyvalue_server.cpp
vashil211/vnx-keyvalue
dbb28a2494c12741ba6ce14c579bc5973981d5ac
[ "MIT" ]
1
2021-06-13T16:13:54.000Z
2021-06-13T16:13:54.000Z
src/vnx_keyvalue_server.cpp
madMAx43v3r/vnx-keyvalue
dbb28a2494c12741ba6ce14c579bc5973981d5ac
[ "MIT" ]
2
2021-06-10T18:10:03.000Z
2021-06-12T05:46:00.000Z
/* * vnx_keyvalue_server.cpp * * Created on: Mar 22, 2020 * Author: mad */ #include <vnx/keyvalue/Server.h> #include <vnx/vnx.h> #include <vnx/Terminal.h> #include <vnx/Server.h> int main(int argc, char** argv) { std::map<std::string, std::string> options; options["s"] = "server"; options["server"] = "server name"; options["n"] = "name"; options["name"] = "collection name"; vnx::init("vnx_keyvalue_server", argc, argv, options); std::string server_name = "StorageServer"; vnx::read_config("server", server_name); { vnx::Handle<vnx::Terminal> terminal = new vnx::Terminal("Terminal"); terminal.start_detached(); } { vnx::Handle<vnx::Server> server = new vnx::Server("Server", vnx::Endpoint::from_url(".vnx_keyvalue_server.sock")); server.start_detached(); } { vnx::Handle<vnx::keyvalue::Server> module = new vnx::keyvalue::Server(server_name); vnx::read_config("name", module->collection); module.start_detached(); } vnx::wait(); }
21.478261
116
0.663968
madMAx43v3r
6fe36be835bebb48bbae0b9c8e24bf76d2cdca23
1,177
cpp
C++
9.File Handling/i-Design/2/User.cpp
Concept-Team/e-box-UTA018
a6caf487c9f27a5ca30a00847ed49a163049f67e
[ "MIT" ]
26
2021-03-17T03:15:22.000Z
2021-06-09T13:29:41.000Z
9.File Handling/i-Design/2/User.cpp
Servatom/e-box-UTA018
a6caf487c9f27a5ca30a00847ed49a163049f67e
[ "MIT" ]
6
2021-03-16T19:04:05.000Z
2021-06-03T13:41:04.000Z
9.File Handling/i-Design/2/User.cpp
Concept-Team/e-box-UTA018
a6caf487c9f27a5ca30a00847ed49a163049f67e
[ "MIT" ]
42
2021-03-17T03:16:22.000Z
2021-06-14T21:11:20.000Z
#include<iostream> #include<string> #include<stdio.h> #include<fstream> #include<list> #include<iterator> #include<sstream> using namespace std; class User{ private: string name; string username; string password; string contactnumber; public: User(){} User(string name, string username, string password, string contactnumber){ this->name = name; this->username = username; this->password = password; this->contactnumber = contactnumber; } void setName(string name){ this->name = name; } void setUsername(string uname){ this->username = uname; } void setPassword(string pass){ this->password = pass; } void setContactNumber(string connum){ this->contactnumber = connum; } string getName(){ return name; } string getUsername(){ return username; } string getPassword(){ return password; } string getContactNumber(){ return contactnumber; } };
24.520833
82
0.540357
Concept-Team
6fe38eaf77b861677540d0680f3905e2307a1ef7
801
cpp
C++
src/index/ranker/ranker_factory.cpp
saq7/MeTA
0392964c1cdc073ae5123f7d64affdc4105acc4f
[ "MIT" ]
null
null
null
src/index/ranker/ranker_factory.cpp
saq7/MeTA
0392964c1cdc073ae5123f7d64affdc4105acc4f
[ "MIT" ]
null
null
null
src/index/ranker/ranker_factory.cpp
saq7/MeTA
0392964c1cdc073ae5123f7d64affdc4105acc4f
[ "MIT" ]
1
2021-09-06T06:08:38.000Z
2021-09-06T06:08:38.000Z
/** * @file ranker_factory.cpp * @author Chase Geigle */ #include "cpptoml.h" #include "index/ranker/all.h" #include "index/ranker/ranker_factory.h" namespace meta { namespace index { template <class Ranker> void ranker_factory::reg() { add(Ranker::id, make_ranker<Ranker>); } ranker_factory::ranker_factory() { // built-in rankers reg<absolute_discount>(); reg<dirichlet_prior>(); reg<jelinek_mercer>(); reg<okapi_bm25>(); reg<pivoted_length>(); } std::unique_ptr<ranker> make_ranker(const cpptoml::table& config) { auto function = config.get_as<std::string>("method"); if (!function) throw ranker_factory::exception{ "ranking-function required to construct a ranker"}; return ranker_factory::get().create(*function, config); } } }
19.536585
65
0.679151
saq7
6fe831bce94053dac21d5d4c5d9aaa44fd35b756
278
cpp
C++
Programmers/MidWord.cpp
YEAjiJUNG/AlgorithmPractice
720abd9bb3bf1eeadf57402379fdf30921f7c333
[ "Apache-2.0" ]
1
2021-05-21T02:23:38.000Z
2021-05-21T02:23:38.000Z
Programmers/MidWord.cpp
YEAjiJUNG/AlgorithmPractice
720abd9bb3bf1eeadf57402379fdf30921f7c333
[ "Apache-2.0" ]
null
null
null
Programmers/MidWord.cpp
YEAjiJUNG/AlgorithmPractice
720abd9bb3bf1eeadf57402379fdf30921f7c333
[ "Apache-2.0" ]
null
null
null
#include <string> #include <vector> using namespace std; string solution(string s) { string answer = ""; if(s.size() % 2 == 0){ answer += s[s.size()/2 -1]; answer += s[s.size()/2]; } else{ answer = s[s.size()/2]; } return answer; }
16.352941
35
0.507194
YEAjiJUNG
6fec4faf907996fac4d71b4ecf1a61147969ef04
4,863
cpp
C++
osal/mpp_platform.cpp
Fruit-Pi/mpp
dd7097fbab86eeed807e177620212847a9bc8f70
[ "Apache-2.0" ]
312
2016-12-26T12:32:03.000Z
2022-03-29T13:37:59.000Z
osal/mpp_platform.cpp
Fruit-Pi/mpp
dd7097fbab86eeed807e177620212847a9bc8f70
[ "Apache-2.0" ]
271
2017-01-12T03:59:31.000Z
2022-03-31T02:26:45.000Z
osal/mpp_platform.cpp
Fruit-Pi/mpp
dd7097fbab86eeed807e177620212847a9bc8f70
[ "Apache-2.0" ]
195
2016-12-01T07:22:01.000Z
2022-03-30T23:09:00.000Z
/* * Copyright 2015 Rockchip Electronics Co. LTD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define MODULE_TAG "mpp_platform" #include <string.h> #include "mpp_env.h" #include "mpp_log.h" #include "mpp_common.h" #include "mpp_platform.h" #include "mpp_service.h" static MppKernelVersion check_kernel_version(void) { static const char *kernel_version_path = "/proc/version"; MppKernelVersion version = KERNEL_UNKNOWN; FILE *fp = NULL; char buf[32]; if (access(kernel_version_path, F_OK | R_OK)) return version; fp = fopen(kernel_version_path, "rb"); if (fp) { size_t len = fread(buf, 1, sizeof(buf) - 1, fp); char *pos = NULL; buf[len] = '\0'; pos = strstr(buf, "Linux version "); if (pos) { RK_S32 major = 0; RK_S32 minor = 0; RK_S32 last = 0; RK_S32 count = 0; pos += 14; count = sscanf(pos, "%d.%d.%d ", &major, &minor, &last); if (count >= 2 && major > 0 && minor > 0) { if (major == 3) version = KERNEL_3_10; else if (major == 4) { version = KERNEL_4_4; if (minor >= 19) version = KERNEL_4_19; } } } fclose(fp); } return version; } class MppPlatformService { private: // avoid any unwanted function MppPlatformService(); ~MppPlatformService() {}; MppPlatformService(const MppPlatformService &); MppPlatformService &operator=(const MppPlatformService &); MppIoctlVersion ioctl_version; MppKernelVersion kernel_version; RK_U32 vcodec_type; RK_U32 hw_ids[32]; MppServiceCmdCap mpp_service_cmd_cap; const MppSocInfo *soc_info; const char *soc_name; public: static MppPlatformService *get_instance() { static MppPlatformService instance; return &instance; } MppIoctlVersion get_ioctl_version(void) { return ioctl_version; }; MppKernelVersion get_kernel_version(void) { return kernel_version; }; const char *get_soc_name() { return soc_name; }; MppServiceCmdCap *get_mpp_service_cmd_cap() { return &mpp_service_cmd_cap; }; RK_U32 get_hw_id(RK_S32 client_type); }; MppPlatformService::MppPlatformService() : ioctl_version(IOCTL_MPP_SERVICE_V1), kernel_version(KERNEL_UNKNOWN), vcodec_type(0), soc_info(NULL), soc_name(NULL) { /* judge vdpu support version */ MppServiceCmdCap *cap = &mpp_service_cmd_cap; /* default value */ cap->support_cmd = 0; cap->query_cmd = MPP_CMD_QUERY_BASE + 1; cap->init_cmd = MPP_CMD_INIT_BASE + 1; cap->send_cmd = MPP_CMD_SEND_BASE + 1; cap->poll_cmd = MPP_CMD_POLL_BASE + 1; cap->ctrl_cmd = MPP_CMD_CONTROL_BASE + 0; mpp_env_get_u32("mpp_debug", &mpp_debug, 0); /* read soc name */ soc_name = mpp_get_soc_name(); soc_info = mpp_get_soc_info(); if (soc_info->soc_type == ROCKCHIP_SOC_AUTO) mpp_log("can not found match soc name: %s\n", soc_name); ioctl_version = IOCTL_VCODEC_SERVICE; if (mpp_get_mpp_service_name()) { ioctl_version = IOCTL_MPP_SERVICE_V1; check_mpp_service_cap(&vcodec_type, hw_ids, cap); } kernel_version = check_kernel_version(); vcodec_type = soc_info->vcodec_type; } RK_U32 MppPlatformService::get_hw_id(RK_S32 client_type) { RK_U32 hw_id = 0; if (vcodec_type & (1 << client_type)) hw_id = hw_ids[client_type]; return hw_id; } MppIoctlVersion mpp_get_ioctl_version(void) { return MppPlatformService::get_instance()->get_ioctl_version(); } MppKernelVersion mpp_get_kernel_version(void) { return MppPlatformService::get_instance()->get_kernel_version(); } RK_U32 mpp_get_2d_hw_flag(void) { RK_U32 flag = 0; if (!access("/dev/rga", F_OK)) flag |= HAVE_RGA; if (!access("/dev/iep", F_OK)) flag |= HAVE_IEP; return flag; } const MppServiceCmdCap *mpp_get_mpp_service_cmd_cap(void) { return MppPlatformService::get_instance()->get_mpp_service_cmd_cap(); } RK_U32 mpp_get_client_hw_id(RK_S32 client_type) { return MppPlatformService::get_instance()->get_hw_id(client_type); }
27.788571
84
0.644047
Fruit-Pi
6ff5413513d9f236e76309c83167a7ae1242665a
1,503
hpp
C++
HW05/hw05.hpp
MetalheadKen/NTUST-Parallel-Course
4a4e726a5220eaf7403375b61cf6ce8a7cd9cbb9
[ "MIT" ]
null
null
null
HW05/hw05.hpp
MetalheadKen/NTUST-Parallel-Course
4a4e726a5220eaf7403375b61cf6ce8a7cd9cbb9
[ "MIT" ]
null
null
null
HW05/hw05.hpp
MetalheadKen/NTUST-Parallel-Course
4a4e726a5220eaf7403375b61cf6ce8a7cd9cbb9
[ "MIT" ]
null
null
null
#pragma once #include <cstring> #include <cmath> #include "YoUtil.hpp" struct mygpu { YoUtil::GPU *gpu; cl::CommandQueue cmdQueue; cl::Device device; cl::Context context; cl::Program *program; cl::Buffer point_buf; cl::Buffer accum_buf; }; void prepareGPU(mygpu& gpu); void releaseGPU(mygpu& gpu); struct mydata { size_t size; cl_double *point; }; bool readPointCloud(const char *filename, mydata& data, mygpu& gpu); double centerPointCloudToOrigin(mydata &data, mygpu &gpu); struct accumulator { size_t *accum; size_t n_theta; size_t n_phi; size_t n_rho; cl_double rho_max; cl_double d_theta; cl_double d_phi; cl_double d_rho; }; void prepareAccumulator(accumulator& votes, const double rho_max, const size_t n_theta, const size_t n_phi, const size_t n_rho, mygpu& gpu); void releaseAccumulator(accumulator& votes); void houghTransform(const mydata &data, accumulator &votes, mygpu& gpu); // This struct should store resultant plane parameters in descending order struct houghPlanes { size_t votes; double theta; double phi; double rho; }; void identifyPlaneParameters(const accumulator &votes, houghPlanes &planes, mygpu& gpu); void releaseHoughPlanes(houghPlanes &planes); bool outputPtxFile(const mydata& data, const houghPlanes &results, const accumulator &votes, const char *outputCloudData, mygpu &gpu); void release(mydata& data);
24.241935
141
0.698603
MetalheadKen
b5008194f9a06527ecf6fe1cf98b96de0345d8a6
2,782
cpp
C++
app/src/main/jni/jniCalls/gestureClass.cpp
smkang99/openGL
321edc6b473cfdb33ad448fdf83fabb35707858f
[ "Apache-2.0" ]
null
null
null
app/src/main/jni/jniCalls/gestureClass.cpp
smkang99/openGL
321edc6b473cfdb33ad448fdf83fabb35707858f
[ "Apache-2.0" ]
null
null
null
app/src/main/jni/jniCalls/gestureClass.cpp
smkang99/openGL
321edc6b473cfdb33ad448fdf83fabb35707858f
[ "Apache-2.0" ]
null
null
null
// // Created by 15102 on 3/9/2020. // #include <jni.h> //#include "modelAssimp.h" #include <myJNIHelper.h> #include <modelAssimp.h> #ifdef __cplusplus extern "C" { #endif extern ModelAssimp *gAssimpObject; JNIEXPORT void JNICALL Java_com_example_hellojni_GestureClass_DoubleTapNative(JNIEnv *env, jobject instance) { if (gAssimpObject == NULL) { return; } gAssimpObject->DoubleTapAction(); } /** * one finger drag - compute normalized current position and normalized displacement * from previous position */ JNIEXPORT void JNICALL Java_com_example_hellojni_GestureClass_ScrollNative(JNIEnv *env, jobject instance, jfloat distanceX, jfloat distanceY, jfloat positionX, jfloat positionY) { if (gAssimpObject == NULL) { return; } // normalize movements on the screen wrt GL surface dimensions // invert dY to be consistent with GLES conventions float dX = (float) distanceX / gAssimpObject->GetScreenWidth(); float dY = -(float) distanceY / gAssimpObject->GetScreenHeight(); float posX = 2*positionX/ gAssimpObject->GetScreenWidth() - 1.; float posY = -2*positionY / gAssimpObject->GetScreenHeight() + 1.; posX = fmax(-1., fmin(1., posX)); posY = fmax(-1., fmin(1., posY)); gAssimpObject->ScrollAction(dX, dY, posX, posY); } /** * Pinch-and-zoom gesture: pass the change in scale to class' method */ JNIEXPORT void JNICALL Java_com_example_hellojni_GestureClass_ScaleNative(JNIEnv *env, jobject instance, jfloat scaleFactor) { if (gAssimpObject == NULL) { return; } gAssimpObject->ScaleAction((float) scaleFactor); } /** * Two-finger drag - normalize the distance moved wrt GLES surface size */ JNIEXPORT void JNICALL Java_com_example_hellojni_GestureClass_MoveNative(JNIEnv *env, jobject instance, jfloat distanceX, jfloat distanceY) { if (gAssimpObject == NULL) { return; } // normalize movements on the screen wrt GL surface dimensions // invert dY to be consistent with GLES conventions float dX = distanceX / gAssimpObject->GetScreenWidth(); float dY = -distanceY / gAssimpObject->GetScreenHeight(); gAssimpObject->MoveAction(dX, dY); } JNIEXPORT void JNICALL Java_com_example_hellojni_GestureClass_turnOffLight(JNIEnv *env, jobject thiz) { gAssimpObject->TurnOffLight(); // TODO: implement turnOffLight() } JNIEXPORT void JNICALL Java_com_example_hellojni_GestureClass_turnOnLight(JNIEnv *env, jobject thiz) { gAssimpObject->TurnOnLight(); // TODO: implement turnOnLight() } #ifdef __cplusplus } #endif
28.387755
89
0.670022
smkang99
b501c34433a2e60198711749c6b60b82f2520efc
471
cpp
C++
lintcode/besttimetobuyandsellstock.cpp
WIZARD-CXY/pl
22b7f5d81804f4e333d3cff6433364ba1a0ac7ef
[ "Apache-2.0" ]
1
2016-01-20T08:26:34.000Z
2016-01-20T08:26:34.000Z
lintcode/besttimetobuyandsellstock.cpp
WIZARD-CXY/pl
22b7f5d81804f4e333d3cff6433364ba1a0ac7ef
[ "Apache-2.0" ]
1
2015-10-21T05:38:17.000Z
2015-11-02T07:42:55.000Z
lintcode/besttimetobuyandsellstock.cpp
WIZARD-CXY/pl
22b7f5d81804f4e333d3cff6433364ba1a0ac7ef
[ "Apache-2.0" ]
null
null
null
class Solution { public: /** * @param prices: Given an integer array * @return: Maximum profit */ int maxProfit(vector<int> &prices) { // write your code here int minprice=INT_MAX; int res=0; for(auto price : prices){ minprice=min(minprice,price); int profit=price-minprice; res=max(profit,res); } return res; } };
19.625
44
0.477707
WIZARD-CXY
b504542f8702ec26723a813f4c76c73fa641682d
607
hpp
C++
source/pkgsrc/games/criticalmass/patches/patch-game_ParticleGroupManager.hpp
Scottx86-64/dotfiles-1
51004b1e2b032664cce6b553d2052757c286087d
[ "Unlicense" ]
1
2021-11-20T22:46:39.000Z
2021-11-20T22:46:39.000Z
source/pkgsrc/games/criticalmass/patches/patch-game_ParticleGroupManager.hpp
Scottx86-64/dotfiles-1
51004b1e2b032664cce6b553d2052757c286087d
[ "Unlicense" ]
null
null
null
source/pkgsrc/games/criticalmass/patches/patch-game_ParticleGroupManager.hpp
Scottx86-64/dotfiles-1
51004b1e2b032664cce6b553d2052757c286087d
[ "Unlicense" ]
null
null
null
$NetBSD: patch-game_ParticleGroupManager.hpp,v 1.1 2013/06/16 20:40:40 joerg Exp $ --- game/ParticleGroupManager.hpp.orig 2013-06-15 10:08:18.000000000 +0000 +++ game/ParticleGroupManager.hpp @@ -47,7 +47,7 @@ private: ParticleGroupManager &operator=(const ParticleGroupManager&); hash_map< - const string, ParticleGroup*, hash<const string>, equal_to<const string> > _particleGroupMap; + const string, ParticleGroup*, HASH_NAMESPACE::hash<const string>, equal_to<const string> > _particleGroupMap; list<ParticleGroup*> _particleGroupList; struct LinkedParticleGroup
43.357143
118
0.736409
Scottx86-64
b504a01594dae37b8379ab8d0546b9ba5b066487
2,858
hh
C++
src/ggl/MR_ApplyRule.hh
michaelapeterka/GGL
99e585b773ad8f33e39160d2cbd71c00e036fa37
[ "MIT" ]
20
2017-05-09T15:37:04.000Z
2021-11-24T10:51:02.000Z
src/ggl/MR_ApplyRule.hh
michaelapeterka/GGL
99e585b773ad8f33e39160d2cbd71c00e036fa37
[ "MIT" ]
2
2017-05-24T08:00:25.000Z
2017-05-24T08:01:01.000Z
src/ggl/MR_ApplyRule.hh
michaelapeterka/GGL
99e585b773ad8f33e39160d2cbd71c00e036fa37
[ "MIT" ]
7
2017-05-29T10:55:18.000Z
2020-12-04T14:24:51.000Z
#ifndef GGL_MR_APPLYRULE_HH_ #define GGL_MR_APPLYRULE_HH_ #include "sgm/Match_Reporter.hh" #include "ggl/Graph_Storage.hh" #include "ggl/Graph.hh" #include "ggl/RuleGraph.hh" #include <climits> namespace ggl { /*! @brief Graph Grammar Rule application for each reported match * * A sgm::Match_Reporter implementation that applies a graph grammar ggl::Rule * to a graph and generates the resulting graph. The new graph is added * to a specified container for further handling like storage or output. * The pattern graph has to be an instance of ggl::LeftSidePattern. * * @author Martin Mann (c) 2008 http://www.bioinf.uni-freiburg.de/~mmann/ * */ class MR_ApplyRule : public sgm::Match_Reporter { protected: //! the storage to that "reportHit(..)" adds the resulting graphs //! after the application of a rule to a matched target graph. Graph_Storage & storage; //! we apply undirected rules or not const bool undirectedRule; /*! if set to true, than all components of the Rules LeftSidePattern * are matched to an own target graph copy if two components map to * the same target graph. */ const bool addEachComponent; public: /*! Construction of a MR_ApplyRule object that adds the resulting * graphs to the given Graph_Storage object. * @param storage the Graph_Storage object to add the results to * @param addEachComponent if set to true, than all components of the * Rules LeftSidePattern are matched to an own target graph * copy if two components map to the same target graph. * NOTE: only important for rules with multi-component * LeftSidePattern! */ MR_ApplyRule( Graph_Storage & storage , const bool addEachComponent = false ); virtual ~MR_ApplyRule(); //! Applies the Rule represented by the pattern onto the matched //! subgraph of target and adds the resulting graph to the internal //! Graph_Storage object. //! NOTE: It is assumed that pattern is an instance of //! ggl::LeftSidePattern! //! @param pattern the pattern graph that was searched for //! @param target the graph the pattern was found within //! @param match contains the indices of the matched pattern nodes in //! the target graph. match[i] corresponds to the mapping of the i-th //! vertex in the pattern graph. virtual void reportHit ( const sgm::Pattern_Interface & pattern, const sgm::Graph_Interface & target, const sgm::Match & match ); }; //////////////////////////////////////////////////////////////////////////////// } // namespace ggl #include "ggl/MR_ApplyRule.icc" #endif /*MR_APPLYRULE_HH_*/
32.11236
83
0.644507
michaelapeterka
b504dc03621f5bbc2c9585a00ab2448c02992932
37,853
cpp
C++
URL.cpp
malord/prime
f0e8be99b7dcd482708b9c928322bc07a3128506
[ "MIT" ]
null
null
null
URL.cpp
malord/prime
f0e8be99b7dcd482708b9c928322bc07a3128506
[ "MIT" ]
null
null
null
URL.cpp
malord/prime
f0e8be99b7dcd482708b9c928322bc07a3128506
[ "MIT" ]
null
null
null
// Copyright 2000-2021 Mark H. P. Lord #include "URL.h" #include "Range.h" #include "StringUtils.h" #include "Templates.h" #include "TextEncoding.h" namespace Prime { inline StringView RebaseStringView(StringView view, const char* oldBase, const char* newBase) { return StringView(view.begin() - oldBase + newBase, view.end() - oldBase + newBase); } // // URLView // URLView::URLView() { } URLView::URLView(const URLView& copy) : _protocol(copy._protocol) , _host(copy._host) , _port(copy._port) , _path(copy._path) , _query(copy._query) , _fragment(copy._fragment) , _username(copy._username) , _password(copy._password) , _parameter(copy._parameter) { } URLView::URLView(const URL& url) { operator=(url); } URLView::URLView(StringView string, const ParseOptions& options) { parse(string, options); } URLView::URLView(const char* string, const ParseOptions& options) { parse(string, options); } URLView::URLView(const std::string& string, const ParseOptions& options) { parse(string, options); } const char* URLView::parseHostAndPort(const char* ptr, const char* end) { // Everything up to the next / is the "net_loc". const char* slash = std::find(ptr, end, '/'); _host = StringView(ptr, slash); ptr = slash; // If there's an '@' in there, it's the username and password. StringView::iterator at = std::find(_host.begin(), _host.end(), '@'); if (at != _host.end()) { _username = StringView(_host.begin(), at); _host = StringView(at + 1, _host.end()); // Anything following a : in the username is a password StringView::iterator password = std::find(_username.begin(), _username.end(), ':'); if (password != _username.end()) { _password = StringView(password + 1, _username.end()); _username = StringView(_username.begin(), password); } else { _password = StringView(); } } else { _username = StringView(); _password = StringView(); } // If there's a ':' in there, it's the port. StringView::iterator colon = std::find(_host.begin(), _host.end(), ':'); if (colon != _host.end()) { _port = StringView(colon + 1, _host.end()); _host = StringView(_host.begin(), colon); } else { _port = StringView(); } return ptr; } bool URLView::parse(StringView string, const ParseOptions& options) { // This is a slightly more liberal implementation of the parsing logic specified in RFC 1808. const char* begin = string.begin(); const char* ptr = begin; const char* end = string.end(); // // Extract the fragment // const char* fragment = std::find(ptr, end, '#'); if (fragment != end) { _fragment = StringView(fragment + 1, end); end = fragment; } else { _fragment = StringView(); } // // Extract the scheme (protocol) // bool foundScheme; const char* schemeBegin = ptr; static const char notSchemeChars[] = ":/\\#?;@"; static const char* notSchemeCharsEnd = notSchemeChars + PRIME_COUNTOF(notSchemeChars) - 1; while (ptr != end && std::find(notSchemeChars, notSchemeCharsEnd, *ptr) == notSchemeCharsEnd) { ++ptr; } if (ptr != end && *ptr == ':' && (options.getAllowProtocolWithoutLocation() || (end - ptr >= 3 && memcmp(ptr, "://", 3) == 0))) { _protocol = StringView(schemeBegin, ptr); foundScheme = true; ++ptr; } else { _protocol = StringView(); foundScheme = false; ptr = schemeBegin; } // // Extract the "net_loc" (RFC 1808) // if ((foundScheme || options.getAllowRelativeHosts() || options.getHostOnly()) && end - ptr >= 2 && strncmp(ptr, "//", 2) == 0) { ptr += 2; ptr = parseHostAndPort(ptr, end); } else if (options.getHostOnly()) { ptr = parseHostAndPort(ptr, end); } // // Extract the query // const char* query = std::find(ptr, end, '?'); if (query != end) { _query = StringView(query + 1, end); end = query; } else { _query = StringView(); } // // Extract the parameter // const char* param = std::find(ptr, end, ';'); if (param != end) { _parameter = StringView(param + 1, end); end = param; } else { _parameter = StringView(); } // // We're left with the path // _path = StringView(ptr, end); return true; } bool URLView::isEmpty() const { return _protocol.empty() && _username.empty() && _password.empty() && _host.empty() && _port.empty() && _path.empty() && _parameter.empty() && _query.empty() && _fragment.empty(); } StringView URLView::getPathWithoutSlash() const { StringView path = getPath(); if (!path.empty() && path[0] == '/') { path.remove_prefix(1); } return path; } std::string URLView::toString(const StringOptions& options) const { std::string temp; appendString(temp, options); return temp; } void URLView::toString(std::string& buffer, const StringOptions& options) const { buffer.resize(0); appendString(buffer, options); } void URLView::appendString(std::string& buffer, const StringOptions& options) const { size_t lengthWas = buffer.size(); if (!options.getResourceOnly() && !_protocol.empty()) { buffer += _protocol; buffer += ':'; } bool haveLocation = false; if (options.getResourceOnly()) { haveLocation = true; } else if (!_username.empty() || !_password.empty() || !_host.empty() || !_port.empty()) { haveLocation = true; buffer += "//"; if (!_username.empty()) { if (options.getDiscardCredentials()) { buffer += "..."; } else { buffer += getUsername(); } } if (!_password.empty()) { buffer += ':'; if (options.getDiscardCredentials()) { buffer += "..."; } else { buffer += getPassword(); } } if (!_username.empty() || !_password.empty()) { buffer += '@'; } buffer += _host; if (!_port.empty()) { buffer += ':'; buffer += _port; } } if (!_path.empty()) { if (haveLocation && (_path.empty() || _path[0] != '/')) { buffer += '/'; } buffer += _path; } if (!_parameter.empty()) { buffer += ';'; if (options.getDiscardQuery()) { buffer += "..."; } else { buffer += getParameter(); } } if (!_query.empty()) { buffer += '?'; if (options.getDiscardQuery()) { buffer += "..."; } else { buffer += _query; } } if (!options.getDiscardFragment() && !_fragment.empty()) { buffer += '#'; if (options.getDiscardQuery()) { buffer += "..."; } else { buffer += _fragment; } } for (size_t i = lengthWas; i < buffer.size(); ++i) { if (!IsURLLegal((unsigned char)buffer[i])) { char escaped[4]; StringFormat(escaped, sizeof(escaped), "%%%02x", (uint8_t)buffer[i]); buffer.replace(i, 1, escaped, 3); i += 2; } } } std::string URLView::getHostWithPort() const { std::string result; if (_port.empty()) { StringCopy(result, _host); } else { StringCopy(result, _host); result += ':'; StringAppend(result, _port); } return result; } bool URLView::hasLocation() const PRIME_NOEXCEPT { return !(StringIsEmpty(getUsername()) && StringIsEmpty(getPassword()) && _host.empty() && _port.empty()); } URLView URLView::getRoot() const { URLView root; root.setProtocol(getProtocol()); root.setUsername(getUsername()); root.setPassword(getPassword()); root.setHost(getHost()); root.setPort(getPort()); return root; } StringView URLView::getEncodedQuery(StringView name) const { return URLQueryParser::getQueryParameter(getQuery(), name); } std::vector<StringView> URLView::getEncodedQueryArray(StringView name) const { return URLQueryParser::getQueryParameters(getQuery(), name); } std::string URLView::getQuery(StringView name) const { return URLDecode(getEncodedQuery(name), URLDecodeFlagPlusesAsSpaces); } std::vector<std::string> URLView::getQueryArray(StringView name) const { std::vector<StringView> encoded = getEncodedQueryArray(name); std::vector<std::string> decoded(encoded.size()); for (size_t i = 0; i != encoded.size(); ++i) { StringCopy(decoded[i], encoded[i]); } return decoded; } StringView URLView::getEncodedParameter(StringView name) const { return URLQueryParser::getQueryParameter(getParameter(), name); } std::vector<StringView> URLView::getEncodedParameterArray(StringView name) const { return URLQueryParser::getQueryParameters(getParameter(), name); } std::string URLView::getParameter(StringView name) const { return URLDecode(getEncodedParameter(name), URLDecodeFlagPlusesAsSpaces); } std::vector<std::string> URLView::getParameterArray(StringView name) const { std::vector<StringView> encoded = getEncodedParameterArray(name); std::vector<std::string> decoded(encoded.size()); for (size_t i = 0; i != encoded.size(); ++i) { StringCopy(decoded[i], encoded[i]); } return decoded; } URLPath URLView::getPathComponents() const { return URLPath(getPath()); } URLDictionary URLView::getQueryComponents() const { URLDictionary result; URL::parseQueryString(result, getQuery()); return result; } // // URL // void URL::parseQueryString(URLDictionary& dictionary, StringView queryString) { URLQueryParser qs(queryString); URLQueryParser::Parameter qsp; while (qs.read(qsp)) { dictionary.add(URLDecode(qsp.name, URLDecodeFlagPlusesAsSpaces), URLDecode(qsp.value, URLDecodeFlagPlusesAsSpaces)); } } void URL::parseQueryString(Value::Dictionary& dictionary, StringView queryString) { URLQueryParser qs(queryString); URLQueryParser::Parameter qsp; while (qs.read(qsp)) { Value& value = dictionary.access(URLDecode(qsp.name, URLDecodeFlagPlusesAsSpaces)); if (value.isUndefined()) { value = URLDecode(qsp.value, URLDecodeFlagPlusesAsSpaces); } else { value.accessVector().push_back(URLDecode(qsp.value, URLDecodeFlagPlusesAsSpaces)); } } } std::string URL::buildQueryString(const URLDictionary& dictionary) { std::string buffer; for (size_t i = 0; i != dictionary.getSize(); ++i) { const std::string& name = dictionary.pair(i).first; const std::string& value = dictionary.pair(i).second; if (i > 0) { buffer += '&'; } URLEncodeAppend(buffer, name, URLEncodeFlagSpacesAsPluses); buffer += '='; URLEncodeAppend(buffer, value, URLEncodeFlagSpacesAsPluses); } return buffer; } std::string URL::buildQueryString(const Value::Dictionary& dictionary) { std::string buffer; for (size_t i = 0; i != dictionary.size(); ++i) { const std::string& name = dictionary.pair(i).first; const Value& value = dictionary.pair(i).second; if (i > 0) { buffer += '&'; } URLEncodeAppend(buffer, name, URLEncodeFlagSpacesAsPluses); buffer += '='; URLEncodeAppend(buffer, value.toString(), URLEncodeFlagSpacesAsPluses); } return buffer; } void URL::tidyPath(std::string& path) { // Make sure we never pop the leading '/' when removing supefluous slashes. const ptrdiff_t minNewPathSize = (path.empty() || path[0] != '/') ? 0 : 1; std::string::iterator ptr = path.begin() + minNewPathSize; // 6a. Remove all occurences of ./ for (;;) { while (ptr != path.end() && *ptr == '/') { ++ptr; } if (ptr == path.end()) { break; } if (*ptr == '.' && (ptr + 1) != path.end() && ptr[1] == '/') { path.erase(ptr, ptr + 2); ptr = path.begin() + minNewPathSize; } else { do { ++ptr; } while (ptr != path.end() && *ptr != '/'); } } // 6b. If the path ends with a . as the complete path segment, remove the . ptr = FindLastNot(path.begin(), path.end(), '/'); if (path.end() - ptr == 1 && *ptr == '.') { path.resize(path.size() - 1); } // 6c. Remove all occurences of segment/../ ptr = path.begin() + minNewPathSize; for (;;) { while (ptr != path.end() && *ptr == '/') { ++ptr; } if (ptr == path.end()) { break; } std::string::iterator start = ptr; do { ++ptr; } while (ptr != path.end() && *ptr != '/'); if (ptr == path.end()) { break; } if (ptr - start == 2 && start[0] == '.' && start[1] == '.') { continue; // Skip .. appearing at the start } do { ++ptr; } while (ptr != path.end() && *ptr == '/'); if (path.end() - ptr >= 3 && ptr[0] == '.' && ptr[1] == '.' && ptr[2] == '/') { path.erase(start, ptr + 3); ptr = path.begin() + minNewPathSize; } } // 6d. If the path ends with segment/.. then remove it ptr = FindLastNot(path.begin(), path.end(), '/'); if (path.end() - ptr == 2 && ptr[0] == '.' && ptr[1] == '.') { ptr = path.end() - 2; while (ptr > path.begin() + minNewPathSize && ptr[-1] == '/') { --ptr; } while (ptr > path.begin() + minNewPathSize && ptr[-1] != '/') { --ptr; } path.erase(ptr, path.end()); } } URL::URL() { } URL::URL(StringView string, const ParseOptions& options) : _storage(string.begin(), string.end()) { _view.parse(_storage, options); } URL::URL(const char* string, const ParseOptions& options) : _storage(string) { _view.parse(_storage, options); } URL::URL(const std::string& string, const ParseOptions& options) : _storage(string) { _view.parse(_storage, options); } #ifdef PRIME_COMPILER_RVALUEREF URL::URL(std::string&& string, const ParseOptions& options) : _storage(std::move(string)) { _view.parse(_storage, options); } #endif URL::URL(const URLView& view) { view.toString(_storage); _view.parse(_storage); } #ifdef PRIME_COMPILER_RVALUEREF URL::URL(URL&& other) { move(other); } #endif URL::URL(const URL& copy) : _storage(copy._storage) { _view.parse(_storage); } URL& URL::operator=(const URL& other) { if (this != &other) { const char* oldBase = other._storage.data(); _storage = other._storage; const char* newBase = _storage.data(); _view.setProtocol(RebaseStringView(other.getProtocol(), oldBase, newBase)); _view.setUsername(RebaseStringView(other.getUsername(), oldBase, newBase)); _view.setPassword(RebaseStringView(other.getPassword(), oldBase, newBase)); _view.setHost(RebaseStringView(other.getHost(), oldBase, newBase)); _view.setPort(RebaseStringView(other.getPort(), oldBase, newBase)); _view.setPath(RebaseStringView(other.getPath(), oldBase, newBase)); _view.setParameter(RebaseStringView(other.getParameter(), oldBase, newBase)); _view.setQuery(RebaseStringView(other.getQuery(), oldBase, newBase)); _view.setFragment(RebaseStringView(other.getFragment(), oldBase, newBase)); return *this; } return *this; } void URL::move(URL& other) { const char* oldBase = other._storage.data(); _storage.swap(other._storage); const char* newBase = _storage.data(); _view.setProtocol(RebaseStringView(other.getProtocol(), oldBase, newBase)); _view.setUsername(RebaseStringView(other.getUsername(), oldBase, newBase)); _view.setPassword(RebaseStringView(other.getPassword(), oldBase, newBase)); _view.setHost(RebaseStringView(other.getHost(), oldBase, newBase)); _view.setPort(RebaseStringView(other.getPort(), oldBase, newBase)); _view.setPath(RebaseStringView(other.getPath(), oldBase, newBase)); _view.setParameter(RebaseStringView(other.getParameter(), oldBase, newBase)); _view.setQuery(RebaseStringView(other.getQuery(), oldBase, newBase)); _view.setFragment(RebaseStringView(other.getFragment(), oldBase, newBase)); other._storage.resize(0); other._view.setProtocol(other._storage); other._view.setUsername(other._storage); other._view.setPassword(other._storage); other._view.setHost(other._storage); other._view.setPort(other._storage); other._view.setPath(other._storage); other._view.setParameter(other._storage); other._view.setQuery(other._storage); other._view.setFragment(other._storage); } #ifdef PRIME_COMPILER_RVALUEREF URL& URL::operator=(URL&& other) { if (&other != this) { move(other); } return *this; } #endif URL& URL::operator=(const URLView& view) { view.toString(_storage); _view.parse(_storage); return *this; } URL::URL(const URLBuilder& builder) { operator=(builder); } URL& URL::operator=(const URLBuilder& builder) { return operator=(builder.getView()); } bool URL::parse(StringView string, const ParseOptions& options) { StringCopy(_storage, string); return _view.parse(_storage, options); } bool URL::parse(const char* string, const ParseOptions& options) { StringCopy(_storage, string); return _view.parse(_storage, options); } bool URL::parse(const std::string& string, const ParseOptions& options) { _storage = string; return _view.parse(_storage, options); } #ifdef PRIME_COMPILER_RVALUEREF bool URL::parse(std::string&& string, const ParseOptions& options) { _storage.swap(string); return _view.parse(_storage, options); } #endif // We store the URL as a single string and a URLView in to that string, allowing us to pass only one memory // allocation around instead of many. The set functions could possibly avoid a memory allocation by replacing // the component of _storage then shuffling the other components along. I tried it, but corner cases (like // having to insert a ://, :, @, ;, ? etc) outweighed the slight potential gain of avoiding that allocation. URL& URL::updateFromView() { std::string temp; _view.toString(temp); _storage.swap(temp); _view.parse(_storage); return *this; } URL& URL::setProtocol(StringView protocol) { _view.setProtocol(protocol); return updateFromView(); } URL& URL::setHost(StringView host) { _view.setHost(host); return updateFromView(); } URL& URL::setPort(StringView port) { _view.setPort(port); return updateFromView(); } URL& URL::setPath(StringView path) { _view.setPath(path); return updateFromView(); } URL& URL::setQuery(StringView query) { _view.setQuery(query); return updateFromView(); } URL& URL::setFragment(StringView fragment) { _view.setFragment(fragment); return updateFromView(); } URL& URL::setUsername(StringView username) { _view.setUsername(username); return updateFromView(); } URL& URL::setPassword(StringView password) { _view.setPassword(password); return updateFromView(); } URL& URL::setParameter(StringView parameter) { _view.setParameter(parameter); return updateFromView(); } URL URL::resolve(const URLView& embedded) const { return resolve(_view, embedded); } URL URL::resolve(const URLView& base, const URLView& embedded) { // Implement section 4 of RFC 1808 // 1 if (base.isEmpty()) { return URL(embedded); } // 2a if (embedded.isEmpty()) { return URL(base); } // 2b if (!StringIsEmpty(embedded.getProtocol())) { return URL(embedded); } URLView result(embedded); std::string newPath; // needs to exist outside the scope where it's used // 2c result.setProtocol(base.getProtocol()); // 3 if (!embedded.hasLocation()) { result.setUsername(base.getUsername()); result.setPassword(base.getPassword()); result.setHost(base.getHost()); result.setPort(base.getPort()); // 5 if (StringIsEmpty(embedded.getPath())) { // 5 result.setPath(base.getPath()); // 5a if (StringIsEmpty(embedded.getParameter())) { result.setParameter(base.getParameter()); // 5b if (StringIsEmpty(embedded.getQuery())) { result.setQuery(base.getQuery()); } } } // 4 else if (embedded.getPath()[0] != '/') { StringCopy(newPath, base.getPath()); // 6 std::string::iterator ptr = FindLastNot(newPath.begin(), newPath.end(), '/'); newPath.replace(ptr, newPath.end(), embedded.getPath().begin(), embedded.getPath().end()); // 6a, 6b, 6c, 6d tidyPath(newPath); result.setPath(newPath); } } // 7 return URL(result); } URLPath URL::getPathComponents() const { return URLPath(getPath()); } void URL::setPathComponents(const URLPath& path) { setPath(path.toString()); } URLDictionary URL::getQueryComponents() const { URLDictionary result; URL::parseQueryString(result, getQuery()); return result; } void URL::setQueryComponents(const URLDictionary& query) { setQuery(URL::buildQueryString(query)); } // // URLQueryParser // StringView URLQueryParser::getQueryParameter(StringView queryString, StringView name) { URLQueryParser qs(queryString); Parameter parameter; while (qs.read(parameter)) { if (ASCIIEqualIgnoringCase(parameter.name, name)) { return parameter.value; } } return StringView(); } std::vector<StringView> URLQueryParser::getQueryParameters(StringView queryString, StringView name) { std::vector<StringView> values; URLQueryParser qs(queryString); Parameter parameter; while (qs.read(parameter)) { if (StringEndsWith(parameter.name, "[]")) { parameter.name = parameter.name.substr(0, parameter.name.size() - 2); } if (ASCIIEqualIgnoringCase(parameter.name, name)) { values.push_back(parameter.value); } } return values; } bool URLQueryParser::read(Parameter& parameter) { if (_ptr != _end) { // Find the next '&' or ';' - that's the limit of this one parameter. const char* amp = std::find(_ptr, _end, '&'); const char* semi = _semi ? std::find(_ptr, amp, ';') : amp; const char* next = amp < semi ? amp : semi; // Find the first '=', and that separates the name and the value. If we don't find it then the whole // thing between _ptr and next is a name. const char* eq = std::find(_ptr, next, '='); // URL spec says all whitespace should be ignored, but we only ignore it on either side of the // & or =. parameter.name = StringViewTrim(StringView(_ptr, eq)); if (eq != next) { ++eq; } parameter.value = StringViewTrim(StringView(eq, next)); // Skip the separator. _ptr = next; if (_ptr != _end) { ++_ptr; } return true; } return false; } // // URLBuilder // URLBuilder& URLBuilder::operator=(const URLBuilder& copy) { _protocol = copy._protocol; _host = copy._host; _port = copy._port; _path = copy._path; _query = copy._query; _fragment = copy._fragment; if (!copy._rare.get()) { _rare.reset(); } else { _rare.reset(new Rare(*copy._rare)); } return *this; } URLBuilder::URLBuilder(const URLView& view) { operator=(view); } URLBuilder::URLBuilder(const URL& url) { operator=(url); } void URLBuilder::setPassword(StringView password) { if (password.empty() && !_rare.get()) { return; } needRare(); StringCopy(_rare->password, password); } void URLBuilder::setUsername(StringView username) { if (username.empty() && !_rare.get()) { return; } needRare(); StringCopy(_rare->username, username); } void URLBuilder::setParameter(StringView parameter) { if (parameter.empty() && !_rare.get()) { return; } needRare(); StringCopy(_rare->parameter, parameter); } std::string URLBuilder::getHostWithPort() const { if (_port.empty()) { return _host; } return _host + ":" + _port; } void URLBuilder::needRare() { if (!_rare.get()) { _rare.reset(new Rare); } } bool URLBuilder::parse(StringView string, const ParseOptions& options) { URLView parser; if (!parser.parse(string, options)) { return false; } operator=(parser); return true; } URLBuilder& URLBuilder::operator=(const URLView& view) { StringCopy(_protocol, view.getProtocol()); StringCopy(_host, view.getHost()); StringCopy(_port, view.getPort()); StringCopy(_path, view.getPath()); StringCopy(_query, view.getQuery()); StringCopy(_fragment, view.getFragment()); if (_rare || !view.getUsername().empty() || !view.getPassword().empty() || !view.getParameter().empty()) { needRare(); StringCopy(_rare->username, view.getUsername()); StringCopy(_rare->password, view.getPassword()); StringCopy(_rare->parameter, view.getParameter()); } return *this; } URLBuilder& URLBuilder::operator=(const URL& url) { return operator=(url.getView()); } std::string URLBuilder::toString(const StringOptions& options) const { return getView().toString(options); } void URLBuilder::toString(std::string& buffer, const StringOptions& options) const { return getView().toString(buffer, options); } bool URLBuilder::isEmpty() const PRIME_NOEXCEPT { return _protocol.empty() && StringIsEmpty(getUsername()) && StringIsEmpty(getPassword()) && _host.empty() && _port.empty() && _path.empty() && StringIsEmpty(getParameter()) && _query.empty() && _fragment.empty(); } bool URLBuilder::hasLocation() const PRIME_NOEXCEPT { return !(StringIsEmpty(getUsername()) && StringIsEmpty(getPassword()) && _host.empty() && _port.empty()); } URLPath URLBuilder::getPathComponents() const { return URLPath(getPath()); } void URLBuilder::setPathComponents(const URLPath& path) { setPath(path.toString()); } URLDictionary URLBuilder::getQueryComponents() const { URLDictionary result; URL::parseQueryString(result, getQuery()); return result; } void URLBuilder::setQueryComponents(const URLDictionary& query) { setQuery(URL::buildQueryString(query)); } URLBuilder URLBuilder::resolve(const URLBuilder& embedded) const { URL url = URL::resolve(getView(), embedded.getView()); return URLBuilder(url); } URLBuilder URLBuilder::resolve(const URLView& embedded) const { URL url = URL::resolve(getView(), embedded); return URLBuilder(url); } URLBuilder URLBuilder::resolve(const URL& embedded) const { URL url = URL::resolve(getView(), embedded); return URLBuilder(url); } void URLBuilder::swap(URLBuilder& rhs) { _protocol.swap(rhs._protocol); _host.swap(rhs._host); _port.swap(rhs._port); _path.swap(rhs._path); _query.swap(rhs._query); _fragment.swap(rhs._fragment); _rare.swap(rhs._rare); } void URLBuilder::move(URLBuilder& rhs) { #ifdef PRIME_COMPILER_RVALUEREF _protocol = std::move(rhs._protocol); _host = std::move(rhs._host); _port = std::move(rhs._port); _path = std::move(rhs._path); _query = std::move(rhs._query); _fragment = std::move(rhs._fragment); _rare = std::move(rhs._rare); #else swap(rhs); #endif } URLView URLBuilder::getView() const { URLView view; view.setProtocol(getProtocol()); view.setHost(getHost()); view.setPort(getPort()); view.setPath(getPath()); view.setQuery(getQuery()); view.setFragment(getFragment()); view.setUsername(getUsername()); view.setPassword(getPassword()); view.setParameter(getParameter()); return view; } // // URLPath // bool URLPath::isUnsafe(StringView string) PRIME_NOEXCEPT { for (const char* ptr = string.begin(); ptr != string.end(); ++ptr) { if (isUnsafe(*ptr)) { return true; } } return false; } bool URLPath::parse(StringView string) { const char* ptr = string.begin(); const char* end = string.end(); bool result = true; // TODO: we could write components directly in to _storage std::string component; _storage.clear(); _lengths.clear(); for (;;) { const char* slash = std::find(ptr, end, '/'); size_t length = (size_t)(slash - ptr); component.resize(0); URLDecodeAppend(component, StringView(ptr, slash), 0); if (!component.empty() && component != ".") { if (component == "..") { if (!_lengths.empty()) { _lengths.pop_back(); } } else { if (isUnsafe(component)) { result = false; } if (component.size() == length && memcmp(component.data(), ptr, length) == 0) { _storage.append(ptr, slash); _lengths.push_back(slash - ptr); } else { _storage.append(component.begin(), component.end()); _lengths.push_back(component.size()); } } } ptr = slash; if (ptr == end) { break; } if (ptr + 1 == end) { // Empty components within a path (e.g., a/b//c/d) are ignored, but a trailing / denotes a directory, // so we end with an empty component. _lengths.push_back(0); break; } ++ptr; } return result; } std::string URLPath::toString(const StringOptions& options) const { const bool relative = options.getWithoutLeadingSlash(); const bool urlEscape = !options.getWithoutEscaping(); if (_lengths.empty()) { return relative ? "" : "/"; } std::string path; size_t offset = 0; bool previousComponent = false; for (size_t i = 0; i != _lengths.size(); ++i) { StringView component(_storage.data() + offset, _storage.data() + offset + _lengths[i]); offset += _lengths[i]; if (options.getSkipUnsafeComponents() && isUnsafe(component)) { continue; } if (!relative || previousComponent) { path += '/'; } if (urlEscape) { URLEncodeAppend(path, component, 0); } else { path.append(component.begin(), component.end()); } previousComponent = true; } return std::string(path.begin(), path.end()); } size_t URLPath::offsetOfComponent(size_t index) const { PRIME_DEBUG_ASSERT(index <= getComponentCount()); size_t offset = 0; const size_t* lengths = &_lengths[0]; while (index--) { offset += *lengths++; } return offset; } URLPath URLPath::getTail(size_t skip) const { URLPath result; if (PRIME_GUARD(skip <= getComponentCount())) { size_t offset = offsetOfComponent(skip); result._storage.assign(_storage.data() + offset, _storage.size() - offset); result._lengths.assign(_lengths.begin() + skip, _lengths.end()); } return result; } URLPath& URLPath::addComponent(StringView component) { _lengths.push_back(component.size()); _storage.append(component.begin(), component.end()); return *this; } void URLPath::removeLastComponent() { _storage.resize(_storage.size() - _lengths.back()); _lengths.pop_back(); } URLPath URLPath::getWithLastComponentRemoved() const { URLPath result(*this); result.removeLastComponent(); return result; } StringView URLPath::getComponent(size_t index) const PRIME_NOEXCEPT { if (!PRIME_GUARD(index < getComponentCount())) { return StringView(); } return StringView(_storage).substr(offsetOfComponent(index), _lengths[index]); } StringView URLPath::getComponentElse(size_t index, StringView defaultValue) const { if (index < _lengths.size()) { return getComponent(index); } return defaultValue; } URLPath URLPath::toDirectory() const { if (isDirectory()) { return *this; } URLPath directory = *this; directory._lengths.push_back(0); return directory; } bool URLPath::operator==(const URLPath& rhs) const PRIME_NOEXCEPT { return _lengths == rhs._lengths && _storage == rhs._storage; } bool URLPath::operator<(const URLPath& rhs) const PRIME_NOEXCEPT { size_t minComponentCount = std::min(_lengths.size(), rhs._lengths.size()); for (size_t i = 0; i != minComponentCount; ++i) { // Could track the two offsets... StringView leftComponent = getComponent(i); StringView rightComponent = rhs.getComponent(i); if (leftComponent < rightComponent) { return true; } if (leftComponent != rightComponent) { return false; } } return _lengths.size() < rhs._lengths.size(); } URLPath URLPath::getRelative(const URLPath& relative) const { URLPath absolute = *this; if (absolute.isDirectory()) { absolute.removeLastComponent(); } absolute._lengths.insert(absolute._lengths.end(), relative._lengths.begin(), relative._lengths.end()); absolute._storage.append(relative._storage); return absolute; } bool URLPath::startsWith(const URLPath& prefix) const PRIME_NOEXCEPT { size_t count = prefix.getComponentCount(); if (prefix.isDirectory()) { --count; } if (getComponentCount() < count) { return false; } if (!std::equal(prefix._lengths.begin(), prefix._lengths.begin() + count, _lengths.begin())) { return false; } size_t offset = offsetOfComponent(count); if (offset != prefix._storage.size()) { return false; } return memcmp(_storage.data(), prefix._storage.data(), offset) == 0; } // // URLDictionary // void URLDictionary::clear() PRIME_NOEXCEPT { _pairs.clear(); } const std::string& URLDictionary::get(StringView key) const PRIME_NOEXCEPT { for (size_t i = 0; i != _pairs.size(); ++i) { const value_type& pair = _pairs.pair(i); if (equalKeys(pair.first, key)) { return pair.second; } } return emptyString; } const std::string& URLDictionary::operator[](StringView key) const PRIME_NOEXCEPT { return get(key); } bool URLDictionary::has(StringView key) const PRIME_NOEXCEPT { for (size_t i = 0; i != _pairs.size(); ++i) { const value_type& pair = _pairs.pair(i); if (equalKeys(pair.first, key)) { return true; } } return false; } std::vector<std::string> URLDictionary::getAll(StringView key) const { std::vector<std::string> array; for (size_t i = 0; i != _pairs.size(); ++i) { const value_type& pair = _pairs.pair(i); if (equalKeys(pair.first, key)) { array.push_back(pair.second); } } return array; } std::vector<StringView> URLDictionary::getAllViews(StringView key) const { std::vector<StringView> array; for (size_t i = 0; i != _pairs.size(); ++i) { const value_type& pair = _pairs.pair(i); if (equalKeys(pair.first, key)) { array.push_back(pair.second); } } return array; } void URLDictionary::set(StringView key, StringView value) { bool first = true; for (size_t i = 0; i != _pairs.size(); ++i) { value_type& pair = _pairs.pair(i); if (equalKeys(pair.first, key)) { if (first) { StringCopy(pair.second, value); first = false; } else { _pairs.erase(_pairs.begin() + (ptrdiff_t)i); --i; } } } if (first) { add(key, value); } } void URLDictionary::add(StringView key, StringView value) { _pairs.push_back(value_type()); value_type& pair = _pairs.back(); pair.first.assign(key.begin(), key.end()); StringCopy(pair.second, value); } void URLDictionary::remove(StringView key) { for (size_t i = 0; i != _pairs.size(); ++i) { value_type& pair = _pairs.pair(i); if (equalKeys(pair.first, key)) { _pairs.erase(_pairs.begin() + (ptrdiff_t)i); --i; } } } URLDictionary::iterator URLDictionary::find(StringView key) PRIME_NOEXCEPT { for (iterator i = begin(); i != end(); ++i) { if (equalKeys(i->first, key)) { return i; } } return end(); } #ifdef PRIME_HAVE_VALUE Value::Dictionary URLDictionary::toDictionary() const { Value::Dictionary dict; dict.reserve(_pairs.size()); for (const_iterator i = begin(); i != end(); ++i) { dict.set(i->first, i->second); } return dict; } #endif // // StringAppend // bool StringAppend(std::string& output, const URLView& url) { url.appendString(output); return true; } bool StringAppend(std::string& output, const URL& url) { url.appendString(output); return true; } bool StringAppend(std::string& output, const URLBuilder& url) { output += url.toString(); return true; } }
24.280308
216
0.603968
malord
b505660d07d2b5c52b2dc66d597edda14aa7df49
842
cpp
C++
main.cpp
MCLEANS/STM32F4_FreeRTOS_TEMPLATE
b7ca381938baed6eb3295d7ec3511e15a9c06706
[ "MIT" ]
1
2021-08-21T03:48:09.000Z
2021-08-21T03:48:09.000Z
main.cpp
MCLEANS/STM32F4_FreeRTOS_TEMPLATE
b7ca381938baed6eb3295d7ec3511e15a9c06706
[ "MIT" ]
null
null
null
main.cpp
MCLEANS/STM32F4_FreeRTOS_TEMPLATE
b7ca381938baed6eb3295d7ec3511e15a9c06706
[ "MIT" ]
null
null
null
#include "stm32f4xx.h" #include "clockconfig.h" #include <FreeRTOS.h> #include <task.h> #include <portmacro.h> custom_libraries::clock_config system_clock; extern "C" void led1_task(void* pvParameter){ while(1){ for(volatile int i = 0; i < 2000000; i++){} GPIOD->ODR ^= (1<<12); } } extern "C" void led2_task(void* pvParameter){ while(1){ for(volatile int i = 0; i < 2000000; i++){} GPIOD->ODR ^= (1<<13); } } int main(void) { system_clock.initialize(); RCC->AHB1ENR |= RCC_AHB1ENR_GPIODEN; GPIOD->MODER |= GPIO_MODER_MODER12_0; GPIOD->ODR |= GPIO_ODR_ODR_12; GPIOD->MODER |= GPIO_MODER_MODER13_0; GPIOD->ODR |= GPIO_ODR_ODR_13; xTaskCreate(led1_task,"led 1 controller",100,NULL,1,NULL); xTaskCreate(led2_task,"led 2 controller",100,NULL,1,NULL); vTaskStartScheduler(); while(1){ } }
21.05
60
0.665083
MCLEANS
b506c91327b7d0379aeb3de194e5c62f8f232bbf
3,246
cc
C++
mysql-server/unittest/gunit/mysys_my_loadpath-t.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/unittest/gunit/mysys_my_loadpath-t.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/unittest/gunit/mysys_my_loadpath-t.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
/* Copyright (c) 2013, 2019, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. 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, version 2.0, 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <gtest/gtest.h> #include <stddef.h> #include "my_inttypes.h" #include "my_io.h" #include "my_sys.h" namespace mysys_my_load_path { TEST(Mysys, MyLoadPath) { char dest[FN_REFLEN]; static const std::string filename = "filename"; // Path with absolute path component. std::string absolute_path_name = FN_LIBCHAR + filename; my_load_path(dest, absolute_path_name.c_str(), nullptr); EXPECT_STREQ(dest, absolute_path_name.c_str()); // Path with home directory component. dest[0] = '\0'; std::string home_dir_path_name = FN_HOMELIB + (FN_LIBCHAR + filename); my_load_path(dest, home_dir_path_name.c_str(), nullptr); EXPECT_STREQ(dest, home_dir_path_name.c_str()); // Path with current directory component. dest[0] = '\0'; std::string parent_dir_path_name = FN_CURLIB + (FN_LIBCHAR + filename); my_load_path(dest, parent_dir_path_name.c_str(), nullptr); char temp_buf[256]; my_getwd(temp_buf, sizeof(temp_buf), MYF(0)); EXPECT_STREQ(dest, (temp_buf + filename).c_str()); // Path with prefix component appended. dest[0] = '\0'; std::string prefix_path_name = "/basedir/"; my_load_path(dest, filename.c_str(), prefix_path_name.c_str()); EXPECT_STREQ(dest, (prefix_path_name + filename).c_str()); // Path that has length FN_REFLEN-1 dest[0] = '\0'; std::string cur_dir_path_name; for (int i = 0; i < (FN_REFLEN - 3); i++) cur_dir_path_name.append("y"); cur_dir_path_name = FN_CURLIB + (FN_LIBCHAR + cur_dir_path_name); my_load_path(dest, cur_dir_path_name.c_str(), nullptr); EXPECT_STREQ(dest, cur_dir_path_name.c_str()); // Path that has length FN_REFLEN. dest[0] = '\0'; cur_dir_path_name.append("y"); my_load_path(dest, cur_dir_path_name.c_str(), nullptr); EXPECT_STREQ(dest, cur_dir_path_name.substr(0, FN_REFLEN - 1).c_str()); // Path that has length exceeding FN_REFLEN dest[0] = '\0'; cur_dir_path_name.append("y"); my_load_path(dest, cur_dir_path_name.c_str(), nullptr); EXPECT_STREQ(dest, cur_dir_path_name.substr(0, FN_REFLEN - 1).c_str()); } } // namespace mysys_my_load_path
39.108434
79
0.735675
silenc3502
b508fbfdd518f36bd26fcf04dcd37df520ef145f
3,829
cpp
C++
src/model/io/yuv420rgbbuffer.cpp
fanghaocong/GitlHEVCAnalyzer
1dbf3adca4822b0a55af03c7a7f49c92798c91d6
[ "Apache-2.0" ]
null
null
null
src/model/io/yuv420rgbbuffer.cpp
fanghaocong/GitlHEVCAnalyzer
1dbf3adca4822b0a55af03c7a7f49c92798c91d6
[ "Apache-2.0" ]
null
null
null
src/model/io/yuv420rgbbuffer.cpp
fanghaocong/GitlHEVCAnalyzer
1dbf3adca4822b0a55af03c7a7f49c92798c91d6
[ "Apache-2.0" ]
null
null
null
#include "yuv420rgbbuffer.h" #include <QFile> #include <QDebug> extern "C" { #include "libswscale/swscale.h" #include "libavutil/imgutils.h" #include "libavutil/frame.h" } static enum AVPixelFormat bitDepth2PixelFormat( int iBitDepth ) { enum AVPixelFormat pixelFormat; if ( iBitDepth == 8 ) { pixelFormat = AV_PIX_FMT_YUV420P; } else if ( iBitDepth == 10 ) { pixelFormat = AV_PIX_FMT_YUV420P10LE; } else if ( iBitDepth == 16 ) { pixelFormat = AV_PIX_FMT_YUV420P16LE; } return pixelFormat; } YUV420RGBBuffer::YUV420RGBBuffer() { m_iBufferWidth = 0; m_iBufferHeight = 0; m_iFrameCount = -1; m_iBitDepth = -1; m_puhYUVBuffer = NULL; m_puhRGBBuffer = NULL; m_pFrameYUV = av_frame_alloc(); m_pFrameRGB = av_frame_alloc(); m_pConvertCxt = NULL; } YUV420RGBBuffer::~YUV420RGBBuffer() { av_free(m_puhYUVBuffer); m_puhYUVBuffer = NULL; av_free(m_puhRGBBuffer); m_puhRGBBuffer = NULL; av_frame_free(&m_pFrameYUV); av_frame_free(&m_pFrameRGB); sws_freeContext(m_pConvertCxt); } bool YUV420RGBBuffer::openYUVFile( const QString& strYUVPath, int iWidth, int iHeight, int iBitDepth ) { /// if new size dosen't match current size, delete old one and create new one if( iWidth != m_iBufferWidth || iHeight != m_iBufferHeight || iBitDepth != m_iBitDepth ) { enum AVPixelFormat pixelFormat = bitDepth2PixelFormat(iBitDepth); av_free(m_puhYUVBuffer); m_puhYUVBuffer = (uint8_t *)av_malloc(av_image_get_buffer_size(pixelFormat, iWidth, iHeight, 1) * sizeof(uint8_t)); av_free(m_puhRGBBuffer); m_puhRGBBuffer = (uint8_t *)av_malloc(av_image_get_buffer_size(AV_PIX_FMT_RGB32, iWidth, iHeight, 1) * sizeof(uint8_t)); av_image_fill_arrays(m_pFrameYUV->data, m_pFrameYUV->linesize, m_puhYUVBuffer, pixelFormat, iWidth, iHeight, 1); av_image_fill_arrays(m_pFrameRGB->data, m_pFrameRGB->linesize, m_puhRGBBuffer, AV_PIX_FMT_RGB32, iWidth, iHeight, 1); sws_freeContext(m_pConvertCxt); m_pConvertCxt = sws_getContext(iWidth, iHeight, pixelFormat, iWidth, iHeight, AV_PIX_FMT_RGB32, SWS_BICUBIC, NULL, NULL, NULL); } m_iBufferWidth = iWidth; m_iBufferHeight = iHeight; m_iBitDepth = iBitDepth; /// set YUV file reader if( !m_cIOYUV.openYUVFilePath(strYUVPath) ) { qCritical() << "YUV Buffer Initialization Fail"; return false; } return true; } QPixmap* YUV420RGBBuffer::getFrame(int iFrameCount) { QPixmap* pcFramePixmap = NULL; if( xReadFrame(iFrameCount) ) { QImage cFrameImg(m_puhRGBBuffer, m_iBufferWidth, m_iBufferHeight, QImage::Format_RGB32 ); m_cFramePixmap = QPixmap::fromImage(cFrameImg); pcFramePixmap = &m_cFramePixmap; } else { qCritical() << "Read YUV File Failure."; } return pcFramePixmap; } bool YUV420RGBBuffer::xReadFrame(int iFrameCount) { if( iFrameCount < 0 ) return false; m_iFrameCount = iFrameCount; enum AVPixelFormat pixelFormat = bitDepth2PixelFormat(m_iBitDepth); int iFrameSizeInByte = av_image_get_buffer_size(pixelFormat, m_iBufferWidth, m_iBufferHeight, 1); if( m_cIOYUV.seekTo(iFrameCount*iFrameSizeInByte) == false ) return false; int iReadBytes = 0; ///read iReadBytes = m_cIOYUV.readOneFrame(m_puhYUVBuffer, (uint)iFrameSizeInByte); if( iReadBytes != iFrameSizeInByte ) { qCritical() << "Read YUV Frame Error"; return false; } else { /// YUV to RGB conversion sws_scale(m_pConvertCxt, (const uint8_t *const *) m_pFrameYUV->data, m_pFrameYUV->linesize, 0, m_iBufferHeight, m_pFrameRGB->data, m_pFrameRGB->linesize); return true; } }
26.776224
135
0.680595
fanghaocong
b515866b31997aa2964694fb5b68f587dddcebd0
1,268
cc
C++
src/profiling/symbolizer/local_symbolizer_unittest.cc
jumeder/perfetto
df3ae5e6f975204d2f35aeed61cbbd0746151d8e
[ "Apache-2.0" ]
null
null
null
src/profiling/symbolizer/local_symbolizer_unittest.cc
jumeder/perfetto
df3ae5e6f975204d2f35aeed61cbbd0746151d8e
[ "Apache-2.0" ]
1
2021-02-23T11:18:01.000Z
2021-02-23T11:18:01.000Z
src/profiling/symbolizer/local_symbolizer_unittest.cc
jumeder/perfetto
df3ae5e6f975204d2f35aeed61cbbd0746151d8e
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "perfetto/base/build_config.h" #include "test/gtest_and_gmock.h" // This translation unit is built only on Linux and MacOS. See //gn/BUILD.gn. #if PERFETTO_BUILDFLAG(PERFETTO_LOCAL_SYMBOLIZER) #include "src/profiling/symbolizer/local_symbolizer.h" namespace perfetto { namespace profiling { namespace { TEST(LocalSymbolizerTest, ParseLineWindows) { std::string file_name; uint32_t lineno; ASSERT_TRUE( ParseLlvmSymbolizerLine("C:\\Foo\\Bar.cc:123:1", &file_name, &lineno)); EXPECT_EQ(file_name, "C:\\Foo\\Bar.cc"); EXPECT_EQ(lineno, 123u); } } // namespace } // namespace profiling } // namespace perfetto #endif
29.488372
77
0.73817
jumeder
b517ad009d89ba9a9df95013f0dab81716a2a52f
1,077
cpp
C++
code/clock_real/mts_clock_real.cpp
mtsquant/MTS
ab7ecab0f88c844289b5c81e5627326fe36e682f
[ "Apache-2.0" ]
8
2019-03-28T04:15:59.000Z
2021-03-23T14:29:43.000Z
code/clock_real/mts_clock_real.cpp
mtsquant/MTS
ab7ecab0f88c844289b5c81e5627326fe36e682f
[ "Apache-2.0" ]
null
null
null
code/clock_real/mts_clock_real.cpp
mtsquant/MTS
ab7ecab0f88c844289b5c81e5627326fe36e682f
[ "Apache-2.0" ]
5
2019-11-06T12:39:21.000Z
2021-01-28T19:14:14.000Z
/***************************************************************************** * Copyright [2017-2019] [MTSQuant] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "clock_real_api.h" #include "ClockReal.h" #include "mts_core/enums.h" extern "C" { MTS_CLOCK_REAL_API mts::Clock* createClock(mts::EnvironmentMode mode) { if (mode != mts::ENVIR_REAL) { return nullptr; } return new mts::ClockReal(); } MTS_CLOCK_REAL_API void releaseClock(mts::Clock* clock) { delete clock; } }
34.741935
78
0.629526
mtsquant
b518c4c20432ed4d234525178b2092092974d575
2,351
cpp
C++
vegastrike/src/cmd/fg_util.cpp
Ezeer/VegaStrike_win32FR
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
[ "MIT" ]
null
null
null
vegastrike/src/cmd/fg_util.cpp
Ezeer/VegaStrike_win32FR
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
[ "MIT" ]
null
null
null
vegastrike/src/cmd/fg_util.cpp
Ezeer/VegaStrike_win32FR
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
[ "MIT" ]
null
null
null
#include "savegame.h" #include "fg_util.h" #include "faction_generic.h" #include <algorithm> namespace fg_util { // void itoa( unsigned int dat, char *output ) { if (dat == 0) { *output++ = '0'; *output = '\0'; } else { char *s = output; while (dat) { *s++ = '0'+dat%10; dat /= 10; } *s = '\0'; std::reverse( output, s ); } } std::string MakeFactionKey( int faction ) { char output[16]; output[0] = 'F'; output[1] = 'F'; output[2] = ':'; itoa( faction, output+3 ); return std::string( output ); } bool IsFGKey( const std::string &fgcandidate ) { if (fgcandidate.length() > 3 && fgcandidate[0] == 'F' && fgcandidate[1] == 'G' && fgcandidate[2] == ':') return true; return false; } static std::string gFG = "FG:"; std::string MakeFGKey( const std::string &fgname, int faction ) { char tmp[16]; tmp[0] = '|'; itoa( faction, tmp+1 ); return gFG+fgname+tmp; } static std::string gSS = "SS:"; std::string MakeStarSystemFGKey( const std::string &starsystem ) { return gSS+starsystem; } unsigned int ShipListOffset() { return 3; } unsigned int PerShipDataSize() { return 3; } bool CheckFG( std::vector< std::string > &data ) { bool retval = false; unsigned int leg = data.size(); unsigned int inc = PerShipDataSize(); for (unsigned int i = ShipListOffset()+1; i+1 < leg; i += inc) { std::string *numlanded = &data[i+1]; std::string *numtotal = &data[i]; if (*numlanded != *numtotal) { retval = true; *numlanded = *numtotal; } } return retval; } bool CheckFG( SaveGame *sg, const std::string &fgname, unsigned int faction ) { std::string key = MakeFGKey( fgname, faction ); return CheckFG( sg->getMissionStringData( key ) ); } void PurgeZeroShips( SaveGame *sg, unsigned int faction ) { std::string key = MakeFactionKey( faction ); unsigned int len = sg->getMissionStringDataLength( key ); unsigned int i = 0; while (i < len) { CheckFG( sg, sg->getMissionStringData( key )[i] /*flightgroup*/, faction ); i += 1; } } void PurgeZeroShips( SaveGame *sg ) { for (unsigned int i = 0; i < factions.size(); ++i) fg_util::PurgeZeroShips( sg, i ); } // }
21.18018
121
0.56997
Ezeer
b518e4b42c4ca9a8a5577f4ff97282c4bdab6f52
13,542
cpp
C++
main.cpp
Joel714/GameProject
417b0f65d2f2c9dde2d2bf68f6ac092501dfcabc
[ "MIT" ]
null
null
null
main.cpp
Joel714/GameProject
417b0f65d2f2c9dde2d2bf68f6ac092501dfcabc
[ "MIT" ]
null
null
null
main.cpp
Joel714/GameProject
417b0f65d2f2c9dde2d2bf68f6ac092501dfcabc
[ "MIT" ]
null
null
null
#include <cstdlib> #include <cstdio> #include <cassert> #include <GL/gl.h> #include <GL/glut.h> #ifdef FREEGLUT #include <GL/freeglut_ext.h> #endif #ifndef NDEBUG #define msglError( ) _msglError( stderr, __FILE__, __LINE__ ) #else #define msglError( ) #endif #include <FreeImage.h> #include "keys.h" #include "player.h" #include "enemy.h" #include "mapfileReader.h" #include "camera.h" #include "states.h" Keys keys; Player player; GLuint playerTextureId; float playerTexCoords[33][8] = { { 0.0, 1.0, 0.0625, 1.0, 0.0625, 0.90625, 0.0, 0.90625},//0 stand still :Right {0.125, 1.0, 0.1875, 1.0, 0.1875, 0.90625, 0.125, 0.90625}, {0.5, 0.90625, 0.5625, 0.90625, 0.5625, 0.8125, 0.5, 0.8125},//2 jump/fall :Right {0.5, 0.8125, 0.5625, 0.8125, 0.5625, 0.71875, 0.5, 0.71875}, {0.0, 0.90625, 0.0625, 0.90625, 0.0625, 0.8125, 0.0, 0.8125},//4 walking 1 :Right {0.0, 0.8125, 0.0625, 0.8125, 0.0625, 0.71875, 0.0, 0.71875}, {0.0625, 0.90625, 0.125, 0.90625, 0.125, 0.8125, 0.0625, 0.8125},//6 walking 2 :Right {0.0625, 0.8125, 0.125, 0.8125, 0.125, 0.71875, 0.0625, 0.71875}, {0.125, 0.90625, 0.1875, 0.90625, 0.1875, 0.8125, 0.125, 0.8125},//8 walking 3 :Right {0.125, 0.8125, 0.1875, 0.8125, 0.1875, 0.71875, 0.125, 0.71875}, {0.1875, 0.90625, 0.25, 0.90625, 0.25, 0.8125, 0.1875, 0.8125},//10 walking 4 :Right {0.1875, 0.8125, 0.25, 0.8125, 0.25, 0.71875, 0.1875, 0.71875}, {0.25, 1.0, 0.3125, 1.0, 0.3125, 0.90625, 0.25, 0.90625},//12 hit :Right {0.0625, 1.0, 0.125, 1.0, 0.125, 0.90625, 0.0625, 0.90625},//13 stand still :Left {0.1875, 1.0, 0.25, 1.0, 0.25, 0.90625, 0.1875, 0.90625}, { 0.5625, 0.90625, 0.625, 0.90625, 0.625, 0.8125, 0.5625, 0.8125},//15 jump/fall :Left {0.5625, 0.8125, 0.625, 0.8125, 0.625, 0.71875, 0.5625, 0.71875}, {0.25, 0.90625, 0.3125, 0.90625, 0.3125, 0.8125, 0.25, 0.8125},//17 walking 1 :Left {0.25, 0.8125, 0.3125, 0.8125, 0.3125, 0.71875, 0.25, 0.71875}, {0.3125, 0.90625, 0.375, 0.90625, 0.375, 0.8125, 0.3125, 0.8125},//19 walking 2 :Left {0.3125, 0.8125, 0.375, 0.8125, 0.375, 0.71875, 0.3125, 0.71875}, {0.375, 0.90625, 0.4375, 0.90625, 0.4375, 0.8125, 0.375, 0.8125},//21 walking 3 :Left {0.375, 0.8125, 0.4375, 0.8125, 0.4375, 0.71875, 0.375, 0.71875}, {0.4375, 0.90625, 0.5, 0.90625, 0.5, 0.8125, 0.4375, 0.8125},//23 walking 4 :Left {0.4375, 0.8125, 0.5, 0.8125, 0.5, 0.71875, 0.4375, 0.71875}, {0.3125, 1.0, 0.375, 1.0, 0.375, 0.90625, 0.3125, 0.90625},//25 hit :Left {0.375, 1.0, 0.4375, 1.0, 0.4375, 0.90625, 0.375, 0.90625},//26 chunk 1 {0.4375, 1.0, 0.5, 1.0, 0.5, 0.90625, 0.4375, 0.90625},//27 chunk 2 {0.5, 1.0, 0.5625, 1.0, 0.5625, 0.90625, 0.5, 0.90625},//28 chunk 3 {0.90625, 1.0, 1.0, 1.0, 1.0, 0.96875, 0.90625, 0.96875},//29 bar {0.9375, 0.96875, 0.96875, 0.96875, 0.96875, 0.9375, 0.9375, 0.9375},//30 red {0.96875, 0.96875, 1.0, 0.96875, 1.0, 0.9375, 0.96875, 0.9375},//31 bullet {0.5625 , 1.0, 0.625, 1.0, 0.625, 0.90625, 0.5625, 0.90625}//32 invisible }; int mapWidth = 0; int mapHeight = 0; int *mapData; GLuint mapTexureId; float mapTexCoords[4][8] = { {0.0, 1.0, 0.5, 1.0, 0.5, 0.5, 0.0, 0.5}, {0.5, 1.0, 1.0, 1.0, 1.0, 0.5, 0.5, 0.5}, {0.0, 0.5, 0.5, 0.5, 0.5, 0.0, 0.0, 0.0}, {0.5, 0.5, 1.0, 0.5, 1.0, 0.0, 0.5, 0.0} }; const int enemyArraySize = 3; Enemy enemyArray[enemyArraySize]; GLuint enemyTextureId; float etexCoords[16][8] = { {0.0, 1.0, 0.25, 1.0, 0.25, 0.5, 0.0, 0.5},//0 Looking/standing stil : Left {0.25, 1.0, 0.5, 1.0, 0.5, 0.5, 0.25, 0.5},//1 arm half way up : Left {0.5, 1.0, 0.75, 1.0, 0.75, 0.5, 0.5, 0.5},//2 arm up/firing : Left {0.75, 1.0, 0.875, 1.0, 0.875, 0.875, 0.75, 0.875},//3 bullet {0.0, 0.5, 0.25, 0.5, 0.25, 0.0, 0.0, 0.0},//4 dying animation 1 : Left {0.25, 0.5, 0.5, 0.5, 0.5, 0.0, 0.25, 0.0},//5 dying animation 2 : Left {0.5, 0.5, 0.75, 0.5, 0.75, 0.0, 0.5, 0.0},//6 dying animation 3 : Left {0.75, 0.5, 1.0, 0.5, 1.0, 0.0, 0.75, 0.0},//7 dead : Left {0.25, 1.0, 0.0, 1.0, 0.0, 0.5, 0.25, 0.5},//8 Looking/standing stil : Right {0.5, 1.0, 0.25, 1.0, 0.25, 0.5, 0.5, 0.5},//9 arm half way up : Right {0.75, 1.0, 0.5, 1.0, 0.5, 0.5, 0.75, 0.5},//10 arm up/firing : Right {0.875, 1.0, 0.75, 1.0, 0.75, 0.875, 0.875, 0.875},//bullet {0.25, 0.5, 0.0, 0.5, 0.0, 0.0, 0.25, 0.0},//12 dying animation 1 : Right {0.5, 0.5, 0.25, 0.5, 0.25, 0.0, 0.5, 0.0},//13 dying animation 2 : Right {0.75, 0.5, 0.5, 0.5, 0.5, 0.0, 0.75, 0.0},//14 dying animation 3 : Right {1.0, 0.5, 0.75, 0.5, 0.75, 0.0, 1.0, 0.0}//15 dead : Right }; bool gameStarted = false; bool gameEnded = false; Camera myCamera; bool _msglError( FILE *out, const char *filename, int line ){ bool ret = false; GLenum err = glGetError( ); while( err != GL_NO_ERROR ) { ret = true; fprintf( out, "GL ERROR:%s:%d: %s\n", filename, line, (char*)gluErrorString( err ) ); err = glGetError( ); } return( ret ); } void initOpenGL( ){ glClearColor( 0.5f, 0.5f, 0.5f, 1.0f ); glEnable( GL_DEPTH_TEST ); glDepthRange(0.0, 1.0); glDepthFunc(GL_LEQUAL); glMatrixMode( GL_PROJECTION ); glLoadIdentity( ); glMatrixMode( GL_MODELVIEW ); glLoadIdentity( ); msglError( ); } void initKeys(){ keys.a_isDown = false; keys.d_isDown = false; keys.w_isDown = false; keys.f_isDown = false; } //uses FreeImage to load a texture void textureLoader(const char *filename, GLuint *textureid){ FIBITMAP* bitmap = NULL; FREE_IMAGE_FORMAT fif = FreeImage_GetFileType(filename, 0); if( fif == FIF_UNKNOWN ){ fif = FreeImage_GetFIFFromFilename(filename); } if( (fif != FIF_UNKNOWN) && FreeImage_FIFSupportsReading(fif)){ bitmap = FreeImage_Load(fif, filename, 0); assert(bitmap); } assert(bitmap); FREE_IMAGE_COLOR_TYPE fic = FreeImage_GetColorType(bitmap); assert( fic == FIC_RGB || fic == FIC_RGBALPHA ); unsigned int bpp = FreeImage_GetBPP(bitmap); assert(bpp == 24 || bpp == 32); GLenum pixelFormat; if(bpp == 24){ pixelFormat = GL_BGR; }else{ pixelFormat = GL_BGRA; } int width = FreeImage_GetWidth(bitmap); int height = FreeImage_GetHeight(bitmap); glGenTextures(1, textureid); glBindTexture(GL_TEXTURE_2D, *textureid); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, pixelFormat, GL_UNSIGNED_BYTE, (void*)FreeImage_GetBits(bitmap)); } void resetLevel(){ player.currentState = Still; player.previousState = Still; player.frameCount = 0; player.texIndex = 0; player.xVelocity = 0; player.yVelocity = 0; player.facingLeft = false; player.bulletLifeTime = 0; player.bulletIsFired = false; player.health = 3; player.isHit = false; player.invulnerableTime = 0; player.invulnerableTimeLimit = 180; player.isDead = false; player.x = 64; player.y = 240; for(int i = 0; i < enemyArraySize; i++){ enemyArray[i].currentState = Looking; enemyArray[i].frameCount = 0; enemyArray[i].texIndex = 0; enemyArray[i].facingRight = false; enemyArray[i].bulletLifeTime = 0; enemyArray[i].bulletIsFired = false; } } void keyboardDown( unsigned char key, int x, int y ){ switch( key ){ case 27: // The 'esc' key case 'q': delete [] mapData; #ifdef FREEGLUT glutLeaveMainLoop( ); #else exit( 0 ); #endif break; case 'a': keys.a_isDown = true; break; case 'd': keys.d_isDown = true; break; case 'w': keys.w_isDown = true; break; case 'f': keys.f_isDown = true; break; case 's': gameStarted = true; break; case 'r': if(gameEnded){ gameEnded = false; resetLevel(); } break; default: break; } } void keyboardUp( unsigned char key, int x, int y ){ switch( key ){ case 'a': keys.a_isDown = false; break; case 'd': keys.d_isDown = false; break; case 'w': keys.w_isDown = false; break; case 'f': keys.f_isDown = false; break; default: break; } } void display( ){ msglError( ); glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, mapTexureId); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); if(gameEnded){ //show ending menu glBindTexture(GL_TEXTURE_2D, playerTextureId); glBegin(GL_QUADS); glTexCoord2f(0.0, 0.4375); glVertex3f(-1.0, 1.0, 0.0); glTexCoord2f(0.25, 0.4375); glVertex3f(1.0, 1.0, 0.0); glTexCoord2f(0.25, 0.15625); glVertex3f(1.0, -1.0, 0.0); glTexCoord2f(0.0, 0.15625); glVertex3f(-1.0, -1.0, 0.0); glEnd(); }else if(gameStarted){ //the maximum and minumum amount of //tiles that are viewed on screen int minXview = 0; int maxXview = 0; int minYview = 0; int maxYview = 0; //get max and min of viewable tiles if(myCamera.x % 32 == 0){ minXview = myCamera.x/32 - 5; maxXview = myCamera.x/32 + 4; }else{ minXview = myCamera.x/32 - 5; maxXview = myCamera.x/32 + 5; } if(myCamera.y % 32 == 0){ minYview = myCamera.y/32 - 5; maxYview = myCamera.y/32 + 4; }else{ minYview = myCamera.y/32 - 5; maxYview = myCamera.y/32 + 5; } //check if it's within possible values if(minXview < 0 || minXview > (mapWidth - 1)){ minXview = 0; } if(maxXview > (mapWidth - 1) || maxXview < 0 ){ maxXview = 0; } if(minYview < 0 || minYview > (mapHeight - 1)){ minYview = 0; } if(maxYview > (mapHeight - 1) || maxYview < 0 ){ maxYview = 0; } //loop through map data and draw the tiles for(int i = minYview; i <= maxYview; i++){ for(int j = minXview; j <= maxXview; j++){ if(mapData[(i * mapWidth) + j] == 0){ }else if(mapData[(i * mapWidth) + j] == 1){ myCamera.drawSprite(j * 32, i * 32, 32, 32, mapTexCoords, 1); } } } glBindTexture(GL_TEXTURE_2D, playerTextureId); //draw player sprite myCamera.drawSprite(player.x, player.y, 48, 32, playerTexCoords, player.texIndex); //draw red healthbar myCamera.drawSprite(myCamera.x - 160, myCamera.y - 160, 16, 16 * player.health, playerTexCoords, 30); //draw healthbar outline myCamera.drawSprite(myCamera.x - 160, myCamera.y - 160, 16, 48, playerTexCoords, 29); //draw player bullet if it's fired if(player.bulletIsFired){ myCamera.drawSprite(player.bulletX, player.bulletY, 16, 16, playerTexCoords, 31); } //loop through enemy array and draw //enemy sprite and bullet glBindTexture(GL_TEXTURE_2D, enemyTextureId); for(int eIndex = 0; eIndex < enemyArraySize; eIndex++){ myCamera.drawSprite(enemyArray[eIndex].x, enemyArray[eIndex].y, 64, 32, etexCoords, enemyArray[eIndex].texIndex); if(enemyArray[eIndex].bulletIsFired){ myCamera.drawSprite(enemyArray[eIndex].bulletX, enemyArray[eIndex].bulletY, 16, 16, etexCoords, 3); } } }else if(!gameStarted){ //show strating menu glBindTexture(GL_TEXTURE_2D, playerTextureId); glBegin(GL_QUADS); glTexCoord2f(0.0, 0.71875); glVertex3f(-1.0, 1.0, 0.0); glTexCoord2f(0.25, 0.71875); glVertex3f(1.0, 1.0, 0.0); glTexCoord2f(0.25, 0.4375); glVertex3f(1.0, -1.0, 0.0); glTexCoord2f(0.0, 0.4375); glVertex3f(-1.0, -1.0, 0.0); glEnd(); } glDisable(GL_TEXTURE_2D); glutSwapBuffers( ); msglError( ); } void reshape( int width, int height ){ if (height == 0){ height = 1; } glViewport( 0, 0, (GLsizei)width, (GLsizei)height ); glMatrixMode( GL_PROJECTION ); glLoadIdentity( ); glMatrixMode( GL_MODELVIEW ); glLoadIdentity( ); } void update(int x){ //end game when player reaches //the end of the map if(player.x >= (mapWidth - 2) * 32){ gameEnded = true; } //reset level if player dies if(player.isDead || player.y > (mapHeight * 32)){ resetLevel(); } //if the game has started then //go through the player and enemy fsm if(gameStarted && !gameEnded){ player.FSM(mapData, mapWidth, mapHeight, &keys); myCamera.updatePosition(player.x, player.y, mapHeight, mapWidth); for(int i = 0; i < enemyArraySize; i++){ enemyArray[i].FSM(&player); } } glutTimerFunc(16, update, 0); glutPostRedisplay(); } int main(int argc, const char* argv[]){ glutInit( &argc, (char**)argv ); glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH ); glutInitWindowSize( 640, 640); glutCreateWindow( "Demo" ); initOpenGL( ); initKeys(); getMapData(&mapWidth, &mapHeight, mapData); player.x = 64; player.y = 240; enemyArray[0].x = 640; enemyArray[0].y = 224; enemyArray[1].x = 1120; enemyArray[1].y = 160; enemyArray[2].x = 1600; enemyArray[2].y = 224; textureLoader("data/playerSprites.png", &playerTextureId); textureLoader("data/enemySprites.png", &enemyTextureId); textureLoader("data/tileSprites.png", &mapTexureId); glutKeyboardFunc( keyboardDown ); glutKeyboardUpFunc( keyboardUp ); glutDisplayFunc( display ); glutReshapeFunc( reshape ); glutTimerFunc(16, update, 0); glutMainLoop( ); return(0); }
28.812766
127
0.603604
Joel714
b519402bd985faa4b8e0961fa74cd224cdcf84ff
555
cpp
C++
cpp/evenOddQuery.cpp
Rohit-RA-2020/hackerrank-math
466a9b25311c8ba9d457720d618d8930667e498f
[ "MIT" ]
null
null
null
cpp/evenOddQuery.cpp
Rohit-RA-2020/hackerrank-math
466a9b25311c8ba9d457720d618d8930667e498f
[ "MIT" ]
null
null
null
cpp/evenOddQuery.cpp
Rohit-RA-2020/hackerrank-math
466a9b25311c8ba9d457720d618d8930667e498f
[ "MIT" ]
null
null
null
// https://www.hackerrank.com/challenges/even-odd-query #include <iostream> using namespace std; int A[100008], N; int find(int x, int y) { if (A[x] % 2) return 1; if (x == y) return 0; if (A[x + 1] == 0) return 1; return 0; } int main() { int x, y, Q; cin >> N; for (int i = 1; i <= N; i++) cin >> A[i]; cin >> Q; while (Q--) { cin >> x >> y; if (find(x, y)) cout << "Odd" << endl; else cout << "Even" << endl; } return 0; }
16.323529
55
0.421622
Rohit-RA-2020
b51c26cf9fa26a79b625b701c31623f4b175f203
16,938
cpp
C++
franka_polishing/src/nodes/nflat_surfaces_node.cpp
amaroUC/TOOLING4G
d25d43c0e14798617b7c4be60fd9eed2df25aa17
[ "Apache-2.0" ]
2
2020-11-18T09:01:49.000Z
2021-09-24T10:31:14.000Z
franka_polishing/src/nodes/nflat_surfaces_node.cpp
amaroUC/TOOLING4G
d25d43c0e14798617b7c4be60fd9eed2df25aa17
[ "Apache-2.0" ]
1
2021-11-12T12:19:15.000Z
2021-11-16T12:17:01.000Z
franka_polishing/src/nodes/nflat_surfaces_node.cpp
amaroUC/TOOLING4G
d25d43c0e14798617b7c4be60fd9eed2df25aa17
[ "Apache-2.0" ]
2
2020-07-25T07:38:20.000Z
2021-11-08T15:19:08.000Z
// ============================================================================= // Name : nflat_surfaces_node.cpp // Author : Hélio Ochoa // Description : // ============================================================================= #include <franka_polishing/spacenav.h> #include <visualization_msgs/Marker.h> #include <tf/transform_broadcaster.h> geometry_msgs::PoseStamped marker_pose; // STATE MACHINE -------------------------------------------------------------- #define MOVE2POINT 0 #define PATTERN 1 #define MOVEUP 2 #define CHOOSEPLANE 3 #define INTERRUPT 4 // ----------------------------------------------------------------------------- int main(int argc, char** argv) { ros::init(argc, argv, "nflat_surfaces_node"); ros::NodeHandle nh; franka_polishing::Spacenav panda(nh); // --------------------------------------------------------------------------- // VIZUALIZATIONS MARKERS INITIALIZATION // --------------------------------------------------------------------------- ros::Publisher marker_pub = nh.advertise<visualization_msgs::Marker>("visualization_marker", 20); visualization_msgs::Marker points, line_strip; points.header.frame_id = line_strip.header.frame_id = "/panda_link0"; points.header.stamp = line_strip.header.stamp = ros::Time::now(); points.ns = "points"; line_strip.ns = "lines"; points.id = 0; line_strip.id = 1; points.action = line_strip.action = visualization_msgs::Marker::ADD; points.type = visualization_msgs::Marker::POINTS; line_strip.type = visualization_msgs::Marker::LINE_STRIP; points.pose.orientation.w = line_strip.pose.orientation.w = 1.0; // POINTS markers use x and y scale for width/height respectively points.scale.x = 0.01; points.scale.y = 0.01; // Set the color -- be sure to set alpha to something non-zero! points.color.a = 1.0; points.color.r = 1.0; points.color.g = 0.0; points.color.b = 0.0; // LINE_STRIP/LINE_LIST markers use only the x component of scale, for the line width line_strip.scale.x = 0.01; // Line strip is green line_strip.color.a = 1.0; line_strip.color.g = 1.0; // --------------------------------------------------------------------------- // TF BROADCASTER // --------------------------------------------------------------------------- tf::TransformBroadcaster br, br_d; tf::Transform transform, transform_d; // --------------------------------------------------------------------------- // GET THE CO-MANIPULATION PATTERN FROM A FILE // --------------------------------------------------------------------------- Eigen::MatrixXd position; // matrix to save the robot positions in Base-frame Eigen::MatrixXd orientation; // matrix to save the robot orientations in Base-frame std::ifstream pattern_file; std::string pattern_path; pattern_path = "/home/panda/catkin_ws/src/TOOLING4G/franka_polishing/co_manipulation_data/pattern"; pattern_file.open(pattern_path); double time, px, py, pz, qx, qy, qz, qw; std::string line; getline(pattern_file, line); // first line getline(pattern_file, line); // second line int column = 0; position.resize(3, column + 1); orientation.resize(4, column + 1); if(pattern_file.is_open()){ while(pattern_file >> time >> px >> py >> pz >> qx >> qy >> qz >> qw){ // save the values in the matrix position.conservativeResize(3, column + 1); orientation.conservativeResize(4, column + 1); position(0, column) = px; position(1, column) = py; position(2, column) = pz; orientation(0, column) = qx; orientation(1, column) = qy; orientation(2, column) = qz; orientation(3, column) = qw; column++; } } else{ std::cout << "\nError open the file!" << std::endl; return(0); } pattern_file.close(); //std::cout << position.transpose() << std::endl; //std::cout << orientation.transpose() << std::endl; Eigen::Quaterniond Qpattern; Qpattern.coeffs() = orientation.col(0); Eigen::Matrix3d Rpattern(Qpattern); // --------------------------------------------------------------------------- // COMPUTE OFFSETS BETWEEN POSITIONS // --------------------------------------------------------------------------- Eigen::MatrixXd OFFSET; OFFSET.resize(3, column-1); for(int i = 0; i < column-1; i++){ OFFSET(0, i) = position(0, i+1) - position(0, i); OFFSET(1, i) = position(1, i+1) - position(1, i); OFFSET(2, i) = position(2, i+1) - position(2, i); } //std::cout << OFFSET.transpose() << std::endl; // --------------------------------------------------------------------------- // GET MOULD POINTS FROM A FILE // --------------------------------------------------------------------------- std::ifstream file_plane; std::string path_plane; double x, y, z; Eigen::MatrixXd P; path_plane = "/home/panda/catkin_ws/src/TOOLING4G/franka_polishing/co_manipulation_data/mold_workspace"; file_plane.open(path_plane); int n_points = 0; P.resize(3, n_points + 1); if(file_plane.is_open()){ while(file_plane >> x >> y >> z){ // save the values in the matrix P.conservativeResize(3, n_points + 1); P(0, n_points) = x; P(1, n_points) = y; P(2, n_points) = z; n_points++; } } else{ std::cout << "Error open the file!" << std::endl; return(0); } file_plane.close(); // std::cout << P << std::endl; int n_planes = n_points/4; int n = 0; Eigen::Vector3d P1(P.col(n)); Eigen::Vector3d P2(P.col(n+1)); Eigen::Vector3d P3(P.col(n+2)); Eigen::Vector3d P4(P.col(n+3)); Eigen::Matrix3d Rmould; Rmould = panda.points2Rotation(P1, P2, P4); //std::cout << Rmould << std::endl; // mould orientation in Quaternion unit Eigen::Quaterniond Qmould(Rmould); // compute the desired rotation in all points of plane Eigen::Matrix3d Rpoints(Rmould * Rpattern); Eigen::Quaterniond Qpoints(Rpoints); // build a vector with all points of the mould work space int Nx = 5; int Ny = 5; Eigen::Vector3d delta_synthetic; delta_synthetic << 0.0, 0.0, 0.0; Eigen::MatrixXd Xd; Xd = panda.moldWorkSpace(P1, P2, P4, delta_synthetic, Nx, Ny); // std::cout << Xd.transpose() << std::endl; geometry_msgs::Point p, l; // points and lines int n_columns = 0; while(n_columns < (Nx+1)*(Ny+1)){ p.x = Xd(0, n_columns); p.y = Xd(1, n_columns); p.z = Xd(2, n_columns); points.points.push_back(p); n_columns++; } // --------------------------------------------------------------------------- // GET INITIAL POSE // --------------------------------------------------------------------------- Eigen::Matrix4d O_T_EE_i; Eigen::VectorXd pose_i(7,1); O_T_EE_i = panda.O_T_EE; pose_i = panda.robot_pose(O_T_EE_i); // --------------------------------------------------------------------------- // TRAJECTORY TO FIRST POINT // --------------------------------------------------------------------------- Eigen::Vector3d pi, pf; int num_cols = n_columns-1; pi << pose_i[0], pose_i[1], pose_i[2]; pf << Xd(0, num_cols), Xd(1, num_cols), Xd(2, num_cols); double ti = 1.0; double tf = 6.0; double t = 0.0; double delta_t = 0.001; // orientation Eigen::Quaterniond oi, of; oi.coeffs() << pose_i[3], pose_i[4], pose_i[5], pose_i[6]; of.coeffs() << Qpoints.vec()[0], Qpoints.vec()[1], Qpoints.vec()[2], Qpoints.w(); double t1 = 0.0; double delta_t1 = delta_t/(tf-ti); // --------------------------------------------------------------------------- // TRAJECTORY MOVE UP CONDITIONS // --------------------------------------------------------------------------- Eigen::Vector3d delta_up; delta_up << 0.0, 0.0, 0.1; // --------------------------------------------------------------------------- // DEFINE WORK-SPACE LIMITS // --------------------------------------------------------------------------- // distances between the 4 points that delimit the plane Eigen::Vector3d l12(P2 - P1); Eigen::Vector3d l23(P3 - P2); Eigen::Vector3d l34(P4 - P3); Eigen::Vector3d l41(P1 - P4); // --------------------------------------------------------------------------- // MAIN LOOP // --------------------------------------------------------------------------- Eigen::Vector3d position_d(pi); Eigen::Quaterniond orientation_d(oi); Eigen::Vector3d new_position_d(position_d); Eigen::Vector3d mould_offset; mould_offset.setZero(); Eigen::Vector3d l1P, l2P, l3P, l4P; l1P.setZero(); l2P.setZero(); l3P.setZero(); l4P.setZero(); double signal1 = 0.0; double signal2 = 0.0; double signal3 = 0.0; double signal4 = 0.0; int flag_pattern = 0; int flag_print = 0; int flag_interrupt = 0; int count = 0; int k = 0; ros::Rate loop_rate(1000); while (ros::ok()){ switch (flag_pattern) { //////////////////////////////////////////////////// // ----------------------------------------------------------------------- case MOVE2POINT: if(flag_print == 0){ std::cout << CLEANWINDOW << "ROBOT IS MOVING TO A MOLD POINT..." << std::endl; flag_print = 1; } // --> MOVE TO MOULD POINT <-- if( (t >= ti) && (t <= tf) ){ position_d = panda.polynomial3_trajectory(pi, pf, ti, tf, t); if ( t1 <= 1.0 ){ orientation_d = oi.slerp(t1, of); orientation_d.normalize(); } t1 = t1 + delta_t1; } else if(t > tf){ flag_pattern = PATTERN; count = 0; } t = t + delta_t; new_position_d = position_d; // INTERRUPT if(panda.spacenav_button_2 == 1){ flag_pattern = INTERRUPT; } break; // ----------------------------------------------------------------------- case PATTERN: if(flag_print == 1){ std::cout << CLEANWINDOW << "PATTERN IS EXECUTING, IF YOU WOULD LIKE TO STOP PRESS SPACENAV BUTTON <2>..." << std::endl; flag_print = 2; } // PATTERN if (count < column-1){ mould_offset << OFFSET(0, count), OFFSET(1, count), OFFSET(2, count); new_position_d = new_position_d + Rmould * mould_offset; // distances between the pattern points and the 4 points that delimit the plane l1P = (new_position_d - P1); l2P = (new_position_d - P2); l3P = (new_position_d - P3); l4P = (new_position_d - P4); // signal between the 2 vectors signal1 = l1P.dot(l12); signal2 = l2P.dot(l23); signal3 = l3P.dot(l34); signal4 = l4P.dot(l41); if( (signal1 >= 0.0) && (signal2 >= 0.0) && (signal3 >= 0.0) && (signal4 >= 0.0) ){ position_d = new_position_d; } }// -------------------------------------------------------------------- else{ flag_pattern = MOVEUP; O_T_EE_i = panda.O_T_EE; pose_i = panda.robot_pose(O_T_EE_i); // get current pose pi << pose_i[0], pose_i[1], pose_i[2]; pf << pi + delta_up; t = 0; // reset the time } count++; // draw the lines of the polished area if(count % 100 == 0){ l.x = position_d[0]; l.y = position_d[1]; l.z = position_d[2]; line_strip.points.push_back(l); marker_pub.publish(line_strip); } // INTERRUPT if(panda.spacenav_button_2 == 1){ flag_pattern = INTERRUPT; } break; // ----------------------------------------------------------------------- case MOVEUP: if(flag_print == 2){ std::cout << CLEANWINDOW << "PATTERN WAS EXECUTED AND THE ROBOT IS MOVING UP!" << std::endl; flag_print = 0; } // --> MOVE UP <-- ti = 0.0; tf = 3.0; if((t >= ti) && (t <= tf)){ position_d = panda.polynomial3_trajectory(pi, pf, ti, tf, t); } else if(t > tf){ if(num_cols > 0){ num_cols--; flag_pattern = MOVE2POINT; O_T_EE_i = panda.O_T_EE; // get current pose pose_i = panda.robot_pose(O_T_EE_i); pi << pose_i[0], pose_i[1], pose_i[2]; pf << Xd(0, num_cols), Xd(1, num_cols), Xd(2, num_cols); t = 0.0; ti = 0.0; tf = 3.0; } else{ if(flag_print == 0){ std::cout << CLEANWINDOW << "MOLD AREA POLISHED!" << std::endl; flag_print = 3; } if(k < n_planes){ k = k + 1; // next plane n = n + 4; // next 4 points flag_pattern = CHOOSEPLANE; } } } t = t + delta_t; // INTERRUPT if(panda.spacenav_button_2 == 1){ flag_pattern = INTERRUPT; } break; // ----------------------------------------------------------------------- case CHOOSEPLANE: if(flag_print == 3){ std::cout << CLEANWINDOW << "WAIT UNTIL NEW PLANE IS BUILT..." << std::endl; flag_print = 0; } if(k >= n_planes) { std::cout << CLEANWINDOW << "ALL MOLD AREAS POLISHED!" << std::endl; return 0; } else{ P1 = P.col(n); P2 = P.col(n+1); P3 = P.col(n+2); P4 = P.col(n+3); Rmould = panda.points2Rotation(P1, P2, P4); Qmould = Rmould; // compute the desired rotation in all points of plane Rpoints = Rmould * Rpattern; Qpoints = Rpoints; // build a matrix with all points of the mould work space Xd = panda.moldWorkSpace(P1, P2, P4, delta_synthetic, Nx, Ny); n_columns = 0; while(n_columns < (Nx+1)*(Ny+1)){ p.x = Xd(0, n_columns); p.y = Xd(1, n_columns); p.z = Xd(2, n_columns); points.points.push_back(p); n_columns++; } l12 = (P2 - P1); l23 = (P3 - P2); l34 = (P4 - P3); l41 = (P1 - P4); flag_pattern = MOVE2POINT; O_T_EE_i = panda.O_T_EE; // get current pose pose_i = panda.robot_pose(O_T_EE_i); num_cols = n_columns-1; pi << pose_i[0], pose_i[1], pose_i[2]; pf << Xd(0, num_cols), Xd(1, num_cols), Xd(2, num_cols); t = 0.0; ti = 0.0; tf = 3.0; oi.coeffs() << pose_i[3], pose_i[4], pose_i[5], pose_i[6]; of.coeffs() << Qpoints.vec()[0], Qpoints.vec()[1], Qpoints.vec()[2], Qpoints.w(); t1 = 0.0; delta_t1 = delta_t/(tf-ti); } break; // ----------------------------------------------------------------------- case INTERRUPT: if(flag_interrupt == 0){ std::cout << CLEANWINDOW << "PROGRAM INTERRUPTED! IF YOU WOULD LIKE TO CONTINUE, PLEASE PRESS SPACENAV BUTTON <1>..." << std::endl; flag_interrupt = 1; } if(panda.spacenav_button_1 == 1){ flag_print = 2; flag_interrupt = 0; flag_pattern = MOVEUP; O_T_EE_i = panda.O_T_EE; pose_i = panda.robot_pose(O_T_EE_i); // get current pose pi << pose_i[0], pose_i[1], pose_i[2]; pf << pi + delta_up; t = 0; } break; }////////////////////////////////////////////////////////////////////////// // std::cout << CLEANWINDOW << position_d << std::endl; // std::cout << CLEANWINDOW << orientation_d.coeffs() << std::endl; panda.posePublisherCallback(marker_pose, position_d, orientation_d); // ------------------------------------------------------------------------- // TF AND VISUALIZATION MARKERS // ------------------------------------------------------------------------- marker_pub.publish(points); // draw the points of the mould work-space // Draw the mould transform transform.setOrigin( tf::Vector3(P1(0), P1(1), P1(2)) ); transform.setRotation( tf::Quaternion(Qmould.vec()[0], Qmould.vec()[1], Qmould.vec()[2], Qmould.w()) ); br.sendTransform(tf::StampedTransform(transform, ros::Time::now(), "/panda_link0", "/mould")); // Draw the desired EE transform transform_d.setOrigin( tf::Vector3(position_d(0), position_d(1), position_d(2)) ); transform_d.setRotation( tf::Quaternion(orientation_d.vec()[0], orientation_d.vec()[1], orientation_d.vec()[2], orientation_d.w()) ); br_d.sendTransform(tf::StampedTransform(transform_d, ros::Time::now(), "/panda_link0", "/panda_EE_d")); // ------------------------------------------------------------------------- if(sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) break; ros::spinOnce(); loop_rate.sleep(); } return 0; }
33.146771
141
0.483115
amaroUC
b51c63825b0872889f37f5883f6eeafb83052b81
1,650
cc
C++
ir/value/foreign_fn.cc
perimosocordiae/Icarus
183098eff886a0503562e5571e7009dd22719367
[ "Apache-2.0" ]
10
2015-10-28T18:54:41.000Z
2021-12-29T16:48:31.000Z
ir/value/foreign_fn.cc
perimosocordiae/Icarus
183098eff886a0503562e5571e7009dd22719367
[ "Apache-2.0" ]
95
2020-02-27T22:34:02.000Z
2022-03-06T19:45:24.000Z
ir/value/foreign_fn.cc
perimosocordiae/Icarus
183098eff886a0503562e5571e7009dd22719367
[ "Apache-2.0" ]
2
2019-02-01T23:16:04.000Z
2020-02-27T16:06:02.000Z
#include "ir/value/foreign_fn.h" #include "absl/container/flat_hash_map.h" #include "base/debug.h" #include "base/flyweight_map.h" #include "base/guarded.h" namespace ir { namespace { // Note: We store both the foreign function pointer and it's type. This means // that we could have the same foreign function multiple times with different // types. This is intentional and can occur in two contexts. First, because // named parameters are part of the type, we could easily have all of the // following: // // ``` // foreign("malloc", (num_bytes: u64) -> [*]i64) // foreign("malloc", (bytes_to_alloc: u64) -> [*]i64) // foreign("malloc", u64 -> [*]i64) // ``` // // Second, in generic contexts, the return type may be different: // // ``` // allocate ::= (T :: type, num: i32) -> [*]T { // malloc ::= foreign("malloc", u64 -> [*]T) // return malloc(T'bytes * (num as u64)) // } // ``` // struct ForeignFnData { void (*fn)(); type::Function const *type; template <typename H> friend H AbslHashValue(H h, ForeignFnData data) { return H::combine(std::move(h), data.fn, data.type); } friend constexpr bool operator==(ForeignFnData lhs, ForeignFnData rhs) { return lhs.fn == rhs.fn and lhs.type == rhs.type; } }; base::guarded<base::flyweight_map<ForeignFnData>> foreign_fns; } // namespace ForeignFn::ForeignFn(void (*fn)(), type::Function const *t) : id_(foreign_fns.lock()->get(ForeignFnData{fn, t})) {} type::Function const *ForeignFn::type() const { return foreign_fns.lock()->get(id_).type; } ForeignFn::void_fn_ptr ForeignFn::get() const { return foreign_fns.lock()->get(id_).fn; } } // namespace ir
26.190476
77
0.664848
perimosocordiae
b52316be55163b26ceef1181b10414f4fa4b8a9f
400
cpp
C++
Codeforces 915B.cpp
Jvillegasd/Codeforces
ffdd2d5db1dabc7ff76f8f92270c79233a77b933
[ "MIT" ]
null
null
null
Codeforces 915B.cpp
Jvillegasd/Codeforces
ffdd2d5db1dabc7ff76f8f92270c79233a77b933
[ "MIT" ]
null
null
null
Codeforces 915B.cpp
Jvillegasd/Codeforces
ffdd2d5db1dabc7ff76f8f92270c79233a77b933
[ "MIT" ]
null
null
null
#include <stdio.h> #include <math.h> #include <algorithm> using namespace std; int main(){ int n, p, l, r; scanf("%d %d %d %d", &n, &p, &l, &r); if(l == 1 && r == n) printf("0\n"); else if(l == 1 && r != n) printf("%d\n", abs(p - r) + 1); else if(r == n && l != 1) printf("%d\n", abs(p - l) + 1); else printf("%d\n", min(abs(p - l), abs(p - r)) + 2 + r - l); return 0; }
26.666667
65
0.455
Jvillegasd
dde249bfdafe6afef31f10f3bf6464b7719a2bcf
40,247
cpp
C++
export/windows/obj/src/lime/text/Font.cpp
arturspon/zombie-killer
07848c5006916e9079537a3d703ffe3740afaa5a
[ "MIT" ]
null
null
null
export/windows/obj/src/lime/text/Font.cpp
arturspon/zombie-killer
07848c5006916e9079537a3d703ffe3740afaa5a
[ "MIT" ]
null
null
null
export/windows/obj/src/lime/text/Font.cpp
arturspon/zombie-killer
07848c5006916e9079537a3d703ffe3740afaa5a
[ "MIT" ]
1
2021-07-16T22:57:01.000Z
2021-07-16T22:57:01.000Z
// Generated by Haxe 4.0.0-rc.2+77068e10c #include <hxcpp.h> #ifndef INCLUDED_Std #include <Std.h> #endif #ifndef INCLUDED_haxe_IMap #include <haxe/IMap.h> #endif #ifndef INCLUDED_haxe_ds_IntMap #include <haxe/ds/IntMap.h> #endif #ifndef INCLUDED_haxe_io_Bytes #include <haxe/io/Bytes.h> #endif #ifndef INCLUDED_haxe_io_Path #include <haxe/io/Path.h> #endif #ifndef INCLUDED_lime__internal_backend_native_NativeCFFI #include <lime/_internal/backend/native/NativeCFFI.h> #endif #ifndef INCLUDED_lime_app_Future #include <lime/app/Future.h> #endif #ifndef INCLUDED_lime_app_Promise_lime_text_Font #include <lime/app/Promise_lime_text_Font.h> #endif #ifndef INCLUDED_lime_graphics_Image #include <lime/graphics/Image.h> #endif #ifndef INCLUDED_lime_graphics_ImageBuffer #include <lime/graphics/ImageBuffer.h> #endif #ifndef INCLUDED_lime_graphics_ImageType #include <lime/graphics/ImageType.h> #endif #ifndef INCLUDED_lime_math_Vector2 #include <lime/math/Vector2.h> #endif #ifndef INCLUDED_lime_net__HTTPRequest_AbstractHTTPRequest #include <lime/net/_HTTPRequest/AbstractHTTPRequest.h> #endif #ifndef INCLUDED_lime_net__HTTPRequest_Bytes #include <lime/net/_HTTPRequest_Bytes.h> #endif #ifndef INCLUDED_lime_net__HTTPRequest_lime_text_Font #include <lime/net/_HTTPRequest_lime_text_Font.h> #endif #ifndef INCLUDED_lime_net__IHTTPRequest #include <lime/net/_IHTTPRequest.h> #endif #ifndef INCLUDED_lime_text_Font #include <lime/text/Font.h> #endif #ifndef INCLUDED_lime_text_GlyphMetrics #include <lime/text/GlyphMetrics.h> #endif #ifndef INCLUDED_lime_utils_ArrayBufferView #include <lime/utils/ArrayBufferView.h> #endif #ifndef INCLUDED_lime_utils_Assets #include <lime/utils/Assets.h> #endif #ifndef INCLUDED_lime_utils_TAError #include <lime/utils/TAError.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_51012fd6257f8a4a_54_new,"lime.text.Font","new",0x97494f29,"lime.text.Font.new","lime/text/Font.hx",54,0x3be57807) HX_LOCAL_STACK_FRAME(_hx_pos_51012fd6257f8a4a_103_decompose,"lime.text.Font","decompose",0x6e29ff3a,"lime.text.Font.decompose","lime/text/Font.hx",103,0x3be57807) HX_LOCAL_STACK_FRAME(_hx_pos_51012fd6257f8a4a_181_getGlyph,"lime.text.Font","getGlyph",0x5bf955cd,"lime.text.Font.getGlyph","lime/text/Font.hx",181,0x3be57807) HX_LOCAL_STACK_FRAME(_hx_pos_51012fd6257f8a4a_188_getGlyphs,"lime.text.Font","getGlyphs",0x1e31be06,"lime.text.Font.getGlyphs","lime/text/Font.hx",188,0x3be57807) HX_LOCAL_STACK_FRAME(_hx_pos_51012fd6257f8a4a_198_getGlyphMetrics,"lime.text.Font","getGlyphMetrics",0x8c9677f6,"lime.text.Font.getGlyphMetrics","lime/text/Font.hx",198,0x3be57807) HX_LOCAL_STACK_FRAME(_hx_pos_51012fd6257f8a4a_215_renderGlyph,"lime.text.Font","renderGlyph",0xe6e51a3f,"lime.text.Font.renderGlyph","lime/text/Font.hx",215,0x3be57807) HX_LOCAL_STACK_FRAME(_hx_pos_51012fd6257f8a4a_254_renderGlyphs,"lime.text.Font","renderGlyphs",0x2191dd54,"lime.text.Font.renderGlyphs","lime/text/Font.hx",254,0x3be57807) HX_LOCAL_STACK_FRAME(_hx_pos_51012fd6257f8a4a_418___copyFrom,"lime.text.Font","__copyFrom",0x8a0b5b36,"lime.text.Font.__copyFrom","lime/text/Font.hx",418,0x3be57807) HX_LOCAL_STACK_FRAME(_hx_pos_51012fd6257f8a4a_442___fromBytes,"lime.text.Font","__fromBytes",0x257c2b4a,"lime.text.Font.__fromBytes","lime/text/Font.hx",442,0x3be57807) HX_LOCAL_STACK_FRAME(_hx_pos_51012fd6257f8a4a_455___fromFile,"lime.text.Font","__fromFile",0x6331ec7d,"lime.text.Font.__fromFile","lime/text/Font.hx",455,0x3be57807) HX_LOCAL_STACK_FRAME(_hx_pos_51012fd6257f8a4a_468___initializeSource,"lime.text.Font","__initializeSource",0xb57a50c2,"lime.text.Font.__initializeSource","lime/text/Font.hx",468,0x3be57807) HX_LOCAL_STACK_FRAME(_hx_pos_51012fd6257f8a4a_495___loadFromName,"lime.text.Font","__loadFromName",0x6b610412,"lime.text.Font.__loadFromName","lime/text/Font.hx",495,0x3be57807) HX_LOCAL_STACK_FRAME(_hx_pos_51012fd6257f8a4a_592___setSize,"lime.text.Font","__setSize",0x86a86dec,"lime.text.Font.__setSize","lime/text/Font.hx",592,0x3be57807) HX_LOCAL_STACK_FRAME(_hx_pos_51012fd6257f8a4a_120_fromBytes,"lime.text.Font","fromBytes",0x65a32e2a,"lime.text.Font.fromBytes","lime/text/Font.hx",120,0x3be57807) HX_LOCAL_STACK_FRAME(_hx_pos_51012fd6257f8a4a_134_fromFile,"lime.text.Font","fromFile",0x07a4e59d,"lime.text.Font.fromFile","lime/text/Font.hx",134,0x3be57807) HX_LOCAL_STACK_FRAME(_hx_pos_51012fd6257f8a4a_149_loadFromBytes,"lime.text.Font","loadFromBytes",0x5727f7a4,"lime.text.Font.loadFromBytes","lime/text/Font.hx",149,0x3be57807) HX_LOCAL_STACK_FRAME(_hx_pos_51012fd6257f8a4a_157_loadFromFile,"lime.text.Font","loadFromFile",0x5ed36963,"lime.text.Font.loadFromFile","lime/text/Font.hx",157,0x3be57807) HX_LOCAL_STACK_FRAME(_hx_pos_51012fd6257f8a4a_153_loadFromFile,"lime.text.Font","loadFromFile",0x5ed36963,"lime.text.Font.loadFromFile","lime/text/Font.hx",153,0x3be57807) HX_LOCAL_STACK_FRAME(_hx_pos_51012fd6257f8a4a_174_loadFromName,"lime.text.Font","loadFromName",0x64170d32,"lime.text.Font.loadFromName","lime/text/Font.hx",174,0x3be57807) namespace lime{ namespace text{ void Font_obj::__construct(::String name){ HX_STACKFRAME(&_hx_pos_51012fd6257f8a4a_54_new) HXLINE( 55) if (hx::IsNotNull( name )) { HXLINE( 57) this->name = name; } HXLINE( 60) if (!(this->_hx___init)) { HXLINE( 62) this->ascender = 0; HXLINE( 66) this->descender = 0; HXLINE( 70) this->height = 0; HXLINE( 74) this->numGlyphs = 0; HXLINE( 78) this->underlinePosition = 0; HXLINE( 82) this->underlineThickness = 0; HXLINE( 86) this->unitsPerEM = 0; HXLINE( 88) if (hx::IsNotNull( this->_hx___fontID )) { HXLINE( 90) if (::lime::utils::Assets_obj::isLocal(this->_hx___fontID,null(),null())) { HXLINE( 92) this->_hx___fromBytes(::lime::utils::Assets_obj::getBytes(this->_hx___fontID)); } } else { HXLINE( 95) if (hx::IsNotNull( this->_hx___fontPath )) { HXLINE( 97) this->_hx___fromFile(this->_hx___fontPath); } } } } Dynamic Font_obj::__CreateEmpty() { return new Font_obj; } void *Font_obj::_hx_vtable = 0; Dynamic Font_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< Font_obj > _hx_result = new Font_obj(); _hx_result->__construct(inArgs[0]); return _hx_result; } bool Font_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x6aed2e71; } ::Dynamic Font_obj::decompose(){ HX_STACKFRAME(&_hx_pos_51012fd6257f8a4a_103_decompose) HXLINE( 105) if (hx::IsNull( this->src )) { HXLINE( 105) HX_STACK_DO_THROW(HX_("Uninitialized font handle.",3a,84,ab,29)); } HXLINE( 106) ::Dynamic data = ( ( ::Dynamic)(::lime::_internal::backend::native::NativeCFFI_obj::lime_font_outline_decompose(hx::DynamicPtr(this->src),20480)) ); HXLINE( 113) return data; } HX_DEFINE_DYNAMIC_FUNC0(Font_obj,decompose,return ) int Font_obj::getGlyph(::String character){ HX_STACKFRAME(&_hx_pos_51012fd6257f8a4a_181_getGlyph) HXDLIN( 181) return ::lime::_internal::backend::native::NativeCFFI_obj::lime_font_get_glyph_index(hx::DynamicPtr(this->src),character); } HX_DEFINE_DYNAMIC_FUNC1(Font_obj,getGlyph,return ) ::Array< int > Font_obj::getGlyphs(::String __o_characters){ ::String characters = __o_characters; if (hx::IsNull(__o_characters)) characters = HX_("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^`'\"/\\&*()[]{}<>|:;_-+=?,. ",c1,f6,34,50); HX_STACKFRAME(&_hx_pos_51012fd6257f8a4a_188_getGlyphs) HXLINE( 190) ::Dynamic glyphs = ( ( ::Dynamic)(::lime::_internal::backend::native::NativeCFFI_obj::lime_font_get_glyph_indices(hx::DynamicPtr(this->src),characters)) ); HXLINE( 191) return ( (::Array< int >)(glyphs) ); } HX_DEFINE_DYNAMIC_FUNC1(Font_obj,getGlyphs,return ) ::lime::text::GlyphMetrics Font_obj::getGlyphMetrics(int glyph){ HX_GC_STACKFRAME(&_hx_pos_51012fd6257f8a4a_198_getGlyphMetrics) HXLINE( 200) ::Dynamic value = ( ( ::Dynamic)(::lime::_internal::backend::native::NativeCFFI_obj::lime_font_get_glyph_metrics(hx::DynamicPtr(this->src),glyph)) ); HXLINE( 201) ::lime::text::GlyphMetrics metrics = ::lime::text::GlyphMetrics_obj::__alloc( HX_CTX ); HXLINE( 203) metrics->advance = ::lime::math::Vector2_obj::__alloc( HX_CTX ,value->__Field(HX_("horizontalAdvance",fe,57,3e,ce),hx::paccDynamic),value->__Field(HX_("verticalAdvance",ac,8e,f7,57),hx::paccDynamic)); HXLINE( 204) metrics->height = ( (int)(value->__Field(HX_("height",e7,07,4c,02),hx::paccDynamic)) ); HXLINE( 205) metrics->horizontalBearing = ::lime::math::Vector2_obj::__alloc( HX_CTX ,value->__Field(HX_("horizontalBearingX",ae,21,22,6c),hx::paccDynamic),value->__Field(HX_("horizontalBearingY",af,21,22,6c),hx::paccDynamic)); HXLINE( 206) metrics->verticalBearing = ::lime::math::Vector2_obj::__alloc( HX_CTX ,value->__Field(HX_("verticalBearingX",40,c3,78,64),hx::paccDynamic),value->__Field(HX_("verticalBearingY",41,c3,78,64),hx::paccDynamic)); HXLINE( 208) return metrics; } HX_DEFINE_DYNAMIC_FUNC1(Font_obj,getGlyphMetrics,return ) ::lime::graphics::Image Font_obj::renderGlyph(int glyph,int fontSize){ HX_GC_STACKFRAME(&_hx_pos_51012fd6257f8a4a_215_renderGlyph) HXLINE( 217) this->_hx___setSize(fontSize); HXLINE( 219) ::haxe::io::Bytes bytes = ::haxe::io::Bytes_obj::alloc(0); HXLINE( 222) int dataPosition = 0; HXLINE( 223) bytes = ( ( ::Dynamic)(::lime::_internal::backend::native::NativeCFFI_obj::lime_font_render_glyph(hx::DynamicPtr(this->src),glyph,hx::DynamicPtr(bytes))) ); HXLINE( 225) bool _hx_tmp; HXDLIN( 225) if (hx::IsNotNull( bytes )) { HXLINE( 225) _hx_tmp = (bytes->length > 0); } else { HXLINE( 225) _hx_tmp = false; } HXDLIN( 225) if (_hx_tmp) { HXLINE( 227) int index = (((( (int)(bytes->b->__get(dataPosition)) ) | (( (int)(bytes->b->__get((dataPosition + 1))) ) << 8)) | (( (int)(bytes->b->__get((dataPosition + 2))) ) << 16)) | (( (int)(bytes->b->__get((dataPosition + 3))) ) << 24)); HXLINE( 228) dataPosition = (dataPosition + 4); HXLINE( 229) int width = (((( (int)(bytes->b->__get(dataPosition)) ) | (( (int)(bytes->b->__get((dataPosition + 1))) ) << 8)) | (( (int)(bytes->b->__get((dataPosition + 2))) ) << 16)) | (( (int)(bytes->b->__get((dataPosition + 3))) ) << 24)); HXLINE( 230) dataPosition = (dataPosition + 4); HXLINE( 231) int height = (((( (int)(bytes->b->__get(dataPosition)) ) | (( (int)(bytes->b->__get((dataPosition + 1))) ) << 8)) | (( (int)(bytes->b->__get((dataPosition + 2))) ) << 16)) | (( (int)(bytes->b->__get((dataPosition + 3))) ) << 24)); HXLINE( 232) dataPosition = (dataPosition + 4); HXLINE( 233) int x = (((( (int)(bytes->b->__get(dataPosition)) ) | (( (int)(bytes->b->__get((dataPosition + 1))) ) << 8)) | (( (int)(bytes->b->__get((dataPosition + 2))) ) << 16)) | (( (int)(bytes->b->__get((dataPosition + 3))) ) << 24)); HXLINE( 234) dataPosition = (dataPosition + 4); HXLINE( 235) int y = (((( (int)(bytes->b->__get(dataPosition)) ) | (( (int)(bytes->b->__get((dataPosition + 1))) ) << 8)) | (( (int)(bytes->b->__get((dataPosition + 2))) ) << 16)) | (( (int)(bytes->b->__get((dataPosition + 3))) ) << 24)); HXLINE( 236) dataPosition = (dataPosition + 4); HXLINE( 238) ::haxe::io::Bytes data = bytes->sub(dataPosition,(width * height)); HXLINE( 239) dataPosition = (dataPosition + (width * height)); HXLINE( 241) ::lime::utils::ArrayBufferView this1; HXDLIN( 241) if (hx::IsNotNull( data )) { HXLINE( 241) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,4); HXDLIN( 241) int in_byteOffset = 0; HXDLIN( 241) if ((in_byteOffset < 0)) { HXLINE( 241) HX_STACK_DO_THROW(::lime::utils::TAError_obj::RangeError_dyn()); } HXDLIN( 241) if ((hx::Mod(in_byteOffset,_this->bytesPerElement) != 0)) { HXLINE( 241) HX_STACK_DO_THROW(::lime::utils::TAError_obj::RangeError_dyn()); } HXDLIN( 241) int bufferByteLength = data->length; HXDLIN( 241) int elementSize = _this->bytesPerElement; HXDLIN( 241) int newByteLength = bufferByteLength; HXDLIN( 241) { HXLINE( 241) newByteLength = (bufferByteLength - in_byteOffset); HXDLIN( 241) if ((hx::Mod(bufferByteLength,_this->bytesPerElement) != 0)) { HXLINE( 241) HX_STACK_DO_THROW(::lime::utils::TAError_obj::RangeError_dyn()); } HXDLIN( 241) if ((newByteLength < 0)) { HXLINE( 241) HX_STACK_DO_THROW(::lime::utils::TAError_obj::RangeError_dyn()); } } HXDLIN( 241) _this->buffer = data; HXDLIN( 241) _this->byteOffset = in_byteOffset; HXDLIN( 241) _this->byteLength = newByteLength; HXDLIN( 241) _this->length = ::Std_obj::_hx_int((( (Float)(newByteLength) ) / ( (Float)(_this->bytesPerElement) ))); HXDLIN( 241) this1 = _this; } else { HXLINE( 241) HX_STACK_DO_THROW(HX_("Invalid constructor arguments for UInt8Array",6b,44,d5,85)); } HXDLIN( 241) ::lime::graphics::ImageBuffer buffer = ::lime::graphics::ImageBuffer_obj::__alloc( HX_CTX ,this1,width,height,8,null()); HXLINE( 242) ::lime::graphics::Image image = ::lime::graphics::Image_obj::__alloc( HX_CTX ,buffer,0,0,width,height,null(),null()); HXLINE( 243) image->x = ( (Float)(x) ); HXLINE( 244) image->y = ( (Float)(y) ); HXLINE( 246) return image; } HXLINE( 250) return null(); } HX_DEFINE_DYNAMIC_FUNC2(Font_obj,renderGlyph,return ) ::haxe::ds::IntMap Font_obj::renderGlyphs(::Array< int > glyphs,int fontSize){ HX_GC_STACKFRAME(&_hx_pos_51012fd6257f8a4a_254_renderGlyphs) HXLINE( 256) ::haxe::ds::IntMap uniqueGlyphs = ::haxe::ds::IntMap_obj::__alloc( HX_CTX ); HXLINE( 258) { HXLINE( 258) int _g = 0; HXDLIN( 258) while((_g < glyphs->length)){ HXLINE( 258) int glyph = glyphs->__get(_g); HXDLIN( 258) _g = (_g + 1); HXLINE( 260) uniqueGlyphs->set(glyph,true); } } HXLINE( 263) ::Array< int > glyphList = ::Array_obj< int >::__new(0); HXLINE( 265) { HXLINE( 265) ::Dynamic key = uniqueGlyphs->keys(); HXDLIN( 265) while(( (bool)(key->__Field(HX_("hasNext",6d,a5,46,18),hx::paccDynamic)()) )){ HXLINE( 265) int key1 = ( (int)(key->__Field(HX_("next",f3,84,02,49),hx::paccDynamic)()) ); HXLINE( 267) glyphList->push(key1); } } HXLINE( 281) ::lime::_internal::backend::native::NativeCFFI_obj::lime_font_set_size(hx::DynamicPtr(this->src),fontSize); HXLINE( 283) ::haxe::io::Bytes bytes = ::haxe::io::Bytes_obj::alloc(0); HXLINE( 284) bytes = ( ( ::Dynamic)(::lime::_internal::backend::native::NativeCFFI_obj::lime_font_render_glyphs(hx::DynamicPtr(this->src),hx::DynamicPtr(glyphList),hx::DynamicPtr(bytes))) ); HXLINE( 286) bool _hx_tmp; HXDLIN( 286) if (hx::IsNotNull( bytes )) { HXLINE( 286) _hx_tmp = (bytes->length > 0); } else { HXLINE( 286) _hx_tmp = false; } HXDLIN( 286) if (_hx_tmp) { HXLINE( 288) int bytesPosition = 0; HXLINE( 289) int count = (((( (int)(bytes->b->__get(bytesPosition)) ) | (( (int)(bytes->b->__get((bytesPosition + 1))) ) << 8)) | (( (int)(bytes->b->__get((bytesPosition + 2))) ) << 16)) | (( (int)(bytes->b->__get((bytesPosition + 3))) ) << 24)); HXLINE( 290) bytesPosition = (bytesPosition + 4); HXLINE( 292) int bufferWidth = 128; HXLINE( 293) int bufferHeight = 128; HXLINE( 294) int offsetX = 0; HXLINE( 295) int offsetY = 0; HXLINE( 296) int maxRows = 0; HXLINE( 298) int width; HXDLIN( 298) int height; HXLINE( 299) int i = 0; HXLINE( 301) while((i < count)){ HXLINE( 303) bytesPosition = (bytesPosition + 4); HXLINE( 304) width = (((( (int)(bytes->b->__get(bytesPosition)) ) | (( (int)(bytes->b->__get((bytesPosition + 1))) ) << 8)) | (( (int)(bytes->b->__get((bytesPosition + 2))) ) << 16)) | (( (int)(bytes->b->__get((bytesPosition + 3))) ) << 24)); HXLINE( 305) bytesPosition = (bytesPosition + 4); HXLINE( 306) height = (((( (int)(bytes->b->__get(bytesPosition)) ) | (( (int)(bytes->b->__get((bytesPosition + 1))) ) << 8)) | (( (int)(bytes->b->__get((bytesPosition + 2))) ) << 16)) | (( (int)(bytes->b->__get((bytesPosition + 3))) ) << 24)); HXLINE( 307) bytesPosition = (bytesPosition + 4); HXLINE( 309) bytesPosition = (bytesPosition + (8 + (width * height))); HXLINE( 311) if (((offsetX + width) > bufferWidth)) { HXLINE( 313) offsetY = (offsetY + (maxRows + 1)); HXLINE( 314) offsetX = 0; HXLINE( 315) maxRows = 0; } HXLINE( 318) if (((offsetY + height) > bufferHeight)) { HXLINE( 320) if ((bufferWidth < bufferHeight)) { HXLINE( 322) bufferWidth = (bufferWidth * 2); } else { HXLINE( 326) bufferHeight = (bufferHeight * 2); } HXLINE( 329) offsetX = 0; HXLINE( 330) offsetY = 0; HXLINE( 331) maxRows = 0; HXLINE( 335) bytesPosition = 4; HXLINE( 336) i = 0; HXLINE( 337) continue; } HXLINE( 340) offsetX = (offsetX + (width + 1)); HXLINE( 342) if ((height > maxRows)) { HXLINE( 344) maxRows = height; } HXLINE( 347) i = (i + 1); } HXLINE( 350) ::haxe::ds::IntMap map = ::haxe::ds::IntMap_obj::__alloc( HX_CTX ); HXLINE( 351) ::lime::graphics::ImageBuffer buffer = ::lime::graphics::ImageBuffer_obj::__alloc( HX_CTX ,null(),bufferWidth,bufferHeight,8,null()); HXLINE( 352) int dataPosition = 0; HXLINE( 353) ::haxe::io::Bytes data = ::haxe::io::Bytes_obj::alloc((bufferWidth * bufferHeight)); HXLINE( 355) bytesPosition = 4; HXLINE( 356) offsetX = 0; HXLINE( 357) offsetY = 0; HXLINE( 358) maxRows = 0; HXLINE( 360) int index; HXDLIN( 360) int x; HXDLIN( 360) int y; HXDLIN( 360) ::lime::graphics::Image image; HXLINE( 362) { HXLINE( 362) int _g1 = 0; HXDLIN( 362) int _g2 = count; HXDLIN( 362) while((_g1 < _g2)){ HXLINE( 362) _g1 = (_g1 + 1); HXDLIN( 362) int i1 = (_g1 - 1); HXLINE( 364) index = (((( (int)(bytes->b->__get(bytesPosition)) ) | (( (int)(bytes->b->__get((bytesPosition + 1))) ) << 8)) | (( (int)(bytes->b->__get((bytesPosition + 2))) ) << 16)) | (( (int)(bytes->b->__get((bytesPosition + 3))) ) << 24)); HXLINE( 365) bytesPosition = (bytesPosition + 4); HXLINE( 366) width = (((( (int)(bytes->b->__get(bytesPosition)) ) | (( (int)(bytes->b->__get((bytesPosition + 1))) ) << 8)) | (( (int)(bytes->b->__get((bytesPosition + 2))) ) << 16)) | (( (int)(bytes->b->__get((bytesPosition + 3))) ) << 24)); HXLINE( 367) bytesPosition = (bytesPosition + 4); HXLINE( 368) height = (((( (int)(bytes->b->__get(bytesPosition)) ) | (( (int)(bytes->b->__get((bytesPosition + 1))) ) << 8)) | (( (int)(bytes->b->__get((bytesPosition + 2))) ) << 16)) | (( (int)(bytes->b->__get((bytesPosition + 3))) ) << 24)); HXLINE( 369) bytesPosition = (bytesPosition + 4); HXLINE( 370) x = (((( (int)(bytes->b->__get(bytesPosition)) ) | (( (int)(bytes->b->__get((bytesPosition + 1))) ) << 8)) | (( (int)(bytes->b->__get((bytesPosition + 2))) ) << 16)) | (( (int)(bytes->b->__get((bytesPosition + 3))) ) << 24)); HXLINE( 371) bytesPosition = (bytesPosition + 4); HXLINE( 372) y = (((( (int)(bytes->b->__get(bytesPosition)) ) | (( (int)(bytes->b->__get((bytesPosition + 1))) ) << 8)) | (( (int)(bytes->b->__get((bytesPosition + 2))) ) << 16)) | (( (int)(bytes->b->__get((bytesPosition + 3))) ) << 24)); HXLINE( 373) bytesPosition = (bytesPosition + 4); HXLINE( 375) if (((offsetX + width) > bufferWidth)) { HXLINE( 377) offsetY = (offsetY + (maxRows + 1)); HXLINE( 378) offsetX = 0; HXLINE( 379) maxRows = 0; } HXLINE( 382) { HXLINE( 382) int _g11 = 0; HXDLIN( 382) int _g21 = height; HXDLIN( 382) while((_g11 < _g21)){ HXLINE( 382) _g11 = (_g11 + 1); HXDLIN( 382) int i2 = (_g11 - 1); HXLINE( 384) dataPosition = (((i2 + offsetY) * bufferWidth) + offsetX); HXLINE( 385) data->blit(dataPosition,bytes,bytesPosition,width); HXLINE( 386) bytesPosition = (bytesPosition + width); } } HXLINE( 389) image = ::lime::graphics::Image_obj::__alloc( HX_CTX ,buffer,offsetX,offsetY,width,height,null(),null()); HXLINE( 390) image->x = ( (Float)(x) ); HXLINE( 391) image->y = ( (Float)(y) ); HXLINE( 393) map->set(index,image); HXLINE( 395) offsetX = (offsetX + (width + 1)); HXLINE( 397) if ((height > maxRows)) { HXLINE( 399) maxRows = height; } } } HXLINE( 406) ::lime::utils::ArrayBufferView this1; HXDLIN( 406) if (hx::IsNotNull( data )) { HXLINE( 406) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,4); HXDLIN( 406) int in_byteOffset = 0; HXDLIN( 406) if ((in_byteOffset < 0)) { HXLINE( 406) HX_STACK_DO_THROW(::lime::utils::TAError_obj::RangeError_dyn()); } HXDLIN( 406) if ((hx::Mod(in_byteOffset,_this->bytesPerElement) != 0)) { HXLINE( 406) HX_STACK_DO_THROW(::lime::utils::TAError_obj::RangeError_dyn()); } HXDLIN( 406) int bufferByteLength = data->length; HXDLIN( 406) int elementSize = _this->bytesPerElement; HXDLIN( 406) int newByteLength = bufferByteLength; HXDLIN( 406) { HXLINE( 406) newByteLength = (bufferByteLength - in_byteOffset); HXDLIN( 406) if ((hx::Mod(bufferByteLength,_this->bytesPerElement) != 0)) { HXLINE( 406) HX_STACK_DO_THROW(::lime::utils::TAError_obj::RangeError_dyn()); } HXDLIN( 406) if ((newByteLength < 0)) { HXLINE( 406) HX_STACK_DO_THROW(::lime::utils::TAError_obj::RangeError_dyn()); } } HXDLIN( 406) _this->buffer = data; HXDLIN( 406) _this->byteOffset = in_byteOffset; HXDLIN( 406) _this->byteLength = newByteLength; HXDLIN( 406) _this->length = ::Std_obj::_hx_int((( (Float)(newByteLength) ) / ( (Float)(_this->bytesPerElement) ))); HXDLIN( 406) this1 = _this; } else { HXLINE( 406) HX_STACK_DO_THROW(HX_("Invalid constructor arguments for UInt8Array",6b,44,d5,85)); } HXDLIN( 406) buffer->data = this1; HXLINE( 409) return map; } HXLINE( 413) return null(); } HX_DEFINE_DYNAMIC_FUNC2(Font_obj,renderGlyphs,return ) void Font_obj::_hx___copyFrom( ::lime::text::Font other){ HX_STACKFRAME(&_hx_pos_51012fd6257f8a4a_418___copyFrom) HXDLIN( 418) if (hx::IsNotNull( other )) { HXLINE( 420) this->ascender = other->ascender; HXLINE( 421) this->descender = other->descender; HXLINE( 422) this->height = other->height; HXLINE( 423) this->name = other->name; HXLINE( 424) this->numGlyphs = other->numGlyphs; HXLINE( 425) this->src = other->src; HXLINE( 426) this->underlinePosition = other->underlinePosition; HXLINE( 427) this->underlineThickness = other->underlineThickness; HXLINE( 428) this->unitsPerEM = other->unitsPerEM; HXLINE( 430) this->_hx___fontID = other->_hx___fontID; HXLINE( 431) this->_hx___fontPath = other->_hx___fontPath; HXLINE( 434) this->_hx___fontPathWithoutDirectory = other->_hx___fontPathWithoutDirectory; HXLINE( 437) this->_hx___init = true; } } HX_DEFINE_DYNAMIC_FUNC1(Font_obj,_hx___copyFrom,(void)) void Font_obj::_hx___fromBytes( ::haxe::io::Bytes bytes){ HX_STACKFRAME(&_hx_pos_51012fd6257f8a4a_442___fromBytes) HXLINE( 443) this->_hx___fontPath = null(); HXLINE( 446) this->_hx___fontPathWithoutDirectory = null(); HXLINE( 448) this->src = ( ( ::Dynamic)(::lime::_internal::backend::native::NativeCFFI_obj::lime_font_load_bytes(hx::DynamicPtr(bytes))) ); HXLINE( 450) this->_hx___initializeSource(); } HX_DEFINE_DYNAMIC_FUNC1(Font_obj,_hx___fromBytes,(void)) void Font_obj::_hx___fromFile(::String path){ HX_STACKFRAME(&_hx_pos_51012fd6257f8a4a_455___fromFile) HXLINE( 456) this->_hx___fontPath = path; HXLINE( 459) this->_hx___fontPathWithoutDirectory = ::haxe::io::Path_obj::withoutDirectory(this->_hx___fontPath); HXLINE( 461) this->src = ( ( ::Dynamic)(::lime::_internal::backend::native::NativeCFFI_obj::lime_font_load_file(hx::DynamicPtr(this->_hx___fontPath))) ); HXLINE( 463) this->_hx___initializeSource(); } HX_DEFINE_DYNAMIC_FUNC1(Font_obj,_hx___fromFile,(void)) void Font_obj::_hx___initializeSource(){ HX_STACKFRAME(&_hx_pos_51012fd6257f8a4a_468___initializeSource) HXLINE( 470) if (hx::IsNotNull( this->src )) { HXLINE( 472) if (hx::IsNull( this->name )) { HXLINE( 477) this->name = ( (::String)(( ( ::Dynamic)(::lime::_internal::backend::native::NativeCFFI_obj::lime_font_get_family_name(hx::DynamicPtr(this->src))) )) ); } HXLINE( 481) this->ascender = ::lime::_internal::backend::native::NativeCFFI_obj::lime_font_get_ascender(hx::DynamicPtr(this->src)); HXLINE( 482) this->descender = ::lime::_internal::backend::native::NativeCFFI_obj::lime_font_get_descender(hx::DynamicPtr(this->src)); HXLINE( 483) this->height = ::lime::_internal::backend::native::NativeCFFI_obj::lime_font_get_height(hx::DynamicPtr(this->src)); HXLINE( 484) this->numGlyphs = ::lime::_internal::backend::native::NativeCFFI_obj::lime_font_get_num_glyphs(hx::DynamicPtr(this->src)); HXLINE( 485) this->underlinePosition = ::lime::_internal::backend::native::NativeCFFI_obj::lime_font_get_underline_position(hx::DynamicPtr(this->src)); HXLINE( 486) this->underlineThickness = ::lime::_internal::backend::native::NativeCFFI_obj::lime_font_get_underline_thickness(hx::DynamicPtr(this->src)); HXLINE( 487) this->unitsPerEM = ::lime::_internal::backend::native::NativeCFFI_obj::lime_font_get_units_per_em(hx::DynamicPtr(this->src)); } HXLINE( 491) this->_hx___init = true; } HX_DEFINE_DYNAMIC_FUNC0(Font_obj,_hx___initializeSource,(void)) ::lime::app::Future Font_obj::_hx___loadFromName(::String name){ HX_GC_STACKFRAME(&_hx_pos_51012fd6257f8a4a_495___loadFromName) HXLINE( 496) ::lime::app::Promise_lime_text_Font promise = ::lime::app::Promise_lime_text_Font_obj::__alloc( HX_CTX ); HXLINE( 557) promise->error(HX_("",00,00,00,00)); HXLINE( 560) return promise->future; } HX_DEFINE_DYNAMIC_FUNC1(Font_obj,_hx___loadFromName,return ) void Font_obj::_hx___setSize(int size){ HX_STACKFRAME(&_hx_pos_51012fd6257f8a4a_592___setSize) HXDLIN( 592) ::lime::_internal::backend::native::NativeCFFI_obj::lime_font_set_size(hx::DynamicPtr(this->src),size); } HX_DEFINE_DYNAMIC_FUNC1(Font_obj,_hx___setSize,(void)) ::lime::text::Font Font_obj::fromBytes( ::haxe::io::Bytes bytes){ HX_GC_STACKFRAME(&_hx_pos_51012fd6257f8a4a_120_fromBytes) HXLINE( 121) if (hx::IsNull( bytes )) { HXLINE( 121) return null(); } HXLINE( 123) ::lime::text::Font font = ::lime::text::Font_obj::__alloc( HX_CTX ,null()); HXLINE( 124) font->_hx___fromBytes(bytes); HXLINE( 127) if (hx::IsNotNull( font->src )) { HXLINE( 127) return font; } else { HXLINE( 127) return null(); } HXDLIN( 127) return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Font_obj,fromBytes,return ) ::lime::text::Font Font_obj::fromFile(::String path){ HX_GC_STACKFRAME(&_hx_pos_51012fd6257f8a4a_134_fromFile) HXLINE( 135) if (hx::IsNull( path )) { HXLINE( 135) return null(); } HXLINE( 137) ::lime::text::Font font = ::lime::text::Font_obj::__alloc( HX_CTX ,null()); HXLINE( 138) font->_hx___fromFile(path); HXLINE( 141) if (hx::IsNotNull( font->src )) { HXLINE( 141) return font; } else { HXLINE( 141) return null(); } HXDLIN( 141) return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Font_obj,fromFile,return ) ::lime::app::Future Font_obj::loadFromBytes( ::haxe::io::Bytes bytes){ HX_STACKFRAME(&_hx_pos_51012fd6257f8a4a_149_loadFromBytes) HXDLIN( 149) return ::lime::app::Future_obj::withValue(::lime::text::Font_obj::fromBytes(bytes)); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Font_obj,loadFromBytes,return ) ::lime::app::Future Font_obj::loadFromFile(::String path){ HX_BEGIN_LOCAL_FUNC_S0(hx::LocalFunc,_hx_Closure_0) HXARGC(1) ::lime::app::Future _hx_run( ::lime::text::Font font){ HX_GC_STACKFRAME(&_hx_pos_51012fd6257f8a4a_157_loadFromFile) HXLINE( 157) if (hx::IsNotNull( font )) { HXLINE( 159) return ::lime::app::Future_obj::withValue(font); } else { HXLINE( 163) return ::lime::app::Future_obj::withError(HX_("",00,00,00,00)); } HXLINE( 157) return null(); } HX_END_LOCAL_FUNC1(return) HX_GC_STACKFRAME(&_hx_pos_51012fd6257f8a4a_153_loadFromFile) HXLINE( 154) ::lime::net::_HTTPRequest_lime_text_Font request = ::lime::net::_HTTPRequest_lime_text_Font_obj::__alloc( HX_CTX ,null()); HXLINE( 155) return request->load(path)->then( ::Dynamic(new _hx_Closure_0())); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Font_obj,loadFromFile,return ) ::lime::app::Future Font_obj::loadFromName(::String path){ HX_STACKFRAME(&_hx_pos_51012fd6257f8a4a_174_loadFromName) HXDLIN( 174) return ::lime::app::Future_obj::withError(HX_("",00,00,00,00)); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Font_obj,loadFromName,return ) hx::ObjectPtr< Font_obj > Font_obj::__new(::String name) { hx::ObjectPtr< Font_obj > __this = new Font_obj(); __this->__construct(name); return __this; } hx::ObjectPtr< Font_obj > Font_obj::__alloc(hx::Ctx *_hx_ctx,::String name) { Font_obj *__this = (Font_obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(Font_obj), true, "lime.text.Font")); *(void **)__this = Font_obj::_hx_vtable; __this->__construct(name); return __this; } Font_obj::Font_obj() { } void Font_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(Font); HX_MARK_MEMBER_NAME(ascender,"ascender"); HX_MARK_MEMBER_NAME(descender,"descender"); HX_MARK_MEMBER_NAME(height,"height"); HX_MARK_MEMBER_NAME(name,"name"); HX_MARK_MEMBER_NAME(numGlyphs,"numGlyphs"); HX_MARK_MEMBER_NAME(src,"src"); HX_MARK_MEMBER_NAME(underlinePosition,"underlinePosition"); HX_MARK_MEMBER_NAME(underlineThickness,"underlineThickness"); HX_MARK_MEMBER_NAME(unitsPerEM,"unitsPerEM"); HX_MARK_MEMBER_NAME(_hx___fontID,"__fontID"); HX_MARK_MEMBER_NAME(_hx___fontPath,"__fontPath"); HX_MARK_MEMBER_NAME(_hx___fontPathWithoutDirectory,"__fontPathWithoutDirectory"); HX_MARK_MEMBER_NAME(_hx___init,"__init"); HX_MARK_END_CLASS(); } void Font_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(ascender,"ascender"); HX_VISIT_MEMBER_NAME(descender,"descender"); HX_VISIT_MEMBER_NAME(height,"height"); HX_VISIT_MEMBER_NAME(name,"name"); HX_VISIT_MEMBER_NAME(numGlyphs,"numGlyphs"); HX_VISIT_MEMBER_NAME(src,"src"); HX_VISIT_MEMBER_NAME(underlinePosition,"underlinePosition"); HX_VISIT_MEMBER_NAME(underlineThickness,"underlineThickness"); HX_VISIT_MEMBER_NAME(unitsPerEM,"unitsPerEM"); HX_VISIT_MEMBER_NAME(_hx___fontID,"__fontID"); HX_VISIT_MEMBER_NAME(_hx___fontPath,"__fontPath"); HX_VISIT_MEMBER_NAME(_hx___fontPathWithoutDirectory,"__fontPathWithoutDirectory"); HX_VISIT_MEMBER_NAME(_hx___init,"__init"); } hx::Val Font_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp) { switch(inName.length) { case 3: if (HX_FIELD_EQ(inName,"src") ) { return hx::Val( src ); } break; case 4: if (HX_FIELD_EQ(inName,"name") ) { return hx::Val( name ); } break; case 6: if (HX_FIELD_EQ(inName,"height") ) { return hx::Val( height ); } if (HX_FIELD_EQ(inName,"__init") ) { return hx::Val( _hx___init ); } break; case 8: if (HX_FIELD_EQ(inName,"ascender") ) { return hx::Val( ascender ); } if (HX_FIELD_EQ(inName,"__fontID") ) { return hx::Val( _hx___fontID ); } if (HX_FIELD_EQ(inName,"getGlyph") ) { return hx::Val( getGlyph_dyn() ); } break; case 9: if (HX_FIELD_EQ(inName,"descender") ) { return hx::Val( descender ); } if (HX_FIELD_EQ(inName,"numGlyphs") ) { return hx::Val( numGlyphs ); } if (HX_FIELD_EQ(inName,"decompose") ) { return hx::Val( decompose_dyn() ); } if (HX_FIELD_EQ(inName,"getGlyphs") ) { return hx::Val( getGlyphs_dyn() ); } if (HX_FIELD_EQ(inName,"__setSize") ) { return hx::Val( _hx___setSize_dyn() ); } break; case 10: if (HX_FIELD_EQ(inName,"unitsPerEM") ) { return hx::Val( unitsPerEM ); } if (HX_FIELD_EQ(inName,"__fontPath") ) { return hx::Val( _hx___fontPath ); } if (HX_FIELD_EQ(inName,"__copyFrom") ) { return hx::Val( _hx___copyFrom_dyn() ); } if (HX_FIELD_EQ(inName,"__fromFile") ) { return hx::Val( _hx___fromFile_dyn() ); } break; case 11: if (HX_FIELD_EQ(inName,"renderGlyph") ) { return hx::Val( renderGlyph_dyn() ); } if (HX_FIELD_EQ(inName,"__fromBytes") ) { return hx::Val( _hx___fromBytes_dyn() ); } break; case 12: if (HX_FIELD_EQ(inName,"renderGlyphs") ) { return hx::Val( renderGlyphs_dyn() ); } break; case 14: if (HX_FIELD_EQ(inName,"__loadFromName") ) { return hx::Val( _hx___loadFromName_dyn() ); } break; case 15: if (HX_FIELD_EQ(inName,"getGlyphMetrics") ) { return hx::Val( getGlyphMetrics_dyn() ); } break; case 17: if (HX_FIELD_EQ(inName,"underlinePosition") ) { return hx::Val( underlinePosition ); } break; case 18: if (HX_FIELD_EQ(inName,"underlineThickness") ) { return hx::Val( underlineThickness ); } if (HX_FIELD_EQ(inName,"__initializeSource") ) { return hx::Val( _hx___initializeSource_dyn() ); } break; case 26: if (HX_FIELD_EQ(inName,"__fontPathWithoutDirectory") ) { return hx::Val( _hx___fontPathWithoutDirectory ); } } return super::__Field(inName,inCallProp); } bool Font_obj::__GetStatic(const ::String &inName, Dynamic &outValue, hx::PropertyAccess inCallProp) { switch(inName.length) { case 8: if (HX_FIELD_EQ(inName,"fromFile") ) { outValue = fromFile_dyn(); return true; } break; case 9: if (HX_FIELD_EQ(inName,"fromBytes") ) { outValue = fromBytes_dyn(); return true; } break; case 12: if (HX_FIELD_EQ(inName,"loadFromFile") ) { outValue = loadFromFile_dyn(); return true; } if (HX_FIELD_EQ(inName,"loadFromName") ) { outValue = loadFromName_dyn(); return true; } break; case 13: if (HX_FIELD_EQ(inName,"loadFromBytes") ) { outValue = loadFromBytes_dyn(); return true; } } return false; } hx::Val Font_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp) { switch(inName.length) { case 3: if (HX_FIELD_EQ(inName,"src") ) { src=inValue.Cast< ::Dynamic >(); return inValue; } break; case 4: if (HX_FIELD_EQ(inName,"name") ) { name=inValue.Cast< ::String >(); return inValue; } break; case 6: if (HX_FIELD_EQ(inName,"height") ) { height=inValue.Cast< int >(); return inValue; } if (HX_FIELD_EQ(inName,"__init") ) { _hx___init=inValue.Cast< bool >(); return inValue; } break; case 8: if (HX_FIELD_EQ(inName,"ascender") ) { ascender=inValue.Cast< int >(); return inValue; } if (HX_FIELD_EQ(inName,"__fontID") ) { _hx___fontID=inValue.Cast< ::String >(); return inValue; } break; case 9: if (HX_FIELD_EQ(inName,"descender") ) { descender=inValue.Cast< int >(); return inValue; } if (HX_FIELD_EQ(inName,"numGlyphs") ) { numGlyphs=inValue.Cast< int >(); return inValue; } break; case 10: if (HX_FIELD_EQ(inName,"unitsPerEM") ) { unitsPerEM=inValue.Cast< int >(); return inValue; } if (HX_FIELD_EQ(inName,"__fontPath") ) { _hx___fontPath=inValue.Cast< ::String >(); return inValue; } break; case 17: if (HX_FIELD_EQ(inName,"underlinePosition") ) { underlinePosition=inValue.Cast< int >(); return inValue; } break; case 18: if (HX_FIELD_EQ(inName,"underlineThickness") ) { underlineThickness=inValue.Cast< int >(); return inValue; } break; case 26: if (HX_FIELD_EQ(inName,"__fontPathWithoutDirectory") ) { _hx___fontPathWithoutDirectory=inValue.Cast< ::String >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void Font_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_("ascender",37,98,10,60)); outFields->push(HX_("descender",17,65,27,ab)); outFields->push(HX_("height",e7,07,4c,02)); outFields->push(HX_("name",4b,72,ff,48)); outFields->push(HX_("numGlyphs",2d,44,5a,5f)); outFields->push(HX_("src",e4,a6,57,00)); outFields->push(HX_("underlinePosition",d5,5d,6b,96)); outFields->push(HX_("underlineThickness",c8,ba,9b,91)); outFields->push(HX_("unitsPerEM",96,b6,60,21)); outFields->push(HX_("__fontID",8a,5a,1e,a3)); outFields->push(HX_("__fontPath",34,76,08,70)); outFields->push(HX_("__fontPathWithoutDirectory",59,11,28,91)); outFields->push(HX_("__init",30,9e,b3,f4)); super::__GetFields(outFields); }; #ifdef HXCPP_SCRIPTABLE static hx::StorageInfo Font_obj_sMemberStorageInfo[] = { {hx::fsInt,(int)offsetof(Font_obj,ascender),HX_("ascender",37,98,10,60)}, {hx::fsInt,(int)offsetof(Font_obj,descender),HX_("descender",17,65,27,ab)}, {hx::fsInt,(int)offsetof(Font_obj,height),HX_("height",e7,07,4c,02)}, {hx::fsString,(int)offsetof(Font_obj,name),HX_("name",4b,72,ff,48)}, {hx::fsInt,(int)offsetof(Font_obj,numGlyphs),HX_("numGlyphs",2d,44,5a,5f)}, {hx::fsObject /* ::Dynamic */ ,(int)offsetof(Font_obj,src),HX_("src",e4,a6,57,00)}, {hx::fsInt,(int)offsetof(Font_obj,underlinePosition),HX_("underlinePosition",d5,5d,6b,96)}, {hx::fsInt,(int)offsetof(Font_obj,underlineThickness),HX_("underlineThickness",c8,ba,9b,91)}, {hx::fsInt,(int)offsetof(Font_obj,unitsPerEM),HX_("unitsPerEM",96,b6,60,21)}, {hx::fsString,(int)offsetof(Font_obj,_hx___fontID),HX_("__fontID",8a,5a,1e,a3)}, {hx::fsString,(int)offsetof(Font_obj,_hx___fontPath),HX_("__fontPath",34,76,08,70)}, {hx::fsString,(int)offsetof(Font_obj,_hx___fontPathWithoutDirectory),HX_("__fontPathWithoutDirectory",59,11,28,91)}, {hx::fsBool,(int)offsetof(Font_obj,_hx___init),HX_("__init",30,9e,b3,f4)}, { hx::fsUnknown, 0, null()} }; static hx::StaticInfo *Font_obj_sStaticStorageInfo = 0; #endif static ::String Font_obj_sMemberFields[] = { HX_("ascender",37,98,10,60), HX_("descender",17,65,27,ab), HX_("height",e7,07,4c,02), HX_("name",4b,72,ff,48), HX_("numGlyphs",2d,44,5a,5f), HX_("src",e4,a6,57,00), HX_("underlinePosition",d5,5d,6b,96), HX_("underlineThickness",c8,ba,9b,91), HX_("unitsPerEM",96,b6,60,21), HX_("__fontID",8a,5a,1e,a3), HX_("__fontPath",34,76,08,70), HX_("__fontPathWithoutDirectory",59,11,28,91), HX_("__init",30,9e,b3,f4), HX_("decompose",b1,c3,a7,7a), HX_("getGlyph",36,0d,dc,f5), HX_("getGlyphs",7d,82,af,2a), HX_("getGlyphMetrics",ad,6f,39,58), HX_("renderGlyph",76,2a,b6,61), HX_("renderGlyphs",3d,fd,ae,1d), HX_("__copyFrom",df,7e,99,6b), HX_("__fromBytes",81,3b,4d,a0), HX_("__fromFile",26,10,c0,44), HX_("__initializeSource",6b,c5,c1,17), HX_("__loadFromName",3b,b0,f4,80), HX_("__setSize",63,32,26,93), ::String(null()) }; hx::Class Font_obj::__mClass; static ::String Font_obj_sStaticFields[] = { HX_("fromBytes",a1,f2,20,72), HX_("fromFile",06,9d,87,a1), HX_("loadFromBytes",9b,c3,86,f4), HX_("loadFromFile",4c,89,f0,5a), HX_("loadFromName",1b,2d,34,60), ::String(null()) }; void Font_obj::__register() { Font_obj _hx_dummy; Font_obj::_hx_vtable = *(void **)&_hx_dummy; hx::Static(__mClass) = new hx::Class_obj(); __mClass->mName = HX_("lime.text.Font",b7,86,7e,d1); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &Font_obj::__GetStatic; __mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField; __mClass->mStatics = hx::Class_obj::dupFunctions(Font_obj_sStaticFields); __mClass->mMembers = hx::Class_obj::dupFunctions(Font_obj_sMemberFields); __mClass->mCanCast = hx::TCanCast< Font_obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = Font_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = Font_obj_sStaticStorageInfo; #endif hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace lime } // end namespace text
47.970203
248
0.682014
arturspon
dde40449f8455a3781147ccc19987bfef51bcdaf
73
cpp
C++
LearningOpenGL/Source/Core/Material/Material.cpp
zhengweifu/LearningOpenGL
0d73b035ffa11112d62f0af974f4a8622eef6598
[ "MIT" ]
null
null
null
LearningOpenGL/Source/Core/Material/Material.cpp
zhengweifu/LearningOpenGL
0d73b035ffa11112d62f0af974f4a8622eef6598
[ "MIT" ]
null
null
null
LearningOpenGL/Source/Core/Material/Material.cpp
zhengweifu/LearningOpenGL
0d73b035ffa11112d62f0af974f4a8622eef6598
[ "MIT" ]
null
null
null
#include "Core/Material/Material.h" LEARN_OPENGL_BEGIN LEARN_OPENGL_END
14.6
35
0.849315
zhengweifu
ddeb3b3e963ca7fc1ade5249914d8461ee1b7e69
5,219
cpp
C++
hyperUI/source/StandardUI/UIRoundProgressElement.cpp
sadcatsoft/hyperui
f26242a9034ad1e0abf54bd7691fe48809262f5b
[ "MIT" ]
2
2019-05-17T16:16:21.000Z
2019-08-21T20:18:22.000Z
hyperUI/source/StandardUI/UIRoundProgressElement.cpp
sadcatsoft/hyperui
f26242a9034ad1e0abf54bd7691fe48809262f5b
[ "MIT" ]
1
2018-10-18T22:05:12.000Z
2018-10-18T22:05:12.000Z
hyperUI/source/StandardUI/UIRoundProgressElement.cpp
sadcatsoft/hyperui
f26242a9034ad1e0abf54bd7691fe48809262f5b
[ "MIT" ]
null
null
null
/***************************************************************************** Disclaimer: This software is supplied to you by Sad Cat Software ("Sad Cat") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Sad Cat software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Sad Cat software. This software is provided "as is". Sad Cat Software makes no warranties, express or implied, including without limitation the implied warranties of non-infringement, merchantability and fitness for a particular purpose, regarding Sad Cat's software or its use and operation alone or in combination with other hardware or software products. In no event shall Sad Cat Software be liable for any special, indirect, incidental, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) arising in any way out of the use, reproduction, modification and/or distribution of Sad Cat's software however caused and whether under theory of contract, tort (including negligence), strict liability or otherwise, even if Sad Cat Software has been advised of the possibility of such damage. Copyright (C) 2012, Sad Cat Software. All Rights Reserved. *****************************************************************************/ #include "stdafx.h" #define VALUE_ANIM_TIME 0.35 #define VALUE_ANIM_OFFSET_TIME 0.25 namespace HyperUI { /*****************************************************************************/ UIRoundProgressElement::UIRoundProgressElement(UIPlane* pParentPlane) : UIElement(pParentPlane) { onAllocated(pParentPlane); } /*****************************************************************************/ void UIRoundProgressElement::onAllocated(IBaseObject* pData) { UIElement::onAllocated(pData); myMinProgress = 0.0; myMaxProgress = 1.0; myCurrProgress = 0.0; myAnim.setNonAnimValue(0); } /*****************************************************************************/ void UIRoundProgressElement::stopCurrProgAnim() { GTIME lTime = Application::getInstance()->getGlobalTime(getClockType()); myAnim.setNonAnimValue(myAnim.getValue()); } /*****************************************************************************/ void UIRoundProgressElement::setProgress(FLOAT_TYPE fValue, bool bAnimated, FLOAT_TYPE fOverrideTime, bool bContinueFromCurrentAnim, FLOAT_TYPE fOffsetTime) { myCurrProgress = fValue; if(bAnimated) { if(bContinueFromCurrentAnim) { GTIME lTime = Application::getInstance()->getGlobalTime(getClockType()); FLOAT_TYPE fCurrVal = myAnim.getValue(); FLOAT_TYPE fFullTime = fOverrideTime > 0 ? fOverrideTime : VALUE_ANIM_TIME; FLOAT_TYPE fRemTime = fFullTime*(1.0 - fCurrVal); myAnim.setAnimation(fCurrVal, 1, fRemTime, getClockType()); //myAnim.setAnimation(fCurrVal, 1, fRemTime, getClockType(), AnimOverActionNone, NULL, fOffsetTime < 0 ? VALUE_ANIM_OFFSET_TIME : fOffsetTime); } else myAnim.setAnimation(0, 1, fOverrideTime > 0 ? fOverrideTime : VALUE_ANIM_TIME, getClockType()); //myAnim.setAnimation(0, 1, fOverrideTime > 0 ? fOverrideTime : VALUE_ANIM_TIME, getClockType(), AnimOverActionNone, NULL, fOffsetTime < 0 ? VALUE_ANIM_OFFSET_TIME : fOffsetTime); } else { myAnim.setNonAnimValue(1.0); } } /*****************************************************************************/ void UIRoundProgressElement::onPreRenderChildren(const SVector2D& svScroll, FLOAT_TYPE fOpacity, FLOAT_TYPE fScale) { UIElement::onPreRenderChildren(svScroll, fOpacity, fScale); SVector2D svPos; FLOAT_TYPE fFinalOpac, fLocScale; this->getLocalPosition(svPos, &fFinalOpac, &fLocScale); // , &fLocRotAngle); fFinalOpac *= fOpacity; svPos += svScroll; getDrawingCache()->flush(); // Render our actual progress GTIME lTime = Application::getInstance()->getGlobalTime(getClockType()); FLOAT_TYPE fAnim = myAnim.getValue(); renderProgressAnimInternal(svPos, fAnim, fFinalOpac, fScale); // Now render our top cap anim, if applicable: if(this->doesPropertyExist(PropertyCapImage)) { theCommonString = this->getStringProp(PropertyCapImage); getDrawingCache()->addSprite(theCommonString.c_str(), svPos.x, svPos.y, fFinalOpac, 0, fScale, 1.0, true); } } /*****************************************************************************/ void UIRoundProgressElement::renderProgressAnimInternal(SVector2D& svCenter, FLOAT_TYPE fAnimValue, FLOAT_TYPE fFinalOpacity, FLOAT_TYPE fScale) { FLOAT_TYPE fProgress = (myCurrProgress - myMinProgress)/(myMaxProgress - myMinProgress); fProgress *= fAnimValue; theCommonString = this->getStringProp(PropertyObjThirdAnim); FLOAT_TYPE fRadius = getTextureManager()->getFileWidth(theCommonString.c_str())*fScale*0.5; RenderUtils::renderCircularProgress(getParentWindow(), fProgress, theCommonString.c_str(), svCenter.x, svCenter.y, fRadius, fFinalOpacity); } /*****************************************************************************/ };
45.780702
183
0.659513
sadcatsoft
ddebca10b021a7199efef6f9a0c6c75f07d7e582
1,201
hpp
C++
gui/myscene.hpp
mguludag/QTextRecognizer
29dd7b746be831c01b6260ab20ca926f7ff835ca
[ "MIT" ]
25
2020-05-01T01:20:03.000Z
2022-01-19T02:48:12.000Z
gui/myscene.hpp
mguludag/QTextRecognizer
29dd7b746be831c01b6260ab20ca926f7ff835ca
[ "MIT" ]
null
null
null
gui/myscene.hpp
mguludag/QTextRecognizer
29dd7b746be831c01b6260ab20ca926f7ff835ca
[ "MIT" ]
7
2020-07-20T12:02:34.000Z
2022-01-06T03:09:31.000Z
#ifndef MYSCENE_HPP #define MYSCENE_HPP #include <QGraphicsScene> #include <QGraphicsSceneMouseEvent> #include <QMimeData> #include <QObject> #include <QUrl> #include <QWidget> class MyScene : public QGraphicsScene { Q_OBJECT struct Props { QPointF m_pos, m_topleft, m_bottomright; } Props; public: QString filename; explicit MyScene(QWidget *parent = nullptr); void mouseMoveEvent(QGraphicsSceneMouseEvent *event); void mousePressEvent(QGraphicsSceneMouseEvent *event); void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); struct Props getProps() { return Props; } signals: void moveSignal(); void pressSignal(); void releaseSignal(); void drop(); public slots: protected: void dragEnterEvent(QGraphicsSceneDragDropEvent *event) { if (event->mimeData()->hasUrls()) { event->acceptProposedAction(); } } void dragMoveEvent(QGraphicsSceneDragDropEvent *) {} void dropEvent(QGraphicsSceneDragDropEvent *event) { filename = event->mimeData()->urls()[0].toLocalFile(); event->acceptProposedAction(); emit drop(); } private: }; #endif // MYSCENE_HPP
21.836364
62
0.68443
mguludag
ddec9c4d0072be8232273bcf815412ca49de9664
1,383
hpp
C++
redemption/src/utils/serialize.hpp
DianaAssistant/DIANA
6a4c51c1861f6a936941b21c2c905fc291c229d7
[ "MIT" ]
null
null
null
redemption/src/utils/serialize.hpp
DianaAssistant/DIANA
6a4c51c1861f6a936941b21c2c905fc291c229d7
[ "MIT" ]
null
null
null
redemption/src/utils/serialize.hpp
DianaAssistant/DIANA
6a4c51c1861f6a936941b21c2c905fc291c229d7
[ "MIT" ]
null
null
null
/* This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. Product name: redemption, a FLOSS RDP proxy Copyright (C) Wallix 2014 Author(s): Christophe Grosjean bunch of functions used to serialized binary data */ #pragma once #include <array> #include <vector> inline std::array<uint8_t, 2> out_uint16_le(unsigned int v) { return {uint8_t(v), uint8_t(v >> 8)}; } inline std::array<uint8_t, 1> out_uint8(unsigned int v) { return {uint8_t(v)}; } inline std::array<uint8_t, 4> out_uint32_le(unsigned int v) { return {uint8_t(v), uint8_t(v >> 8), uint8_t(v >> 16), uint8_t(v >> 24)}; } inline void push_back_array(std::vector<uint8_t> & v, u8_array_view a) { v.insert(std::end(v), a.data(), a.data() + a.size()); }
29.425532
77
0.71222
DianaAssistant
ddf16c028182f525afa574368bb95a15376b0483
2,551
cpp
C++
Data Structures/Arrays/Dynamic Array.cpp
VaibhavDS19/Hackerrankchallenges
5207c4145547ad6707bb86f71c692be23445b56a
[ "MIT" ]
null
null
null
Data Structures/Arrays/Dynamic Array.cpp
VaibhavDS19/Hackerrankchallenges
5207c4145547ad6707bb86f71c692be23445b56a
[ "MIT" ]
null
null
null
Data Structures/Arrays/Dynamic Array.cpp
VaibhavDS19/Hackerrankchallenges
5207c4145547ad6707bb86f71c692be23445b56a
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; string ltrim(const string &); string rtrim(const string &); vector<string> split(const string &); /* * Complete the 'dynamicArray' function below. * * The function is expected to return an INTEGER_ARRAY. * The function accepts following parameters: * 1. INTEGER n * 2. 2D_INTEGER_ARRAY queries */ vector<int> dynamicArray(int n, vector<vector<int>> queries) { vector<vector<int>> seqlist(n); vector<int> sol; int lastAnswer=0, seq, size; for(vector<int> i:queries) { seq = (i[1]^lastAnswer)%n; if(i[0]==1) { seqlist[seq].push_back(i[2]); } else { size=seqlist[seq].size(); lastAnswer=seqlist[seq][i[2]%size]; sol.push_back(lastAnswer); } } return sol; } int main() { ofstream fout(getenv("OUTPUT_PATH")); string first_multiple_input_temp; getline(cin, first_multiple_input_temp); vector<string> first_multiple_input = split(rtrim(first_multiple_input_temp)); int n = stoi(first_multiple_input[0]); int q = stoi(first_multiple_input[1]); vector<vector<int>> queries(q); for (int i = 0; i < q; i++) { queries[i].resize(3); string queries_row_temp_temp; getline(cin, queries_row_temp_temp); vector<string> queries_row_temp = split(rtrim(queries_row_temp_temp)); for (int j = 0; j < 3; j++) { int queries_row_item = stoi(queries_row_temp[j]); queries[i][j] = queries_row_item; } } vector<int> result = dynamicArray(n, queries); for (int i = 0; i < result.size(); i++) { fout << result[i]; if (i != result.size() - 1) { fout << "\n"; } } fout << "\n"; fout.close(); return 0; } string ltrim(const string &str) { string s(str); s.erase( s.begin(), find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace))) ); return s; } string rtrim(const string &str) { string s(str); s.erase( find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(), s.end() ); return s; } vector<string> split(const string &str) { vector<string> tokens; string::size_type start = 0; string::size_type end = 0; while ((end = str.find(" ", start)) != string::npos) { tokens.push_back(str.substr(start, end - start)); start = end + 1; } tokens.push_back(str.substr(start)); return tokens; }
20.909836
82
0.577813
VaibhavDS19
ddf38c23944d3160b61f3fbc21fc437d746fc983
6,836
cpp
C++
src/CoreGenPortal/PortalCore/CoreRegClassInfoWin.cpp
opensocsysarch/CoreGenPortal
b6c8c9ca13fa8add969511f153331cad83953799
[ "Apache-2.0" ]
1
2019-06-25T13:06:14.000Z
2019-06-25T13:06:14.000Z
src/CoreGenPortal/PortalCore/CoreRegClassInfoWin.cpp
opensocsysarch/CoreGenPortal
b6c8c9ca13fa8add969511f153331cad83953799
[ "Apache-2.0" ]
128
2018-10-23T12:45:15.000Z
2021-12-28T13:09:39.000Z
src/CoreGenPortal/PortalCore/CoreRegClassInfoWin.cpp
opensocsysarch/CoreGenPortal
b6c8c9ca13fa8add969511f153331cad83953799
[ "Apache-2.0" ]
1
2021-01-20T23:17:34.000Z
2021-01-20T23:17:34.000Z
// // _COREREGCLASSINFOWIN_CPP_ // // Copyright (C) 2017-2020 Tactical Computing Laboratories, LLC // All Rights Reserved // contact@tactcomplabs.com // // See LICENSE in the top level directory for licensing details // #include "CoreGenPortal/PortalCore/CoreRegClassInfoWin.h" // Event Table wxBEGIN_EVENT_TABLE(CoreRegClassInfoWin, wxDialog) EVT_BUTTON(wxID_OK, CoreRegClassInfoWin::OnPressOk) EVT_BUTTON(wxID_SAVE, CoreRegClassInfoWin::OnSave) wxEND_EVENT_TABLE() CoreRegClassInfoWin::CoreRegClassInfoWin( wxWindow* parent, wxWindowID id, const wxString& title, CoreGenRegClass *RegClass ) : wxDialog( parent, id, title, wxDefaultPosition, wxSize(500,320), wxDEFAULT_DIALOG_STYLE|wxVSCROLL ){ RegClassNode = RegClass; // init the internals this->SetLayoutAdaptationMode(wxDIALOG_ADAPTATION_MODE_ENABLED); this->SetSizeHints( wxDefaultSize, wxDefaultSize ); // create the outer box sizer OuterSizer = new wxBoxSizer( wxVERTICAL ); // create the scrolled window Wnd = new wxScrolledWindow(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0, wxT("Scroll")); // create the inner sizer InnerSizer = new wxBoxSizer( wxVERTICAL ); // add all the interior data // -- reg class RegClassNameSizer = new wxBoxSizer( wxHORIZONTAL ); RegClassNameText = new wxStaticText( Wnd, 2, wxT("Register Class Name"), wxDefaultPosition, wxSize(160, -1), 0 ); RegClassNameText->Wrap(-1); RegClassNameSizer->Add( RegClassNameText, 0, wxALIGN_CENTER_VERTICAL|wxALL, 0 ); RegClassNameCtrl = new wxTextCtrl( Wnd, 0, RegClass ? wxString(RegClass->GetName()) : "", wxDefaultPosition, wxSize(320,25), 0, wxDefaultValidator, wxT("Reg Class Name") ); RegClassNameSizer->Add( RegClassNameCtrl, 0, wxALL, 0 ); InnerSizer->Add( RegClassNameSizer, 0, wxALIGN_CENTER|wxALL, 5 ); // -- Write ports ReadPortsSizer = new wxBoxSizer( wxHORIZONTAL ); ReadPortsText = new wxStaticText( Wnd, 4, wxT("Read Ports"), wxDefaultPosition, wxSize(160, -1), 0 ); ReadPortsText->Wrap(-1); ReadPortsSizer->Add( ReadPortsText, 0, wxALIGN_CENTER_VERTICAL|wxALL, 0 ); ReadPortsCtrl = new wxTextCtrl( Wnd, 5, RegClass ? wxString(std::to_string(RegClass->GetReadPorts())) : "", wxDefaultPosition, wxSize(320,25), 0, wxDefaultValidator, wxT("Read Ports") ); ReadPortsSizer->Add( ReadPortsCtrl, 0, wxALL, 0 ); InnerSizer->Add( ReadPortsSizer, 0, wxALIGN_CENTER|wxALL, 5 ); // -- write ports WritePortsSizer = new wxBoxSizer( wxHORIZONTAL ); WritePortsText = new wxStaticText( Wnd, 6, wxT("Write Ports"), wxDefaultPosition, wxSize(160, -1), 0 ); WritePortsText->Wrap(-1); WritePortsSizer->Add( WritePortsText, 0, wxALIGN_CENTER_VERTICAL|wxALL, 0 ); WritePortsCtrl = new wxTextCtrl( Wnd, 7, RegClass ? wxString(std::to_string(RegClass->GetWritePorts())) : "", wxDefaultPosition, wxSize(320,25), 0, wxDefaultValidator, wxT("Write Ports") ); WritePortsSizer->Add( WritePortsCtrl, 0, wxALL, 0 ); InnerSizer->Add( WritePortsSizer, 0, wxALIGN_CENTER|wxALL, 5 ); //-- registers RegNameSizer = new wxBoxSizer( wxHORIZONTAL ); RegNameText = new wxStaticText( Wnd, 3, wxT("Registers"), wxDefaultPosition, wxSize(160,-1), 0 ); RegNameText->Wrap(-1); RegNameSizer->Add( RegNameText, 0, wxALIGN_CENTER|wxALL, 0 ); RegNameCtrl = new wxTextCtrl( Wnd, 1, wxEmptyString, wxDefaultPosition, wxSize(320,100), wxTE_MULTILINE|wxHSCROLL, wxDefaultValidator, wxT("registers") ); if(RegClass){ for( unsigned i=0; i<RegClass->GetNumReg(); i++ ){ RegNameCtrl->AppendText(wxString(RegClass->GetReg(i)->GetName())+wxT("\n") ); } } RegNameSizer->Add( RegNameCtrl, 0, wxALL, 0 ); InnerSizer->Add( RegNameSizer, 0, wxALIGN_CENTER|wxALL, 5 ); // add the static line FinalStaticLine = new wxStaticLine( Wnd, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL ); InnerSizer->Add( FinalStaticLine, 1, wxEXPAND | wxALL, 5 ); // setup all the buttons m_socbuttonsizer = new wxStdDialogButtonSizer(); m_userOK = new wxButton( Wnd, wxID_CANCEL ); m_userSAVE = new wxButton( Wnd, wxID_SAVE); m_socbuttonsizer->SetAffirmativeButton( m_userOK ); m_socbuttonsizer->SetCancelButton( m_userSAVE ); m_socbuttonsizer->Realize(); InnerSizer->Add( m_socbuttonsizer, 0, wxALL, 5 ); Wnd->SetScrollbars(20,20,50,50); Wnd->SetSizer( InnerSizer ); Wnd->SetAutoLayout(true); Wnd->Layout(); // draw the dialog box until we get more info OuterSizer->Add(Wnd, 1, wxEXPAND | wxALL, 5 ); this->SetSizer( OuterSizer ); this->SetAutoLayout( true ); this->Layout(); } void CoreRegClassInfoWin::OnPressOk(wxCommandEvent& ok){ this->EndModal(wxID_OK); } void CoreRegClassInfoWin::OnSave(wxCommandEvent& save){ PortalMainFrame *PMF = (PortalMainFrame*)this->GetParent(); if(PMF->OnSave(this, this->RegClassNode, CGRegC)) this->EndModal(wxID_SAVE); } CoreRegClassInfoWin::~CoreRegClassInfoWin(){ } // EOF
37.355191
101
0.521065
opensocsysarch
ddf4dc2e60f13eb507819fa679390a2faface3ec
809
cpp
C++
c++/07 overload/src/main.cpp
dev-go/hello-world
a99e6dfb2868cfc5f04ccab87888619c5c420d0a
[ "BSD-3-Clause" ]
null
null
null
c++/07 overload/src/main.cpp
dev-go/hello-world
a99e6dfb2868cfc5f04ccab87888619c5c420d0a
[ "BSD-3-Clause" ]
null
null
null
c++/07 overload/src/main.cpp
dev-go/hello-world
a99e6dfb2868cfc5f04ccab87888619c5c420d0a
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2020, devgo.club // All rights reserved. #include <stdint.h> #include <stdlib.h> #include <iostream> int32_t get_max(int32_t x = 101, int32_t y = 102, int32_t z = 103); int32_t get_max(int32_t x, int32_t y); int main(int argc, char **argv) { int32_t a = 1; int32_t b = 2; int32_t c = 3; std::cout << "get_max: " << get_max(a, b, c) << std::endl; // std::cout << "get_max: " << get_max(a, b) << std::endl; // error: call to // 'get_max' is ambiguous return EXIT_SUCCESS; } int32_t get_max(int32_t x, int32_t y, int32_t z) { int32_t result = x; if (y > result) { result = y; } if (z > result) { result = z; } return result; } int32_t get_max(int32_t x, int32_t y) { int32_t result = x; if (y > result) { result = y; } return result; }
17.212766
78
0.599506
dev-go
ddf6a1deca6d3f253dfa1803ab574c0dcd66aead
660
cpp
C++
contest/1453/d/d.cpp
GoatGirl98/cf
4077ca8e0fe29dc2bbb7b60166989857cc062e17
[ "MIT" ]
null
null
null
contest/1453/d/d.cpp
GoatGirl98/cf
4077ca8e0fe29dc2bbb7b60166989857cc062e17
[ "MIT" ]
null
null
null
contest/1453/d/d.cpp
GoatGirl98/cf
4077ca8e0fe29dc2bbb7b60166989857cc062e17
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define watch(x) std::cout << (#x) << " is " << (x) << std::endl using LL = long long; int main() { //freopen("in", "r", stdin); std::cin.tie(nullptr)->sync_with_stdio(false); int cas = 1; std::cin >> cas; while (cas--) { LL n; std::cin >> n; if (n & 1) { std::cout << -1 << std::endl; continue; } n /= 2; std::vector<int> a; while (n) { --n; int x = 1; while (n >> x) ++x; --x; n -= (1LL << x); a.emplace_back(1); for (int i = 1; i < x; ++i) a.emplace_back(0); } std::cout << a.size() << std::endl; for (auto x : a) std::cout << x << " "; std::cout << std::endl; } return 0; }
20
64
0.480303
GoatGirl98
fb04460a52eaf8025e256f7b7a5bdc70ab6f86ef
7,202
cpp
C++
SDK/PUBG_Niagara_functions.cpp
realrespecter/PUBG-FULL-SDK
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
[ "MIT" ]
7
2019-03-06T11:04:52.000Z
2019-07-10T20:00:51.000Z
SDK/PUBG_Niagara_functions.cpp
realrespecter/PUBG-FULL-SDK
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
[ "MIT" ]
null
null
null
SDK/PUBG_Niagara_functions.cpp
realrespecter/PUBG-FULL-SDK
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
[ "MIT" ]
10
2019-03-06T11:53:46.000Z
2021-02-18T14:01:11.000Z
// PUBG FULL SDK - Generated By Respecter (5.3.4.11 [06/03/2019]) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "PUBG_Niagara_parameters.hpp" namespace SDK { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function Niagara.NiagaraComponent.SetRenderingEnabled // (Final, Native) // Parameters: // bool bInRenderingEnabled (Parm, ZeroConstructor, IsPlainOldData) void UNiagaraComponent::SetRenderingEnabled(bool bInRenderingEnabled) { static auto fn = UObject::FindObject<UFunction>("Function Niagara.NiagaraComponent.SetRenderingEnabled"); UNiagaraComponent_SetRenderingEnabled_Params params; params.bInRenderingEnabled = bInRenderingEnabled; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Niagara.NiagaraComponent.SetNiagaraVariableVec4 // (Final, Native) // Parameters: // class FString* InVariableName (Parm, ZeroConstructor) // struct FVector4* InValue (ConstParm, Parm, OutParm, ReferenceParm, IsPlainOldData) void UNiagaraComponent::SetNiagaraVariableVec4(class FString* InVariableName, struct FVector4* InValue) { static auto fn = UObject::FindObject<UFunction>("Function Niagara.NiagaraComponent.SetNiagaraVariableVec4"); UNiagaraComponent_SetNiagaraVariableVec4_Params params; params.InVariableName = InVariableName; params.InValue = InValue; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Niagara.NiagaraComponent.SetNiagaraVariableVec3 // (Final, Native) // Parameters: // class FString* InVariableName (Parm, ZeroConstructor) // struct FVector* InValue (Parm, IsPlainOldData) void UNiagaraComponent::SetNiagaraVariableVec3(class FString* InVariableName, struct FVector* InValue) { static auto fn = UObject::FindObject<UFunction>("Function Niagara.NiagaraComponent.SetNiagaraVariableVec3"); UNiagaraComponent_SetNiagaraVariableVec3_Params params; params.InVariableName = InVariableName; params.InValue = InValue; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Niagara.NiagaraComponent.SetNiagaraVariableVec2 // (Final, Native) // Parameters: // class FString* InVariableName (Parm, ZeroConstructor) // struct FVector2D* InValue (Parm, IsPlainOldData) void UNiagaraComponent::SetNiagaraVariableVec2(class FString* InVariableName, struct FVector2D* InValue) { static auto fn = UObject::FindObject<UFunction>("Function Niagara.NiagaraComponent.SetNiagaraVariableVec2"); UNiagaraComponent_SetNiagaraVariableVec2_Params params; params.InVariableName = InVariableName; params.InValue = InValue; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Niagara.NiagaraComponent.SetNiagaraVariableFloat // (Final, Native) // Parameters: // class FString* InVariableName (Parm, ZeroConstructor) // float* InValue (Parm, ZeroConstructor, IsPlainOldData) void UNiagaraComponent::SetNiagaraVariableFloat(class FString* InVariableName, float* InValue) { static auto fn = UObject::FindObject<UFunction>("Function Niagara.NiagaraComponent.SetNiagaraVariableFloat"); UNiagaraComponent_SetNiagaraVariableFloat_Params params; params.InVariableName = InVariableName; params.InValue = InValue; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Niagara.NiagaraComponent.SetNiagaraVariableBool // (Final, Native) // Parameters: // class FString* InVariableName (Parm, ZeroConstructor) // bool* InValue (Parm, ZeroConstructor, IsPlainOldData) void UNiagaraComponent::SetNiagaraVariableBool(class FString* InVariableName, bool* InValue) { static auto fn = UObject::FindObject<UFunction>("Function Niagara.NiagaraComponent.SetNiagaraVariableBool"); UNiagaraComponent_SetNiagaraVariableBool_Params params; params.InVariableName = InVariableName; params.InValue = InValue; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Niagara.NiagaraComponent.SetNiagaraStaticMeshDataInterfaceActor // (Final, Native) // Parameters: // class FString* InVariableName (Parm, ZeroConstructor) // class AActor** InSource (Parm, ZeroConstructor, IsPlainOldData) void UNiagaraComponent::SetNiagaraStaticMeshDataInterfaceActor(class FString* InVariableName, class AActor** InSource) { static auto fn = UObject::FindObject<UFunction>("Function Niagara.NiagaraComponent.SetNiagaraStaticMeshDataInterfaceActor"); UNiagaraComponent_SetNiagaraStaticMeshDataInterfaceActor_Params params; params.InVariableName = InVariableName; params.InSource = InSource; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Niagara.NiagaraComponent.SetNiagaraEmitterSpawnRate // (Final, Native) // Parameters: // class FString* InEmitterName (Parm, ZeroConstructor) // float* InValue (Parm, ZeroConstructor, IsPlainOldData) void UNiagaraComponent::SetNiagaraEmitterSpawnRate(class FString* InEmitterName, float* InValue) { static auto fn = UObject::FindObject<UFunction>("Function Niagara.NiagaraComponent.SetNiagaraEmitterSpawnRate"); UNiagaraComponent_SetNiagaraEmitterSpawnRate_Params params; params.InEmitterName = InEmitterName; params.InValue = InValue; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Niagara.NiagaraComponent.ResetEffect // (Final, Native) void UNiagaraComponent::ResetEffect() { static auto fn = UObject::FindObject<UFunction>("Function Niagara.NiagaraComponent.ResetEffect"); UNiagaraComponent_ResetEffect_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Niagara.NiagaraComponent.ReinitializeEffect // (Final, Native) void UNiagaraComponent::ReinitializeEffect() { static auto fn = UObject::FindObject<UFunction>("Function Niagara.NiagaraComponent.ReinitializeEffect"); UNiagaraComponent_ReinitializeEffect_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
30.260504
125
0.711469
realrespecter