hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
32a41e70dacf34144ee21b788e81882f3e67b773
224
cpp
C++
Aaaah/main.cpp
KalawelaLo/Kattis
cbe2cc742f9902f5d325deb04fd39208774070c5
[ "Unlicense" ]
null
null
null
Aaaah/main.cpp
KalawelaLo/Kattis
cbe2cc742f9902f5d325deb04fd39208774070c5
[ "Unlicense" ]
null
null
null
Aaaah/main.cpp
KalawelaLo/Kattis
cbe2cc742f9902f5d325deb04fd39208774070c5
[ "Unlicense" ]
null
null
null
#include <iostream> #include <string> using namespace std; int main() { string pat, doc; cin>> pat >> doc; if(pat.size() >= doc.size() ){ cout << "go\n";} else{ cout << "no\n";} return 0;}
20.363636
34
0.508929
KalawelaLo
32a734a47f29b1a3bd0f4f996292d833c6b809f3
636
hpp
C++
LeetCode/2124_CheckIfAllAsAppearBeforeBs.hpp
defUserName-404/Online-Judge
197ac5bf3e2149474b191eeff106b12cd723ec8c
[ "MIT" ]
null
null
null
LeetCode/2124_CheckIfAllAsAppearBeforeBs.hpp
defUserName-404/Online-Judge
197ac5bf3e2149474b191eeff106b12cd723ec8c
[ "MIT" ]
null
null
null
LeetCode/2124_CheckIfAllAsAppearBeforeBs.hpp
defUserName-404/Online-Judge
197ac5bf3e2149474b191eeff106b12cd723ec8c
[ "MIT" ]
null
null
null
#include <algorithm> #include <string> class Solution { public: bool checkString(std::string &s); }; /* ? Solution 1: Accepted ? 8ms(23.53% faster) */ // bool Solution::checkString(std::string s) // { // std::string sSorted = s; // std::sort(sSorted.begin(), sSorted.end()); // return s == sSorted; // } /* ? Solution 1: Accepted ? 5ms(70% faster) */ bool Solution::checkString(std::string &s) { bool bSeen = false; for (const auto &ch : s) { if (!bSeen && ch == 'b') bSeen = true; if (bSeen && ch == 'a') return false; } return true; }
16.307692
49
0.528302
defUserName-404
32ab54505766855b05cb8df09bf8afb467aafed8
3,726
cpp
C++
ert/ertlibc/syscall.cpp
thomasten/edgelessrt
2b42deefdaaa75dbc6568ff4f8152b6ae74862bf
[ "MIT" ]
null
null
null
ert/ertlibc/syscall.cpp
thomasten/edgelessrt
2b42deefdaaa75dbc6568ff4f8152b6ae74862bf
[ "MIT" ]
null
null
null
ert/ertlibc/syscall.cpp
thomasten/edgelessrt
2b42deefdaaa75dbc6568ff4f8152b6ae74862bf
[ "MIT" ]
null
null
null
// Copyright (c) Edgeless Systems GmbH. // Licensed under the MIT License. #include "syscall.h" #include <openenclave/internal/malloc.h> #include <openenclave/internal/trace.h> #include <sys/syscall.h> #include <cerrno> #include <clocale> #include <cstdlib> #include <cstring> #include <exception> #include <stdexcept> #include <system_error> #include "ertthread.h" #include "locale.h" #include "syscalls.h" using namespace std; using namespace ert; long ert_syscall(long n, long x1, long x2, long x3, long, long, long) { try { switch (n) { case SYS_sched_yield: __builtin_ia32_pause(); return 0; case SYS_clock_gettime: return sc::clock_gettime( static_cast<int>(x1), reinterpret_cast<timespec*>(x2)); case SYS_gettid: return ert_thread_self()->tid; case SYS_exit_group: sc::exit_group(static_cast<int>(x1)); return 0; case SYS_getrandom: return sc::getrandom( reinterpret_cast<void*>(x1), // buf static_cast<size_t>(x2), // buflen static_cast<unsigned int>(x3) // flags ); case SYS_sched_getaffinity: return sc::sched_getaffinity( static_cast<pid_t>(x1), static_cast<size_t>(x2), reinterpret_cast<cpu_set_t*>(x3)); case SYS_mprotect: case SYS_madvise: case SYS_mlock: case SYS_munlock: case SYS_mlockall: case SYS_munlockall: case SYS_mlock2: // These can all be noops. return 0; case SYS_rt_sigaction: sc::rt_sigaction( static_cast<int>(x1), // signum reinterpret_cast<k_sigaction*>(x2), // act reinterpret_cast<k_sigaction*>(x3)); // oldact return 0; case SYS_rt_sigprocmask: return 0; // Not supported. Silently ignore and return success. case SYS_sigaltstack: sc::sigaltstack( reinterpret_cast<stack_t*>(x1), reinterpret_cast<stack_t*>(x2)); return 0; } } catch (const system_error& e) { OE_TRACE_ERROR("%s", e.what()); return -e.code().value(); } catch (const runtime_error& e) { OE_TRACE_ERROR("%s", e.what()); } catch (const exception& e) { OE_TRACE_FATAL("%s", e.what()); abort(); } return -ENOSYS; } // This function is defined in this source file to guarantee that it overrides // the weak symbol in ert/libc/locale.c. extern "C" locale_t __newlocale(int mask, const char* locale, locale_t loc) { if (!(mask > 0 && !loc && locale && strcmp(locale, "C") == 0)) return newlocale(mask, locale, loc); // Caller may be stdc++. We must return a struct that satisfies glibc // internals (see glibc/locale/global-locale.c). The following struct is // also compatible with musl. static const __locale_struct c_locale{ {}, reinterpret_cast<const unsigned short*>(nl_C_LC_CTYPE_class + 128)}; return const_cast<locale_t>(&c_locale); } // The debug malloc check runs on enclave termination and prints errors for heap // memory that has not been freed. As some global objects in (std)c++ use heap // memory and don't free it by design, we cannot use this feature. static int _init = [] { oe_disable_debug_malloc_check = true; return 0; }();
31.310924
80
0.567901
thomasten
32abb8fe555c12e7c93a94570e29a92f8d04d5ac
30,229
hh
C++
sdl2/openblock/external/libSDL2pp/SDL2pp/Font.hh
pdpdds/SDLGameProgramming
3af68e2133296f3e7bc3d7454d9301141bca2d5a
[ "BSD-2-Clause" ]
null
null
null
sdl2/openblock/external/libSDL2pp/SDL2pp/Font.hh
pdpdds/SDLGameProgramming
3af68e2133296f3e7bc3d7454d9301141bca2d5a
[ "BSD-2-Clause" ]
null
null
null
sdl2/openblock/external/libSDL2pp/SDL2pp/Font.hh
pdpdds/SDLGameProgramming
3af68e2133296f3e7bc3d7454d9301141bca2d5a
[ "BSD-2-Clause" ]
null
null
null
/* libSDL2pp - C++11 bindings/wrapper for SDL2 Copyright (C) 2014-2015 Dmitry Marakasov <amdmi3@amdmi3.ru> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef SDL2PP_FONT_HH #define SDL2PP_FONT_HH #include <string> #include <SDL2/SDL_ttf.h> #include <SDL2pp/Optional.hh> #include <SDL2pp/Point.hh> #include <SDL2pp/Surface.hh> #include <SDL2pp/Export.hh> namespace SDL2pp { class RWops; //////////////////////////////////////////////////////////// /// \brief Holder of a loaded font /// /// \ingroup ttf /// /// \headerfile SDL2pp/Font.hh /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC56 /// //////////////////////////////////////////////////////////// class SDL2PP_EXPORT Font { private: TTF_Font* font_; ///< Managed TTF_Font object public: ///@{ /// \name Construction and destruction //////////////////////////////////////////////////////////// /// \brief Construct from existing TTF_Font structure /// /// \param[in] font Existing TTF_Font to manage /// //////////////////////////////////////////////////////////// Font(TTF_Font* font); //////////////////////////////////////////////////////////// /// \brief Loads font from .ttf or .fon file /// /// \param[in] file Pointer File name to load font from /// \param[in] ptsize %Point size (based on 72DPI) to load font as. This basically translates to pixel height /// \param[in] index Choose a font face from a file containing multiple font faces. The first face is always index 0 /// /// \throws SDL2pp::Exception /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC14 /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC16 /// //////////////////////////////////////////////////////////// Font(const std::string& file, int ptsize, long index = 0); //////////////////////////////////////////////////////////// /// \brief Loads font with RWops /// /// \param[in] rwops RWops to load font from /// \param[in] ptsize %Point size (based on 72DPI) to load font as. This basically translates to pixel height /// \param[in] index Choose a font face from a file containing multiple font faces. The first face is always index 0 /// /// \throws SDL2pp::Exception /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC15 /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC17 /// //////////////////////////////////////////////////////////// Font(RWops& rwops, int ptsize, long index = 0); //////////////////////////////////////////////////////////// /// \brief Destructor /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC18 /// //////////////////////////////////////////////////////////// virtual ~Font(); ///@} ///@{ /// \name Copy and move //////////////////////////////////////////////////////////// /// \brief Move constructor /// /// \param[in] other SDL2pp::Font object to move data from /// //////////////////////////////////////////////////////////// Font(Font&& other) noexcept; //////////////////////////////////////////////////////////// /// \brief Move assignment /// /// \param[in] other SDL2pp::Font object to move data from /// /// \returns Reference to self /// //////////////////////////////////////////////////////////// Font& operator=(Font&& other) noexcept; //////////////////////////////////////////////////////////// /// \brief Deleted copy constructor /// /// This class is not copyable /// //////////////////////////////////////////////////////////// Font(const Font&) = delete; //////////////////////////////////////////////////////////// /// \brief Deleted assignment operator /// /// This class is not copyable /// //////////////////////////////////////////////////////////// Font& operator=(const Font&) = delete; ///@} ///@{ /// \name Compatibility with legacy SDL code //////////////////////////////////////////////////////////// /// \brief Get pointer to managed TTF_Font structure /// /// \returns Pointer to managed TTF_Font structure /// //////////////////////////////////////////////////////////// TTF_Font* Get() const; ///@{ /// \name Attributes: font style //////////////////////////////////////////////////////////// /// \brief Get the rendering style of the loaded font /// /// \returns The style as a bitmask composed of the following masks: /// TTF_STYLE_BOLD, TTF_STYLE_ITALIC, TTF_STYLE_UNDERLINE, /// TTF_STYLE_STRIKETHROUGH. If no style is set then /// TTF_STYLE_NORMAL is returned /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC21 /// //////////////////////////////////////////////////////////// int GetStyle() const; //////////////////////////////////////////////////////////// /// \brief Set the rendering style of the loaded font /// /// \param[in] style The style as a bitmask composed of the following masks: /// TTF_STYLE_BOLD, TTF_STYLE_ITALIC, TTF_STYLE_UNDERLINE, /// TTF_STYLE_STRIKETHROUGH. If no style is desired then use /// TTF_STYLE_NORMAL, which is the default. /// /// \note This will flush the internal cache of previously rendered /// glyphs, even if there is no change in style, so it may be best /// to check the current style by using GetStyle() first /// /// \note TTF_STYLE_UNDERLINE may cause surfaces created by TTF_RenderGlyph_* /// functions to be extended vertically, downward only, to encompass the /// underline if the original glyph metrics didn't allow for the underline /// to be drawn below. This does not change the math used to place a glyph /// using glyph metrics. /// On the other hand TTF_STYLE_STRIKETHROUGH doesn't extend the glyph, /// since this would invalidate the metrics used to position the glyph /// when blitting, because they would likely be extended vertically upward. /// There is perhaps a workaround, but it would require programs to be /// smarter about glyph blitting math than they are currently designed for. /// Still, sometimes the underline or strikethrough may be outside of the /// generated surface, and thus not visible when blitted to the screen. /// In this case, you should probably turn off these styles and draw your /// own strikethroughs and underlines. /// /// \returns Reference to self /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC22 /// //////////////////////////////////////////////////////////// Font& SetStyle(int style = TTF_STYLE_NORMAL); //////////////////////////////////////////////////////////// /// \brief Get the current outline size of the loaded font /// /// \returns The size of the outline currently set on the font, in pixels /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC23 /// //////////////////////////////////////////////////////////// int GetOutline() const; //////////////////////////////////////////////////////////// /// \brief Set the outline pixel width of the loaded font /// /// \param[in] outline The size of outline desired, in pixels. /// Use 0 (zero) to turn off outlining. /// /// \note This will flush the internal cache of previously rendered /// glyphs, even if there is no change in outline size, so it may be best /// to check the current outline size by using GetOutline() first /// /// \returns Reference to self /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC24 /// //////////////////////////////////////////////////////////// Font& SetOutline(int outline = 0); ///@} ///@{ /// \name Attributes: font settings //////////////////////////////////////////////////////////// /// \brief Get the current hinting setting of the loaded font /// /// \returns The hinting type matching one of the following defined values: /// TTF_HINTING_NORMAL, TTF_HINTING_LIGHT, TTF_HINTING_MONO, /// TTF_HINTING_NONE. If no hinting is set then TTF_HINTING_NORMAL is returned /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC25 /// //////////////////////////////////////////////////////////// int GetHinting() const; //////////////////////////////////////////////////////////// /// \brief Set the hinting of the loaded font /// /// \param[in] hinting The hinting setting desired, which is one of: /// TTF_HINTING_NORMAL, TTF_HINTING_LIGHT, TTF_HINTING_MONO, /// TTF_HINTING_NONE. The default is TTF_HINTING_NORMAL /// /// You should experiment with this setting if you know which font /// you are using beforehand, especially when using smaller sized /// fonts. If the user is selecting a font, you may wish to let them /// select the hinting mode for that font as well /// /// \note This will flush the internal cache of previously rendered /// glyphs, even if there is no change in hinting, so it may be best /// to check the current hinting by using GetHinting() first /// /// \returns Reference to self /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC26 /// //////////////////////////////////////////////////////////// Font& SetHinting(int hinting = TTF_HINTING_NORMAL); //////////////////////////////////////////////////////////// /// \brief Get the current kerning setting of the loaded font /// /// \returns False if kerning is disabled. True when enabled. /// The default for a newly loaded font is true, enabled /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC27 /// //////////////////////////////////////////////////////////// bool GetKerning() const; //////////////////////////////////////////////////////////// /// \brief Set whether to use kerning when rendering the loaded font /// /// \param[in] allowed False to disable kerning, true to enable kerning. /// The default is true, enabled /// /// Set whether to use kerning when rendering the loaded font. /// This has no effect on individual glyphs, but rather when /// rendering whole strings of characters, at least a word at /// a time. Perhaps the only time to disable this is when kerning /// is not working for a specific font, resulting in overlapping /// glyphs or abnormal spacing within words. /// /// \returns Reference to self /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC28 /// //////////////////////////////////////////////////////////// Font& SetKerning(bool allowed = true); ///@} ///@{ /// \name Attributes: font metrics //////////////////////////////////////////////////////////// /// \brief Get the maximum pixel height of all glyphs of the loaded font /// /// \returns The maximum pixel height of all glyphs in the font /// /// You may use this height for rendering text as close together /// vertically as possible, though adding at least one pixel height /// to it will space it so they can't touch. Remember that SDL_ttf /// doesn't handle multiline printing, so you are responsible for /// line spacing, see the GetLineSkip() as well. /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC29 /// //////////////////////////////////////////////////////////// int GetHeight() const; //////////////////////////////////////////////////////////// /// \brief Get the maximum pixel ascent of all glyphs of the loaded font /// /// \returns The maximum pixel ascent of all glyphs in the font /// /// This can also be interpreted as the distance from the top of /// the font to the baseline. It could be used when drawing an /// individual glyph relative to a top point, by combining it /// with the glyph's maxy metric to resolve the top of the /// rectangle used when blitting the glyph on the screen. /// /// \code{.cpp} /// rect.y = top + Font.GetAscent() - glyph_metric.maxy; /// \endcode /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC30 /// //////////////////////////////////////////////////////////// int GetAscent() const; //////////////////////////////////////////////////////////// /// \brief Get the maximum pixel descent of all glyphs of the loaded font /// /// \returns The maximum pixel height of all glyphs in the font /// /// This can also be interpreted as the distance from the /// baseline to the bottom of the font. /// It could be used when drawing an individual glyph relative /// to a bottom point, by combining it with the glyph's maxy /// metric to resolve the top of the rectangle used when blitting /// the glyph on the screen. /// /// \code{.cpp} /// rect.y = bottom - TTF_FontDescent(font) - glyph_metric.maxy; /// \endcode /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC31 /// //////////////////////////////////////////////////////////// int GetDescent() const; //////////////////////////////////////////////////////////// /// \brief Get the recommended pixel height of a rendered line of text of the loaded font /// /// \returns The maximum pixel height of all glyphs in the font /// /// This is usually larger than the GetHeight() of the font /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC32 /// //////////////////////////////////////////////////////////// int GetLineSkip() const; ///@} ///@{ /// \name Attributes: face attributes //////////////////////////////////////////////////////////// /// \brief Get the number of faces ("sub-fonts") available in the loaded font /// /// \returns The number of faces in the font /// /// This is a count of the number of specific fonts (based on size /// and style and other typographical features perhaps) contained /// in the font itself. It seems to be a useless fact to know, /// since it can't be applied in any other SDL_ttf functions. /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC33 /// //////////////////////////////////////////////////////////// long GetNumFaces() const; //////////////////////////////////////////////////////////// /// \brief Test if the current font face of the loaded font is a fixed width font /// /// \returns True if font is a fixed width font. False if not a fixed width font /// /// Fixed width fonts are monospace, meaning every character /// that exists in the font is the same width, thus you can /// assume that a rendered string's width is going to be the /// result of a simple calculation: /// /// \code{.cpp} /// glyph_width * string_length /// \endcode /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC34 /// //////////////////////////////////////////////////////////// bool IsFixedWidth() const; //////////////////////////////////////////////////////////// /// \brief Get the current font face family name from the loaded font /// /// \returns The current family name of of the face of the font, or NullOpt perhaps /// /// This function may return NullOpt, in which case the information is not available. /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC35 /// //////////////////////////////////////////////////////////// Optional<std::string> GetFamilyName() const; //////////////////////////////////////////////////////////// /// \brief Get the current font face style name from the loaded font /// /// \returns The current style name of of the face of the font, or NullOpt perhaps /// /// This function may return NullOpt, in which case the information is not available /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC36 /// //////////////////////////////////////////////////////////// Optional<std::string> GetStyleName() const; ///@} ///@{ /// \name Attributes: glyphs //////////////////////////////////////////////////////////// /// \brief Get the status of the availability of the glyph from the loaded font /// /// \param[in] ch Unicode character to test glyph availability of /// /// \returns The index of the glyph for ch in font, or 0 for an undefined character code /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC37 /// //////////////////////////////////////////////////////////// int IsGlyphProvided(Uint16 ch) const; //////////////////////////////////////////////////////////// /// \brief Get glyph metrics of the UNICODE char /// /// \param[in] ch UNICODE char to get the glyph metrics for /// \param[out] minx Variable to store the returned minimum X offset into /// \param[out] maxx Variable to store the returned maximum X offset into /// \param[out] miny Variable to store the returned minimum Y offset into /// \param[out] maxy Variable to store the returned maximum Y offset into /// \param[out] advance Variable to store the returned advance offset into /// /// \throws SDL2pp::Exception /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC38 /// \see http://freetype.sourceforge.net/freetype2/docs/tutorial/step2.html /// //////////////////////////////////////////////////////////// void GetGlyphMetrics(Uint16 ch, int& minx, int& maxx, int& miny, int& maxy, int& advance) const; //////////////////////////////////////////////////////////// /// \brief Get rect part of glyph metrics of the UNICODE char /// /// \param[in] ch UNICODE char to get the glyph metrics for /// /// \returns Rect representing glyph offset info /// /// \throws SDL2pp::Exception /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC38 /// \see http://freetype.sourceforge.net/freetype2/docs/tutorial/step2.html /// //////////////////////////////////////////////////////////// Rect GetGlyphRect(Uint16 ch) const; //////////////////////////////////////////////////////////// /// \brief Get advance part of glyph metrics of the UNICODE char /// /// \param[in] ch UNICODE char to get the glyph metrics for /// /// \returns Advance offset into /// /// \throws SDL2pp::Exception /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC38 /// \see http://freetype.sourceforge.net/freetype2/docs/tutorial/step2.html /// //////////////////////////////////////////////////////////// int GetGlyphAdvance(Uint16 ch) const; ///@} ///@{ /// \name Attributes: text metrics //////////////////////////////////////////////////////////// /// \brief Calculate the resulting surface size of the LATIN1 encoded text rendered using font /// /// \param[in] text String to size up /// /// \returns Point representing dimensions of the rendered text /// /// \throws SDL2pp::Exception /// /// No actual rendering is done, however correct kerning is done /// to get the actual width. The height returned in h is the same /// as you can get using GetHeight() /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC39 /// //////////////////////////////////////////////////////////// Point GetSizeText(const std::string& text) const; //////////////////////////////////////////////////////////// /// \brief Calculate the resulting surface size of the UTF8 encoded text rendered using font /// /// \param[in] text UTF8 encoded string to size up /// /// \returns Point representing dimensions of the rendered text /// /// \throws SDL2pp::Exception /// /// No actual rendering is done, however correct kerning is done /// to get the actual width. The height returned in h is the same /// as you can get using GetHeight() /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC40 /// //////////////////////////////////////////////////////////// Point GetSizeUTF8(const std::string& text) const; //////////////////////////////////////////////////////////// /// \brief Calculate the resulting surface size of the UNICODE encoded text rendered using font /// /// \param[in] text UNICODE null terminated string to size up /// /// \returns Point representing dimensions of the rendered text /// /// \throws SDL2pp::Exception /// /// No actual rendering is done, however correct kerning is done /// to get the actual width. The height returned in h is the same /// as you can get using GetHeight() /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC41 /// //////////////////////////////////////////////////////////// Point GetSizeUNICODE(const Uint16* text) const; //////////////////////////////////////////////////////////// /// \brief Calculate the resulting surface size of the UNICODE encoded text rendered using font /// /// \param[in] text UNICODE null terminated string to size up /// /// \returns Point representing dimensions of the rendered text /// /// \throws SDL2pp::Exception /// /// No actual rendering is done, however correct kerning is done /// to get the actual width. The height returned in h is the same /// as you can get using GetHeight() /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC41 /// //////////////////////////////////////////////////////////// Point GetSizeUNICODE(const std::u16string& text) const; ///@} ///@{ /// \name Rendering: solid //////////////////////////////////////////////////////////// /// \brief Render LATIN1 text using solid mode /// /// \param[in] text LATIN1 string to render /// \param[in] fg Color to render the text in /// /// \returns Surface containing rendered text /// /// \throws SDL2pp::Exception /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC43 /// //////////////////////////////////////////////////////////// Surface RenderText_Solid(const std::string& text, SDL_Color fg); //////////////////////////////////////////////////////////// /// \brief Render UTF8 text using solid mode /// /// \param[in] text UTF8 string to render /// \param[in] fg Color to render the text in /// /// \returns Surface containing rendered text /// /// \throws SDL2pp::Exception /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC44 /// //////////////////////////////////////////////////////////// Surface RenderUTF8_Solid(const std::string& text, SDL_Color fg); //////////////////////////////////////////////////////////// /// \brief Render UNICODE encoded text using solid mode /// /// \param[in] text UNICODE encoded string to render /// \param[in] fg Color to render the text in /// /// \returns Surface containing rendered text /// /// \throws SDL2pp::Exception /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC45 /// //////////////////////////////////////////////////////////// Surface RenderUNICODE_Solid(const Uint16* text, SDL_Color fg); //////////////////////////////////////////////////////////// /// \brief Render UNICODE encoded text using solid mode /// /// \param[in] text UNICODE encoded string to render /// \param[in] fg Color to render the text in /// /// \returns Surface containing rendered text /// /// \throws SDL2pp::Exception /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC45 /// //////////////////////////////////////////////////////////// Surface RenderUNICODE_Solid(const std::u16string& text, SDL_Color fg); //////////////////////////////////////////////////////////// /// \brief Render the glyph for UNICODE character using solid mode /// /// \param[in] ch UNICODE character to render /// \param[in] fg Color to render the glyph in /// /// \returns Surface containing rendered text /// /// \throws SDL2pp::Exception /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC46 /// //////////////////////////////////////////////////////////// Surface RenderGlyph_Solid(Uint16 ch, SDL_Color fg); ///@} ///@{ /// \name Rendering: shaded //////////////////////////////////////////////////////////// /// \brief Render LATIN1 text using shaded mode /// /// \param[in] text LATIN1 string to render /// \param[in] fg Color to render the text in /// \param[in] bg Color to render the background box in /// /// \returns Surface containing rendered text /// /// \throws SDL2pp::Exception /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC47 /// //////////////////////////////////////////////////////////// Surface RenderText_Shaded(const std::string& text, SDL_Color fg, SDL_Color bg); //////////////////////////////////////////////////////////// /// \brief Render UTF8 text using shaded mode /// /// \param[in] text UTF8 string to render /// \param[in] fg Color to render the text in /// \param[in] bg Color to render the background box in /// /// \returns Surface containing rendered text /// /// \throws SDL2pp::Exception /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC48 /// //////////////////////////////////////////////////////////// Surface RenderUTF8_Shaded(const std::string& text, SDL_Color fg, SDL_Color bg); //////////////////////////////////////////////////////////// /// \brief Render UNICODE encoded text using shaded mode /// /// \param[in] text UNICODE encoded string to render /// \param[in] fg Color to render the text in /// \param[in] bg Color to render the background box in /// /// \returns Surface containing rendered text /// /// \throws SDL2pp::Exception /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC49 /// //////////////////////////////////////////////////////////// Surface RenderUNICODE_Shaded(const Uint16* text, SDL_Color fg, SDL_Color bg); //////////////////////////////////////////////////////////// /// \brief Render UNICODE encoded text using shaded mode /// /// \param[in] text UNICODE encoded string to render /// \param[in] fg Color to render the text in /// \param[in] bg Color to render the background box in /// /// \returns Surface containing rendered text /// /// \throws SDL2pp::Exception /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC49 /// //////////////////////////////////////////////////////////// Surface RenderUNICODE_Shaded(const std::u16string& text, SDL_Color fg, SDL_Color bg); //////////////////////////////////////////////////////////// /// \brief Render the glyph for UNICODE character using shaded mode /// /// \param[in] ch UNICODE character to render /// \param[in] fg Color to render the glyph in /// \param[in] bg Color to render the background box in /// /// \returns Surface containing rendered text /// /// \throws SDL2pp::Exception /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC50 /// //////////////////////////////////////////////////////////// Surface RenderGlyph_Shaded(Uint16 ch, SDL_Color fg, SDL_Color bg); ///@} ///@{ /// \name Rendering: blended //////////////////////////////////////////////////////////// /// \brief Render LATIN1 text using blended mode /// /// \param[in] text LATIN1 string to render /// \param[in] fg Color to render the text in /// /// \returns Surface containing rendered text /// /// \throws SDL2pp::Exception /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC51 /// //////////////////////////////////////////////////////////// Surface RenderText_Blended(const std::string& text, SDL_Color fg); //////////////////////////////////////////////////////////// /// \brief Render UTF8 text using blended mode /// /// \param[in] text UTF8 string to render /// \param[in] fg Color to render the text in /// /// \returns Surface containing rendered text /// /// \throws SDL2pp::Exception /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC52 /// //////////////////////////////////////////////////////////// Surface RenderUTF8_Blended(const std::string& text, SDL_Color fg); //////////////////////////////////////////////////////////// /// \brief Render UNICODE encoded text using blended mode /// /// \param[in] text UNICODE encoded string to render /// \param[in] fg Color to render the text in /// /// \returns Surface containing rendered text /// /// \throws SDL2pp::Exception /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC53 /// //////////////////////////////////////////////////////////// Surface RenderUNICODE_Blended(const Uint16* text, SDL_Color fg); //////////////////////////////////////////////////////////// /// \brief Render UNICODE encoded text using blended mode /// /// \param[in] text UNICODE encoded string to render /// \param[in] fg Color to render the text in /// /// \returns Surface containing rendered text /// /// \throws SDL2pp::Exception /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC53 /// //////////////////////////////////////////////////////////// Surface RenderUNICODE_Blended(const std::u16string& text, SDL_Color fg); //////////////////////////////////////////////////////////// /// \brief Render the glyph for UNICODE character using blended mode /// /// \param[in] ch UNICODE character to render /// \param[in] fg Color to render the glyph in /// /// \returns Surface containing rendered text /// /// \throws SDL2pp::Exception /// /// \see https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html#SEC54 /// //////////////////////////////////////////////////////////// Surface RenderGlyph_Blended(Uint16 ch, SDL_Color fg); ///@} }; } #endif
36.289316
117
0.553012
pdpdds
32ad881ee3d62285faa1035437facfee4bb8c9c5
4,859
cpp
C++
vislib/src/sys/Event.cpp
xge/megamol
1e298dd3d8b153d7468ed446f6b2ed3ac49f0d5b
[ "BSD-3-Clause" ]
49
2017-08-23T13:24:24.000Z
2022-03-16T09:10:58.000Z
vislib/src/sys/Event.cpp
xge/megamol
1e298dd3d8b153d7468ed446f6b2ed3ac49f0d5b
[ "BSD-3-Clause" ]
200
2018-07-20T15:18:26.000Z
2022-03-31T11:01:44.000Z
vislib/src/sys/Event.cpp
xge/megamol
1e298dd3d8b153d7468ed446f6b2ed3ac49f0d5b
[ "BSD-3-Clause" ]
31
2017-07-31T16:19:29.000Z
2022-02-14T23:41:03.000Z
/* * Event.cpp * * Copyright (C) 2006 - 2007 by Universitaet Stuttgart (VIS). * Alle Rechte vorbehalten. */ #include "vislib/sys/Event.h" #ifndef _WIN32 #include <climits> #endif /* !_WIN32 */ #include "vislib/IllegalParamException.h" #include "vislib/Trace.h" #include "vislib/UnsupportedOperationException.h" #include "vislib/assert.h" #include "vislib/sys/SystemException.h" #include "vislib/sys/error.h" /* * vislib::sys::Event::TIMEOUT_INFINITE */ #ifdef _WIN32 const DWORD vislib::sys::Event::TIMEOUT_INFINITE = INFINITE; #else /* _WIN32 */ const DWORD vislib::sys::Event::TIMEOUT_INFINITE = UINT_MAX; #endif /* _WIN32 */ /* * vislib::sys::Event::Event */ vislib::sys::Event::Event(const bool isManualReset, const bool isInitiallySignaled) #ifndef _WIN32 : isManualReset(isManualReset) , semaphore(isInitiallySignaled ? 1 : 0, 1) #endif /* _WIN32 */ { #ifdef _WIN32 this->handle = ::CreateEventA(NULL, isManualReset ? TRUE : FALSE, isInitiallySignaled ? TRUE : FALSE, NULL); ASSERT(this->handle != NULL); #endif /* _WIN32 */ } /* * vislib::sys::Event::Event */ vislib::sys::Event::Event(const char* name, const bool isManualReset, const bool isInitiallySignaled, bool* outIsNew) #ifndef _WIN32 : isManualReset(isManualReset) , semaphore(name, isInitiallySignaled ? 1 : 0, 1, outIsNew) #endif /* _WIN32 */ { #ifdef _WIN32 if (outIsNew != NULL) { *outIsNew = false; } /* Try to open existing event first. */ if ((this->handle = ::OpenEventA(SYNCHRONIZE | EVENT_MODIFY_STATE, FALSE, name)) == NULL) { this->handle = ::CreateEventA(NULL, isManualReset ? TRUE : FALSE, isInitiallySignaled ? TRUE : FALSE, name); if (outIsNew != NULL) { *outIsNew = true; } } ASSERT(this->handle != NULL); #endif /* _WIN32 */ } /* * vislib::sys::Event::Event */ vislib::sys::Event::Event(const wchar_t* name, const bool isManualReset, const bool isInitiallySignaled, bool* outIsNew) #ifndef _WIN32 : isManualReset(isManualReset) , semaphore(name, isInitiallySignaled ? 1 : 0, 1, outIsNew) #endif /* _WIN32 */ { #ifdef _WIN32 if (outIsNew != NULL) { *outIsNew = false; } /* Try to open existing event first. */ if ((this->handle = ::OpenEventW(SYNCHRONIZE | EVENT_MODIFY_STATE, FALSE, name)) == NULL) { this->handle = ::CreateEventW(NULL, isManualReset ? TRUE : FALSE, isInitiallySignaled ? TRUE : FALSE, name); if (outIsNew != NULL) { *outIsNew = true; } } ASSERT(this->handle != NULL); #endif /* _WIN32 */ } /* * vislib::sys::Event::~Event */ vislib::sys::Event::~Event(void) { #ifdef _WIN32 ::CloseHandle(this->handle); #else /* _WIN32 */ /* Nothing to do. */ #endif /* _WIN32 */ } /* * vislib::sys::Event::Reset */ void vislib::sys::Event::Reset(void) { #ifdef _WIN32 if (!::ResetEvent(this->handle)) { throw SystemException(__FILE__, __LINE__); } #else /* _WIN32 */ VLTRACE(vislib::Trace::LEVEL_VL_VERBOSE, "Event::Reset\n"); this->semaphore.TryLock(); ASSERT(!this->semaphore.TryLock()); #endif /* _WIN32 */ } /* * vislib::sys::Event::Set */ void vislib::sys::Event::Set(void) { #ifdef _WIN32 if (!::SetEvent(this->handle)) { throw SystemException(__FILE__, __LINE__); } #else /* _WIN32 */ VLTRACE(vislib::Trace::LEVEL_VL_VERBOSE, "Event::Set\n"); this->semaphore.TryLock(); this->semaphore.Unlock(); #endif /* _WIN32 */ } /* * vislib::sys::Event::Wait */ bool vislib::sys::Event::Wait(const DWORD timeout) { #ifdef _WIN32 switch (::WaitForSingleObject(this->handle, timeout)) { case WAIT_OBJECT_0: /* falls through. */ case WAIT_ABANDONED: return true; /* Unreachable. */ case WAIT_TIMEOUT: return false; /* Unreachable. */ default: throw SystemException(__FILE__, __LINE__); /* Unreachable. */ } #else /* _WIN32 */ VLTRACE(vislib::Trace::LEVEL_VL_VERBOSE, "Event::Wait\n"); bool retval = false; if (timeout == TIMEOUT_INFINITE) { this->semaphore.Lock(); retval = true; } else { retval = this->semaphore.TryLock(timeout); } if (retval && this->isManualReset) { VLTRACE(vislib::Trace::LEVEL_VL_VERBOSE, "Event::Wait signal again\n"); this->semaphore.Unlock(); } return retval; #endif /* _WIN32 */ } /* * vislib::sys::Event::Event */ vislib::sys::Event::Event(const Event& rhs) { throw UnsupportedOperationException("vislib::sys::Event::Event", __FILE__, __LINE__); } /* * vislib::sys::Event::operator = */ vislib::sys::Event& vislib::sys::Event::operator=(const Event& rhs) { if (this != &rhs) { throw IllegalParamException("rhs", __FILE__, __LINE__); } return *this; }
22.705607
120
0.626878
xge
32ae75958086bad97657ea28f12aebb3dd3173f2
94
cpp
C++
uppdev/Centrum/Centrum.cpp
dreamsxin/ultimatepp
41d295d999f9ff1339b34b43c99ce279b9b3991c
[ "BSD-2-Clause" ]
2
2016-04-07T07:54:26.000Z
2020-04-14T12:37:34.000Z
uppdev/Centrum/Centrum.cpp
dreamsxin/ultimatepp
41d295d999f9ff1339b34b43c99ce279b9b3991c
[ "BSD-2-Clause" ]
null
null
null
uppdev/Centrum/Centrum.cpp
dreamsxin/ultimatepp
41d295d999f9ff1339b34b43c99ce279b9b3991c
[ "BSD-2-Clause" ]
null
null
null
#include <Core/Core.h> VectorMap<int32, Vector<int> > map; CONSOLE_APP_MAIN { }
9.4
37
0.617021
dreamsxin
32af2514e1ead7564365cb478f275cf7c2ea948a
2,664
hpp
C++
src/FclEx.DataStructuresCpp/Iterator.hpp
huoshan12345/FxUtility.DataStructures
cdad625154407c381ec0b5d1003cc7eabc37e829
[ "MIT" ]
1
2017-04-30T21:12:55.000Z
2017-04-30T21:12:55.000Z
src/FclEx.DataStructuresCpp/Iterator.hpp
huoshan12345/FxUtility.DataStructures
cdad625154407c381ec0b5d1003cc7eabc37e829
[ "MIT" ]
null
null
null
src/FclEx.DataStructuresCpp/Iterator.hpp
huoshan12345/FxUtility.DataStructures
cdad625154407c381ec0b5d1003cc7eabc37e829
[ "MIT" ]
1
2018-10-04T23:54:26.000Z
2018-10-04T23:54:26.000Z
#pragma once #include <iterator> namespace FclEx { namespace Node { using namespace std; template <class Node, class IteratorType> class Iterator : public iterator<forward_iterator_tag, typename Node::value_type, typename Node::difference_type, typename Node::pointer, typename Node::reference> { public: typedef Node node_type; typedef typename node_type::BaseNode BaseNode; typedef typename BaseNode::allocator_type allocator_type; typedef typename BaseNode::difference_type difference_type; typedef typename BaseNode::reference reference; typedef typename BaseNode::const_reference const_reference; typedef typename BaseNode::pointer pointer; typedef typename BaseNode::const_pointer const_pointer; typedef IteratorType self_type; explicit Iterator(node_type *node) :_pNode(node) { } virtual ~Iterator() { } virtual self_type &operator++() = 0; virtual self_type operator++(int) = 0; reference operator*() { return _pNode->Item; } pointer operator->() { return &_pNode->Item; } bool operator==(const self_type &other) const { return _pNode == other._pNode; } bool operator!=(const self_type &other) const { return !operator==(other); } protected: node_type *_pNode; }; template <class Node, class IteratorType> class ConstIterator : public iterator<forward_iterator_tag, typename Node::value_type, typename Node::difference_type, typename Node::const_pointer, typename Node::const_reference> { public: typedef Node node_type; typedef typename node_type::BaseNode BaseNode; typedef typename BaseNode::allocator_type allocator_type; typedef typename BaseNode::difference_type difference_type; typedef typename BaseNode::reference reference; typedef typename BaseNode::const_reference const_reference; typedef typename BaseNode::pointer pointer; typedef typename BaseNode::const_pointer const_pointer; typedef IteratorType self_type; explicit ConstIterator(const node_type *node) :_pNode(node) { } virtual ~ConstIterator() { } virtual self_type &operator++() const = 0; virtual self_type operator++(int) const = 0; const_reference operator*() const { return _pNode->Item; } const_pointer operator->() const { return &_pNode->Item; } bool operator==(const self_type &other) const { return _pNode == other._pNode; } bool operator!=(const self_type &other) const { return !operator==(other); } protected: node_type *_pNode; }; } }
23.368421
66
0.693318
huoshan12345
32b2309a290661a0ad89ef638222708b7bd2f6de
57,976
cc
C++
chrome/browser/ui/app_list/arc/arc_app_list_prefs.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
chrome/browser/ui/app_list/arc/arc_app_list_prefs.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
chrome/browser/ui/app_list/arc/arc_app_list_prefs.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/app_list/arc/arc_app_list_prefs.h" #include <stddef.h> #include <string> #include <utility> #include "base/files/file_util.h" #include "base/metrics/histogram_functions.h" #include "base/metrics/histogram_macros.h" #include "base/strings/string_number_conversions.h" #include "base/task_scheduler/post_task.h" #include "base/values.h" #include "chrome/browser/chromeos/arc/arc_session_manager.h" #include "chrome/browser/chromeos/arc/arc_util.h" #include "chrome/browser/chromeos/arc/policy/arc_policy_util.h" #include "chrome/browser/chromeos/login/session/user_session_manager.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/app_list/arc/arc_app_list_prefs_factory.h" #include "chrome/browser/ui/app_list/arc/arc_app_utils.h" #include "chrome/browser/ui/app_list/arc/arc_package_syncable_service.h" #include "chrome/browser/ui/app_list/arc/arc_pai_starter.h" #include "chrome/grit/generated_resources.h" #include "components/arc/arc_prefs.h" #include "components/arc/arc_service_manager.h" #include "components/arc/arc_util.h" #include "components/arc/connection_holder.h" #include "components/crx_file/id_util.h" #include "components/pref_registry/pref_registry_syncable.h" #include "components/prefs/scoped_user_pref_update.h" #include "components/user_manager/user_manager.h" #include "content/public/browser/browser_thread.h" #include "ui/base/l10n/l10n_util.h" namespace { constexpr char kActivity[] = "activity"; constexpr char kIconResourceId[] = "icon_resource_id"; constexpr char kInstallTime[] = "install_time"; constexpr char kIntentUri[] = "intent_uri"; constexpr char kInvalidatedIcons[] = "invalidated_icons"; constexpr char kLastBackupAndroidId[] = "last_backup_android_id"; constexpr char kLastBackupTime[] = "last_backup_time"; constexpr char kLastLaunchTime[] = "lastlaunchtime"; constexpr char kLaunchable[] = "launchable"; constexpr char kName[] = "name"; constexpr char kNotificationsEnabled[] = "notifications_enabled"; constexpr char kPackageName[] = "package_name"; constexpr char kPackageVersion[] = "package_version"; constexpr char kSticky[] = "sticky"; constexpr char kShortcut[] = "shortcut"; constexpr char kShouldSync[] = "should_sync"; constexpr char kSystem[] = "system"; constexpr char kUninstalled[] = "uninstalled"; constexpr char kVPNProvider[] = "vpnprovider"; constexpr base::TimeDelta kDetectDefaultAppAvailabilityTimeout = base::TimeDelta::FromMinutes(1); // Provider of write access to a dictionary storing ARC prefs. class ScopedArcPrefUpdate : public DictionaryPrefUpdate { public: ScopedArcPrefUpdate(PrefService* service, const std::string& id, const std::string& path) : DictionaryPrefUpdate(service, path), id_(id) {} ~ScopedArcPrefUpdate() override {} // DictionaryPrefUpdate overrides: base::DictionaryValue* Get() override { base::DictionaryValue* dict = DictionaryPrefUpdate::Get(); base::Value* dict_item = dict->FindKeyOfType(id_, base::Value::Type::DICTIONARY); if (!dict_item) { dict_item = dict->SetKey(id_, base::Value(base::Value::Type::DICTIONARY)); } return static_cast<base::DictionaryValue*>(dict_item); } private: const std::string id_; DISALLOW_COPY_AND_ASSIGN(ScopedArcPrefUpdate); }; // Accessor for deferred set notifications enabled requests in prefs. class SetNotificationsEnabledDeferred { public: explicit SetNotificationsEnabledDeferred(PrefService* prefs) : prefs_(prefs) {} void Put(const std::string& app_id, bool enabled) { DictionaryPrefUpdate update( prefs_, arc::prefs::kArcSetNotificationsEnabledDeferred); base::DictionaryValue* const dict = update.Get(); dict->SetKey(app_id, base::Value(enabled)); } bool Get(const std::string& app_id, bool* enabled) { const base::DictionaryValue* dict = prefs_->GetDictionary(arc::prefs::kArcSetNotificationsEnabledDeferred); return dict->GetBoolean(app_id, enabled); } void Remove(const std::string& app_id) { DictionaryPrefUpdate update( prefs_, arc::prefs::kArcSetNotificationsEnabledDeferred); base::DictionaryValue* const dict = update.Get(); dict->RemoveWithoutPathExpansion(app_id, /* out_value */ nullptr); } private: PrefService* const prefs_; }; bool InstallIconFromFileThread(const base::FilePath& icon_path, const std::vector<uint8_t>& content_png) { DCHECK(!content_png.empty()); base::CreateDirectory(icon_path.DirName()); int wrote = base::WriteFile(icon_path, reinterpret_cast<const char*>(&content_png[0]), content_png.size()); if (wrote != static_cast<int>(content_png.size())) { VLOG(2) << "Failed to write ARC icon file: " << icon_path.MaybeAsASCII() << "."; if (!base::DeleteFile(icon_path, false)) { VLOG(2) << "Couldn't delete broken icon file" << icon_path.MaybeAsASCII() << "."; } return false; } return true; } void DeleteAppFolderFromFileThread(const base::FilePath& path) { DCHECK(path.DirName().BaseName().MaybeAsASCII() == arc::prefs::kArcApps && (!base::PathExists(path) || base::DirectoryExists(path))); const bool deleted = base::DeleteFile(path, true); DCHECK(deleted); } // TODO(crbug.com/672829): Due to shutdown procedure dependency, // ArcAppListPrefs may try to touch ArcSessionManager related stuff. // Specifically, this returns false on shutdown phase. // Remove this check after the shutdown behavior is fixed. bool IsArcAlive() { const auto* arc_session_manager = arc::ArcSessionManager::Get(); return arc_session_manager && arc_session_manager->IsAllowed(); } // Returns true if ARC Android instance is supposed to be enabled for the // profile. This can happen for if the user has opted in for the given profile, // or when ARC always starts after login. bool IsArcAndroidEnabledForProfile(const Profile* profile) { return arc::ShouldArcAlwaysStart() || arc::IsArcPlayStoreEnabledForProfile(profile); } bool GetInt64FromPref(const base::DictionaryValue* dict, const std::string& key, int64_t* value) { DCHECK(dict); std::string value_str; if (!dict->GetStringWithoutPathExpansion(key, &value_str)) { VLOG(2) << "Can't find key in local pref dictionary. Invalid key: " << key << "."; return false; } if (!base::StringToInt64(value_str, value)) { VLOG(2) << "Can't change string to int64_t. Invalid string value: " << value_str << "."; return false; } return true; } base::FilePath ToIconPath(const base::FilePath& app_path, ui::ScaleFactor scale_factor) { DCHECK(!app_path.empty()); switch (scale_factor) { case ui::SCALE_FACTOR_100P: return app_path.AppendASCII("icon_100p.png"); case ui::SCALE_FACTOR_125P: return app_path.AppendASCII("icon_125p.png"); case ui::SCALE_FACTOR_133P: return app_path.AppendASCII("icon_133p.png"); case ui::SCALE_FACTOR_140P: return app_path.AppendASCII("icon_140p.png"); case ui::SCALE_FACTOR_150P: return app_path.AppendASCII("icon_150p.png"); case ui::SCALE_FACTOR_180P: return app_path.AppendASCII("icon_180p.png"); case ui::SCALE_FACTOR_200P: return app_path.AppendASCII("icon_200p.png"); case ui::SCALE_FACTOR_250P: return app_path.AppendASCII("icon_250p.png"); case ui::SCALE_FACTOR_300P: return app_path.AppendASCII("icon_300p.png"); default: NOTREACHED(); return base::FilePath(); } } } // namespace // static ArcAppListPrefs* ArcAppListPrefs::Create( Profile* profile, arc::ConnectionHolder<arc::mojom::AppInstance, arc::mojom::AppHost>* app_connection_holder) { return new ArcAppListPrefs(profile, app_connection_holder); } // static void ArcAppListPrefs::RegisterProfilePrefs( user_prefs::PrefRegistrySyncable* registry) { registry->RegisterDictionaryPref(arc::prefs::kArcApps); registry->RegisterDictionaryPref(arc::prefs::kArcPackages); registry->RegisterDictionaryPref( arc::prefs::kArcSetNotificationsEnabledDeferred); } // static ArcAppListPrefs* ArcAppListPrefs::Get(content::BrowserContext* context) { return ArcAppListPrefsFactory::GetInstance()->GetForBrowserContext(context); } // static std::string ArcAppListPrefs::GetAppId(const std::string& package_name, const std::string& activity) { if (package_name == arc::kPlayStorePackage && activity == arc::kPlayStoreActivity) { return arc::kPlayStoreAppId; } const std::string input = package_name + "#" + activity; const std::string app_id = crx_file::id_util::GenerateId(input); return app_id; } std::string ArcAppListPrefs::GetAppIdByPackageName( const std::string& package_name) const { const base::DictionaryValue* apps = prefs_->GetDictionary(arc::prefs::kArcApps); if (!apps) return std::string(); for (const auto& it : apps->DictItems()) { const base::Value& value = it.second; const base::Value* installed_package_name = value.FindKeyOfType(kPackageName, base::Value::Type::STRING); if (!installed_package_name || installed_package_name->GetString() != package_name) continue; const base::Value* activity_name = value.FindKeyOfType(kActivity, base::Value::Type::STRING); return activity_name ? GetAppId(package_name, activity_name->GetString()) : std::string(); } return std::string(); } ArcAppListPrefs::ArcAppListPrefs( Profile* profile, arc::ConnectionHolder<arc::mojom::AppInstance, arc::mojom::AppHost>* app_connection_holder) : profile_(profile), prefs_(profile->GetPrefs()), app_connection_holder_(app_connection_holder), default_apps_(this, profile), weak_ptr_factory_(this) { DCHECK(profile); DCHECK(app_connection_holder); DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); const base::FilePath& base_path = profile->GetPath(); base_path_ = base_path.AppendASCII(arc::prefs::kArcApps); invalidated_icon_scale_factor_mask_ = 0; for (ui::ScaleFactor scale_factor : ui::GetSupportedScaleFactors()) invalidated_icon_scale_factor_mask_ |= (1U << scale_factor); arc::ArcSessionManager* arc_session_manager = arc::ArcSessionManager::Get(); if (!arc_session_manager) return; DCHECK(arc::IsArcAllowedForProfile(profile)); const std::vector<std::string> existing_app_ids = GetAppIds(); tracked_apps_.insert(existing_app_ids.begin(), existing_app_ids.end()); // Once default apps are ready OnDefaultAppsReady is called. } ArcAppListPrefs::~ArcAppListPrefs() { arc::ArcSessionManager* arc_session_manager = arc::ArcSessionManager::Get(); if (!arc_session_manager) return; DCHECK(arc::ArcServiceManager::Get()); arc_session_manager->RemoveObserver(this); app_connection_holder_->RemoveObserver(this); } void ArcAppListPrefs::StartPrefs() { // Don't tie ArcAppListPrefs created with sync test profile in sync // integration test to ArcSessionManager. if (!ArcAppListPrefsFactory::IsFactorySetForSyncTest()) { arc::ArcSessionManager* arc_session_manager = arc::ArcSessionManager::Get(); CHECK(arc_session_manager); if (arc_session_manager->profile()) { // Note: If ArcSessionManager has profile, it should be as same as the one // this instance has, because ArcAppListPrefsFactory creates an instance // only if the given Profile meets ARC's requirement. // Anyway, just in case, check it here. DCHECK_EQ(profile_, arc_session_manager->profile()); OnArcPlayStoreEnabledChanged( arc::IsArcPlayStoreEnabledForProfile(profile_)); } arc_session_manager->AddObserver(this); } app_connection_holder_->SetHost(this); app_connection_holder_->AddObserver(this); if (!app_connection_holder_->IsConnected()) OnConnectionClosed(); } base::FilePath ArcAppListPrefs::GetAppPath(const std::string& app_id) const { return base_path_.AppendASCII(app_id); } base::FilePath ArcAppListPrefs::MaybeGetIconPathForDefaultApp( const std::string& app_id, ui::ScaleFactor scale_factor) const { const ArcDefaultAppList::AppInfo* default_app = default_apps_.GetApp(app_id); if (!default_app || default_app->app_path.empty()) return base::FilePath(); return ToIconPath(default_app->app_path, scale_factor); } base::FilePath ArcAppListPrefs::GetIconPath( const std::string& app_id, ui::ScaleFactor scale_factor) const { return ToIconPath(GetAppPath(app_id), scale_factor); } bool ArcAppListPrefs::IsIconRequestRecorded( const std::string& app_id, ui::ScaleFactor scale_factor) const { const auto iter = request_icon_recorded_.find(app_id); if (iter == request_icon_recorded_.end()) return false; return iter->second & (1 << scale_factor); } void ArcAppListPrefs::MaybeRemoveIconRequestRecord(const std::string& app_id) { request_icon_recorded_.erase(app_id); } void ArcAppListPrefs::ClearIconRequestRecord() { request_icon_recorded_.clear(); } void ArcAppListPrefs::RequestIcon(const std::string& app_id, ui::ScaleFactor scale_factor) { DCHECK_NE(app_id, arc::kPlayStoreAppId); // ArcSessionManager can be terminated during test tear down, before callback // into this function. // TODO(victorhsieh): figure out the best way/place to handle this situation. if (arc::ArcSessionManager::Get() == nullptr) return; if (!IsRegistered(app_id)) { VLOG(2) << "Request to load icon for non-registered app: " << app_id << "."; return; } // In case app is not ready, recorded request will be send to ARC when app // becomes ready. // This record will prevent ArcAppIcon from resending request to ARC for app // icon when icon file decode failure is suffered in case app sends bad icon. request_icon_recorded_[app_id] |= (1 << scale_factor); if (!ready_apps_.count(app_id)) return; if (!app_connection_holder_->IsConnected()) { // AppInstance should be ready since we have app_id in ready_apps_. This // can happen in browser_tests. return; } std::unique_ptr<AppInfo> app_info = GetApp(app_id); if (!app_info) { VLOG(2) << "Failed to get app info: " << app_id << "."; return; } if (app_info->icon_resource_id.empty()) { auto* app_instance = ARC_GET_INSTANCE_FOR_METHOD(app_connection_holder_, RequestAppIcon); // Version 0 instance should always be available here because IsConnected() // returned true above. DCHECK(app_instance); app_instance->RequestAppIcon( app_info->package_name, app_info->activity, static_cast<arc::mojom::ScaleFactor>(scale_factor)); } else { auto* app_instance = ARC_GET_INSTANCE_FOR_METHOD(app_connection_holder_, RequestIcon); if (!app_instance) return; // The instance version on ARC side was too old. app_instance->RequestIcon( app_info->icon_resource_id, static_cast<arc::mojom::ScaleFactor>(scale_factor), base::Bind(&ArcAppListPrefs::OnIcon, base::Unretained(this), app_id, static_cast<arc::mojom::ScaleFactor>(scale_factor))); } } void ArcAppListPrefs::MaybeRequestIcon(const std::string& app_id, ui::ScaleFactor scale_factor) { if (!IsIconRequestRecorded(app_id, scale_factor)) RequestIcon(app_id, scale_factor); } void ArcAppListPrefs::SetNotificationsEnabled(const std::string& app_id, bool enabled) { if (!IsRegistered(app_id)) { VLOG(2) << "Request to set notifications enabled flag for non-registered " << "app:" << app_id << "."; return; } std::unique_ptr<AppInfo> app_info = GetApp(app_id); if (!app_info) { VLOG(2) << "Failed to get app info: " << app_id << "."; return; } // In case app is not ready, defer this request. if (!ready_apps_.count(app_id)) { SetNotificationsEnabledDeferred(prefs_).Put(app_id, enabled); for (auto& observer : observer_list_) observer.OnNotificationsEnabledChanged(app_info->package_name, enabled); return; } auto* app_instance = ARC_GET_INSTANCE_FOR_METHOD(app_connection_holder_, SetNotificationsEnabled); if (!app_instance) return; SetNotificationsEnabledDeferred(prefs_).Remove(app_id); app_instance->SetNotificationsEnabled(app_info->package_name, enabled); } void ArcAppListPrefs::AddObserver(Observer* observer) { observer_list_.AddObserver(observer); } void ArcAppListPrefs::RemoveObserver(Observer* observer) { observer_list_.RemoveObserver(observer); } bool ArcAppListPrefs::HasObserver(Observer* observer) { return observer_list_.HasObserver(observer); } base::RepeatingCallback<std::string(const std::string&)> ArcAppListPrefs::GetAppIdByPackageNameCallback() { return base::BindRepeating( [](base::WeakPtr<ArcAppListPrefs> self, const std::string& package_name) { if (!self) return std::string(); return self->GetAppIdByPackageName(package_name); }, weak_ptr_factory_.GetWeakPtr()); } std::unique_ptr<ArcAppListPrefs::PackageInfo> ArcAppListPrefs::GetPackage( const std::string& package_name) const { if (!IsArcAlive() || !IsArcAndroidEnabledForProfile(profile_)) return nullptr; const base::DictionaryValue* package = nullptr; const base::DictionaryValue* packages = prefs_->GetDictionary(arc::prefs::kArcPackages); if (!packages || !packages->GetDictionaryWithoutPathExpansion(package_name, &package)) return std::unique_ptr<PackageInfo>(); bool uninstalled = false; if (package->GetBoolean(kUninstalled, &uninstalled) && uninstalled) return nullptr; int32_t package_version = 0; int64_t last_backup_android_id = 0; int64_t last_backup_time = 0; bool should_sync = false; bool system = false; bool vpn_provider = false; GetInt64FromPref(package, kLastBackupAndroidId, &last_backup_android_id); GetInt64FromPref(package, kLastBackupTime, &last_backup_time); package->GetInteger(kPackageVersion, &package_version); package->GetBoolean(kShouldSync, &should_sync); package->GetBoolean(kSystem, &system); package->GetBoolean(kVPNProvider, &vpn_provider); return std::make_unique<PackageInfo>(package_name, package_version, last_backup_android_id, last_backup_time, should_sync, system, vpn_provider); } std::vector<std::string> ArcAppListPrefs::GetAppIds() const { if (arc::ShouldArcAlwaysStart()) return GetAppIdsNoArcEnabledCheck(); if (!IsArcAlive() || !IsArcAndroidEnabledForProfile(profile_)) { // Default ARC apps available before OptIn. std::vector<std::string> ids; for (const auto& default_app : default_apps_.app_map()) { if (default_apps_.HasApp(default_app.first)) ids.push_back(default_app.first); } return ids; } return GetAppIdsNoArcEnabledCheck(); } std::vector<std::string> ArcAppListPrefs::GetAppIdsNoArcEnabledCheck() const { std::vector<std::string> ids; const base::DictionaryValue* apps = prefs_->GetDictionary(arc::prefs::kArcApps); DCHECK(apps); // crx_file::id_util is de-facto utility for id generation. for (base::DictionaryValue::Iterator app_id(*apps); !app_id.IsAtEnd(); app_id.Advance()) { if (!crx_file::id_util::IdIsValid(app_id.key())) continue; ids.push_back(app_id.key()); } return ids; } std::unique_ptr<ArcAppListPrefs::AppInfo> ArcAppListPrefs::GetApp( const std::string& app_id) const { // Information for default app is available before ARC enabled. if ((!IsArcAlive() || !IsArcAndroidEnabledForProfile(profile_)) && !default_apps_.HasApp(app_id)) return std::unique_ptr<AppInfo>(); const base::DictionaryValue* app = nullptr; const base::DictionaryValue* apps = prefs_->GetDictionary(arc::prefs::kArcApps); if (!apps || !apps->GetDictionaryWithoutPathExpansion(app_id, &app)) return std::unique_ptr<AppInfo>(); std::string name; std::string package_name; std::string activity; std::string intent_uri; std::string icon_resource_id; bool sticky = false; bool notifications_enabled = true; bool shortcut = false; bool launchable = true; app->GetString(kName, &name); app->GetString(kPackageName, &package_name); app->GetString(kActivity, &activity); app->GetString(kIntentUri, &intent_uri); app->GetString(kIconResourceId, &icon_resource_id); app->GetBoolean(kSticky, &sticky); app->GetBoolean(kNotificationsEnabled, &notifications_enabled); app->GetBoolean(kShortcut, &shortcut); app->GetBoolean(kLaunchable, &launchable); DCHECK(!name.empty()); DCHECK(!shortcut || activity.empty()); DCHECK(!shortcut || !intent_uri.empty()); int64_t last_launch_time_internal = 0; base::Time last_launch_time; if (GetInt64FromPref(app, kLastLaunchTime, &last_launch_time_internal)) { last_launch_time = base::Time::FromInternalValue(last_launch_time_internal); } bool deferred; if (SetNotificationsEnabledDeferred(prefs_).Get(app_id, &deferred)) notifications_enabled = deferred; return std::make_unique<AppInfo>( name, package_name, activity, intent_uri, icon_resource_id, last_launch_time, GetInstallTime(app_id), sticky, notifications_enabled, ready_apps_.count(app_id) > 0, launchable && arc::ShouldShowInLauncher(app_id), shortcut, launchable); } bool ArcAppListPrefs::IsRegistered(const std::string& app_id) const { if ((!IsArcAlive() || !IsArcAndroidEnabledForProfile(profile_)) && !default_apps_.HasApp(app_id)) return false; const base::DictionaryValue* app = nullptr; const base::DictionaryValue* apps = prefs_->GetDictionary(arc::prefs::kArcApps); return apps && apps->GetDictionaryWithoutPathExpansion(app_id, &app); } bool ArcAppListPrefs::IsDefault(const std::string& app_id) const { return default_apps_.HasApp(app_id); } bool ArcAppListPrefs::IsOem(const std::string& app_id) const { const ArcDefaultAppList::AppInfo* app_info = default_apps_.GetApp(app_id); return app_info && app_info->oem; } bool ArcAppListPrefs::IsShortcut(const std::string& app_id) const { std::unique_ptr<ArcAppListPrefs::AppInfo> app_info = GetApp(app_id); return app_info && app_info->shortcut; } void ArcAppListPrefs::SetLastLaunchTime(const std::string& app_id) { if (!IsRegistered(app_id)) { NOTREACHED(); return; } // Usage time on hidden should not be tracked. if (!arc::ShouldShowInLauncher(app_id)) return; const base::Time time = base::Time::Now(); ScopedArcPrefUpdate update(prefs_, app_id, arc::prefs::kArcApps); base::DictionaryValue* app_dict = update.Get(); const std::string string_value = base::Int64ToString(time.ToInternalValue()); app_dict->SetString(kLastLaunchTime, string_value); for (auto& observer : observer_list_) observer.OnAppLastLaunchTimeUpdated(app_id); if (first_launch_app_request_) { first_launch_app_request_ = false; // UI Shown time may not be set in unit tests. const user_manager::UserManager* user_manager = user_manager::UserManager::Get(); if (arc::ArcSessionManager::Get()->is_directly_started() && !user_manager->IsLoggedInAsKioskApp() && !user_manager->IsLoggedInAsArcKioskApp() && !chromeos::UserSessionManager::GetInstance() ->ui_shown_time() .is_null()) { UMA_HISTOGRAM_CUSTOM_TIMES( "Arc.FirstAppLaunchRequest.TimeDelta", time - chromeos::UserSessionManager::GetInstance()->ui_shown_time(), base::TimeDelta::FromSeconds(1), base::TimeDelta::FromMinutes(2), 20); } } } void ArcAppListPrefs::DisableAllApps() { std::unordered_set<std::string> old_ready_apps; old_ready_apps.swap(ready_apps_); for (auto& app_id : old_ready_apps) NotifyAppReadyChanged(app_id, false); } void ArcAppListPrefs::NotifyRegisteredApps() { if (apps_restored_) return; DCHECK(ready_apps_.empty()); std::vector<std::string> app_ids = GetAppIdsNoArcEnabledCheck(); for (const auto& app_id : app_ids) { std::unique_ptr<AppInfo> app_info = GetApp(app_id); if (!app_info) { NOTREACHED(); continue; } // Default apps are reported earlier. if (tracked_apps_.insert(app_id).second) { for (auto& observer : observer_list_) observer.OnAppRegistered(app_id, *app_info); } } apps_restored_ = true; } void ArcAppListPrefs::RemoveAllAppsAndPackages() { std::vector<std::string> app_ids = GetAppIdsNoArcEnabledCheck(); for (const auto& app_id : app_ids) { if (!default_apps_.HasApp(app_id)) { RemoveApp(app_id); } else { if (ready_apps_.count(app_id)) { ready_apps_.erase(app_id); NotifyAppReadyChanged(app_id, false); } } } DCHECK(ready_apps_.empty()); const std::vector<std::string> package_names_to_remove = GetPackagesFromPrefs(false /* check_arc_alive */, true /* installed */); for (const auto& package_name : package_names_to_remove) { if (!default_apps_.HasPackage(package_name)) RemovePackageFromPrefs(prefs_, package_name); for (auto& observer : observer_list_) observer.OnPackageRemoved(package_name, false); } } void ArcAppListPrefs::OnArcPlayStoreEnabledChanged(bool enabled) { SetDefaultAppsFilterLevel(); // TODO(victorhsieh): Implement opt-in and opt-out. if (arc::ShouldArcAlwaysStart()) return; if (enabled) NotifyRegisteredApps(); else RemoveAllAppsAndPackages(); } void ArcAppListPrefs::SetDefaultAppsFilterLevel() { // There is no a blacklisting mechanism for Android apps. Until there is // one, we have no option but to ban all pre-installed apps on Android side. // Match this requirement and don't show pre-installed apps for managed users // in app list. if (arc::policy_util::IsAccountManaged(profile_)) { default_apps_.set_filter_level( arc::IsArcPlayStoreEnabledForProfile(profile_) ? ArcDefaultAppList::FilterLevel::OPTIONAL_APPS : ArcDefaultAppList::FilterLevel::ALL); } else { default_apps_.set_filter_level(ArcDefaultAppList::FilterLevel::NOTHING); } // Register default apps if it was not registered before. RegisterDefaultApps(); } void ArcAppListPrefs::OnDefaultAppsReady() { // Apply uninstalled packages now. const std::vector<std::string> uninstalled_package_names = GetPackagesFromPrefs(false /* check_arc_alive */, false /* installed */); for (const auto& uninstalled_package_name : uninstalled_package_names) default_apps_.MaybeMarkPackageUninstalled(uninstalled_package_name, true); SetDefaultAppsFilterLevel(); default_apps_ready_ = true; if (!default_apps_ready_callback_.is_null()) default_apps_ready_callback_.Run(); StartPrefs(); } void ArcAppListPrefs::RegisterDefaultApps() { // Report default apps first, note, app_map includes uninstalled and filtered // out apps as well. for (const auto& default_app : default_apps_.app_map()) { const std::string& app_id = default_app.first; if (!default_apps_.HasApp(app_id)) continue; // Skip already tracked app. if (tracked_apps_.count(app_id)) { // Icon should be already taken from the cache. Play Store icon is loaded // from internal resources. if (ready_apps_.count(app_id) || app_id == arc::kPlayStoreAppId) continue; // Notify that icon is ready for default app. for (auto& observer : observer_list_) { for (ui::ScaleFactor scale_factor : ui::GetSupportedScaleFactors()) observer.OnAppIconUpdated(app_id, scale_factor); } continue; } const ArcDefaultAppList::AppInfo& app_info = *default_app.second.get(); AddAppAndShortcut(false /* app_ready */, app_info.name, app_info.package_name, app_info.activity, std::string() /* intent_uri */, std::string() /* icon_resource_id */, false /* sticky */, false /* notifications_enabled */, false /* shortcut */, true /* launchable */); } } base::Value* ArcAppListPrefs::GetPackagePrefs(const std::string& package_name, const std::string& key) { if (!GetPackage(package_name)) { LOG(ERROR) << package_name << " can not be found."; return nullptr; } ScopedArcPrefUpdate update(prefs_, package_name, arc::prefs::kArcPackages); return update.Get()->FindKey(key); } void ArcAppListPrefs::SetPackagePrefs(const std::string& package_name, const std::string& key, base::Value value) { if (!GetPackage(package_name)) { LOG(ERROR) << package_name << " can not be found."; return; } ScopedArcPrefUpdate update(prefs_, package_name, arc::prefs::kArcPackages); update.Get()->SetKey(key, std::move(value)); } void ArcAppListPrefs::SetDefaltAppsReadyCallback(base::Closure callback) { DCHECK(!callback.is_null()); DCHECK(default_apps_ready_callback_.is_null()); default_apps_ready_callback_ = callback; if (default_apps_ready_) default_apps_ready_callback_.Run(); } void ArcAppListPrefs::SimulateDefaultAppAvailabilityTimeoutForTesting() { if (!detect_default_app_availability_timeout_.IsRunning()) return; detect_default_app_availability_timeout_.Stop(); DetectDefaultAppAvailability(); } void ArcAppListPrefs::OnConnectionReady() { // Note, sync_service_ may be nullptr in testing. sync_service_ = arc::ArcPackageSyncableService::Get(profile_); is_initialized_ = false; if (!app_list_refreshed_callback_.is_null()) std::move(app_list_refreshed_callback_).Run(); } void ArcAppListPrefs::OnConnectionClosed() { DisableAllApps(); installing_packages_count_ = 0; default_apps_installations_.clear(); detect_default_app_availability_timeout_.Stop(); ClearIconRequestRecord(); if (sync_service_) { sync_service_->StopSyncing(syncer::ARC_PACKAGE); sync_service_ = nullptr; } is_initialized_ = false; package_list_initial_refreshed_ = false; app_list_refreshed_callback_.Reset(); } void ArcAppListPrefs::HandleTaskCreated(const base::Optional<std::string>& name, const std::string& package_name, const std::string& activity) { DCHECK(IsArcAndroidEnabledForProfile(profile_)); const std::string app_id = GetAppId(package_name, activity); if (IsRegistered(app_id)) { SetLastLaunchTime(app_id); } else { // Create runtime app entry that is valid for the current user session. This // entry is not shown in App Launcher and only required for shelf // integration. AddAppAndShortcut(true /* app_ready */, name.has_value() ? *name : "", package_name, activity, std::string() /* intent_uri */, std::string() /* icon_resource_id */, false /* sticky */, false /* notifications_enabled */, false /* shortcut */, false /* launchable */); } } void ArcAppListPrefs::AddAppAndShortcut(bool app_ready, const std::string& name, const std::string& package_name, const std::string& activity, const std::string& intent_uri, const std::string& icon_resource_id, const bool sticky, const bool notifications_enabled, const bool shortcut, const bool launchable) { const std::string app_id = shortcut ? GetAppId(package_name, intent_uri) : GetAppId(package_name, activity); // Do not add Play Store app for Public Session and Kiosk modes. if (app_id == arc::kPlayStoreAppId && arc::IsRobotAccountMode()) return; std::string updated_name = name; // Add "(beta)" string to Play Store. See crbug.com/644576 for details. if (app_id == arc::kPlayStoreAppId) updated_name = l10n_util::GetStringUTF8(IDS_ARC_PLAYSTORE_ICON_TITLE_BETA); const bool was_tracked = tracked_apps_.count(app_id); if (was_tracked) { std::unique_ptr<ArcAppListPrefs::AppInfo> app_old_info = GetApp(app_id); DCHECK(app_old_info); DCHECK(launchable); if (updated_name != app_old_info->name) { for (auto& observer : observer_list_) observer.OnAppNameUpdated(app_id, updated_name); } } ScopedArcPrefUpdate update(prefs_, app_id, arc::prefs::kArcApps); base::DictionaryValue* app_dict = update.Get(); app_dict->SetString(kName, updated_name); app_dict->SetString(kPackageName, package_name); app_dict->SetString(kActivity, activity); app_dict->SetString(kIntentUri, intent_uri); app_dict->SetString(kIconResourceId, icon_resource_id); app_dict->SetBoolean(kSticky, sticky); app_dict->SetBoolean(kNotificationsEnabled, notifications_enabled); app_dict->SetBoolean(kShortcut, shortcut); app_dict->SetBoolean(kLaunchable, launchable); // Note the install time is the first time the Chrome OS sees the app, not the // actual install time in Android side. if (GetInstallTime(app_id).is_null()) { std::string install_time_str = base::Int64ToString(base::Time::Now().ToInternalValue()); app_dict->SetString(kInstallTime, install_time_str); } const bool was_disabled = ready_apps_.count(app_id) == 0; DCHECK(!(!was_disabled && !app_ready)); if (was_disabled && app_ready) ready_apps_.insert(app_id); if (was_tracked) { if (was_disabled && app_ready) NotifyAppReadyChanged(app_id, true); } else { AppInfo app_info(updated_name, package_name, activity, intent_uri, icon_resource_id, base::Time(), GetInstallTime(app_id), sticky, notifications_enabled, app_ready, launchable && arc::ShouldShowInLauncher(app_id), shortcut, launchable); for (auto& observer : observer_list_) observer.OnAppRegistered(app_id, app_info); tracked_apps_.insert(app_id); } if (app_ready) { int icon_update_mask = 0; app_dict->GetInteger(kInvalidatedIcons, &icon_update_mask); auto pending_icons = request_icon_recorded_.find(app_id); if (pending_icons != request_icon_recorded_.end()) icon_update_mask |= pending_icons->second; for (ui::ScaleFactor scale_factor : ui::GetSupportedScaleFactors()) { if (icon_update_mask & (1 << scale_factor)) RequestIcon(app_id, scale_factor); } bool deferred_notifications_enabled; if (SetNotificationsEnabledDeferred(prefs_).Get( app_id, &deferred_notifications_enabled)) { SetNotificationsEnabled(app_id, deferred_notifications_enabled); } } } void ArcAppListPrefs::RemoveApp(const std::string& app_id) { // Delete cached icon if there is any. std::unique_ptr<ArcAppListPrefs::AppInfo> app_info = GetApp(app_id); if (app_info && !app_info->icon_resource_id.empty()) { arc::RemoveCachedIcon(app_info->icon_resource_id); } MaybeRemoveIconRequestRecord(app_id); // From now, app is not available. ready_apps_.erase(app_id); // app_id may be released by observers, get the path first. It should be done // before removing prefs entry in order not to mix with pre-build default apps // files. const base::FilePath app_path = GetAppPath(app_id); // Remove from prefs. DictionaryPrefUpdate update(prefs_, arc::prefs::kArcApps); base::DictionaryValue* apps = update.Get(); const bool removed = apps->Remove(app_id, nullptr); DCHECK(removed); DCHECK(tracked_apps_.count(app_id)); for (auto& observer : observer_list_) observer.OnAppRemoved(app_id); tracked_apps_.erase(app_id); // Remove local data on file system. base::PostTaskWithTraits( FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND}, base::Bind(&DeleteAppFolderFromFileThread, app_path)); } void ArcAppListPrefs::AddOrUpdatePackagePrefs( PrefService* prefs, const arc::mojom::ArcPackageInfo& package) { DCHECK(IsArcAndroidEnabledForProfile(profile_)); const std::string& package_name = package.package_name; default_apps_.MaybeMarkPackageUninstalled(package_name, false); if (package_name.empty()) { VLOG(2) << "Package name cannot be empty."; return; } ScopedArcPrefUpdate update(prefs, package_name, arc::prefs::kArcPackages); base::DictionaryValue* package_dict = update.Get(); const std::string id_str = base::Int64ToString(package.last_backup_android_id); const std::string time_str = base::Int64ToString(package.last_backup_time); int old_package_version = -1; package_dict->GetInteger(kPackageVersion, &old_package_version); package_dict->SetBoolean(kShouldSync, package.sync); package_dict->SetInteger(kPackageVersion, package.package_version); package_dict->SetString(kLastBackupAndroidId, id_str); package_dict->SetString(kLastBackupTime, time_str); package_dict->SetBoolean(kSystem, package.system); package_dict->SetBoolean(kUninstalled, false); package_dict->SetBoolean(kVPNProvider, package.vpn_provider); if (old_package_version == -1 || old_package_version == package.package_version) { return; } InvalidatePackageIcons(package_name); } void ArcAppListPrefs::RemovePackageFromPrefs(PrefService* prefs, const std::string& package_name) { default_apps_.MaybeMarkPackageUninstalled(package_name, true); if (!default_apps_.HasPackage(package_name)) { DictionaryPrefUpdate update(prefs, arc::prefs::kArcPackages); base::DictionaryValue* packages = update.Get(); const bool removed = packages->RemoveWithoutPathExpansion(package_name, nullptr); DCHECK(removed); } else { ScopedArcPrefUpdate update(prefs, package_name, arc::prefs::kArcPackages); base::DictionaryValue* package_dict = update.Get(); package_dict->SetBoolean(kUninstalled, true); } } void ArcAppListPrefs::OnAppListRefreshed( std::vector<arc::mojom::AppInfoPtr> apps) { DCHECK(app_list_refreshed_callback_.is_null()); if (!app_connection_holder_->IsConnected()) { LOG(ERROR) << "App instance is not connected. Delaying app list refresh. " << "See b/70566216."; app_list_refreshed_callback_ = base::BindOnce(&ArcAppListPrefs::OnAppListRefreshed, weak_ptr_factory_.GetWeakPtr(), std::move(apps)); return; } DCHECK(IsArcAndroidEnabledForProfile(profile_)); std::vector<std::string> old_apps = GetAppIds(); ready_apps_.clear(); for (const auto& app : apps) { AddAppAndShortcut(true /* app_ready */, app->name, app->package_name, app->activity, std::string() /* intent_uri */, std::string() /* icon_resource_id */, app->sticky, app->notifications_enabled, false /* shortcut */, true /* launchable */); } // Detect removed ARC apps after current refresh. for (const auto& app_id : old_apps) { if (ready_apps_.count(app_id)) continue; if (IsShortcut(app_id)) { // If this is a shortcut, we just mark it as ready. ready_apps_.insert(app_id); NotifyAppReadyChanged(app_id, true); } else { // Default apps may not be installed yet at this moment. if (!default_apps_.HasApp(app_id)) RemoveApp(app_id); } } if (!is_initialized_) { is_initialized_ = true; UMA_HISTOGRAM_COUNTS_1000("Arc.AppsInstalledAtStartup", ready_apps_.size()); arc::ArcPaiStarter* pai_starter = arc::ArcSessionManager::Get()->pai_starter(); if (pai_starter) { pai_starter->AddOnStartCallback( base::BindOnce(&ArcAppListPrefs::MaybeSetDefaultAppLoadingTimeout, weak_ptr_factory_.GetWeakPtr())); } else { MaybeSetDefaultAppLoadingTimeout(); } } } void ArcAppListPrefs::DetectDefaultAppAvailability() { for (const auto& package : default_apps_.GetActivePackages()) { // Check if already installed or installation in progress. if (!GetPackage(package) && !default_apps_installations_.count(package)) HandlePackageRemoved(package); } } void ArcAppListPrefs::MaybeSetDefaultAppLoadingTimeout() { // Find at least one not installed default app package. for (const auto& package : default_apps_.GetActivePackages()) { if (!GetPackage(package)) { detect_default_app_availability_timeout_.Start(FROM_HERE, kDetectDefaultAppAvailabilityTimeout, this, &ArcAppListPrefs::DetectDefaultAppAvailability); break; } } } void ArcAppListPrefs::AddApp(const arc::mojom::AppInfo& app_info) { if ((app_info.name.empty() || app_info.package_name.empty() || app_info.activity.empty())) { VLOG(2) << "App Name, package name, and activity cannot be empty."; return; } AddAppAndShortcut(true /* app_ready */, app_info.name, app_info.package_name, app_info.activity, std::string() /* intent_uri */, std::string() /* icon_resource_id */, app_info.sticky, app_info.notifications_enabled, false /* shortcut */, true /* launchable */); } void ArcAppListPrefs::OnAppAddedDeprecated(arc::mojom::AppInfoPtr app) { AddApp(*app); } void ArcAppListPrefs::InvalidateAppIcons(const std::string& app_id) { // Ignore Play Store app since we provide its icon in Chrome resources. if (app_id == arc::kPlayStoreAppId) return; // Clean up previous icon records. They may refer to outdated icons. MaybeRemoveIconRequestRecord(app_id); { ScopedArcPrefUpdate update(prefs_, app_id, arc::prefs::kArcApps); base::DictionaryValue* app_dict = update.Get(); app_dict->SetInteger(kInvalidatedIcons, invalidated_icon_scale_factor_mask_); } for (ui::ScaleFactor scale_factor : ui::GetSupportedScaleFactors()) MaybeRequestIcon(app_id, scale_factor); } void ArcAppListPrefs::InvalidatePackageIcons(const std::string& package_name) { for (const std::string& app_id : GetAppsForPackage(package_name)) InvalidateAppIcons(app_id); } void ArcAppListPrefs::OnPackageAppListRefreshed( const std::string& package_name, std::vector<arc::mojom::AppInfoPtr> apps) { if (package_name.empty()) { VLOG(2) << "Package name cannot be empty."; return; } std::unordered_set<std::string> apps_to_remove = GetAppsForPackage(package_name); default_apps_.MaybeMarkPackageUninstalled(package_name, false); for (const auto& app : apps) { const std::string app_id = GetAppId(app->package_name, app->activity); apps_to_remove.erase(app_id); AddApp(*app); } for (const auto& app_id : apps_to_remove) RemoveApp(app_id); } void ArcAppListPrefs::OnInstallShortcut(arc::mojom::ShortcutInfoPtr shortcut) { if ((shortcut->name.empty() || shortcut->intent_uri.empty())) { VLOG(2) << "Shortcut Name, and intent_uri cannot be empty."; return; } AddAppAndShortcut(true /* app_ready */, shortcut->name, shortcut->package_name, std::string() /* activity */, shortcut->intent_uri, shortcut->icon_resource_id, false /* sticky */, false /* notifications_enabled */, true /* shortcut */, true /* launchable */); } void ArcAppListPrefs::OnUninstallShortcut(const std::string& package_name, const std::string& intent_uri) { std::vector<std::string> shortcuts_to_remove; const base::DictionaryValue* apps = prefs_->GetDictionary(arc::prefs::kArcApps); for (base::DictionaryValue::Iterator app_it(*apps); !app_it.IsAtEnd(); app_it.Advance()) { const base::Value* value = &app_it.value(); const base::DictionaryValue* app; bool shortcut; std::string installed_package_name; std::string installed_intent_uri; if (!value->GetAsDictionary(&app) || !app->GetBoolean(kShortcut, &shortcut) || !app->GetString(kPackageName, &installed_package_name) || !app->GetString(kIntentUri, &installed_intent_uri)) { VLOG(2) << "Failed to extract information for " << app_it.key() << "."; continue; } if (!shortcut || installed_package_name != package_name || installed_intent_uri != intent_uri) { continue; } shortcuts_to_remove.push_back(app_it.key()); } for (const auto& shortcut_id : shortcuts_to_remove) RemoveApp(shortcut_id); } std::unordered_set<std::string> ArcAppListPrefs::GetAppsForPackage( const std::string& package_name) const { return GetAppsAndShortcutsForPackage(package_name, false /* include_shortcuts */); } std::unordered_set<std::string> ArcAppListPrefs::GetAppsAndShortcutsForPackage( const std::string& package_name, bool include_shortcuts) const { std::unordered_set<std::string> app_set; const base::DictionaryValue* apps = prefs_->GetDictionary(arc::prefs::kArcApps); for (base::DictionaryValue::Iterator app_it(*apps); !app_it.IsAtEnd(); app_it.Advance()) { const base::Value* value = &app_it.value(); const base::DictionaryValue* app; if (!value->GetAsDictionary(&app)) { NOTREACHED(); continue; } std::string app_package; if (!app->GetString(kPackageName, &app_package)) { NOTREACHED(); continue; } if (package_name != app_package) continue; if (!include_shortcuts) { bool shortcut = false; if (app->GetBoolean(kShortcut, &shortcut) && shortcut) continue; } app_set.insert(app_it.key()); } return app_set; } void ArcAppListPrefs::HandlePackageRemoved(const std::string& package_name) { DCHECK(IsArcAndroidEnabledForProfile(profile_)); const std::unordered_set<std::string> apps_to_remove = GetAppsAndShortcutsForPackage(package_name, true /* include_shortcuts */); for (const auto& app_id : apps_to_remove) RemoveApp(app_id); RemovePackageFromPrefs(prefs_, package_name); } void ArcAppListPrefs::OnPackageRemoved(const std::string& package_name) { HandlePackageRemoved(package_name); for (auto& observer : observer_list_) observer.OnPackageRemoved(package_name, true); } void ArcAppListPrefs::OnAppIcon(const std::string& package_name, const std::string& activity, arc::mojom::ScaleFactor scale_factor, const std::vector<uint8_t>& icon_png_data) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK_NE(0u, icon_png_data.size()); std::string app_id = GetAppId(package_name, activity); if (!IsRegistered(app_id)) { VLOG(2) << "Request to update icon for non-registered app: " << app_id; return; } InstallIcon(app_id, static_cast<ui::ScaleFactor>(scale_factor), icon_png_data); } void ArcAppListPrefs::OnIcon(const std::string& app_id, arc::mojom::ScaleFactor scale_factor, const std::vector<uint8_t>& icon_png_data) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK_NE(0u, icon_png_data.size()); if (!IsRegistered(app_id)) { VLOG(2) << "Request to update icon for non-registered app: " << app_id; return; } InstallIcon(app_id, static_cast<ui::ScaleFactor>(scale_factor), icon_png_data); } void ArcAppListPrefs::OnTaskCreated(int32_t task_id, const std::string& package_name, const std::string& activity, const base::Optional<std::string>& name, const base::Optional<std::string>& intent) { HandleTaskCreated(name, package_name, activity); for (auto& observer : observer_list_) { observer.OnTaskCreated(task_id, package_name, activity, intent.value_or(std::string())); } } void ArcAppListPrefs::OnTaskDescriptionUpdated( int32_t task_id, const std::string& label, const std::vector<uint8_t>& icon_png_data) { for (auto& observer : observer_list_) observer.OnTaskDescriptionUpdated(task_id, label, icon_png_data); } void ArcAppListPrefs::OnTaskDestroyed(int32_t task_id) { for (auto& observer : observer_list_) observer.OnTaskDestroyed(task_id); } void ArcAppListPrefs::OnTaskSetActive(int32_t task_id) { for (auto& observer : observer_list_) observer.OnTaskSetActive(task_id); } void ArcAppListPrefs::OnNotificationsEnabledChanged( const std::string& package_name, bool enabled) { const base::DictionaryValue* apps = prefs_->GetDictionary(arc::prefs::kArcApps); for (base::DictionaryValue::Iterator app(*apps); !app.IsAtEnd(); app.Advance()) { const base::DictionaryValue* app_dict; std::string app_package_name; if (!app.value().GetAsDictionary(&app_dict) || !app_dict->GetString(kPackageName, &app_package_name)) { NOTREACHED(); continue; } if (app_package_name != package_name) { continue; } ScopedArcPrefUpdate update(prefs_, app.key(), arc::prefs::kArcApps); base::DictionaryValue* updateing_app_dict = update.Get(); updateing_app_dict->SetBoolean(kNotificationsEnabled, enabled); } for (auto& observer : observer_list_) observer.OnNotificationsEnabledChanged(package_name, enabled); } bool ArcAppListPrefs::IsUnknownPackage(const std::string& package_name) const { return !GetPackage(package_name) && sync_service_ && !sync_service_->IsPackageSyncing(package_name); } void ArcAppListPrefs::OnPackageAdded( arc::mojom::ArcPackageInfoPtr package_info) { DCHECK(IsArcAndroidEnabledForProfile(profile_)); AddOrUpdatePackagePrefs(prefs_, *package_info); for (auto& observer : observer_list_) observer.OnPackageInstalled(*package_info); } void ArcAppListPrefs::OnPackageModified( arc::mojom::ArcPackageInfoPtr package_info) { DCHECK(IsArcAndroidEnabledForProfile(profile_)); AddOrUpdatePackagePrefs(prefs_, *package_info); for (auto& observer : observer_list_) observer.OnPackageModified(*package_info); } void ArcAppListPrefs::OnPackageListRefreshed( std::vector<arc::mojom::ArcPackageInfoPtr> packages) { DCHECK(IsArcAndroidEnabledForProfile(profile_)); const std::vector<std::string> old_packages(GetPackagesFromPrefs()); std::unordered_set<std::string> current_packages; for (const auto& package : packages) { AddOrUpdatePackagePrefs(prefs_, *package); current_packages.insert((*package).package_name); } for (const auto& package_name : old_packages) { if (!current_packages.count(package_name)) RemovePackageFromPrefs(prefs_, package_name); } package_list_initial_refreshed_ = true; for (auto& observer : observer_list_) observer.OnPackageListInitialRefreshed(); } std::vector<std::string> ArcAppListPrefs::GetPackagesFromPrefs() const { return GetPackagesFromPrefs(true /* check_arc_alive */, true /* installed */); } std::vector<std::string> ArcAppListPrefs::GetPackagesFromPrefs( bool check_arc_alive, bool installed) const { std::vector<std::string> packages; if (check_arc_alive && (!IsArcAlive() || !IsArcAndroidEnabledForProfile(profile_))) { return packages; } const base::DictionaryValue* package_prefs = prefs_->GetDictionary(arc::prefs::kArcPackages); for (base::DictionaryValue::Iterator package(*package_prefs); !package.IsAtEnd(); package.Advance()) { const base::DictionaryValue* package_info; if (!package.value().GetAsDictionary(&package_info)) { NOTREACHED(); continue; } bool uninstalled = false; package_info->GetBoolean(kUninstalled, &uninstalled); if (installed != !uninstalled) continue; packages.push_back(package.key()); } return packages; } base::Time ArcAppListPrefs::GetInstallTime(const std::string& app_id) const { const base::DictionaryValue* app = nullptr; const base::DictionaryValue* apps = prefs_->GetDictionary(arc::prefs::kArcApps); if (!apps || !apps->GetDictionaryWithoutPathExpansion(app_id, &app)) return base::Time(); std::string install_time_str; if (!app->GetString(kInstallTime, &install_time_str)) return base::Time(); int64_t install_time_i64; if (!base::StringToInt64(install_time_str, &install_time_i64)) return base::Time(); return base::Time::FromInternalValue(install_time_i64); } void ArcAppListPrefs::InstallIcon(const std::string& app_id, ui::ScaleFactor scale_factor, const std::vector<uint8_t>& content_png) { const base::FilePath icon_path = GetIconPath(app_id, scale_factor); base::PostTaskWithTraitsAndReplyWithResult( FROM_HERE, {base::MayBlock(), base::TaskPriority::BACKGROUND}, base::Bind(&InstallIconFromFileThread, icon_path, content_png), base::Bind(&ArcAppListPrefs::OnIconInstalled, weak_ptr_factory_.GetWeakPtr(), app_id, scale_factor)); } void ArcAppListPrefs::OnIconInstalled(const std::string& app_id, ui::ScaleFactor scale_factor, bool install_succeed) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (!install_succeed) return; ScopedArcPrefUpdate update(prefs_, app_id, arc::prefs::kArcApps); int invalidated_icon_mask = 0; base::DictionaryValue* app_dict = update.Get(); app_dict->GetInteger(kInvalidatedIcons, &invalidated_icon_mask); invalidated_icon_mask &= (~(1 << scale_factor)); app_dict->SetInteger(kInvalidatedIcons, invalidated_icon_mask); for (auto& observer : observer_list_) observer.OnAppIconUpdated(app_id, scale_factor); } void ArcAppListPrefs::OnInstallationStarted( const base::Optional<std::string>& package_name) { ++installing_packages_count_; if (!package_name.has_value()) return; if (default_apps_.HasPackage(*package_name)) default_apps_installations_.insert(*package_name); for (auto& observer : observer_list_) observer.OnInstallationStarted(*package_name); } void ArcAppListPrefs::OnInstallationFinished( arc::mojom::InstallationResultPtr result) { if (result && default_apps_.HasPackage(result->package_name)) { default_apps_installations_.erase(result->package_name); if (!result->success && !GetPackage(result->package_name)) HandlePackageRemoved(result->package_name); } if (result) { for (auto& observer : observer_list_) observer.OnInstallationFinished(result->package_name, result->success); } if (!installing_packages_count_) { VLOG(2) << "Received unexpected installation finished event"; return; } --installing_packages_count_; } void ArcAppListPrefs::NotifyAppReadyChanged(const std::string& app_id, bool ready) { for (auto& observer : observer_list_) observer.OnAppReadyChanged(app_id, ready); } ArcAppListPrefs::AppInfo::AppInfo(const std::string& name, const std::string& package_name, const std::string& activity, const std::string& intent_uri, const std::string& icon_resource_id, const base::Time& last_launch_time, const base::Time& install_time, bool sticky, bool notifications_enabled, bool ready, bool showInLauncher, bool shortcut, bool launchable) : name(name), package_name(package_name), activity(activity), intent_uri(intent_uri), icon_resource_id(icon_resource_id), last_launch_time(last_launch_time), install_time(install_time), sticky(sticky), notifications_enabled(notifications_enabled), ready(ready), showInLauncher(showInLauncher), shortcut(shortcut), launchable(launchable) {} // Need to add explicit destructor for chromium style checker error: // Complex class/struct needs an explicit out-of-line destructor ArcAppListPrefs::AppInfo::~AppInfo() {} ArcAppListPrefs::PackageInfo::PackageInfo(const std::string& package_name, int32_t package_version, int64_t last_backup_android_id, int64_t last_backup_time, bool should_sync, bool system, bool vpn_provider) : package_name(package_name), package_version(package_version), last_backup_android_id(last_backup_android_id), last_backup_time(last_backup_time), should_sync(should_sync), system(system), vpn_provider(vpn_provider) {}
35.920694
80
0.68863
zipated
32b7f262ecdee5430ec11c40f35d8b6da5a9e9b6
1,577
cpp
C++
asl/audio/DummyPump.cpp
artcom/asl
d47748983678c245ac2da3b5de56245ac41768fe
[ "BSL-1.0" ]
2
2016-01-11T01:06:11.000Z
2019-07-24T02:27:13.000Z
asl/audio/DummyPump.cpp
artcom/asl
d47748983678c245ac2da3b5de56245ac41768fe
[ "BSL-1.0" ]
null
null
null
asl/audio/DummyPump.cpp
artcom/asl
d47748983678c245ac2da3b5de56245ac41768fe
[ "BSL-1.0" ]
1
2016-01-31T18:14:37.000Z
2016-01-31T18:14:37.000Z
/* __ ___ ____ _____ ______ _______ ________ _______ ______ _____ ____ ___ __ // // Copyright (C) 1993-2012, ART+COM AG Berlin, Germany <www.artcom.de> // // This file is part of the ART+COM Standard Library (asl). // // It is 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 "DummyPump.h" #include <asl/base/Logger.h> #include <asl/base/string_functions.h> #include <asl/math/numeric_functions.h> #include <asl/base/Assure.h> //#include <exception> //#include <sstream> //#include <string.h> using namespace std; namespace asl { DummyPump::~DummyPump () { AC_INFO << "DummyPump::~DummyPump"; Pump::stop(); } Time DummyPump::getCurrentTime () { return Time(); } DummyPump::DummyPump () : Pump(SF_F32, 0) { AC_INFO << "DummyPump::DummyPump"; setDeviceName("Dummy Sound Device"); setCardName("Dummy Sound Card"); _curFrame = 0; _myOutputBuffer.init(2048, getNumOutputChannels(), getNativeSampleRate()); dumpState(); start(); } void DummyPump::pump() { static Time lastTime; msleep(unsigned(1000*getLatency())); Time curTime; double TimeSinceLastPump = curTime-lastTime; unsigned numFramesToDeliver = unsigned(TimeSinceLastPump*getNativeSampleRate()); lastTime = curTime; AC_TRACE << "DummyPump::pump: numFramesToDeliver=" << numFramesToDeliver; mix(_myOutputBuffer, numFramesToDeliver); } }
22.855072
84
0.701332
artcom
32b8be4744f527e8ea9b3c385237a08e8bfb3967
1,140
hpp
C++
qtswarmtv/seasonepisodewidget.hpp
annejan/swarmtv
847d82114d1ee2338d37be314a222e386849aad1
[ "Unlicense" ]
1
2019-07-10T10:33:23.000Z
2019-07-10T10:33:23.000Z
qtswarmtv/seasonepisodewidget.hpp
annejan/swarmtv
847d82114d1ee2338d37be314a222e386849aad1
[ "Unlicense" ]
null
null
null
qtswarmtv/seasonepisodewidget.hpp
annejan/swarmtv
847d82114d1ee2338d37be314a222e386849aad1
[ "Unlicense" ]
null
null
null
#ifndef SEASONEPISODEWIDGET_HPP #define SEASONEPISODEWIDGET_HPP #include <QDialog> extern "C" { #include <tvdb.h> } #include <QTreeWidget> #include <taskqueue.hpp> class episodeInfoWidget; namespace Ui { class seasonEpisodeWidget; } class seasonEpisodeWidget : public QDialog { Q_OBJECT public: explicit seasonEpisodeWidget(QWidget *parent = 0); ~seasonEpisodeWidget(); void setSeriesTitle(QString &name); void setSeriesId(int id); void setrieveEpisodeData(); void fillListView(tvdb_list_front_t *); void retrieveEpisodeData(); public slots: // GUI signals void itemExpanded(QTreeWidgetItem *item); void itemDoubleClicked(QTreeWidgetItem *item, int column); // Task signals void seriesResults(tvdb_buffer_t *series_xml); void seriesFailed(); private: void addTask(episodeInfoWidget *widget); QTreeWidgetItem *addSeasonEntry(int seasonNum); void addEpisodeEntry(QTreeWidgetItem *season, tvdb_series_info_t *s); Ui::seasonEpisodeWidget *ui; QString seriesName; int seriesId; taskQueue tc; htvdb_t tvdb; }; #endif // SEASONEPISODEWIDGET_HPP
21.923077
73
0.735088
annejan
32bc74330720c58268f5da7dae316ae1aefe5029
17,303
cpp
C++
lib/rbm/cpp/rbm.cpp
jrrk2/connectal
6c05f083e227423c1b2d8ae5a2364db180a82f4a
[ "MIT" ]
134
2015-01-06T14:24:18.000Z
2022-03-13T22:38:56.000Z
lib/rbm/cpp/rbm.cpp
jrrk2/connectal
6c05f083e227423c1b2d8ae5a2364db180a82f4a
[ "MIT" ]
103
2015-01-02T14:01:29.000Z
2021-11-12T18:45:54.000Z
lib/rbm/cpp/rbm.cpp
jrrk2/connectal
6c05f083e227423c1b2d8ae5a2364db180a82f4a
[ "MIT" ]
39
2015-07-14T20:20:13.000Z
2021-12-01T00:49:23.000Z
// Copyright (c) 2014 Quanta Research Cambridge, Inc. // 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. #undef NDEBUG #include "portalmat.h" #include "rbm.h" #include "mnist.h" float sigmoid(float x) { if (x < -8.0) x = -8.0; if (x > 8.0) x = 8.0; return 1 / (1 + expf(-x)); } void configureSigmoidTable() { sigmoiddevice->tableSize(); sem_wait(&mul_sem); int num_entries = sigmoidindication->tableSize(); int addrsize = log((double)num_entries) / log(2.0); float range = 16.0; float lowest_angle = - range/2.0; double fincr = (float)num_entries / range; double fscale = num_entries / range; fprintf(stderr, "configureSigmoidTable: num_entries=%d addrsize=%d fscale=%f fincr=%f\n", num_entries, addrsize, fscale, fincr); RbmMat sigmoidTable; // each entry consists of [-angle, sigmoid(angle), derivative, 0] sigmoidTable.create(1, 4*num_entries, CV_32F); // v = (index-num_entries/2) / fscale // index = v * fscale + num_entries/2 float fxscale = fscale; float fxllimit = (float)lowest_angle; float fxulimit = (float)-lowest_angle; fprintf(stderr, "configureSigmoidTable num_entries=%d rscale=%f %x llimit=%f %x rlimit=%f %x\n", num_entries, fxscale, *(int*)&fxscale, fxllimit, *(int*)&fxllimit, fxulimit, *(int*)&fxulimit); sigmoiddevice->setLimits(*(int*)&fxscale, *(int*)&fxllimit, *(int*)&fxulimit); int incr = 1; fprintf(stderr, "filling sigmoid table pointer=%x\n", sigmoidTable.reference()); for (int ai = 0; ai < num_entries; ai += incr) { float angle = (ai - num_entries / 2) / fscale; //int index = (int)(angle*fscale); float s = sigmoid(angle); //fprintf(stderr, "ai=%d angle=%f entry_angle=%f sigmoid=%f\n", ai, angle, angle * fscale + num_entries/2, s); sigmoidTable.at<float>(0, 4*ai+0) = -angle; sigmoidTable.at<float>(0, 4*ai+1) = s; if (ai == num_entries-1) { sigmoidTable.at<float>(0, 4*ai+2) = 0; } else if (ai > 0) { float angle_prev = (ai - 1 - num_entries/2) / fscale; float s_prev = sigmoidTable.at<float>(0,4*(ai-1)+1); float dangle = angle - angle_prev; float ds = s - s_prev; float slope = ds / dangle; //fprintf(stderr, "angle=%f angle_prev=%f s=%f s_prev=%f ds=%f dangle=%f slope=%f\n", angle, angle_prev, s, s_prev, ds, dangle, slope); sigmoidTable.at<float>(0, 4*ai+2) = slope; } sigmoidTable.at<float>(0, 4*ai+3) = 0; } fprintf(stderr, "updating sigmoid table pointer=%x\n", sigmoidTable.reference()); sigmoiddevice->updateTable(sigmoidTable.reference(), 0, num_entries); sem_wait(&mul_sem); fprintf(stderr, "sigmoid table updated\n"); } void RbmMat::sigmoid(RbmMat &a) { create(a.rows, a.cols, CV_32F); fprintf(stderr, "RbmMat::sigmoid() %d %d\n", a.rows, a.cols); reference(); cacheFlushInvalidate(); //fprintf(stderr, "sigmoid: a.ref=%d a.rows=%d a.cols=%d\n", a.reference(), a.rows, a.cols); //fprintf(stderr, "sigmoiddevice->sigmoid\n"); sigmoiddevice->sigmoid(a.reference(), 0, reference(), 0, a.rows*a.cols); sem_wait(&mul_sem); } void RbmMat::hiddenStates(RbmMat &a, RbmMat &rand) { create(a.rows, a.cols, CV_32F); fprintf(stderr, "hiddenStates: a.ref=%d a.rows=%d a.cols=%d\n", a.reference(), a.rows, a.cols); rand.reference(); reference(); cacheFlushInvalidate(); fprintf(stderr, "rbmdevice->computeStates ptr=%d randPtr=%d\n", a.reference(), rand.reference()); rbmdevice->computeStates(a.reference(), 0, rand.reference(), 0, reference(), 0, a.rows*a.cols); sem_wait(&mul_sem); } // weights += learningRate * (pos_associations - neg_associations) / num_examples; void RbmMat::updateWeights(RbmMat &posAssociations, RbmMat &negAssociations, float learningRateOverNumExamples) { fprintf(stderr, "rbmdevice->updateWeights pa.ref=%d na.ref=%d\n", posAssociations.reference(), negAssociations.reference()); cacheFlushInvalidate(); rbmdevice->updateWeights(posAssociations.reference(), negAssociations.reference(), reference(), rows*cols, *(int*)&learningRateOverNumExamples); sem_wait(&mul_sem); } void RbmMat::sumOfErrorSquared(RbmMat &pred) { if (rows != pred.rows || cols != pred.cols) { fprintf(stderr, "Mismatched data and pred: data.rows=%d data.cols=%d pred.rows=%d pred.cols=%d\n", rows, cols, pred.rows, pred.cols); exit(-1); } fprintf(stderr, "sumOfErrorSquared called numElts=%d\n", rows*cols); cacheFlushInvalidate(); rbmdevice->sumOfErrorSquared(reference(), pred.reference(), rows*cols); sem_wait(&mul_sem); } void printDynamicRange(const char *label, cv::Mat m) { int min_exp = 0; int max_exp = 0; float min_val = 0.0; float max_val = 0.0; dynamicRange(m, &min_exp, &max_exp, &min_val, &max_val); printf("dynamic range: max_exp=%d min_exp=%d max_val=%f min_val=%f %s\n", max_exp, min_exp, max_val, min_val, label); } float sumOfErrorSquared(cv::Mat &a, cv::Mat &b) { cv::Mat diff = a - b; float error = diff.dot(diff); return error; } void RBM::train(int numVisible, int numHidden, const cv::Mat &trainingData) { bool verify = false; #ifdef SIMULATION int numEpochs = 10; #else int numEpochs = 100; #endif if (verify) numEpochs = 1; float sum_of_errors_squareds[numEpochs]; bool verbose = false; bool dynamicRange = true; //int numExamples = trainingData.rows; if (verbose) dumpMat<float>("trainingData", "%5.6f", trainingData); if (dynamicRange) printDynamicRange("trainingData", trainingData); cv::Mat weights; weights.create(numVisible+1, numHidden+1, CV_32F); for (int i = 0; i < numVisible+1; i++) { for (int j = 0; j < numHidden+1; j++) { float w = 0.1 * drand48(); if (w < 0 || w > 1.0) printf("w out of range %f\n", w); weights.at<float>(i,j) = w; } } if (dynamicRange) printDynamicRange("weights", weights); // insert bias units of 1 into first column of data cv::Mat data; data.create(trainingData.rows, trainingData.cols+1, CV_32F); trainingData.copyTo(data.colRange(1, data.cols)); for (int i = 0; i < data.rows; i++) data.at<float>(i, 0) = 1.0; RbmMat pmData(data); RbmMat pmDataT(pmData.t()); RbmMat pmWeights(weights); RbmMat pmWeightsT; RbmMat pm_pos_hidden_activations; RbmMat pm_pos_hidden_probs; RbmMat pm_rand_mat; RbmMat pm_pos_hidden_states; RbmMat pm_pos_hidden_probsT; RbmMat pm_pos_associations; RbmMat pm_neg_visible_activations; RbmMat pm_neg_visible_probs; RbmMat pm_neg_hidden_activations; RbmMat pm_neg_hidden_probs; RbmMat pm_neg_visible_probsT; RbmMat pm_neg_hidden_probsT; RbmMat pm_neg_associations; RbmMat pm_pos_hidden_statesT; if (verbose) dumpMat<float>("data", "%5.6f", data); if (verbose) dumpMat<float>("weights", "%5.6f", weights); portalTimerStart(0); for (int epoch = 0; epoch < numEpochs; epoch++) { timerdevice->startTimer(); cv::Mat pos_hidden_activations = data * pmWeights; if (dynamicRange) printDynamicRange("pos_hidden_activations", pos_hidden_activations); // fixme transpose pmWeightsT.transpose(pmWeights); if (verbose) dumpMat<float>("pmWeightsT", "%5.1f", pmWeightsT); //RbmMat pm_pos_hidden_activations; pm_pos_hidden_activations.multf(pmDataT, pmWeights); if (verbose) dumpMat<float>("pm_pos_hidden_activations", "%5.1f", pm_pos_hidden_activations); if (verbose) dumpMat<float>(" pos_hidden_activations", "%5.1f", pos_hidden_activations); if (verify) assert(pm_pos_hidden_activations.compare(pos_hidden_activations, __FILE__, __LINE__)); // RbmMat pm_pos_hidden_probs; pm_pos_hidden_probs.sigmoid(pm_pos_hidden_activations); if (dynamicRange) printDynamicRange("pm_pos_hidden_probs", pm_pos_hidden_probs); cv::Mat pos_hidden_probs(pm_pos_hidden_activations); for (int i = 0; i < pm_pos_hidden_activations.rows; i++) { for (int j = 0; j < pm_pos_hidden_activations.cols; j++) { pos_hidden_probs.at<float>(i,j) = sigmoid(pm_pos_hidden_activations.at<float>(i,j)); } } if (verbose) dumpMat<float>("pm_pos_hidden_probs", "%5.1f", pm_pos_hidden_probs); if (verbose) dumpMat<float>(" pos_hidden_probs", "%5.1f", pos_hidden_probs); if (verify) assert(pm_pos_hidden_probs.compare(pos_hidden_probs, __FILE__, __LINE__)); // RbmMat pm_rand_mat; pm_rand_mat.create(pm_pos_hidden_probs.rows, pm_pos_hidden_probs.cols, CV_32F); for (int i = 0; i < pm_pos_hidden_probs.rows; i++) { for (int j = 0; j < pm_pos_hidden_probs.cols; j++) { pm_rand_mat.at<float>(i,j) = (float)drand48(); } } if (verbose) dumpMat<float>("pm_rand_mat", "%5.1f", pm_rand_mat); if (dynamicRange) printDynamicRange("pm_rand_mat", pm_rand_mat); cv::Mat pos_hidden_states; pos_hidden_states.create(pm_pos_hidden_probs.rows, pm_pos_hidden_probs.cols, CV_32F); for (int i = 0; i < pm_pos_hidden_probs.rows; i++) { for (int j = 0; j < pm_pos_hidden_probs.cols; j++) { float val = 0.0; if (pm_pos_hidden_probs.at<float>(i,j) > pm_rand_mat.at<float>(i,j)) val = 1.0; pos_hidden_states.at<float>(i,j) = val; } } if (dynamicRange) printDynamicRange("pos_hidden_states", pos_hidden_states); // RbmMat pm_pos_hidden_states; pm_pos_hidden_states.hiddenStates(pm_pos_hidden_probs, pm_rand_mat); if (verbose) dumpMat<float>("pm_pos_hidden_states", "%5.1f", pm_pos_hidden_states); if (verbose) dumpMat<float>(" pos_hidden_states", "%5.1f", pos_hidden_states); if (verify) assert(pm_pos_hidden_states.compare(pos_hidden_states, __FILE__, __LINE__)); if (verbose) dumpMat<float>("pmDataT", "%5.1f", pmDataT); //RbmMat pmWeights(weights); // back to non-transposed //pmWeights.copy(weights); if (verbose) dumpMat<float>("pmWeights", "%5.1f", pmWeights); pm_pos_hidden_probsT.transpose(pm_pos_hidden_probs); if (verbose) dumpMat<float>("pos_hidden_probsT", "%5.1f", pm_pos_hidden_probsT); cv::Mat pos_associations = pmDataT * pm_pos_hidden_probs; //RbmMat pm_pos_associations; pm_pos_associations.multf(pmData, pm_pos_hidden_probs); if (verbose) dumpMat<float>("pos_associations", "%5.1f", pm_pos_associations); if (dynamicRange) printDynamicRange("pm_pos_associations", pm_pos_associations); // check results if (verify) assert(pm_pos_associations.compare(pos_associations, __FILE__, __LINE__)); // RbmMat pm_neg_visible_activations; pm_pos_hidden_statesT.transpose(pm_pos_hidden_states); pm_neg_visible_activations.multf(pm_pos_hidden_statesT, pmWeightsT); if (verbose) dumpMat<float>("neg_visible_activations", "%5.1f", pm_neg_visible_activations); if (dynamicRange) printDynamicRange("pm_neg_visible_activations", pm_neg_visible_activations); cv::Mat neg_visible_probs; neg_visible_probs.create(pm_neg_visible_activations.rows, pm_neg_visible_activations.cols, CV_32F); for (int i = 0; i < pm_neg_visible_activations.rows; i++) { for (int j = 0; j < pm_neg_visible_activations.cols; j++) { neg_visible_probs.at<float>(i,j) = sigmoid(pm_neg_visible_activations.at<float>(i,j)); } } // RbmMat pm_neg_visible_probs; pm_neg_visible_probs.sigmoid(pm_neg_visible_activations); pm_neg_visible_probsT.transpose(pm_neg_visible_probs); if (verbose) dumpMat<float>("neg_visible_probs", "%5.1f", pm_neg_visible_probs); // pm_neg_visible_probs[:0] = 1; for (int i = 0; i < pm_neg_visible_probs.rows; i++) { pm_neg_visible_probs.at<float>(i,0) = 1.0; neg_visible_probs.at<float>(i,0) = 1.0; } if (dynamicRange) printDynamicRange("pm_neg_visible_probs", pm_neg_visible_probs); if (verify) assert(pm_neg_visible_probs.compare(neg_visible_probs, __FILE__, __LINE__)); // RbmMat pm_neg_hidden_activations; pm_neg_hidden_activations.multf(pm_neg_visible_probsT, pmWeights); if (verbose) dumpMat<float>("pm_neg_hidden_activations", "%5.1f", pm_neg_hidden_activations); if (dynamicRange) printDynamicRange("pm_neg_hidden_activations", pm_neg_hidden_activations); cv::Mat neg_hidden_activations = pm_neg_visible_probs * pmWeights; if (verbose) dumpMat<float>(" neg_hidden_activations", "%5.1f", neg_hidden_activations); if (verify) assert(pm_neg_hidden_activations.compare(neg_hidden_activations, __FILE__, __LINE__, 0.05)); // RbmMat pm_neg_hidden_probs; pm_neg_hidden_probs.sigmoid(pm_neg_hidden_activations); if (verbose) dumpMat<float>("pm_neg_hidden_probs", "%5.1f", pm_neg_hidden_probs); if (dynamicRange) printDynamicRange("pm_neg_hidden_probs", pm_neg_hidden_probs); pm_neg_visible_probsT.transpose(pm_neg_visible_probs); if (verbose) dumpMat<float>("pm_neg_visible_probsT", "%5.1f", pm_neg_visible_probsT); if (dynamicRange) printDynamicRange("pm_neg_visible_probs", pm_neg_visible_probs); pm_neg_hidden_probsT.transpose(pm_neg_hidden_probs); //RbmMat pm_neg_associations; pm_neg_associations.multf(pm_neg_visible_probs, pm_neg_hidden_probs); if (verbose) dumpMat<float>("pm_neg_associations", "%5.1f", pm_neg_associations); cv::Mat neg_associations = pm_neg_visible_probsT * pm_neg_hidden_probs; if (verbose) dumpMat<float>(" neg_associations", "%5.1f", neg_associations); if (dynamicRange) printDynamicRange("pm_neg_associations", pm_neg_associations); if (verbose) dumpMat<float>("pmWeights.before", "%5.1f", pmWeights); // weights += learningRate * (pos_associations - neg_associations) / num_examples; float learningRate = 1.0; float num_examples = data.rows; pmWeights.updateWeights(pm_pos_associations, pm_neg_associations, learningRate / num_examples); if (verbose) dumpMat<float>("pmWeights.after ", "%5.1f", pmWeights); if (dynamicRange) printDynamicRange("weights", weights); fprintf(stderr, "========== %s:%d\n", __FILE__, __LINE__); // error = np.sum((data - neg_visible_probs) ** 2) pmData.sumOfErrorSquared(pm_neg_visible_probs); float error = sumOfErrorSquared(data, pm_neg_visible_probs); fprintf(stderr, "========== %s:%d\n", __FILE__, __LINE__); fprintf(stderr, "completed epoch %d sumOfErrorSquared=%f\n", epoch, error); sum_of_errors_squareds[epoch] = rbmDeviceIndication->sum_of_errors_squared; timerdevice->stopTimer(); } //uint64_t total_cycles = portalTimerLap(0); //uint64_t beats = hostMemServerIndication->getMemoryTraffic(ChannelType_Read); //fprintf(stderr, "total_cycles=%ld beats=%ld utilization=%f\n", (long)total_cycles, (long)beats, (float)beats / (float)total_cycles); for(int i = 0; i < numEpochs; i++) fprintf(stderr, "(%d) %f\n", i, sum_of_errors_squareds[i]); } void RBM::run() { cv::Mat trainingData = (cv::Mat_<float>(6,6) << 1,1,1,0,0,0, 1,0,1,0,0,0, 1,1,1,0,0,0, 0,0,1,1,1,0, 0,0,1,1,0,0, 0,0,1,1,1,0); char name_buff[256]; snprintf(name_buff, 256, "../train-images-idx3-ubyte"); fprintf(stderr, "reading image data from %s\n", name_buff); MnistImageFile imagefile(name_buff); imagefile.open(); int numImages = imagefile.numEntries(); int numPixels = imagefile.rows()*imagefile.cols(); numImages = 200; int cols = 783; // one more column is added below to make the total 784. #ifdef SIMULATION numImages = 32; cols = 31; // one more column is added to make the total 32 #endif if (!cols || numPixels < cols) cols = numPixels; fprintf(stderr, "numImages=%d numPixels=%d imagefile.rows=%d imagefile.cols=%d\n", numImages, numPixels, imagefile.rows(), imagefile.cols()); //numVisible = imagefile.rows()*imagefile.cols(); int numVisible = cols; int numHidden = numVisible / 2; trainingData.create(numImages, cols, CV_32F); for (int i = 0; i < numImages; i++) { //fprintf(stderr, "Reading mat %d\n", i); cv::Mat m = imagefile.mat(i); //dumpMat<unsigned char>("foo", "%02x", m); for (int j = 0; j < imagefile.rows(); j++) { for (int k = 0; k < imagefile.cols(); k++) { int offset = j*imagefile.cols() + k; if (offset < cols) { float f = (float)m.at<unsigned char>(k,j); trainingData.at<float>(i, offset) = f; } } } } fprintf(stderr, "RBM::run() invoking train\n"); train(numVisible, numHidden, trainingData); fprintf(stderr, "trainingData.rows=%d trainingData.cols=%d\n", trainingData.rows, trainingData.cols); }
40.905437
148
0.701035
jrrk2
32c1d7608b90688b8218d44771897257de20408b
950
cpp
C++
module-os/test/performance-monitor.cpp
buk7456/MuditaOS
06ef1e131b27b0f397cc615c96d51bede7050423
[ "BSL-1.0" ]
369
2021-11-10T09:20:29.000Z
2022-03-30T06:36:58.000Z
module-os/test/performance-monitor.cpp
buk7456/MuditaOS
06ef1e131b27b0f397cc615c96d51bede7050423
[ "BSL-1.0" ]
149
2021-11-10T08:38:35.000Z
2022-03-31T23:01:52.000Z
module-os/test/performance-monitor.cpp
buk7456/MuditaOS
06ef1e131b27b0f397cc615c96d51bede7050423
[ "BSL-1.0" ]
41
2021-11-10T08:30:37.000Z
2022-03-29T08:12:46.000Z
#include <limits> #define CATCH_CONFIG_MAIN #include <catch2/catch.hpp> #include "prof.h" TEST_CASE("prof api test") { struct prof_pool_init_data init{0}; prof_pool_init(init); auto pp = prof_pool_get_data(); REQUIRE(pp.size == 0); prof_pool_deinit(); } TEST_CASE("overflow") { struct prof_pool_init_data init { 0 }; prof_pool_init(init); prof_pool_data_set(0,-1); REQUIRE(prof_pool_overflow() == 1); prof_pool_deinit(); } TEST_CASE("prof api sum") { struct prof_pool_init_data init{1}; prof_pool_init(init); auto pp = prof_pool_get_data(); REQUIRE(pp.size == 1); const auto switches = 10; const auto ts = 10; for (auto i =0; i < switches ; ++i) { prof_pool_data_set(0,ts); } task_prof_data mem[1]; prof_pool_flush(mem, 1); REQUIRE(mem->switches == switches); REQUIRE(mem->exec_time == switches*ts); prof_pool_deinit(); }
19
43
0.634737
buk7456
32c1f936fb1be70749f4d54d62e912302a2b70d8
4,383
cpp
C++
libenchant/unittests/dictionary/enchant_dict_is_added_tests.cpp
orynider/php-5.6.3x4VC9
47f9765b797279061c364e004153a0919895b23e
[ "BSD-2-Clause" ]
1
2021-02-24T13:01:00.000Z
2021-02-24T13:01:00.000Z
libenchant/unittests/dictionary/enchant_dict_is_added_tests.cpp
orynider/php-5.6.3x4VC9
47f9765b797279061c364e004153a0919895b23e
[ "BSD-2-Clause" ]
null
null
null
libenchant/unittests/dictionary/enchant_dict_is_added_tests.cpp
orynider/php-5.6.3x4VC9
47f9765b797279061c364e004153a0919895b23e
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (c) 2007 Eric Scott Albright * * 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 <UnitTest++.h> #include <enchant.h> #include "EnchantDictionaryTestFixture.h" struct EnchantDictionaryIsAdded_TestFixture : EnchantDictionaryTestFixture {}; /** * enchant_dict_is_added * @dict: A non-null #EnchantDict * @word: The word you wish to see if it's in your session * @len: the byte length of @word, or -1 for strlen (@word) */ ///////////////////////////////////////////////////////////////////////////// // Test Normal Operation TEST_FIXTURE(EnchantDictionaryIsAdded_TestFixture, EnchantDictionaryIsAdded_AddedToSession_1) { enchant_dict_add_to_session(_dict, "hello", -1); CHECK_EQUAL(1, enchant_dict_is_added(_dict, "hello", -1)); } TEST_FIXTURE(EnchantDictionaryIsAdded_TestFixture, EnchantDictionaryIsAdded_Added_1) { enchant_dict_add(_dict, "hello", -1); CHECK_EQUAL(1, enchant_dict_is_added(_dict, "hello", -1)); } TEST_FIXTURE(EnchantDictionaryIsAdded_TestFixture, EnchantDictionaryIsAdded_NotAdded_0) { CHECK_EQUAL(0, enchant_dict_is_added(_dict, "hello", -1)); } TEST_FIXTURE(EnchantDictionaryIsAdded_TestFixture, EnchantDictionaryIsAdded_OnBrokerPwl_AddedToSession_1) { enchant_dict_add_to_session(_pwl, "hello", -1); CHECK_EQUAL(1, enchant_dict_is_added(_pwl, "hello", -1)); } TEST_FIXTURE(EnchantDictionaryIsAdded_TestFixture, EnchantDictionaryIsAdded_OnBrokerPwl_Added_1) { enchant_dict_add(_pwl, "hello", -1); CHECK_EQUAL(1, enchant_dict_is_added(_pwl, "hello", -1)); } TEST_FIXTURE(EnchantDictionaryIsAdded_TestFixture, EnchantDictionaryIsAdded_OnBrokerPwl_NotAdded_0) { CHECK_EQUAL(0, enchant_dict_is_added(_pwl, "hello", -1)); } TEST_FIXTURE(EnchantDictionaryIsAdded_TestFixture, EnchantDictionaryIsAdded_HasPreviousError_ErrorCleared) { SetErrorOnMockDictionary("something bad happened"); enchant_dict_is_added(_dict, "hello", -1); CHECK_EQUAL((void*)NULL, (void*)enchant_dict_get_error(_dict)); } ///////////////////////////////////////////////////////////////////////////// // Test Error Conditions TEST_FIXTURE(EnchantDictionaryIsAdded_TestFixture, EnchantDictionaryIsAdded_NullDictionary_0) { CHECK_EQUAL(0, enchant_dict_is_added(NULL, "hello", -1)); } TEST_FIXTURE(EnchantDictionaryIsAdded_TestFixture, EnchantDictionaryIsAdded_NullWord_0) { CHECK_EQUAL(0, enchant_dict_is_added(_dict, NULL, -1)); } TEST_FIXTURE(EnchantDictionaryIsAdded_TestFixture, EnchantDictionaryIsAdded_EmptyWord_0) { CHECK_EQUAL(0, enchant_dict_is_added(_dict, "", -1)); } TEST_FIXTURE(EnchantDictionaryIsAdded_TestFixture, EnchantDictionaryIsAdded_WordSize0_0) { CHECK_EQUAL(0, enchant_dict_is_added(_dict, "hello", 0)); } TEST_FIXTURE(EnchantDictionaryIsAdded_TestFixture, EnchantDictionaryIsAdded_InvalidUtf8Word_0) { CHECK_EQUAL(0, enchant_dict_is_added(_dict, "\xa5\xf1\x08", -1)); } TEST_FIXTURE(EnchantDictionaryIsAdded_TestFixture, EnchantDictionaryIsAdded_WordExistsInPwlAndExclude_0) { ExternalAddWordToDictionary("hello"); ExternalAddWordToExclude("hello"); ReloadTestDictionary(); CHECK_EQUAL(0, enchant_dict_is_added(_dict, "hello", -1)); }
32.954887
80
0.726443
orynider
32c3bdd57aafc5644d1a68828373218e4568c994
1,826
cpp
C++
binary-trees/Juez215/Source.cpp
albertopastormr/data-structures-eda
2846e4ba62b5db13788f0c4e6160dc7514070063
[ "MIT" ]
null
null
null
binary-trees/Juez215/Source.cpp
albertopastormr/data-structures-eda
2846e4ba62b5db13788f0c4e6160dc7514070063
[ "MIT" ]
null
null
null
binary-trees/Juez215/Source.cpp
albertopastormr/data-structures-eda
2846e4ba62b5db13788f0c4e6160dc7514070063
[ "MIT" ]
null
null
null
// Alberto Pastor Moreno // E46 #include <iostream> #include <iomanip> #include <fstream> #include <algorithm> #include <vector> #include "bintree_eda.h" struct tSol{ int numNavegables = 0, caudal = 0; tSol(int nn, int c) : numNavegables(nn), caudal(c){} }; // función que resuelve el problema template <class T> tSol aguaslimpias(bintree<T> const & tree) { if (tree.left().empty() && tree.right().empty()) return{ 0, (tree.root() > 0 ? 0 : 1)}; else if (tree.left().empty()){ tSol dr = aguaslimpias(tree.right()); return{ dr.numNavegables + (dr.caudal >= 3 ? 1 : 0), std::max(dr.caudal - tree.root(), 0)}; } else if (tree.right().empty()){ tSol iz = aguaslimpias(tree.left()); return{ iz.numNavegables + (iz.caudal >= 3 ? 1 : 0), std::max(iz.caudal - tree.root(), 0)}; } else{ tSol iz = aguaslimpias(tree.left()); tSol dr = aguaslimpias(tree.right()); return{ iz.numNavegables + dr.numNavegables + (iz.caudal >= 3 ? 1 : 0) + (dr.caudal >= 3 ? 1 : 0), std::max(iz.caudal + dr.caudal - tree.root(),0) }; } } // Resuelve un caso de prueba, leyendo de la entrada la // configuración, y escribiendo la respuesta void resuelveCaso() { // leer los datos de la entrada auto tree = leerArbol(-1); tSol sol = aguaslimpias(tree); // escribir sol std::cout << sol.numNavegables << "\n"; } int main() { // Para la entrada por fichero. // Comentar para acepta el reto #ifndef DOMJUDGE std::ifstream in("datos.txt"); auto cinbuf = std::cin.rdbuf(in.rdbuf()); //save old buf and redirect std::cin to casos.txt #endif int numCasos; std::cin >> numCasos; for (int i = 0; i < numCasos; ++i) resuelveCaso(); // Para restablecer entrada. Comentar para acepta el reto #ifndef DOMJUDGE // para dejar todo como estaba al principio std::cin.rdbuf(cinbuf); system("PAUSE"); #endif return 0; }
26.085714
151
0.653341
albertopastormr
32c3cfe9fde5934fbf1e7fe0fb4d14f8c78085aa
595
hpp
C++
paper/config.hpp
williamstarkro/paper
13266b83b3922fc146cba1eecedac5a9addf6f2a
[ "BSD-2-Clause" ]
null
null
null
paper/config.hpp
williamstarkro/paper
13266b83b3922fc146cba1eecedac5a9addf6f2a
[ "BSD-2-Clause" ]
null
null
null
paper/config.hpp
williamstarkro/paper
13266b83b3922fc146cba1eecedac5a9addf6f2a
[ "BSD-2-Clause" ]
null
null
null
#pragma once #include <chrono> #include <cstddef> namespace paper { // Network variants with different genesis blocks and network parameters enum class paper_networks { // Low work parameters, publicly known genesis key, test IP ports paper_test_network, // Normal work parameters, secret beta genesis key, beta IP ports paper_beta_network, // Normal work parameters, secret live key, live IP ports paper_live_network }; paper::paper_networks const paper_network = paper_networks::ACTIVE_NETWORK; std::chrono::milliseconds const transaction_timeout = std::chrono::milliseconds (1000); }
28.333333
87
0.789916
williamstarkro
32c420a5625bb5fe7b614a2677917e7e88ea0cb8
1,504
cpp
C++
src/MetaAuthoringTool/VRCAT.Wrapper/MRigidMeshComponent.cpp
phs008/PrismSolution
ea2452ef98bdd18216f3947dd0cb5483e2e2a079
[ "MIT" ]
null
null
null
src/MetaAuthoringTool/VRCAT.Wrapper/MRigidMeshComponent.cpp
phs008/PrismSolution
ea2452ef98bdd18216f3947dd0cb5483e2e2a079
[ "MIT" ]
null
null
null
src/MetaAuthoringTool/VRCAT.Wrapper/MRigidMeshComponent.cpp
phs008/PrismSolution
ea2452ef98bdd18216f3947dd0cb5483e2e2a079
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "MRigidMeshComponent.h" #include <Resource/ResourcePath.h> namespace MVRWrapper { MRigidMeshComponent::MRigidMeshComponent() :MContainerComponent(ComponentEnum::RigidMesh) { _pRigidMesh = this->GetNative(); this->setMesh(); } MRigidMeshComponent::MRigidMeshComponent(Code3::Component::ContainerComponent* _containerComponent) :MContainerComponent(_containerComponent) { _pRigidMesh = this->GetNative(); this->setMesh(); } Code3::Scene::RigidMesh* MRigidMeshComponent::GetNative() { return MContainerComponent::GetNative<Code3::Scene::RigidMesh>(); } void MRigidMeshComponent::setMaterial(System::String^ matFile) { InternString path = MarshalHelper::StringToNativeString(matFile); Code3::FileIO::Path p; p.SetAbsolutePath(path); if (p.MakeRelativePath(&Code3::Resource::GetResourcePath().ResourceFolder)) { _pRigidMesh->PropRigidMesh.Material.Value = p; _pRigidMesh->PropRigidMesh.Apply(); //_pRigidMesh->PropRigidMesh.MeshDraw.ResBuffer.Instance->ResMaterial.Instance->SaveToFile(p); /*_pRigidMesh->PropRigidMesh.MeshDraw.ResBuffer.Instance->ResMaterial.Instance->SaveToFile( _pRigidMesh->PropRigidMesh.MeshDraw.ResBuffer.Instance->ResMaterial.Instance->SourceFile);*/ } //_pRigidMesh->PropRigidMesh.Apply(); } void MRigidMeshComponent::setMesh() { _pRigidMesh->PropRigidMesh.Mesh.Value.SetRelativePath(Code3::BasicType::InternString("program"), "<sphere>1.0x30x30"); _pRigidMesh->PropRigidMesh.Apply(); } }
32.695652
120
0.767952
phs008
32c7df49f8ca191fd2d83eca4e261c3ee1c9a7ae
1,169
cpp
C++
tests/test_geometry.cpp
keisukefukuda/tapas
341fad9ecd97607771db4c4c966b76d30b5bfc89
[ "MIT" ]
null
null
null
tests/test_geometry.cpp
keisukefukuda/tapas
341fad9ecd97607771db4c4c966b76d30b5bfc89
[ "MIT" ]
13
2015-04-22T10:32:01.000Z
2016-01-21T10:24:32.000Z
tests/test_geometry.cpp
keisukefukuda/tapas
341fad9ecd97607771db4c4c966b76d30b5bfc89
[ "MIT" ]
null
null
null
#include <cmath> #include <utility> #include <set> #ifndef TAPAS_DEBUG #define TAPAS_DEBUG 1 // always use TAPAS_DEBUG #endif #include <tapas/common.h> #include <tapas/test.h> #include <tapas/geometry.h> SETUP_TEST; using V1 = tapas::Vec<1, double>; using V2 = tapas::Vec<2, double>; using Reg1 = tapas::Region<1, double>; using Reg2 = tapas::Region<2, double>; void Test_Join() { { const int Dim = 1; using FP = double; using Region = tapas::Region<Dim, FP>; auto A = Region::BB(Region({1}, {2}), Region({-1}, {3})); ASSERT_EQ(A.min(0), -1); ASSERT_EQ(A.max(0), 3); auto B = Region::BB(Region({1}, {2}), Region({3}, {4})); ASSERT_EQ(B.min(0), 1); ASSERT_EQ(B.max(0), 4); } { const int Dim = 2; using FP = double; using Region = tapas::Region<Dim, FP>; auto C = Region::BB(Region({1,1}, {2,2}), Region({-1,-1}, {3,3})); ASSERT_EQ(C.max(0), 3); ASSERT_EQ(C.max(1), 3); ASSERT_EQ(C.min(0), -1); ASSERT_EQ(C.min(1), -1); } } int main(int argc, char **argv) { MPI_Init(&argc, &argv); Test_Join(); TEST_REPORT_RESULT(); MPI_Finalize(); return (TEST_SUCCESS() ? 0 : 1); }
19.483333
70
0.586826
keisukefukuda
32c86367a53b92150af27fdf04240e3549386702
13,281
cc
C++
dfplayer/kinect.cc
gleenn/dfplayer
dd390a6f54b3bd8b2a3397fddd6caacfba01b29d
[ "MIT" ]
null
null
null
dfplayer/kinect.cc
gleenn/dfplayer
dd390a6f54b3bd8b2a3397fddd6caacfba01b29d
[ "MIT" ]
null
null
null
dfplayer/kinect.cc
gleenn/dfplayer
dd390a6f54b3bd8b2a3397fddd6caacfba01b29d
[ "MIT" ]
null
null
null
// Copyright 2015, Igor Chernyshev. // Licensed under The MIT License // #include "kinect.h" #include <math.h> #include <opencv2/opencv.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <pthread.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <algorithm> #include <vector> #include "util/lock.h" #include "util/time.h" #include "utils.h" #include "../external/kkonnect/include/kk_connection.h" #include "../external/kkonnect/include/kk_device.h" using kkonnect::Connection; using kkonnect::Device; using kkonnect::DeviceOpenRequest; using kkonnect::ErrorCode; using kkonnect::ImageInfo; // TODO(igorc): Add atexit() to stop this, tcl and visualizer threads, // and to unblock all waiting Python threads. // TODO(igorc): Fix crashes on USB disconnect. class KinectRangeImpl : public KinectRange { public: KinectRangeImpl(); ~KinectRangeImpl() override; void EnableVideo() override; void EnableDepth() override; void Start(int fps) override; int GetWidth() const override; int GetHeight() const override; int GetDepthDataLength() const override; void GetDepthData(uint8_t* dst) const override; void GetVideoData(uint8_t* dst) const override; Bytes* GetAndClearLastDepthColorImage() override; Bytes* GetAndClearLastVideoImage() override; double GetPersonCoordX() const override; private: static KinectRangeImpl* GetInstanceImpl(); void ConnectDevices(); static void* RunMergerLoop(void* arg); void RunMergerLoop(); void MergeImages(); void ContrastDepthLocked(); void ClampDepthDataLocked(); void FindContoursLocked(); int fps_; bool video_enabled_ = false; bool depth_enabled_ = false; Connection* connection_ = nullptr; pthread_t merger_thread_; volatile bool should_exit_ = false; mutable pthread_mutex_t devices_mutex_ = PTHREAD_MUTEX_INITIALIZER; mutable pthread_mutex_t merger_mutex_ = PTHREAD_MUTEX_INITIALIZER; std::vector<Device*> devices_; int width_ = 0; int height_ = 0; bool has_started_thread_ = false; cv::Mat video_data_; cv::Mat depth_data_orig_; cv::Mat depth_data_blur_; cv::Mat depth_data_range_; cv::Mat depth_data_range_copy_; cv::Mat depth_data_range_marked_; cv::Mat erode_element_; cv::Mat dilate_element_; cv::vector<cv::Vec3i> circles_; bool has_new_depth_image_ = false; bool has_new_video_image_ = false; }; KinectRange* KinectRange::instance_ = new KinectRangeImpl(); // static KinectRange* KinectRange::GetInstance() { return instance_; } // static KinectRangeImpl* KinectRangeImpl::GetInstanceImpl() { return reinterpret_cast<KinectRangeImpl*>(GetInstance()); } KinectRangeImpl::KinectRangeImpl() : fps_(15) { erode_element_ = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3)); dilate_element_ = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(8, 8)); } KinectRangeImpl::~KinectRangeImpl() { should_exit_ = true; pthread_join(merger_thread_, NULL); if (connection_) connection_->Close(); } void KinectRangeImpl::EnableVideo() { CHECK(!has_started_thread_); video_enabled_ = true; } void KinectRangeImpl::EnableDepth() { CHECK(!has_started_thread_); depth_enabled_ = true; } void KinectRangeImpl::Start(int fps) { Autolock l1(merger_mutex_); Autolock l2(devices_mutex_); if (has_started_thread_) return; has_started_thread_ = true; fps_ = fps; ConnectDevices(); CHECK(!pthread_create(&merger_thread_, NULL, RunMergerLoop, this)); } void KinectRangeImpl::ConnectDevices() { connection_ = Connection::OpenLocal(); int device_count = connection_->GetDeviceCount(); fprintf(stderr, "Found %d Kinect devices\n", device_count); Device* device = nullptr; DeviceOpenRequest request(0); if (video_enabled_) request.depth_format = kkonnect::kImageFormatVideoRgb; if (depth_enabled_) request.depth_format = kkonnect::kImageFormatDepthMm; ErrorCode err = connection_->OpenDevice(request, &device); if (err != kkonnect::kErrorSuccess) { fprintf(stderr, "Failed to open Kinect device, error=%d\n", err); return; } uint64_t start_time = GetCurrentMillis(); while (device->GetStatus() == kkonnect::kErrorInProgress) { uint64_t elapsed_ms = GetCurrentMillis() - start_time; if (elapsed_ms > 15 * 1000) { fprintf(stderr, "Timed out waiting for a Kinect connection\n"); connection_->CloseDevice(device); return; } Sleep(0.1); } err = device->GetStatus(); if (err != kkonnect::kErrorSuccess) { fprintf(stderr, "Failed to connect to Kinect device, error=%d\n", err); return; } ImageInfo video_info = device->GetVideoImageInfo(); ImageInfo depth_info = device->GetDepthImageInfo(); if (!video_info.enabled && !depth_info.enabled) { fprintf(stderr, "Both video and depth streams are closed\n"); } else if (video_info.enabled && depth_info.enabled) { CHECK(video_info.width == depth_info.width); CHECK(video_info.height == depth_info.height); } if (video_info.enabled) { width_ = video_info.width; height_ = video_info.height; } else if (depth_info.enabled) { width_ = depth_info.width; height_ = depth_info.height; } CHECK(width_ > 0); CHECK(height_ > 0); devices_.push_back(device); // TODO(igorc): Get width and height. video_data_.create(height_, width_ * device_count, CV_8UC3); video_data_.setTo(cv::Scalar(0, 0, 0)); depth_data_orig_.create(height_, width_ * device_count, CV_16UC1); depth_data_blur_.create(height_, width_ * device_count, CV_16UC1); depth_data_orig_.setTo(cv::Scalar(0)); depth_data_blur_.setTo(cv::Scalar(0)); } // static void* KinectRangeImpl::RunMergerLoop(void* arg) { reinterpret_cast<KinectRangeImpl*>(arg)->RunMergerLoop(); return NULL; } void KinectRangeImpl::RunMergerLoop() { uint32_t ms_per_frame = (uint32_t) (1000.0 / (double) fps_); uint64_t next_render_time = GetCurrentMillis() + ms_per_frame; while (!should_exit_) { uint32_t remaining_time = 0; uint64_t now = GetCurrentMillis(); if (next_render_time > now) remaining_time = next_render_time - now; if (remaining_time > 0) Sleep(((double) remaining_time) / 1000.0); next_render_time += ms_per_frame; MergeImages(); } } void KinectRangeImpl::MergeImages() { Autolock l1(merger_mutex_); bool has_depth_update = false; bool has_video_update = false; { // Merge images from all devices into one. Autolock l2(devices_mutex_); for (size_t i = 0; i < devices_.size(); ++i) { Device* device = devices_[i]; int full_witdh = width_ * devices_.size(); has_depth_update |= device->GetAndClearDepthData( reinterpret_cast<uint16_t*>(depth_data_orig_.data), full_witdh * 2); has_video_update |= device->GetAndClearVideoData( video_data_.data, full_witdh * 3); // TODO(igorc): Erase device's part of the image after // a few missing updates. } } circles_.clear(); if (has_depth_update) { ContrastDepthLocked(); FindContoursLocked(); has_new_depth_image_ = true; } if (has_video_update) has_new_video_image_ = true; } void KinectRangeImpl::ContrastDepthLocked() { ClampDepthDataLocked(); // Blur the depth image to reduce noise. // TODO(igorc): Try to reduce CPU usage here (using 10% now?). const int kKernelSize = 7; cv::blur( depth_data_orig_, depth_data_blur_, cv::Size(kKernelSize, kKernelSize), cv::Point(-1,-1)); // Select trigger pixels. // The depth range is approximately 3 meters. The height of the car // is approximately the same. We want to detect objects in the range // from 1 to 1.5 meters away from the Kinect. const uint16_t min_threshold = 1500; const uint16_t max_threshold = 2500; cv::inRange(depth_data_blur_, cv::Scalar(min_threshold), cv::Scalar(max_threshold), depth_data_range_); // Further blur range image, using in-place erode-dilate. cv::erode(depth_data_range_, depth_data_range_, erode_element_); cv::erode(depth_data_range_, depth_data_range_, erode_element_); cv::dilate(depth_data_range_, depth_data_range_, dilate_element_); cv::dilate(depth_data_range_, depth_data_range_, dilate_element_); } struct { bool operator() (cv::Vec3i c1, cv::Vec3i c2) { return (c1[2] > c2[2]); } } CircleComparator; void KinectRangeImpl::FindContoursLocked() { // Find contours of objects in the range image. // Use depth_data_range_copy_ as the image will be modified. cv::vector<cv::vector<cv::Point> > all_contours; cv::vector<cv::Vec4i> hierarchy; depth_data_range_.copyTo(depth_data_range_copy_); depth_data_range_.copyTo(depth_data_range_marked_); cv::findContours(depth_data_range_copy_, all_contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE); int object_count = hierarchy.size(); if (!object_count) { // fprintf(stderr, "No objects found\n"); return; } if (object_count > 100) { fprintf(stderr, "Too many objects found: %d\n", object_count); return; } // fprintf(stderr, "Found %d objects\n", object_count); // Assuming that any human will take at least 10% of the image size. constexpr double kMinObjectRatio = 0.10; // A human as seen from above should be less than 33% of the image size. constexpr double kMaxObjectRatio = 0.33; bool is_first = true; for (int index = 0; index >= 0; index = hierarchy[index][0]) { int parent_index = hierarchy[index][3]; if (parent_index != -1) continue; // Top-level contours only. const cv::vector<cv::Point>& contours = all_contours[index]; cv::Moments moment = cv::moments(contours); double area = moment.m00; double radius = sqrt(area / M_PI); double radius_ratio = radius / 500.0; if (radius_ratio < kMinObjectRatio) continue; if (radius_ratio > kMaxObjectRatio) continue; int x = static_cast<int>(moment.m10 / area); int y = static_cast<int>(moment.m01 / area); if (false) { // cv::Rect rect = cv::boundingRect(contours); fprintf(stderr, "%sFound object idx=%d contours=%d radius=%d x=%d y=%d\n", (is_first ? "-> " : " "), index, (int) contours.size(), static_cast<int>(radius), x, y); } is_first = false; circles_.push_back(cv::Vec3i(x, y, radius)); } std::sort(circles_.begin(), circles_.end(), CircleComparator); } void KinectRangeImpl::ClampDepthDataLocked() { CHECK(depth_data_orig_.elemSize() == 2); uint16_t* data = reinterpret_cast<uint16_t*>(depth_data_orig_.data); for (uint32_t i = 0; i < video_data_.total(); ++i) { // Clamp to practical limits of 0.5-3m. uint16_t distance = data[i]; if (distance < 500) { data[i] = 500; } else if (distance > 3000) { data[i]= 3000; } } } int KinectRangeImpl::GetWidth() const { return width_ * devices_.size(); } int KinectRangeImpl::GetHeight() const { return height_; } int KinectRangeImpl::GetDepthDataLength() const { return depth_data_orig_.total() * depth_data_orig_.elemSize(); } void KinectRangeImpl::GetDepthData(uint8_t* dst) const { Autolock l(merger_mutex_); memcpy(dst, depth_data_blur_.data, GetDepthDataLength()); } void KinectRangeImpl::GetVideoData(uint8_t* dst) const { Autolock l(merger_mutex_); memcpy(dst, video_data_.data, video_data_.total() * video_data_.elemSize()); } Bytes* KinectRangeImpl::GetAndClearLastDepthColorImage() { Autolock l(merger_mutex_); if (!has_new_depth_image_) return NULL; // Expand range to 0..255. double min = 0; double max = 0; cv::minMaxIdx(depth_data_blur_, &min, &max); cv::Mat adjMap; double scale = 255.0 / (max - min); depth_data_blur_.convertTo(adjMap, CV_8UC1, scale, -min * scale); // depth_data_range_.copyTo(adjMap); // Color-code the depth map. cv::Mat coloredMap; cv::applyColorMap(adjMap, coloredMap, cv::COLORMAP_JET); // Convert to RGB. cv::Mat coloredMapRgb; cv::cvtColor(coloredMap, coloredMapRgb, CV_BGR2RGB); for (size_t i = 0; i < circles_.size(); ++i) { const cv::Vec3i& c = circles_[i]; cv::Scalar color = (i == 0 ? cv::Scalar(255, 0, 0) : cv::Scalar(0, 255, 0)); cv::circle(coloredMapRgb, cv::Point(c[0], c[1]), c[2], color, 3); } Bytes* result = new Bytes( coloredMapRgb.data, coloredMapRgb.total() * coloredMapRgb.elemSize()); has_new_depth_image_ = false; return result; } double KinectRangeImpl::GetPersonCoordX() const { Autolock l(merger_mutex_); if (circles_.empty()) return -1; return static_cast<double>(circles_[0][0]) / width_; } Bytes* KinectRangeImpl::GetAndClearLastVideoImage() { Autolock l(merger_mutex_); if (!has_new_video_image_) return NULL; // Unpack 3-byte RGB into RGBA. int width = GetWidth(); int height = GetHeight(); const uint8_t* src = reinterpret_cast<const uint8_t*>(video_data_.data); int dst_size = width * height * 4; uint8_t* dst = new uint8_t[dst_size]; for (int y = 0; y < height; ++y) { uint8_t* dst_row = dst + y * width * 4; const uint8_t* src_row = src + y * width * 3; for (int x = 0; x < width; ++x) { memcpy(dst_row + x * 4, src_row + x * 3, 3); dst_row[3] = 0; } } Bytes* result = new Bytes(); result->MoveOwnership(dst, dst_size); has_new_video_image_ = false; return result; }
29.317881
80
0.701152
gleenn
32ca60aa7761e1341b0036ffae7c4dcf4c6f845d
1,224
cpp
C++
Engine/Source/Runtime/Renderer/Components/Buffers.cpp
1992please/NullEngine
8f5f124e9718b8d6627992bb309cf0f0d106d07a
[ "Apache-2.0" ]
null
null
null
Engine/Source/Runtime/Renderer/Components/Buffers.cpp
1992please/NullEngine
8f5f124e9718b8d6627992bb309cf0f0d106d07a
[ "Apache-2.0" ]
null
null
null
Engine/Source/Runtime/Renderer/Components/Buffers.cpp
1992please/NullEngine
8f5f124e9718b8d6627992bb309cf0f0d106d07a
[ "Apache-2.0" ]
null
null
null
#include "NullPCH.h" #include "Buffers.h" #include "Platform/OpenGL/OpenGLBuffers.h" #include "Renderer/Components/RendererAPI.h" IVertexBuffer* IVertexBuffer::Create(float* InVertices, uint32 InSize) { switch (IRendererAPI::GetAPI()) { case IRendererAPI::Type_None: NE_CHECK_F(false, "None Renderer API is not implemented yet."); return nullptr; case IRendererAPI::Type_OpenGL: return new FOpenGLVertexBuffer(InVertices, InSize); } NE_CHECK_F(false, "Unknown Renderer API!!"); return nullptr; } IVertexBuffer* IVertexBuffer::Create(uint32 InSize) { switch (IRendererAPI::GetAPI()) { case IRendererAPI::Type_None: NE_CHECK_F(false, "None Renderer API is not implemented yet."); return nullptr; case IRendererAPI::Type_OpenGL: return new FOpenGLVertexBuffer(InSize); } NE_CHECK_F(false, "Unknown Renderer API!!"); return nullptr; } IIndexBuffer* IIndexBuffer::Create(uint32* InIndices, uint32 InCount) { switch (IRendererAPI::GetAPI()) { case IRendererAPI::Type_None: NE_CHECK_F(false, "None Renderer API is not implemented yet."); return nullptr; case IRendererAPI::Type_OpenGL: return new FOpenGLIndexBuffer(InIndices, InCount); } NE_CHECK_F(false, "Unknown Renderer API!!"); return nullptr; }
33.081081
111
0.764706
1992please
32ce8492fa335e90ecf599e30210a90e42ff8f14
877
cpp
C++
src/TestInput.cpp
dublet/KARR
4b14090b34dab4d8be4e28814cb4d58cd34639ac
[ "BSD-3-Clause" ]
null
null
null
src/TestInput.cpp
dublet/KARR
4b14090b34dab4d8be4e28814cb4d58cd34639ac
[ "BSD-3-Clause" ]
null
null
null
src/TestInput.cpp
dublet/KARR
4b14090b34dab4d8be4e28814cb4d58cd34639ac
[ "BSD-3-Clause" ]
null
null
null
#include "TestInput.h" #include <thread> #include <time.h> #include "Status.h" #include "CarDefinition.h" using namespace KARR; void generateTestData() { Status &s = Status::instance(); struct timespec sleepTime; sleepTime.tv_sec = 0; sleepTime.tv_nsec = 20 * 1000 * 1000; int rpmDirection = 1; int speedDirection = 1; for (;;) { if (s.getRpm() >= StaticCarDefinition::revs.max) rpmDirection = -1; if (s.getRpm() == StaticCarDefinition::revs.min) rpmDirection = 1; if (s.getSpeed() >= StaticCarDefinition::speed.max) speedDirection = -1; if (s.getSpeed() == StaticCarDefinition::speed.min) speedDirection = 1; s.setRpm(s.getRpm() + rpmDirection); s.setSpeed(s.getSpeed() + speedDirection); nanosleep(&sleepTime, NULL); } } void TestInput::run() { std::thread tt(generateTestData); tt.detach(); }
19.488889
52
0.651083
dublet
32d3084d7c75d5a488629f74a8375ccfd553d2e6
940
cpp
C++
AtCoder/Archives/BeginnerContest76/C.cpp
lxdlam/ACM
cde519ef9732ff9e4e9e3f53c00fb30d07bdb306
[ "MIT" ]
1
2017-10-25T13:33:27.000Z
2017-10-25T13:33:27.000Z
AtCoder/Archives/BeginnerContest76/C.cpp
lxdlam/ACM
cde519ef9732ff9e4e9e3f53c00fb30d07bdb306
[ "MIT" ]
null
null
null
AtCoder/Archives/BeginnerContest76/C.cpp
lxdlam/ACM
cde519ef9732ff9e4e9e3f53c00fb30d07bdb306
[ "MIT" ]
1
2021-05-05T01:16:28.000Z
2021-05-05T01:16:28.000Z
#include <bits/stdc++.h> using namespace std; vector<int> match(const string& t, const string& p) { vector<int> res; bool find; for (int i = 0; i < t.size(); i++) { find = false; if (t[i] == '?' || t[i] == p[0]) { for (int j = 1; j < p.size(); j++) { if (t[i + j] != '?' && t[i + j] != p[j]) { find = true; break; } } if (!find) res.push_back(i); } } return res; } int main() { ios::sync_with_stdio(false); cin.tie(0); string t, p, temp, res; cin >> t >> p; vector<int> poss = match(t, p); if (poss.size() != 0) { res = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"; for (auto pos : poss) { temp = t; for (int i = 0; i < p.size(); i++) temp[pos + i] = p[i]; for (auto& i : temp) if (i == '?') i = 'a'; res = min(res, temp); } } else res = "UNRESTORABLE"; cout << res << endl; return 0; }
21.860465
63
0.469149
lxdlam
77f78d34dea4f79dffd4b2dbf25953ac52db750d
7,085
cpp
C++
Source/ModuleTrails.cpp
JellyBitStudios/JellyBitEngine
4b975a50bb1934dfdbdf72e0c96c53a713e6cfa4
[ "MIT" ]
10
2019-02-05T07:57:21.000Z
2021-10-17T13:44:31.000Z
Source/ModuleTrails.cpp
JellyBitStudios/JellyBitEngine
4b975a50bb1934dfdbdf72e0c96c53a713e6cfa4
[ "MIT" ]
178
2019-02-26T17:29:08.000Z
2019-06-05T10:55:42.000Z
Source/ModuleTrails.cpp
JellyBitStudios/JellyBitEngine
4b975a50bb1934dfdbdf72e0c96c53a713e6cfa4
[ "MIT" ]
2
2020-02-27T18:57:27.000Z
2020-05-28T01:19:59.000Z
#include "ModuleTrails.h" #include "ModuleTimeManager.h" #include "ModuleInput.h" #include "ModuleResourceManager.h" #include "ModuleRenderer3D.h" #include "ModuleInternalResHandler.h" #include "ResourceMaterial.h" #include "ResourceShaderObject.h" #include "ResourceShaderProgram.h" #include "ResourceMesh.h" #include "Optick/include/optick.h" #include <algorithm> #include "MathGeoLib/include/Math/float4x4.h" #include "Application.h" #include "DebugDrawer.h" #include "ComponentTransform.h" #include "GLCache.h" #include "glew/include/GL/glew.h" ModuleTrails::ModuleTrails(bool start_enabled) : Module(start_enabled) {} ModuleTrails::~ModuleTrails() { trails.clear(); } update_status ModuleTrails::PostUpdate() { #ifndef GAMEMODE OPTICK_CATEGORY("ModuleTrails_PostUpdate", Optick::Category::VFX); #endif // !GAMEMODE for (std::list<ComponentTrail*>::iterator trail = trails.begin(); trail != trails.end(); ++trail) { (*trail)->Update(); } return UPDATE_CONTINUE; } void ModuleTrails::Draw() { #ifndef GAMEMODE OPTICK_CATEGORY("ModuleTrails_Draw", Optick::Category::VFX); #endif // !GAMEMODE for (std::list<ComponentTrail*>::iterator trail = trails.begin(); trail != trails.end(); ++trail) { if (!(*trail)->trailVertex.empty()) { if ((*trail)->materialRes == 0) continue; std::list<TrailNode*>::iterator begin = (*trail)->trailVertex.begin(); TrailNode* end = (*trail)->trailVertex.back(); float i = 0.0f; float size = (*trail)->trailVertex.size() + 1; for (std::list<TrailNode*>::iterator curr = (*trail)->trailVertex.begin(); curr != (*trail)->trailVertex.end(); ++curr) { i++; std::list<TrailNode*>::iterator next = curr; ++next; if (next != (*trail)->trailVertex.end()) { ResourceMaterial* resourceMaterial = (ResourceMaterial*)App->res->GetResource((*trail)->materialRes); uint shaderUuid = resourceMaterial->GetShaderUuid(); ResourceShaderProgram* resourceShaderProgram = (ResourceShaderProgram*)App->res->GetResource(shaderUuid); GLuint shaderProgram = resourceShaderProgram->shaderProgram; App->glCache->SwitchShader(shaderProgram); math::float4x4 model_matrix = math::float4x4::identity;// particle matrix model_matrix = model_matrix.Transposed(); math::float4x4 mvp_matrix = model_matrix * App->renderer3D->viewProj_matrix; math::float4x4 normal_matrix = model_matrix; normal_matrix.Inverse(); normal_matrix.Transpose(); uint location = glGetUniformLocation(shaderProgram, "model_matrix"); glUniformMatrix4fv(location, 1, GL_FALSE, model_matrix.ptr()); location = glGetUniformLocation(shaderProgram, "mvp_matrix"); glUniformMatrix4fv(location, 1, GL_FALSE, mvp_matrix.ptr()); location = glGetUniformLocation(shaderProgram, "normal_matrix"); glUniformMatrix3fv(location, 1, GL_FALSE, normal_matrix.Float3x3Part().ptr()); float currUV = (float(i) / size); float nextUV = (float(i + 1) / size); math::float3 originHigh = (*curr)->originHigh; math::float3 originLow = (*curr)->originLow; math::float3 destinationHigh = (*next)->originHigh; math::float3 destinationLow = (*next)->originLow; if ((*trail)->orient) RearrangeVertex(trail, curr, next, currUV, nextUV, originHigh, originLow, destinationHigh, destinationLow); location = glGetUniformLocation(shaderProgram, "currUV"); // cUV glUniform1f(location, currUV); location = glGetUniformLocation(shaderProgram, "nextUV"); // cUV glUniform1f(location, nextUV); location = glGetUniformLocation(shaderProgram, "realColor"); // Color glUniform4f(location, (*trail)->color.x, (*trail)->color.y, (*trail)->color.z, (*trail)->color.w); location = glGetUniformLocation(shaderProgram, "vertex1"); // Current High glUniform3f(location, originHigh.x, originHigh.y, originHigh.z); location = glGetUniformLocation(shaderProgram, "vertex2"); // Current Low glUniform3f(location, originLow.x, originLow.y, originLow.z); location = glGetUniformLocation(shaderProgram, "vertex3"); // Next High glUniform3f(location, destinationHigh.x, destinationHigh.y, destinationHigh.z); location = glGetUniformLocation(shaderProgram, "vertex4"); // Next Low glUniform3f(location, destinationLow.x, destinationLow.y, destinationLow.z); // Unknown uniforms uint textureUnit = 0; std::vector<Uniform> uniforms = resourceMaterial->GetUniforms(); for (uint i = 0; i < uniforms.size(); ++i) { Uniform uniform = uniforms[i]; if (strcmp(uniform.common.name, "material.albedo") == 0 || strcmp(uniform.common.name, "material.specular") == 0) { if (textureUnit < App->renderer3D->GetMaxTextureUnits()) { glActiveTexture(GL_TEXTURE0 + textureUnit); glBindTexture(GL_TEXTURE_2D, uniform.sampler2DU.value.id); glUniform1i(uniform.common.location, textureUnit); ++textureUnit; } } } ResourceMesh* plane = (ResourceMesh*)App->res->GetResource(App->resHandler->plane); glBindVertexArray(plane->GetVAO()); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, plane->GetIBO()); glDrawElements(GL_TRIANGLES, plane->GetIndicesCount(), GL_UNSIGNED_INT, NULL); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, 0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } } // TODO: THIS IS USELESS I THINK glEnd(); glPopMatrix(); } } } void ModuleTrails::RearrangeVertex(std::list<ComponentTrail *>::iterator &trail, std::list<TrailNode *>::iterator &curr, std::list<TrailNode *>::iterator &next, float &currUV, float &nextUV, math::float3 &originHigh, math::float3 &originLow, math::float3 &destinationHigh, math::float3 &destinationLow) { // Rearrange vertex float origin = 0; float dest = 0; GetOriginAndDest(trail, origin, curr, dest, next); if (origin < dest) { float tmp = currUV; currUV = nextUV; nextUV = tmp; math::float3 tmph = originHigh; math::float3 tmpl = originLow; originHigh = destinationHigh; originLow = destinationLow; destinationHigh = tmph; destinationLow = tmpl; } } void ModuleTrails::GetOriginAndDest(std::list<ComponentTrail *>::iterator &trail, float &origin, std::list<TrailNode *>::iterator &curr, float &dest, std::list<TrailNode *>::iterator &next) { switch ((*trail)->vector) { case X: origin = (*curr)->originHigh.x; dest = (*next)->originHigh.x; break; case Y: // This is not right origin = (*curr)->originHigh.x; dest = (*next)->originHigh.x; break; case Z: dest = (*curr)->originHigh.z; origin = (*next)->originHigh.z; break; default: break; } } void ModuleTrails::DebugDraw() const { // Todo } void ModuleTrails::OnSystemEvent(System_Event event) { switch (event.type) { case System_Event_Type::Play: case System_Event_Type::LoadFinished: // Todo break; case System_Event_Type::Stop: // Todo break; } } void ModuleTrails::RemoveTrail(ComponentTrail* trail) { trails.remove(trail); }
29.894515
302
0.692449
JellyBitStudios
77f9ee909641a70f1d118cd6b3981bf2d3afbb95
821
cpp
C++
src/main.cpp
Maou-Shimazu/Operation-Cpp
17398c92b7e64bcabe0d597efc8b01cd724e692b
[ "MIT" ]
null
null
null
src/main.cpp
Maou-Shimazu/Operation-Cpp
17398c92b7e64bcabe0d597efc8b01cd724e692b
[ "MIT" ]
null
null
null
src/main.cpp
Maou-Shimazu/Operation-Cpp
17398c92b7e64bcabe0d597efc8b01cd724e692b
[ "MIT" ]
null
null
null
#include <fstream> #include <iostream> #include <src/format.cc> #include <fmt/core.h> #include <parse_args.h> #include "../include/prompts.hpp" #include "loopTerminal.cpp" #include "../include/argCheck.hpp" using namespace arguments; // todo: impliment directory check for program run in directory void welcomeInfo(){} int main(int argc, char *argv[]) { ParseArgs parse = ParseArgs(argc, argv); if (parse.ParseSelf()){ std::cout << prompt::welcome << std::endl; prompt::loopInformation(); } TerminalHandler terminal; if (parse.DefaultParse("watch")) { std::cout << "Welcome to watch mode! You can type 'help' to get an overview of the commands you can use here." << std::endl; terminal.WatchMode(); } if (parse.DefaultParse("help")) { fmt::print(prompt::help); } return 0; }
24.147059
128
0.677223
Maou-Shimazu
77fa96da8b3c3fbb42952b263753b552ef75eb66
6,837
cpp
C++
src/boost_lagrange.cpp
mugwort-rc/boost_python_lagrange
ae7cc35b1f650e63de91fd7c25996dc6abc550c4
[ "BSD-3-Clause" ]
null
null
null
src/boost_lagrange.cpp
mugwort-rc/boost_python_lagrange
ae7cc35b1f650e63de91fd7c25996dc6abc550c4
[ "BSD-3-Clause" ]
null
null
null
src/boost_lagrange.cpp
mugwort-rc/boost_python_lagrange
ae7cc35b1f650e63de91fd7c25996dc6abc550c4
[ "BSD-3-Clause" ]
null
null
null
// g++ -std=c++11 -I`python -c 'from distutils.sysconfig import *; print(get_python_inc())'` -DPIC -shared -fPIC -o _lagrange.so boost_lagrange.cpp -lboost_python-py35 #include <memory> #include <boost/python.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> #include "lagrange.hpp" template <typename T_> class boost_multiprecision_to_float { public: typedef T_ native_type; static PyObject* convert(const native_type &value) { return boost::python::incref(boost::python::object(static_cast<long double>(value)).ptr()); } }; template <typename T_> class float_converter { public: typedef T_ native_type; static void * convertible(PyObject *pyo) { namespace py = boost::python; if ( ! py::extract<double>(py::object(py::handle<>(py::borrowed(pyo)))).check() ) { return nullptr; } return pyo; } static void construct(PyObject *pyo, boost::python::converter::rvalue_from_python_stage1_data *data) { namespace py = boost::python; double value = py::extract<double>(py::object(py::handle<>(py::borrowed(pyo)))); native_type *storage = new(reinterpret_cast<py::converter::rvalue_from_python_storage<native_type>*>(data)->storage.bytes) native_type(value); data->convertible = storage; } }; template <typename T_> class vector_to_pylist_converter { public: typedef T_ native_type; static PyObject * convert(const native_type &v) { boost::python::list retval; for (auto i : v) { retval.append(boost::python::object(i)); } return boost::python::incref(retval.ptr()); } }; template <typename T_> class pylist_to_vector_converter { public: typedef T_ native_type; static void * convertible(PyObject *pyo) { if ( ! PySequence_Check(pyo) ) { return nullptr; } return pyo; } static void construct(PyObject *pyo, boost::python::converter::rvalue_from_python_stage1_data *data) { namespace py = boost::python; native_type *storage = new(reinterpret_cast<py::converter::rvalue_from_python_storage<native_type>*>(data)->storage.bytes) native_type(); for (py::ssize_t i = 0, l = PySequence_Size(pyo); i < l; ++i) { storage->push_back( py::extract<typename boost::range_value<native_type>::type>( PySequence_GetItem(pyo, i))); } data->convertible = storage; } }; template <typename T> std::string vector_repr(const std::vector<T> &self) { boost::python::list pylist; for (auto item : self) { pylist.append(boost::python::object(item)); } return boost::python::extract<std::string>(boost::python::str(pylist)); } template <typename T> inline void lagrange_input_assertion(const std::vector<T> &x, const std::vector<T> &w) { if ( x.size() != w.size() ) { PyErr_SetString(PyExc_AssertionError, "array must be same langth."); boost::python::throw_error_already_set(); } } template <typename T> std::shared_ptr<Lagrange<T>> make_Lagrange(const std::vector<T> &x, const std::vector<T> &w) { lagrange_input_assertion<T>(x, w); return std::make_shared<Lagrange<T>>(x, w); } template<typename T> boost::python::list tolist(const Lagrange<T> &l) { boost::python::list r; for (const auto & c : l.coefficients ) { r.append(static_cast<long double>(c)); } return r; } template <typename T> void init_Lagrange(const std::string &name) { boost::python::class_<Lagrange<T>, std::shared_ptr<Lagrange<T>>>(("Lagrange_" + name).c_str(), boost::python::no_init) .def("__init__", boost::python::make_constructor(&make_Lagrange<T>)) .def("__call__", &Lagrange<T>::operator()) .def_readonly("c", &Lagrange<T>::coefficients) .def("coefficients", &tolist<T>) ; // T to python::float converter boost::python::to_python_converter<T, boost_multiprecision_to_float<T>>(); // python::float to T converter boost::python::converter::registry::push_back( &float_converter<T>::convertible, &float_converter<T>::construct, boost::python::type_id<T>()) ; // std::vector<T> to python::list converter //boost::python::to_python_converter<std::vector<T>, vector_to_pylist_converter<std::vector<T>>>(); boost::python::class_<std::vector<T>>((name + "_vector").c_str()) .def(boost::python::vector_indexing_suite<std::vector<T>>()) .def("__repr__", &vector_repr<T>) ; // python::list to std::vector<T> converter boost::python::converter::registry::push_back( &pylist_to_vector_converter<std::vector<T>>::convertible, &pylist_to_vector_converter<std::vector<T>>::construct, boost::python::type_id<std::vector<T>>()) ; } //////////////////////////////////////////////////////////////////////////////// template <typename T> std::shared_ptr<DeltaLagrange<T>> make_DeltaLagrange(const std::vector<T> &x, const std::vector<T> &w) { lagrange_input_assertion<T>(x, w); return std::make_shared<DeltaLagrange<T>>(x, w); } template<typename T> boost::python::tuple totuple(const DeltaLagrange<T> &l) { boost::python::list r; for (const auto & c : l.coefficients ) { r.append(static_cast<long double>(c)); } return boost::python::make_tuple( r, static_cast<long double>(l.x0), static_cast<long double>(l.w0) ); } template <typename T> void init_DeltaLagrange(const std::string &name) { boost::python::class_<DeltaLagrange<T>, std::shared_ptr<DeltaLagrange<T>>>(("DeltaLagrange_" + name).c_str(), boost::python::no_init) .def("__init__", boost::python::make_constructor(&make_DeltaLagrange<T>)) .def("__call__", &DeltaLagrange<T>::operator()) .def_readonly("c", &DeltaLagrange<T>::coefficients) .def("coefficients", &totuple<T>) ; } double py_fast(double x, const std::vector<double> &xs, const std::vector<double> &ws) { lagrange_input_assertion<double>(xs, ws); return Lagrange<double>::fast(x, xs, ws); } BOOST_PYTHON_MODULE(_lagrange) { init_Lagrange<boost::multiprecision::cpp_dec_float_50>("float_50"); init_Lagrange<boost::multiprecision::cpp_dec_float_100>("float_100"); init_DeltaLagrange<boost::multiprecision::cpp_dec_float_50>("float_50"); init_DeltaLagrange<boost::multiprecision::cpp_dec_float_100>("float_100"); boost::python::def("fast", &py_fast); // python::list to std::vector<T> converter boost::python::converter::registry::push_back( &pylist_to_vector_converter<std::vector<double>>::convertible, &pylist_to_vector_converter<std::vector<double>>::construct, boost::python::type_id<std::vector<double>>()); }
33.18932
167
0.650578
mugwort-rc
77faa89d81a4b36dab95fe24f37377da962077a4
297
cpp
C++
Porblems/bear_and_big_brother.cpp
ashish-ad/CPP-STL-Practice-and-Cp
ca8a112096ad96ed1abccddc9e99b1ead5cf522b
[ "Unlicense" ]
null
null
null
Porblems/bear_and_big_brother.cpp
ashish-ad/CPP-STL-Practice-and-Cp
ca8a112096ad96ed1abccddc9e99b1ead5cf522b
[ "Unlicense" ]
null
null
null
Porblems/bear_and_big_brother.cpp
ashish-ad/CPP-STL-Practice-and-Cp
ca8a112096ad96ed1abccddc9e99b1ead5cf522b
[ "Unlicense" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main(){ int limak,bob; cin>>limak>>bob; int i=1; while(1){ limak=limak*3; bob=bob*2; if (limak>bob){ cout<<i<<endl; break; } else{ i++; } } }
14.85
26
0.40404
ashish-ad
77fb5c852b5894084a60aee11390464d3b90c236
2,921
hxx
C++
private/shell/ext/mydocs2/precomp.hxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
11
2017-09-02T11:27:08.000Z
2022-01-02T15:25:24.000Z
private/shell/ext/mydocs2/precomp.hxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
null
null
null
private/shell/ext/mydocs2/precomp.hxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
14
2019-01-16T01:01:23.000Z
2022-02-20T15:54:27.000Z
#ifndef _pch_h #define _pch_h #include <windows.h> #include <windowsx.h> #include <shlobj.h> #include <shlwapi.h> #include <ccstock.h> #include <shsemip.h> #include <shlwapip.h> #include <shlapip.h> #include <shlobjp.h> // for shellp.h #include <shellp.h> // SHFOLDERCUSTOMSETTINGS #include <cfdefs.h> // CClassFactory, LPOBJECTINFO #include <comctrlp.h> extern const CLSID CLSID_MyDocsDropTarget; STDAPI_(void) DllAddRef(void); STDAPI_(void) DllRelease(void); #ifdef DBG #define DEBUG 1 #endif // // Avoid bringing in C runtime code for NO reason // #if defined(__cplusplus) inline void * __cdecl operator new(size_t size) { return (void *)LocalAlloc(LPTR, size); } inline void __cdecl operator delete(void *ptr) { LocalFree(ptr); } extern "C" inline __cdecl _purecall(void) { return 0; } #endif // __cplusplus #if defined(DBG) || defined(DEBUG) #ifndef DEBUG #define DEBUG #endif #else #undef DEBUG #endif #ifdef DEBUG #define MDTraceSetMask(dwMask) MDDoTraceSetMask(dwMask) #define MDTraceEnter(dwMask, fn) MDDoTraceEnter(dwMask, TEXT(fn)) #define MDTraceLeave MDDoTraceLeave #define MDTrace MDDoTrace #define MDTraceMsg(s) MDDoTrace(TEXT(s)) void MDDoTraceSetMask(DWORD dwMask); void MDDoTraceEnter(DWORD dwMask, LPCTSTR pName); void MDDoTraceLeave(void); void MDDoTrace(LPCTSTR pFormat, ...); void MDDoTraceAssert(int iLine, LPTSTR pFilename); #define MDTraceLeaveResult(hr) \ { HRESULT __hr = hr; if (FAILED(__hr)) MDTrace(TEXT("Failed (%08x)"), hr); MDTraceLeave(); return __hr; } #else #define MDTraceSetMask(dwMask) #define MDTraceEnter(dwMask, fn) #define MDTraceLeave() #define MDTrace if (FALSE) #define MDTraceMsg(s) #define MDTraceLeaveResult(hr) { return hr; } #endif #define TRACE_COMMON_ASSERT 0x40000000 #define ExitGracefully(hr, result, text) \ { MDTraceMsg(text); hr = result; goto exit_gracefully; } #define FailGracefully(hr, text) \ { if ( FAILED(hr) ) { MDTraceMsg(text); goto exit_gracefully; } } // Magic debug flags #define TRACE_CORE 0x00000001 #define TRACE_FOLDER 0x00000002 #define TRACE_ENUM 0x00000004 #define TRACE_ICON 0x00000008 #define TRACE_DATAOBJ 0x00000010 #define TRACE_IDLIST 0x00000020 #define TRACE_CALLBACKS 0x00000040 #define TRACE_COMPAREIDS 0x00000080 #define TRACE_DETAILS 0x00000100 #define TRACE_QI 0x00000200 #define TRACE_EXT 0x00000400 #define TRACE_UTIL 0x00000800 #define TRACE_SETUP 0x00001000 #define TRACE_PROPS 0x00002000 #define TRACE_COPYHOOK 0x00004000 #define TRACE_FACTORY 0x00008000 #define TRACE_ALWAYS 0xffffffff // use with caution #endif
26.080357
122
0.670318
King0987654
77feeab069b3c47765e14808dc6d98b57875f0db
4,277
cpp
C++
AtCoder/typical90/029 - Long Bricks/main.cpp
t-mochizuki/cpp-study
df0409c2e82d154332cb2424c7810370aa9822f9
[ "MIT" ]
1
2020-05-24T02:27:05.000Z
2020-05-24T02:27:05.000Z
AtCoder/typical90/029 - Long Bricks/main.cpp
t-mochizuki/cpp-study
df0409c2e82d154332cb2424c7810370aa9822f9
[ "MIT" ]
null
null
null
AtCoder/typical90/029 - Long Bricks/main.cpp
t-mochizuki/cpp-study
df0409c2e82d154332cb2424c7810370aa9822f9
[ "MIT" ]
null
null
null
// g++ -std=c++14 -DDEV=1 main.cpp #include <stdio.h> #include <cassert> #include <iostream> #include <fstream> #include <vector> #include <algorithm> #include <map> using std::cin; using std::cout; using std::endl; using std::terminate; using std::vector; using std::max; using std::sort; using std::map; using std::make_pair; // キーワード: 「座標圧縮」で効率化 // // キーワード: 区間に対する処理は「セグメント木」 #define rep(i, a, n) for (int i = (a); i < (n); ++i) #define bit(n, k) ((n >> k) & 1) const long VALUE = 0; class RangeUpdateQuery { private: int M = 1; int N; vector<long> value, lazy; int parent(int i) { return (i - 1) / 2; } int left(int i) { return 2 * i + 1; } int right(int i) { return 2 * i + 2; } void eval(int i) { if (lazy[i] == VALUE) return ; if (i < M - 1) { lazy[left(i)] = lazy[i]; lazy[right(i)] = lazy[i]; } value[i] = lazy[i]; lazy[i] = VALUE; } long find(int lhs, int rhs, int i, int L, int R) { assert(i < N); assert(i >= 0); eval(i); int ret = VALUE; if (rhs <= L || R <= lhs) { ret = VALUE; } else if (lhs <= L && R <= rhs) { ret = value[i]; } else { long lv = find(lhs, rhs, left(i), L, (L + R) / 2); long rv = find(lhs, rhs, right(i), (L + R) / 2, R); ret = max(lv, rv); } return ret; } void update(long x, int lhs, int rhs, int i, int L, int R) { assert(i < N); assert(i >= 0); eval(i); if (rhs <= L || R <= lhs) { } else if (lhs <= L && R <= rhs) { lazy[i] = x; eval(i); } else { update(x, lhs, rhs, left(i), L, (L + R) / 2); update(x, lhs, rhs, right(i), (L + R) / 2, R); value[i] = max(value[left(i)], value[right(i)]); } } public: RangeUpdateQuery(int len) { while (M < len) { M *= 2; } N = 2 * M - 1; value.assign(N, VALUE); lazy.assign(N, VALUE); } long find(int lhs, int rhs) { int root = 0; // 葉の数はM、区間は[0, M) return find(lhs, rhs, root, 0, M); } void update(long x, int lhs, int rhs) { int root = 0; // 葉の数はM、区間は[0, M) return update(x, lhs, rhs, root, 0, M); } }; class Problem { private: int W, N; vector<int> L, R; map<int, int> zip; public: Problem() { cin >> W >> N; assert(2 <= W); assert(W <= 500000); assert(1 <= N); assert(N <= 250000); L.resize(N); R.resize(N); rep(i, 0, N) { cin >> L[i] >> R[i]; assert(1 <= L[i]); assert(W >= L[i]); assert(1 <= R[i]); assert(W >= R[i]); assert(L[i] <= R[i]); } rep(i, 0, N) { if (zip.find(L[i]) == zip.end()) { zip.insert(make_pair(L[i], 1)); } if (zip.find(R[i]) == zip.end()) { zip.insert(make_pair(R[i], 1)); } } int num = 1; for (auto it = zip.begin(); it != zip.end(); ++it) { it->second = num; num++; } } void fullSearch() { vector<int> height; height.assign(W+1, 0); rep(i, 0, N) { int maximum = 0; rep(j, zip[L[i]], zip[R[i]]+1) { maximum = max(height[j], maximum); } maximum++; cout << maximum << endl; rep(j, zip[L[i]], zip[R[i]]+1) height[j] = maximum; } } void solve() { vector<int> height; height.assign(W+1, 0); RangeUpdateQuery tree(zip.size()+5); rep(i, 0, N) { long x = tree.find(zip[L[i]], zip[R[i]]+1); x++; cout << x << endl; tree.update(x, zip[L[i]], zip[R[i]]+1); } } }; int main() { #ifdef DEV std::ifstream in("input"); cin.rdbuf(in.rdbuf()); int t; cin >> t; for (int x = 1; x <= t; ++x) { Problem p; p.solve(); } #else Problem p; p.solve(); #endif return 0; }
19.619266
64
0.416647
t-mochizuki
77fef9ca7e9b463b12918ccca0581b7399ccd45d
1,077
hpp
C++
camera/DumpProfile.hpp
flexibity-team/boost-tools
a6c67eacf7374136f9903680308334fc3408ba91
[ "MIT" ]
null
null
null
camera/DumpProfile.hpp
flexibity-team/boost-tools
a6c67eacf7374136f9903680308334fc3408ba91
[ "MIT" ]
null
null
null
camera/DumpProfile.hpp
flexibity-team/boost-tools
a6c67eacf7374136f9903680308334fc3408ba91
[ "MIT" ]
2
2019-12-26T13:54:29.000Z
2020-10-31T10:19:13.000Z
#ifndef DUMBPROFILE_H_ #define DUMBPROFILE_H_ #include <sys/time.h> #include <stdint.h> #include <string.h> #define DPROFILE dumb_profile dprf = dumb_profile(__FUNCTION__, __LINE__); dprf.start(); struct dumb_profile{ struct timeval start_; struct timeval end_; const char* fname_; const uint32_t lnum_; dumb_profile(const char* fname, const uint32_t lnum): start_(), end_(), fname_(fname), lnum_(lnum){ //start(); } ~dumb_profile(){ stop(); } void start(){ gettimeofday(&start_, 0); } void stop(){ print(); memset(&start_, 0, sizeof(start_)); memset(&end_, 0, sizeof(end_)); } int64_t started(){ return timeval_to_ms(start_); } int64_t timeval_to_ms(struct timeval& tv){ return (tv.tv_sec * 1000000) + tv.tv_usec; } void print(){ gettimeofday(&end_, 0); //uint32_t now_ms = end_.; int32_t delta = ((end_.tv_sec - start_.tv_sec) * 1000000) + end_.tv_usec - start_.tv_usec; // printf("profile: %s:%d: now:%03li:04%li elapsed:%d us\n", fname_, lnum_, end_.tv_sec, end_.tv_usec / 1000 , delta); } }; #endif //DUMBPROFILE_H_
19.944444
119
0.679666
flexibity-team
ae023ba1b61d8f539911c840c19059f293e70936
980
cpp
C++
Codeforces/Solutions/1082B.cpp
Mohammed-Shoaib/HackerRank-Problems
ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b
[ "MIT" ]
54
2019-05-13T12:13:09.000Z
2022-02-27T02:59:00.000Z
Codeforces/Solutions/1082B.cpp
Mohammed-Shoaib/HackerRank-Problems
ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b
[ "MIT" ]
2
2020-10-02T07:16:43.000Z
2020-10-19T04:36:19.000Z
Codeforces/Solutions/1082B.cpp
Mohammed-Shoaib/HackerRank-Problems
ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b
[ "MIT" ]
20
2020-05-26T09:48:13.000Z
2022-03-18T15:18:27.000Z
// Problem Code: 1082B #include <iostream> #include <vector> #include <algorithm> using namespace std; int vovaAndTrophies(int n, string S) { int len, maxLen, g; vector<int> L(n), R(n); len = maxLen = 0; g = count(S.begin(), S.end(), 'G'); if (g == n) return g; if (S[0] == 'G') L[0] = 1; for (int i = 1 ; i < n ; i++) { if (S[i] == 'S') continue; L[i] = 1; L[i] += L[i - 1]; } if (S[n - 1] == 'G') R[n - 1] = 1; for (int i = n - 2 ; i >= 0 ; i--) { if (S[i] == 'S') continue; R[i] = 1; R[i] += R[i + 1]; } if (n == 1) maxLen = L[0]; else { if (S[0] == 'S') maxLen = max(maxLen, R[1]); if (S[n - 1] == 'S') { maxLen = max(maxLen, L[n - 2]); } } for (int i = 1 ; i < n - 1 ; i++) { if (S[i] == 'G') continue; len = L[i - 1] + R[i + 1]; if (len < g) len++; if (len > maxLen) maxLen = len; } return maxLen; } int main() { int n; string S; cin >> n >> S; cout << vovaAndTrophies(n, S); return 0; }
15.555556
38
0.45
Mohammed-Shoaib
ae033e4d44777869c7554d7e250a1ce42554f400
47,761
cpp
C++
source/D2Common/src/DataTbls/SequenceTbls.cpp
raumuongluoc/D2MOO
169de1bd24151cda4c654ef0f8027896a14552ec
[ "MIT" ]
1
2022-03-20T12:12:15.000Z
2022-03-20T12:12:15.000Z
source/D2Common/src/DataTbls/SequenceTbls.cpp
raumuongluoc/D2MOO
169de1bd24151cda4c654ef0f8027896a14552ec
[ "MIT" ]
null
null
null
source/D2Common/src/DataTbls/SequenceTbls.cpp
raumuongluoc/D2MOO
169de1bd24151cda4c654ef0f8027896a14552ec
[ "MIT" ]
1
2022-03-20T12:12:18.000Z
2022-03-20T12:12:18.000Z
#include <D2DataTbls.h> #include <DataTbls/SequenceTbls.h> #include <D2BitManip.h> #include <Units/Units.h> #include <D2Skills.h> #include <D2Composit.h> //D2Common.0x6FDDE6A8 D2MonSeqTxt gPlayerSequenceHandToHand1[13] = { { 0, PLRMODE_ATTACK1, 0, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 3, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 4, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 5, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 7, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 11, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE }, }; //D2Common.0x6FDDE6F8 D2MonSeqTxt gPlayerSequenceHandToHand2[14] = { { 0, PLRMODE_ATTACK1, 0, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 3, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 4, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 5, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 7, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 11, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE }, }; //D2Common.0x6FDDE750 D2MonSeqTxt gPlayerSequenceJab_BOW[18] = { { 0, PLRMODE_ATTACK1, 5, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_PLAY_SOUND }, { 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 11, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 6, 0, MONSEQ_EVENT_PLAY_SOUND }, { 0, PLRMODE_ATTACK2, 8, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 9, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 11, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 6, 0, MONSEQ_EVENT_PLAY_SOUND }, { 0, PLRMODE_ATTACK2, 8, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 9, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_ATTACK2, 10, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 13, 0, MONSEQ_EVENT_NONE }, }; //D2Common.0x6FDDE7C0 D2MonSeqTxt gPlayerSequenceJab_1HS[21] = { { 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 7, 0, MONSEQ_EVENT_PLAY_SOUND }, { 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 15, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 4, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 6, 0, MONSEQ_EVENT_PLAY_SOUND }, { 0, PLRMODE_ATTACK2, 9, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 10, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 15, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 4, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 6, 0, MONSEQ_EVENT_PLAY_SOUND }, { 0, PLRMODE_ATTACK2, 9, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 10, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_ATTACK2, 11, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 13, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 15, 0, MONSEQ_EVENT_NONE }, }; //D2Common.0x6FDDE840 D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceJab = { gPlayerSequenceHandToHand1, 13, 13, gPlayerSequenceJab_BOW, 18, 18, gPlayerSequenceJab_1HS, 21, 21, }; //D2Common.0x6FDDE8E8 D2MonSeqTxt gPlayerSequenceSacrifice_1HT[7] = { { 0, PLRMODE_ATTACK2, 0, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 2, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 4, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 7, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_ATTACK2, 8, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 10, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 13, 0, MONSEQ_EVENT_NONE }, }; //D2Common.0x6FDDE914 D2MonSeqTxt gPlayerSequenceSacrifice_STF[8] = { { 0, PLRMODE_ATTACK1, 0, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 4, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 15, 0, MONSEQ_EVENT_NONE }, }; //D2Common.0x6FDDE948 D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceSacrifice = { gPlayerSequenceHandToHand2, 14, 14, 0, 0, 0, 0, 0, 0, gPlayerSequenceSacrifice_1HT, 7, 7, gPlayerSequenceSacrifice_STF, 8, 8, }; //D2Common.0x6FDDE9F0 D2MonSeqTxt gPlayerSequenceChastise_1HT[16] = { { 0, PLRMODE_SPECIAL1, 3, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 4, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 5, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 6, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 7, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 8, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 10, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 1, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 2, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 4, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 6, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 7, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_ATTACK2, 8, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 10, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 11, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 13, 0, MONSEQ_EVENT_NONE }, }; //D2Common.0x6FDDEA50 D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceChastise = { gPlayerSequenceHandToHand2, 14, 14, 0, 0, 0, 0, 0, 0, gPlayerSequenceChastise_1HT, 16, 16, }; //D2Common.0x6FDDEAF8 D2MonSeqTxt gPlayerSequenceCharge[15] = { { 0, PLRMODE_RUN, 0, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_RUN, 1, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_RUN, 2, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_RUN, 3, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_RUN, 4, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_RUN, 5, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_RUN, 6, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_RUN, 7, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 4, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 5, 0, MONSEQ_EVENT_PLAY_SOUND }, { 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE }, }; //D2Common.0x6FDDEB58 D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceCharge = { gPlayerSequenceCharge, 15, 15, gPlayerSequenceCharge, 15, 15, gPlayerSequenceCharge, 15, 15, gPlayerSequenceCharge, 15, 15, gPlayerSequenceCharge, 15, 15, 0, 0, 0, 0, 0, 0, gPlayerSequenceCharge, 15, 15, }; //D2Common.0x6FDDEC00 D2MonSeqTxt gPlayerSequenceDefiance_1HT[6] = { { 0, PLRMODE_ATTACK2, 5, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 6, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 7, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_ATTACK2, 8, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 10, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 12, 0, MONSEQ_EVENT_NONE }, }; //D2Common.0x6FDDEC28 D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceDefiance = { gPlayerSequenceHandToHand2, 14, 14, 0, 0, 0, 0, 0, 0, gPlayerSequenceDefiance_1HT, 6, 6, }; //D2Common.0x6FDDECD0 D2MonSeqTxt gPlayerSequenceInferno[15] = { { 0, PLRMODE_CAST, 0, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 1, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 2, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 3, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 4, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 5, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 6, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 7, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 8, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_CAST, 10, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 11, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 12, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 13, 0, MONSEQ_EVENT_NONE }, }; //D2Common.0x6FDDED30 D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceInferno = { gPlayerSequenceInferno, 15, 15, gPlayerSequenceInferno, 15, 15, gPlayerSequenceInferno, 15, 15, gPlayerSequenceInferno, 15, 15, gPlayerSequenceInferno, 15, 15, gPlayerSequenceInferno, 15, 15, gPlayerSequenceInferno, 15, 15, gPlayerSequenceInferno, 15, 15, gPlayerSequenceInferno, 15, 15, gPlayerSequenceInferno, 15, 15, gPlayerSequenceInferno, 15, 15, gPlayerSequenceInferno, 15, 15, gPlayerSequenceInferno, 15, 15, gPlayerSequenceInferno, 15, 15, }; //D2Common.0x6FDDEDD8 D2MonSeqTxt gPlayerSequenceStrafe_2HS[13] = { { 0, PLRMODE_ATTACK1, 0, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 3, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 4, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_ATTACK1, 7, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 11, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE }, }; //D2Common.0x6FDDEE28 D2MonSeqTxt gPlayerSequenceStrafe_2HT[20] = { { 0, PLRMODE_ATTACK1, 0, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 3, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 4, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 5, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 7, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 11, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 14, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 15, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 16, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 17, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 18, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 19, 0, MONSEQ_EVENT_NONE }, }; //D2Common.0x6FDDEEA0 D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceStrafe = { gPlayerSequenceHandToHand1, 13, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, gPlayerSequenceStrafe_2HS, 13, 13, gPlayerSequenceStrafe_2HT, 20, 20, }; //D2Common.0x6FDDEF48 D2MonSeqTxt gPlayerSequenceImpale_BOW[21] = { { 0, PLRMODE_ATTACK1, 0, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 3, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 3, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 4, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 4, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 5, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 7, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 11, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 14, 0, MONSEQ_EVENT_NONE }, }; //D2Common.0x6FDDEFC8 D2MonSeqTxt gPlayerSequenceImpale_1HS[24] = { { 0, PLRMODE_ATTACK1, 0, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 3, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 3, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 4, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 4, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 5, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 7, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 11, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 14, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 15, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 16, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 17, 0, MONSEQ_EVENT_NONE }, }; //D2Common.0x6FDDF058 D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceImpale = { gPlayerSequenceHandToHand1, 13, 13, gPlayerSequenceImpale_BOW, 21, 21, gPlayerSequenceImpale_1HS, 24, 24, }; //D2Common.0x6FDDF100 D2MonSeqTxt gPlayerSequenceFend_BOW[16] = { { 0, PLRMODE_ATTACK1, 0, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 3, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 4, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 5, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 6, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 8, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 9, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 12, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 14, 0, MONSEQ_EVENT_NONE }, }; //D2Common.0x6FDDF160 D2MonSeqTxt gPlayerSequenceFend_1HS[16] = { { 0, PLRMODE_ATTACK1, 0, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 2, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 6, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 9, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 10, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 14, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 14, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 15, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 16, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 17, 0, MONSEQ_EVENT_NONE }, { 0, 0, 0, 0, MONSEQ_EVENT_NONE }, }; //D2Common.0x6FDDF1C0 D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceFend = { gPlayerSequenceHandToHand1, 13, 13, gPlayerSequenceFend_BOW, 16, 16, gPlayerSequenceFend_1HS, 16, 16, }; //D2Common.0x6FDDF268 D2MonSeqTxt gPlayerSequenceWhirlwind[8] = { { 0, PLRMODE_ATTACK1, 0, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 3, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_ATTACK1, 3, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 4, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 5, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_MELEE_ATTACK }, }; //D2Common.0x6FDDF298 D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceWhirlwind = { gPlayerSequenceWhirlwind, 8, 8, gPlayerSequenceWhirlwind, 8, 8, gPlayerSequenceWhirlwind, 8, 8, gPlayerSequenceWhirlwind, 8, 8, gPlayerSequenceWhirlwind, 8, 8, 0, 0, 0, 0, 0, 0, gPlayerSequenceWhirlwind, 8, 8, gPlayerSequenceWhirlwind, 8, 8, gPlayerSequenceWhirlwind, 8, 8, gPlayerSequenceWhirlwind, 8, 8, gPlayerSequenceWhirlwind, 8, 8, gPlayerSequenceWhirlwind, 8, 8, gPlayerSequenceWhirlwind, 8, 8, }; //D2Common.0x6FDDF340 D2MonSeqTxt gPlayerSequenceDoubleSwing[17] = { { 0, PLRMODE_ATTACK1, 1, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 2, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 4, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 7, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 11, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 14, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL3, 2, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_SPECIAL3, 4, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL3, 5, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL3, 6, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL3, 8, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL3, 9, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL3, 10, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL3, 11, 0, MONSEQ_EVENT_NONE }, }; //D2Common.0x6FDDF3A8 D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceDoubleSwing = { gPlayerSequenceDoubleSwing, 17, 17, gPlayerSequenceDoubleSwing, 17, 17, gPlayerSequenceDoubleSwing, 17, 17, gPlayerSequenceDoubleSwing, 17, 17, gPlayerSequenceDoubleSwing, 17, 17, gPlayerSequenceDoubleSwing, 17, 17, gPlayerSequenceDoubleSwing, 17, 17, gPlayerSequenceDoubleSwing, 17, 17, gPlayerSequenceDoubleSwing, 17, 17, gPlayerSequenceDoubleSwing, 17, 17, gPlayerSequenceDoubleSwing, 17, 17, gPlayerSequenceDoubleSwing, 17, 17, gPlayerSequenceDoubleSwing, 17, 17, gPlayerSequenceDoubleSwing, 17, 17, }; //D2Common.0x6FDDF450 D2MonSeqTxt gPlayerSequenceLightning[19] = { { 0, PLRMODE_CAST, 0, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 1, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 3, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 4, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 5, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 7, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 8, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 10, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 10, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 11, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 12, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 13, 0, MONSEQ_EVENT_NONE }, }; //D2Common.0x6FDDF4C8 D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceLightning = { gPlayerSequenceLightning, 19, 19, gPlayerSequenceLightning, 19, 19, gPlayerSequenceLightning, 19, 19, gPlayerSequenceLightning, 19, 19, gPlayerSequenceLightning, 19, 19, gPlayerSequenceLightning, 19, 19, gPlayerSequenceLightning, 19, 19, gPlayerSequenceLightning, 19, 19, gPlayerSequenceLightning, 19, 19, gPlayerSequenceLightning, 19, 19, gPlayerSequenceLightning, 19, 19, gPlayerSequenceLightning, 19, 19, gPlayerSequenceLightning, 19, 19, gPlayerSequenceLightning, 19, 19, }; //D2Common.0x6FDDF570 D2MonSeqTxt gPlayerSequenceLeap[15] = { { 0, PLRMODE_SPECIAL1, 0, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 1, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 2, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 3, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 4, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 5, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_SPECIAL1, 6, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 7, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 8, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 9, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 10, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 11, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_SPECIAL1, 12, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 13, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 14, 0, MONSEQ_EVENT_MELEE_ATTACK }, }; //D2Common.0x6FDDF5D0 D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceLeap = { gPlayerSequenceLeap, 15, 15, gPlayerSequenceLeap, 15, 15, gPlayerSequenceLeap, 15, 15, gPlayerSequenceLeap, 15, 15, gPlayerSequenceLeap, 15, 15, gPlayerSequenceLeap, 15, 15, gPlayerSequenceLeap, 15, 15, gPlayerSequenceLeap, 15, 15, gPlayerSequenceLeap, 15, 15, gPlayerSequenceLeap, 15, 15, gPlayerSequenceLeap, 15, 15, gPlayerSequenceLeap, 15, 15, gPlayerSequenceLeap, 15, 15, gPlayerSequenceLeap, 15, 15, }; //D2Common.0x6FDDF678 D2MonSeqTxt gPlayerSequenceLeapAttack_HTH[22] = { { 0, PLRMODE_SPECIAL1, 0, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 1, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 2, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 3, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 4, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 5, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_SPECIAL1, 6, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 7, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 8, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 9, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 10, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 11, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_SPECIAL1, 12, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 13, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 14, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 5, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_ATTACK1, 7, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 11, 0, MONSEQ_EVENT_NONE }, }; //D2Common.0x6FDDF700 D2MonSeqTxt gPlayerSequenceLeapAttack_BOW_1HT[25] = { { 0, PLRMODE_SPECIAL1, 0, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 1, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 2, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 3, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 4, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 5, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_SPECIAL1, 6, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 7, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 8, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 9, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 10, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 11, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_SPECIAL1, 12, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 13, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 14, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 7, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 11, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 14, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 15, 0, MONSEQ_EVENT_NONE }, }; //D2Common.0x6FDDF798 D2MonSeqTxt gPlayerSequenceLeapAttack_1HS_XBW[28] = { { 0, PLRMODE_SPECIAL1, 0, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 1, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 2, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 3, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 4, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 5, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_SPECIAL1, 6, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 7, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 8, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 9, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 10, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 11, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_SPECIAL1, 12, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 13, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 14, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 7, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 11, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 14, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 15, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 16, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 17, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 18, 0, MONSEQ_EVENT_NONE }, }; //D2Common.0x6FDDF840 D2MonSeqTxt gPlayerSequenceLeapAttack_STF[27] = { { 0, PLRMODE_SPECIAL1, 0, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 1, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 2, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 3, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 4, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 5, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_SPECIAL1, 6, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 7, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 8, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 9, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 10, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 11, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_SPECIAL1, 12, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 13, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 14, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 6, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 7, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 8, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_ATTACK1, 9, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 10, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 11, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 12, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 13, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 14, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 15, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 16, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK1, 17, 0, MONSEQ_EVENT_NONE }, }; //D2Common.0x6FDDF8E8 D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceLeapAttack = { gPlayerSequenceLeapAttack_HTH, 22, 22, gPlayerSequenceLeapAttack_BOW_1HT, 25, 25, gPlayerSequenceLeapAttack_1HS_XBW, 28, 28, gPlayerSequenceLeapAttack_BOW_1HT, 25, 25, gPlayerSequenceLeapAttack_STF, 27, 27, 0, 0, 0, 0, 0, 0, gPlayerSequenceLeapAttack_1HS_XBW, 28, 28, gPlayerSequenceLeapAttack_HTH, 22, 22, gPlayerSequenceLeapAttack_HTH, 22, 22, gPlayerSequenceLeapAttack_HTH, 22, 22, gPlayerSequenceLeapAttack_HTH, 22, 22, gPlayerSequenceLeapAttack_HTH, 22, 22, gPlayerSequenceLeapAttack_HTH, 22, 22, }; //D2Common.0x6FDDF990 D2MonSeqTxt gPlayerSequenceDoubleThrow[12] = { { 0, PLRMODE_THROW, 2, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_THROW, 3, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_THROW, 4, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_THROW, 6, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_THROW, 7, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_THROW, 8, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_SPECIAL3, 2, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL3, 4, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL3, 5, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL3, 7, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_SPECIAL3, 8, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL3, 10, 0, MONSEQ_EVENT_NONE }, }; //D2Common.0x6FDDF9D8 D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceDoubleThrow = { gPlayerSequenceDoubleThrow, 12, 12, gPlayerSequenceDoubleThrow, 12, 12, gPlayerSequenceDoubleThrow, 12, 12, gPlayerSequenceDoubleThrow, 12, 12, gPlayerSequenceDoubleThrow, 12, 12, gPlayerSequenceDoubleThrow, 12, 12, gPlayerSequenceDoubleThrow, 12, 12, gPlayerSequenceDoubleThrow, 12, 12, gPlayerSequenceDoubleThrow, 12, 12, gPlayerSequenceDoubleThrow, 12, 12, gPlayerSequenceDoubleThrow, 12, 12, gPlayerSequenceDoubleThrow, 12, 12, gPlayerSequenceDoubleThrow, 12, 12, gPlayerSequenceDoubleThrow, 12, 12, }; //D2Common.0x6FDDFA80 D2MonSeqTxt gPlayerSequenceDragonClaw_HTH_HT1[12] = { { 0, PLRMODE_ATTACK2, 0, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 1, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 2, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 3, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 4, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 5, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 6, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_ATTACK2, 7, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 8, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 9, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 10, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 11, 0, MONSEQ_EVENT_NONE }, }; //D2Common.0x6FDDFAC8 D2MonSeqTxt gPlayerSequenceDragonClaw_HT2[16] = { { 0, PLRMODE_ATTACK2, 0, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 1, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 2, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 3, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 4, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 5, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_ATTACK2, 6, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_SPECIAL4, 3, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL4, 4, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL4, 5, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL4, 6, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_SPECIAL4, 7, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL4, 8, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL4, 9, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL4, 10, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL4, 11, 0, MONSEQ_EVENT_NONE }, }; //D2Common.0x6FDDFB28 D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceDragonClaw = { gPlayerSequenceDragonClaw_HTH_HT1, 12, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, gPlayerSequenceDragonClaw_HTH_HT1, 12, 12, gPlayerSequenceDragonClaw_HT2, 16, 16, }; //D2Common.0x6FDDFBD0 D2MonSeqTxt gPlayerSequenceProjection[19] = { { 0, PLRMODE_CAST, 0, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 1, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 2, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 3, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 4, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 5, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 6, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 7, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_CAST, 8, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 10, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 11, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_CAST, 13, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 14, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 15, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 16, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 17, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 18, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, 0, 0, 0, MONSEQ_EVENT_NONE }, }; //D2Common.0x6FDDFC48 D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceProjection = { gPlayerSequenceProjection, 19, 19, gPlayerSequenceProjection, 19, 19, gPlayerSequenceProjection, 19, 19, gPlayerSequenceProjection, 19, 19, gPlayerSequenceProjection, 19, 19, gPlayerSequenceProjection, 19, 19, gPlayerSequenceProjection, 19, 19, gPlayerSequenceProjection, 19, 19, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, gPlayerSequenceProjection, 19, 19, gPlayerSequenceProjection, 19, 19, }; //D2Common.0x6FDDFCF0 D2MonSeqTxt gPlayerSequenceDragonTalon[20] = { { 0, PLRMODE_KICK, 0, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_KICK, 1, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_KICK, 2, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_KICK, 3, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_KICK, 4, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_KICK, 5, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_KICK, 2, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_KICK, 3, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_KICK, 4, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_KICK, 5, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_KICK, 2, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_KICK, 3, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_KICK, 4, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_KICK, 5, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_KICK, 6, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_KICK, 7, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_KICK, 8, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_KICK, 9, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_KICK, 10, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_KICK, 11, 0, MONSEQ_EVENT_NONE }, }; //D2Common.0x6FDDFD68 D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceDragonTalon = { gPlayerSequenceDragonTalon, 20, 20, gPlayerSequenceDragonTalon, 20, 20, gPlayerSequenceDragonTalon, 20, 20, gPlayerSequenceDragonTalon, 20, 20, gPlayerSequenceDragonTalon, 20, 20, gPlayerSequenceDragonTalon, 20, 20, gPlayerSequenceDragonTalon, 20, 20, gPlayerSequenceDragonTalon, 20, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, gPlayerSequenceDragonTalon, 20, 20, gPlayerSequenceDragonTalon, 20, 20, }; //D2Common.0x6FDDFE10 D2MonSeqTxt gPlayerSequenceArcticBlast[15] = { { 0, PLRMODE_SPECIAL1, 0, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 1, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 2, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 3, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 4, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 5, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 6, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 7, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 8, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 9, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 9, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_SPECIAL1, 10, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 11, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 12, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 13, 0, MONSEQ_EVENT_NONE }, }; //D2Common.0x6FDDFE70 D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceArcticBlast = { gPlayerSequenceArcticBlast, 15, 15, gPlayerSequenceArcticBlast, 15, 15, gPlayerSequenceArcticBlast, 15, 15, gPlayerSequenceArcticBlast, 15, 15, gPlayerSequenceArcticBlast, 15, 15, gPlayerSequenceArcticBlast, 15, 15, gPlayerSequenceArcticBlast, 15, 15, gPlayerSequenceArcticBlast, 15, 15, gPlayerSequenceArcticBlast, 15, 15, gPlayerSequenceArcticBlast, 15, 15, gPlayerSequenceArcticBlast, 15, 15, gPlayerSequenceArcticBlast, 15, 15, gPlayerSequenceArcticBlast, 15, 15, gPlayerSequenceArcticBlast, 15, 15, }; //D2Common.0x6FDDFF18 D2MonSeqTxt gPlayerSequenceDragonBreath[17] = { { 0, PLRMODE_SPECIAL1, 0, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 1, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 2, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 3, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 4, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 5, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 6, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 7, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 8, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_SPECIAL1, 9, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 10, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_SPECIAL1, 11, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 12, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_SPECIAL1, 12, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 13, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_SPECIAL1, 13, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 14, 0, MONSEQ_EVENT_NONE }, }; //D2Common.0x6FDDFF80 D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceDragonBreath = { gPlayerSequenceDragonBreath, 17, 17, gPlayerSequenceDragonBreath, 17, 17, gPlayerSequenceDragonBreath, 17, 17, gPlayerSequenceDragonBreath, 17, 17, gPlayerSequenceDragonBreath, 17, 17, gPlayerSequenceDragonBreath, 17, 17, gPlayerSequenceDragonBreath, 17, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, gPlayerSequenceDragonBreath, 17, 17, gPlayerSequenceDragonBreath, 17, 17, }; //D2Common.0x6FDE0028 D2MonSeqTxt gPlayerSequenceDragonFlight[23] = { { 0, PLRMODE_CAST, 0, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 1, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 2, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 3, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 4, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 5, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 6, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 7, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 8, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_KICK, 0, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_KICK, 1, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_KICK, 2, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_KICK, 3, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_KICK, 4, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_KICK, 5, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_KICK, 6, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_KICK, 7, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_KICK, 8, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_KICK, 9, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_KICK, 10, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_KICK, 11, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_KICK, 12, 0, MONSEQ_EVENT_NONE }, }; //D2Common.0x6FDE00B8 D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceDragonFlight = { gPlayerSequenceDragonFlight, 23, 23, gPlayerSequenceDragonFlight, 23, 23, gPlayerSequenceDragonFlight, 23, 23, gPlayerSequenceDragonFlight, 23, 23, gPlayerSequenceDragonFlight, 23, 23, gPlayerSequenceDragonFlight, 23, 23, gPlayerSequenceDragonFlight, 23, 23, gPlayerSequenceDragonFlight, 23, 23, gPlayerSequenceDragonFlight, 23, 23, gPlayerSequenceDragonFlight, 23, 23, gPlayerSequenceDragonFlight, 23, 23, gPlayerSequenceDragonFlight, 23, 23, gPlayerSequenceDragonFlight, 23, 23, gPlayerSequenceDragonFlight, 23, 23, }; //D2Common.0x6FDE0160 D2MonSeqTxt gPlayerSequenceUnmorph[16] = { { 0, PLRMODE_SPECIAL1, 15, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 14, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 13, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 12, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 11, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 10, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 9, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 8, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 7, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 6, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 5, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 4, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 3, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 2, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_SPECIAL1, 1, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_SPECIAL1, 0, 0, MONSEQ_EVENT_NONE }, }; //D2Common.0x6FDE01C0 D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceUnmorph = { gPlayerSequenceUnmorph, 16, 16, gPlayerSequenceUnmorph, 16, 16, gPlayerSequenceUnmorph, 16, 16, gPlayerSequenceUnmorph, 16, 16, gPlayerSequenceUnmorph, 16, 16, gPlayerSequenceUnmorph, 16, 16, gPlayerSequenceUnmorph, 16, 16, gPlayerSequenceUnmorph, 16, 16, gPlayerSequenceUnmorph, 16, 16, gPlayerSequenceUnmorph, 16, 16, gPlayerSequenceUnmorph, 16, 16, gPlayerSequenceUnmorph, 16, 16, gPlayerSequenceUnmorph, 16, 16, gPlayerSequenceUnmorph, 16, 16, }; //D2Common.0x6FDE0268 D2MonSeqTxt gPlayerSequenceBladeFury[19] = { { 0, PLRMODE_CAST, 0, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 1, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 2, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 3, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 4, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 5, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 6, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 7, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 8, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 9, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 10, 0, MONSEQ_EVENT_MELEE_ATTACK }, { 0, PLRMODE_CAST, 11, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 12, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 13, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 14, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 15, 0, MONSEQ_EVENT_NONE }, { 0, PLRMODE_CAST, 16, 0, MONSEQ_EVENT_NONE }, }; //D2Common.0x6FDE02E0 D2PlayerWeaponSequencesStrc gPlayerWeaponsSequenceBladeFury = { gPlayerSequenceBladeFury, 19, 19, gPlayerSequenceBladeFury, 19, 19, gPlayerSequenceBladeFury, 19, 19, gPlayerSequenceBladeFury, 19, 19, gPlayerSequenceBladeFury, 19, 19, gPlayerSequenceBladeFury, 19, 19, gPlayerSequenceBladeFury, 19, 19, gPlayerSequenceBladeFury, 19, 19, gPlayerSequenceBladeFury, 19, 19, gPlayerSequenceBladeFury, 19, 19, gPlayerSequenceBladeFury, 19, 19, gPlayerSequenceBladeFury, 19, 19, gPlayerSequenceBladeFury, 19, 19, gPlayerSequenceBladeFury, 19, 19, }; //D2Common.0x6FDE0388 D2PlayerWeaponSequencesStrc* gPlayerWeaponsSequenceTable[24] = { NULL, &gPlayerWeaponsSequenceJab, &gPlayerWeaponsSequenceSacrifice, &gPlayerWeaponsSequenceChastise, &gPlayerWeaponsSequenceCharge, &gPlayerWeaponsSequenceDefiance, &gPlayerWeaponsSequenceInferno, &gPlayerWeaponsSequenceStrafe, &gPlayerWeaponsSequenceImpale, &gPlayerWeaponsSequenceFend, &gPlayerWeaponsSequenceWhirlwind, &gPlayerWeaponsSequenceDoubleSwing, &gPlayerWeaponsSequenceLightning, &gPlayerWeaponsSequenceLeap, &gPlayerWeaponsSequenceLeapAttack, &gPlayerWeaponsSequenceDoubleThrow, &gPlayerWeaponsSequenceDragonClaw, &gPlayerWeaponsSequenceProjection, &gPlayerWeaponsSequenceArcticBlast, &gPlayerWeaponsSequenceDragonTalon, &gPlayerWeaponsSequenceDragonBreath, &gPlayerWeaponsSequenceDragonFlight, &gPlayerWeaponsSequenceUnmorph, &gPlayerWeaponsSequenceBladeFury, }; //D2Common.0x6FDE03E8 //Note: This should really just be an array since the indices are ordered anyway... static const int gWeaponIndexToClassMap[14][2] = { { 0, WEAPONCLASS_HTH }, { 1, WEAPONCLASS_1HT }, { 2, WEAPONCLASS_2HT }, { 3, WEAPONCLASS_1HS }, { 4, WEAPONCLASS_2HS }, { 5, WEAPONCLASS_BOW }, { 6, WEAPONCLASS_XBW }, { 7, WEAPONCLASS_STF }, { 8, WEAPONCLASS_1JS }, { 9, WEAPONCLASS_1JT }, { 10, WEAPONCLASS_1SS }, { 11, WEAPONCLASS_1ST }, { 12, WEAPONCLASS_HT1 }, { 13, WEAPONCLASS_HT2 } }; //D2Common.0x6FD727A0 (#10682) D2MonSeqTxt* __stdcall DATATBLS_GetMonSeqTxtRecordFromUnit(D2UnitStrc* pUnit) { D2SeqRecordStrc* pSeqRecord = DATATBLS_GetSeqRecordFromUnit(pUnit); if (pSeqRecord) { return pSeqRecord->pMonSeqTxtRecord; } return NULL; } //D2Common.0x6FD727C0 D2SeqRecordStrc* __fastcall DATATBLS_GetSeqRecordFromUnit(D2UnitStrc* pUnit) { if (D2SkillStrc* pSkill = UNITS_GetUsedSkill(pUnit)) { int nSequenceNum = SKILLS_GetSeqNumFromSkill(pUnit, pSkill); if (nSequenceNum > 0) { int nUnitType = UNIT_TYPES_COUNT; if (pUnit) { nUnitType = pUnit->dwUnitType; } if (nUnitType == UNIT_PLAYER) { int nWeaponClass = WEAPONCLASS_HTH; COMPOSIT_GetWeaponClassId(pUnit, pUnit->pInventory, &nWeaponClass, -1, TRUE); int nWClassIndex = -1; for (int i = 0; i < 14; i++) { if (nWeaponClass == gWeaponIndexToClassMap[i][1]) { nWClassIndex = gWeaponIndexToClassMap[i][0]; break; } } D2_ASSERT(nWClassIndex != -1); return &gPlayerWeaponsSequenceTable[nSequenceNum]->weaponRecords[nWClassIndex]; } else if (nUnitType == UNIT_MONSTER && DATATBLS_GetMonStatsTxtRecord(pUnit->dwClassId)) { return DATATBLS_GetMonSeqTableRecord(nSequenceNum); } } } return NULL; } //D2Common.0x6FD728A0 (#10683) int __stdcall DATATBLS_GetSeqFramePointsCount(D2UnitStrc* pUnit) { D2SeqRecordStrc* pSeqRecord = DATATBLS_GetSeqRecordFromUnit(pUnit); if (pSeqRecord) { return (pSeqRecord->nSeqFramesCount << 8); } return 0; } //D2Common.0x6FD728C0 (#10684) int __stdcall DATATBLS_GetSeqFrameCount(D2UnitStrc* pUnit) { D2SeqRecordStrc* pSeqRecord = DATATBLS_GetSeqRecordFromUnit(pUnit); if (pSeqRecord) { return pSeqRecord->nFramesCount; } return 0; } //D2Common.0x6FD728E0 (#10685) void __stdcall DATATBLS_ComputeSequenceAnimation(D2MonSeqTxt* pMonSeqTxt, int nTargetFramePoint, int nCurrentFramePoint, unsigned int* pMode, unsigned int* pFrame, int* pDirection, int* pEvent) { if (pMonSeqTxt) { const D2MonSeqTxt* pMonSeqTxtRecord = &pMonSeqTxt[nCurrentFramePoint >> 8]; *pMode = pMonSeqTxtRecord->nMode; *pFrame = pMonSeqTxtRecord->nFrame; *pDirection = pMonSeqTxtRecord->nDir; if (nCurrentFramePoint == nTargetFramePoint) { *pEvent = pMonSeqTxtRecord->nEvent; } else // Retrieve the last event, note that it discard the intermediary events. { *pEvent = 0; const int nNextFrame = (nCurrentFramePoint >> 8) + 1; const int nTargetFrame = nTargetFramePoint >> 8; for (int frameIdx = nNextFrame; frameIdx <= nTargetFrame; frameIdx++) { const D2MonSeqEvent nEvent = pMonSeqTxt[frameIdx].nEvent; if (nEvent != MONSEQ_EVENT_NONE) { *pEvent = nEvent; } } } } else { *pMode = 0; *pFrame = 0; *pDirection = 0; *pEvent = MONSEQ_EVENT_NONE; } } //D2Common.0x6FD72990 (#10686) void __stdcall DATATBLS_GetSequenceEvent(D2MonSeqTxt* pMonSeqTxt, int nSeqFramePoint, int* pEvent) { if (pMonSeqTxt) { *pEvent = pMonSeqTxt[nSeqFramePoint >> 8].nEvent; } else { *pEvent = 0; } } //D2Common.0x6FD6F050 void __fastcall DATATBLS_LoadMonSeqTxt(void* pMemPool) { D2BinFieldStrc pTbl[] = { { "sequence", TXTFIELD_NAMETOINDEX, 0, 0, &sgptDataTables->pMonSeqLinker }, { "mode", TXTFIELD_CODETOBYTE, 0, 2, &sgptDataTables->pMonModeLinker }, { "frame", TXTFIELD_BYTE, 0, 3, NULL }, { "dir", TXTFIELD_BYTE, 0, 4, NULL }, { "event", TXTFIELD_BYTE, 0, 5, NULL }, { "end", TXTFIELD_NONE, 0, 0, NULL }, }; sgptDataTables->pMonSeqLinker = (D2TxtLinkStrc*)FOG_AllocLinker(__FILE__, __LINE__); sgptDataTables->pMonSeqTxt = (D2MonSeqTxt*)DATATBLS_CompileTxt(pMemPool, "monseq", pTbl, &sgptDataTables->nMonSeqTxtRecordCount, sizeof(D2MonSeqTxt)); if (sgptDataTables->nMonSeqTxtRecordCount > 0) { sgptDataTables->nMonSeqTableRecordCount = sgptDataTables->pMonSeqTxt[sgptDataTables->nMonSeqTxtRecordCount - 1].wSequence + 1; sgptDataTables->pMonSeqTable = (D2SeqRecordStrc*)D2_CALLOC_SERVER(NULL, sizeof(D2SeqRecordStrc) * sgptDataTables->nMonSeqTableRecordCount); for (int i = 0; i < sgptDataTables->nMonSeqTxtRecordCount; ++i) { int nSequence = sgptDataTables->pMonSeqTxt[i].wSequence; if (!sgptDataTables->pMonSeqTable[nSequence].pMonSeqTxtRecord) { sgptDataTables->pMonSeqTable[nSequence].pMonSeqTxtRecord = &sgptDataTables->pMonSeqTxt[i]; } ++sgptDataTables->pMonSeqTable[nSequence].nSeqFramesCount; ++sgptDataTables->pMonSeqTable[nSequence].nFramesCount; } } } //D2Common.0x6FD6F200 (#11262) D2SeqRecordStrc* __stdcall DATATBLS_GetMonSeqTableRecord(int nSequence) { if (nSequence >= 0 && nSequence < sgptDataTables->nMonSeqTableRecordCount) { return &sgptDataTables->pMonSeqTable[nSequence]; } return NULL; }
35.615958
193
0.731748
raumuongluoc
ae06620b4145aff4fd7b6004b47eeef88f43cf26
1,656
cpp
C++
src/coherence/component/net/extend/protocol/cache/AbstractKeySetRequest.cpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
6
2020-07-01T21:38:30.000Z
2021-11-03T01:35:11.000Z
src/coherence/component/net/extend/protocol/cache/AbstractKeySetRequest.cpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
1
2020-07-24T17:29:22.000Z
2020-07-24T18:29:04.000Z
src/coherence/component/net/extend/protocol/cache/AbstractKeySetRequest.cpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
6
2020-07-10T18:40:58.000Z
2022-02-18T01:23:40.000Z
/* * Copyright (c) 2000, 2020, Oracle and/or its affiliates. * * Licensed under the Universal Permissive License v 1.0 as shown at * http://oss.oracle.com/licenses/upl. */ #include "private/coherence/component/net/extend/protocol/cache/AbstractKeySetRequest.hpp" #include "coherence/util/ArrayList.hpp" // REVIEW COH_OPEN_NAMESPACE6(coherence,component,net,extend,protocol,cache) using coherence::util::ArrayList; // ----- constructors ------------------------------------------------------- AbstractKeySetRequest::AbstractKeySetRequest() : f_vCol(self()) { } // ----- PortableObject interface ------------------------------------------- void AbstractKeySetRequest::readExternal(PofReader::Handle hIn) { AbstractPofRequest::readExternal(hIn); setKeySet(hIn->readCollection(1, ArrayList::create())); } void AbstractKeySetRequest::writeExternal(PofWriter::Handle hOut) const { AbstractPofRequest::writeExternal(hOut); hOut->writeCollection(1, getKeySet()); //release state // m_vCol = NULL; // c++ optimization uses FinalView and thus can't be released } // ----- Describable interface ---------------------------------------------- String::View AbstractKeySetRequest::getDescription() const { return COH_TO_STRING(super::getDescription() << ", KeySet=" << getKeySet()); } // ----- accessors ---------------------------------------------------------- Collection::View AbstractKeySetRequest::getKeySet() const { return f_vCol; } void AbstractKeySetRequest::setKeySet(Collection::View vCol) { initialize(f_vCol, vCol); } COH_CLOSE_NAMESPACE6
25.476923
90
0.61715
chpatel3
ae08ccd123b4592a416711a9e6da05519e2606fb
10,499
cpp
C++
src/kits/shared/JsonMessageWriter.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
1,338
2015-01-03T20:06:56.000Z
2022-03-26T13:49:54.000Z
src/kits/shared/JsonMessageWriter.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
15
2015-01-17T22:19:32.000Z
2021-12-20T12:35:00.000Z
src/kits/shared/JsonMessageWriter.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
350
2015-01-08T14:15:27.000Z
2022-03-21T18:14:35.000Z
/* * Copyright 2017, Andrew Lindesay <apl@lindesay.co.nz> * Distributed under the terms of the MIT License. */ #include "JsonMessageWriter.h" namespace BPrivate { /*! The class and sub-classes of it are used as a stack internal to the BJsonMessageWriter class. As the JSON is parsed, the stack of these internal listeners follows the stack of the JSON parsing in terms of containers; arrays and objects. */ class BStackedMessageEventListener : public BJsonEventListener { public: BStackedMessageEventListener( BJsonMessageWriter* writer, BStackedMessageEventListener* parent, uint32 messageWhat); BStackedMessageEventListener( BJsonMessageWriter* writer, BStackedMessageEventListener* parent, BMessage* message); ~BStackedMessageEventListener(); bool Handle(const BJsonEvent& event); void HandleError(status_t status, int32 line, const char* message); void Complete(); void AddMessage(BMessage* value); status_t ErrorStatus(); virtual const char* NextItemName() = 0; BStackedMessageEventListener* Parent(); protected: void AddBool(bool value); void AddNull(); void AddDouble(double value); void AddString(const char* value); virtual bool WillAdd(); virtual void DidAdd(); void SetStackedListenerOnWriter( BStackedMessageEventListener* stackedListener); BJsonMessageWriter* fWriter; bool fOwnsMessage; BStackedMessageEventListener *fParent; BMessage* fMessage; }; class BStackedArrayMessageEventListener : public BStackedMessageEventListener { public: BStackedArrayMessageEventListener( BJsonMessageWriter* writer, BStackedMessageEventListener* parent); BStackedArrayMessageEventListener( BJsonMessageWriter* writer, BStackedMessageEventListener* parent, BMessage* message); ~BStackedArrayMessageEventListener(); bool Handle(const BJsonEvent& event); const char* NextItemName(); protected: void DidAdd(); private: uint32 fCount; BString fNextItemName; }; class BStackedObjectMessageEventListener : public BStackedMessageEventListener { public: BStackedObjectMessageEventListener( BJsonMessageWriter* writer, BStackedMessageEventListener* parent); BStackedObjectMessageEventListener( BJsonMessageWriter* writer, BStackedMessageEventListener* parent, BMessage* message); ~BStackedObjectMessageEventListener(); bool Handle(const BJsonEvent& event); const char* NextItemName(); protected: bool WillAdd(); void DidAdd(); private: BString fNextItemName; }; } // namespace BPrivate using BPrivate::BStackedMessageEventListener; using BPrivate::BStackedArrayMessageEventListener; using BPrivate::BStackedObjectMessageEventListener; // #pragma mark - BStackedMessageEventListener BStackedMessageEventListener::BStackedMessageEventListener( BJsonMessageWriter* writer, BStackedMessageEventListener* parent, uint32 messageWhat) { fWriter = writer; fParent = parent; fOwnsMessage = true; fMessage = new BMessage(messageWhat); } BStackedMessageEventListener::BStackedMessageEventListener( BJsonMessageWriter* writer, BStackedMessageEventListener* parent, BMessage* message) { fWriter = writer; fParent = parent; fOwnsMessage = false; fMessage = message; } BStackedMessageEventListener::~BStackedMessageEventListener() { if (fOwnsMessage) delete fMessage; } bool BStackedMessageEventListener::Handle(const BJsonEvent& event) { if (fWriter->ErrorStatus() != B_OK) return false; switch (event.EventType()) { case B_JSON_NUMBER: AddDouble(event.ContentDouble()); break; case B_JSON_STRING: AddString(event.Content()); break; case B_JSON_TRUE: AddBool(true); break; case B_JSON_FALSE: AddBool(false); break; case B_JSON_NULL: AddNull(); break; case B_JSON_OBJECT_START: { SetStackedListenerOnWriter(new BStackedObjectMessageEventListener( fWriter, this)); break; } case B_JSON_ARRAY_START: { SetStackedListenerOnWriter(new BStackedArrayMessageEventListener( fWriter, this)); break; } default: { HandleError(B_NOT_ALLOWED, JSON_EVENT_LISTENER_ANY_LINE, "unexpected type of json item to add to container"); return false; } } return ErrorStatus() == B_OK; } void BStackedMessageEventListener::HandleError(status_t status, int32 line, const char* message) { fWriter->HandleError(status, line, message); } void BStackedMessageEventListener::Complete() { // illegal state. HandleError(JSON_EVENT_LISTENER_ANY_LINE, B_NOT_ALLOWED, "Complete() called on stacked message listener"); } void BStackedMessageEventListener::AddMessage(BMessage* message) { if (WillAdd()) { fMessage->AddMessage(NextItemName(), message); DidAdd(); } } status_t BStackedMessageEventListener::ErrorStatus() { return fWriter->ErrorStatus(); } BStackedMessageEventListener* BStackedMessageEventListener::Parent() { return fParent; } void BStackedMessageEventListener::AddBool(bool value) { if (WillAdd()) { fMessage->AddBool(NextItemName(), value); DidAdd(); } } void BStackedMessageEventListener::AddNull() { if (WillAdd()) { fMessage->AddPointer(NextItemName(), (void*)NULL); DidAdd(); } } void BStackedMessageEventListener::AddDouble(double value) { if (WillAdd()) { fMessage->AddDouble(NextItemName(), value); DidAdd(); } } void BStackedMessageEventListener::AddString(const char* value) { if (WillAdd()) { fMessage->AddString(NextItemName(), value); DidAdd(); } } bool BStackedMessageEventListener::WillAdd() { return true; } void BStackedMessageEventListener::DidAdd() { // noop - present for overriding } void BStackedMessageEventListener::SetStackedListenerOnWriter( BStackedMessageEventListener* stackedListener) { fWriter->SetStackedListener(stackedListener); } // #pragma mark - BStackedArrayMessageEventListener BStackedArrayMessageEventListener::BStackedArrayMessageEventListener( BJsonMessageWriter* writer, BStackedMessageEventListener* parent) : BStackedMessageEventListener(writer, parent, B_JSON_MESSAGE_WHAT_ARRAY) { fCount = 0; } BStackedArrayMessageEventListener::BStackedArrayMessageEventListener( BJsonMessageWriter* writer, BStackedMessageEventListener* parent, BMessage* message) : BStackedMessageEventListener(writer, parent, message) { message->what = B_JSON_MESSAGE_WHAT_ARRAY; fCount = 0; } BStackedArrayMessageEventListener::~BStackedArrayMessageEventListener() { } bool BStackedArrayMessageEventListener::Handle(const BJsonEvent& event) { if (fWriter->ErrorStatus() != B_OK) return false; switch (event.EventType()) { case B_JSON_ARRAY_END: { if (fParent != NULL) fParent->AddMessage(fMessage); SetStackedListenerOnWriter(fParent); delete this; break; } default: return BStackedMessageEventListener::Handle(event); } return true; } const char* BStackedArrayMessageEventListener::NextItemName() { fNextItemName.SetToFormat("%" B_PRIu32, fCount); return fNextItemName.String(); } void BStackedArrayMessageEventListener::DidAdd() { BStackedMessageEventListener::DidAdd(); fCount++; } // #pragma mark - BStackedObjectMessageEventListener BStackedObjectMessageEventListener::BStackedObjectMessageEventListener( BJsonMessageWriter* writer, BStackedMessageEventListener* parent) : BStackedMessageEventListener(writer, parent, B_JSON_MESSAGE_WHAT_OBJECT) { } BStackedObjectMessageEventListener::BStackedObjectMessageEventListener( BJsonMessageWriter* writer, BStackedMessageEventListener* parent, BMessage* message) : BStackedMessageEventListener(writer, parent, message) { message->what = B_JSON_MESSAGE_WHAT_OBJECT; } BStackedObjectMessageEventListener::~BStackedObjectMessageEventListener() { } bool BStackedObjectMessageEventListener::Handle(const BJsonEvent& event) { if (fWriter->ErrorStatus() != B_OK) return false; switch (event.EventType()) { case B_JSON_OBJECT_END: { if (fParent != NULL) fParent->AddMessage(fMessage); SetStackedListenerOnWriter(fParent); delete this; break; } case B_JSON_OBJECT_NAME: fNextItemName.SetTo(event.Content()); break; default: return BStackedMessageEventListener::Handle(event); } return true; } const char* BStackedObjectMessageEventListener::NextItemName() { return fNextItemName.String(); } bool BStackedObjectMessageEventListener::WillAdd() { if (0 == fNextItemName.Length()) { HandleError(B_NOT_ALLOWED, JSON_EVENT_LISTENER_ANY_LINE, "missing name for adding value into an object"); return false; } return true; } void BStackedObjectMessageEventListener::DidAdd() { BStackedMessageEventListener::DidAdd(); fNextItemName.SetTo("", 0); } // #pragma mark - BJsonMessageWriter BJsonMessageWriter::BJsonMessageWriter(BMessage& message) { fTopLevelMessage = &message; fStackedListener = NULL; } BJsonMessageWriter::~BJsonMessageWriter() { BStackedMessageEventListener* listener = fStackedListener; while (listener != NULL) { BStackedMessageEventListener* nextListener = listener->Parent(); delete listener; listener = nextListener; } fStackedListener = NULL; } bool BJsonMessageWriter::Handle(const BJsonEvent& event) { if (fErrorStatus != B_OK) return false; if (fStackedListener != NULL) return fStackedListener->Handle(event); else { switch(event.EventType()) { case B_JSON_OBJECT_START: { SetStackedListener(new BStackedObjectMessageEventListener( this, NULL, fTopLevelMessage)); break; } case B_JSON_ARRAY_START: { fTopLevelMessage->what = B_JSON_MESSAGE_WHAT_ARRAY; SetStackedListener(new BStackedArrayMessageEventListener( this, NULL, fTopLevelMessage)); break; } default: { HandleError(B_NOT_ALLOWED, JSON_EVENT_LISTENER_ANY_LINE, "a message object can only handle an object or an array" "at the top level"); return false; } } } return true; // keep going } void BJsonMessageWriter::Complete() { if (fStackedListener != NULL) { HandleError(B_BAD_DATA, JSON_EVENT_LISTENER_ANY_LINE, "unexpected end of input data processing structure"); } } void BJsonMessageWriter::SetStackedListener( BStackedMessageEventListener* listener) { fStackedListener = listener; }
19.51487
80
0.740832
Kirishikesan
ae09b5ccdd4d276517f3989a7ce916f5813cb65a
74
cpp
C++
src/ace/ACE_wrappers/ACEXML/common/Attributes.cpp
wfnex/OpenBRAS
b8c2cd836ae85d5307f7f5ca87573b964342bb49
[ "BSD-3-Clause" ]
8
2017-06-05T08:56:27.000Z
2020-04-08T16:50:11.000Z
src/ace/ACE_wrappers/ACEXML/common/Attributes.cpp
wfnex/OpenBRAS
b8c2cd836ae85d5307f7f5ca87573b964342bb49
[ "BSD-3-Clause" ]
null
null
null
src/ace/ACE_wrappers/ACEXML/common/Attributes.cpp
wfnex/OpenBRAS
b8c2cd836ae85d5307f7f5ca87573b964342bb49
[ "BSD-3-Clause" ]
17
2017-06-05T08:54:27.000Z
2021-08-29T14:19:12.000Z
#include "Attributes.h" ACEXML_Attributes::~ACEXML_Attributes (void) { }
12.333333
44
0.756757
wfnex
ae0b0290fe09ecf6f5ea2fc4f9bf9531d0dc0b63
4,759
cpp
C++
hihope_neptune-oh_hid/00_src/v0.1/foundation/graphic/ui/frameworks/components/ui_toggle_button.cpp
dawmlight/vendor_oh_fun
bc9fb50920f06cd4c27399f60076f5793043c77d
[ "Apache-2.0" ]
1
2022-02-15T08:51:55.000Z
2022-02-15T08:51:55.000Z
hihope_neptune-oh_hid/00_src/v0.1/foundation/graphic/ui/frameworks/components/ui_toggle_button.cpp
dawmlight/vendor_oh_fun
bc9fb50920f06cd4c27399f60076f5793043c77d
[ "Apache-2.0" ]
null
null
null
hihope_neptune-oh_hid/00_src/v0.1/foundation/graphic/ui/frameworks/components/ui_toggle_button.cpp
dawmlight/vendor_oh_fun
bc9fb50920f06cd4c27399f60076f5793043c77d
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "components/ui_toggle_button.h" #include "common/image.h" #include "draw/draw_arc.h" #include "draw/draw_rect.h" #include "imgdecode/cache_manager.h" namespace OHOS { UIToggleButton::UIToggleButton() : width_(DEFAULT_HOT_WIDTH), height_(DEFAULT_HOT_WIDTH), corner_(DEFAULT_CORNER_RADIUS), radius_(DEFAULT_CORNER_RADIUS - DEAFULT_RADIUS_DIFF), rectWidth_(DEFAULT_WIDTH) { image_[UNSELECTED].SetSrc(""); image_[SELECTED].SetSrc(""); Resize(width_, height_); } void UIToggleButton::SetState(bool state) { if (state) { UICheckBox::SetState(SELECTED); } else { UICheckBox::SetState(UNSELECTED); } Invalidate(); } void UIToggleButton::CalculateSize() { int16_t width = GetWidth(); int16_t height = GetHeight(); if ((width_ == width) && (height_ == height)) { return; } width_ = width; height_ = height; int16_t minValue = (width_ > height_) ? height_ : width_; corner_ = DEFAULT_CORNER_RADIUS * minValue / DEFAULT_HOT_HEIGHT; int16_t radiusDiff = DEAFULT_RADIUS_DIFF * minValue / DEFAULT_HOT_WIDTH; radius_ = corner_ - radiusDiff; rectWidth_ = DEFAULT_WIDTH * minValue / DEFAULT_HOT_WIDTH; } void UIToggleButton::OnDraw(const Rect& invalidatedArea) { if ((image_[SELECTED].GetSrcType() != IMG_SRC_UNKNOWN) && (image_[UNSELECTED].GetSrcType() != IMG_SRC_UNKNOWN)) { UICheckBox::OnDraw(invalidatedArea); } else { CalculateSize(); DrawRect::Draw(GetRect(), invalidatedArea, *style_, opaScale_); Rect contentRect = GetContentRect(); int16_t dx = (width_ - rectWidth_) >> 1; int16_t dy = (height_ >> 1) - corner_; int16_t x = contentRect.GetX() + dx; int16_t y = contentRect.GetY() + dy; Rect rectMid; rectMid.SetRect(x, y, x + rectWidth_, y + (corner_ << 1) + 1); Rect trunc = invalidatedArea; bool isIntersect = trunc.Intersect(trunc, contentRect); switch (state_) { case SELECTED: { Style styleSelect = StyleDefault::GetBackgroundTransparentStyle(); styleSelect.borderRadius_ = corner_; styleSelect.bgColor_ = Color::GetColorFromRGB(DEFAULT_BG_RED, DEFAULT_BG_GREEN, DEFAULT_BG_BLUE); styleSelect.bgOpa_ = OPA_OPAQUE; if (isIntersect) { DrawRect::Draw(rectMid, trunc, styleSelect, opaScale_); } ArcInfo arcInfoRight = { { static_cast<int16_t>(x + rectWidth_ - corner_), static_cast<int16_t>(y + corner_) }, { 0 }, radius_, 0, CIRCLE_IN_DEGREE, nullptr }; styleSelect.bgColor_ = Color::White(); styleSelect.lineWidth_ = radius_; styleSelect.lineColor_ = Color::White(); if (isIntersect) { DrawArc::GetInstance()->Draw(arcInfoRight, trunc, styleSelect, OPA_OPAQUE, CapType::CAP_NONE); } break; } case UNSELECTED: { Style styleUnSelect = StyleDefault::GetBackgroundTransparentStyle(); styleUnSelect.bgColor_ = Color::White(); styleUnSelect.bgOpa_ = DEFAULT_UNSELECTED_OPA; styleUnSelect.borderRadius_ = corner_; if (isIntersect) { DrawRect::Draw(rectMid, trunc, styleUnSelect, opaScale_); } ArcInfo arcInfoLeft = { { static_cast<int16_t>(x + corner_), static_cast<int16_t>(y + corner_) }, { 0 }, radius_, 0, CIRCLE_IN_DEGREE, nullptr }; styleUnSelect.lineColor_ = Color::White(); styleUnSelect.lineWidth_ = radius_; if (isIntersect) { DrawArc::GetInstance()->Draw(arcInfoLeft, trunc, styleUnSelect, OPA_OPAQUE, CapType::CAP_NONE); } break; } default: break; } } } } // namespace OHOS
39.991597
120
0.600336
dawmlight
ae0bd9b41366661e5c83824971bbd8235099a335
1,027
cpp
C++
extractor/Utils/DBCReader.cpp
avennstrom/NovusCore-Tools
03c2bd1ee8e6b865498b4d489ac962b0f168ad59
[ "MIT" ]
null
null
null
extractor/Utils/DBCReader.cpp
avennstrom/NovusCore-Tools
03c2bd1ee8e6b865498b4d489ac962b0f168ad59
[ "MIT" ]
2
2020-01-16T13:58:44.000Z
2020-07-01T11:37:00.000Z
extractor/Utils/DBCReader.cpp
avennstrom/NovusCore-Tools
03c2bd1ee8e6b865498b4d489ac962b0f168ad59
[ "MIT" ]
5
2020-01-16T13:56:44.000Z
2021-12-20T22:16:08.000Z
#include "DBCReader.h" /* 1 = Can't open file 2 = Invalid format 3 = Invalid data / string size read */ int DBCReader::Load(std::shared_ptr<Bytebuffer> buffer) { u32 header = 0; buffer->GetU32(header); // Check for WDBC header if (header != NOVUSDBC_WDBC_TOKEN) return 2; try { buffer->GetU32(_rowCount); buffer->GetU32(_fieldCount); buffer->GetU32(_rowSize); buffer->GetU32(_stringSize); } catch (std::exception) { return 2; } // Cleanup Memory if we've previously loaded DBC Files if (_data) { delete[] _data; } u32 dataSize = _rowSize * _rowCount + _stringSize; _data = new unsigned char[dataSize]; std::memset(_data, 0, dataSize); _stringTable = _data + _rowSize * _rowCount; if (!_data || !_stringTable) return 3; buffer->GetBytes(_data, dataSize); return 0; } DBCReader::DBCRow DBCReader::GetRow(u32 id) { return DBCRow(*this, _data + id * _rowSize); }
20.137255
58
0.6037
avennstrom
ae1126f4317e7224849ef4da6c39a7f628d6738e
523
cpp
C++
exercises/6/Seminar_02 - Introduction to classes/structures_unions_alignment/unions.cpp
triffon/oop-2019-20
db199631d59ddefdcc0c8eb3d689de0095618f92
[ "MIT" ]
19
2020-02-21T16:46:50.000Z
2022-01-26T19:59:49.000Z
exercises/6/Seminar_02 - Introduction to classes/structures_unions_alignment/unions.cpp
triffon/oop-2019-20
db199631d59ddefdcc0c8eb3d689de0095618f92
[ "MIT" ]
1
2020-03-14T08:09:45.000Z
2020-03-14T08:09:45.000Z
exercises/6/Seminar_02 - Introduction to classes/structures_unions_alignment/unions.cpp
triffon/oop-2019-20
db199631d59ddefdcc0c8eb3d689de0095618f92
[ "MIT" ]
11
2020-02-23T12:29:58.000Z
2021-04-11T08:30:12.000Z
#include <iostream> //Source: https://www.youtube.com/watch?v=6uqU9Y578n4 struct Vector2 { float x, y; }; struct Vector4 { union { struct { float x, y, z, w; }; struct { Vector2 a, b; }; }; }; void printVector2(const Vector2& vector) { std::cout << "( " << vector.x << ", " << vector.y << " )" << std::endl; } int main() { Vector4 vec = { 1.0f, 2.0f, 3.0f, 4.0f }; printVector2(vec.a); std::cout << "----------------------" << std::endl; vec.z = 500.0f; printVector2(vec.b); return 0; }
14.527778
72
0.529637
triffon
ae1a3eda22f78d49e393cd55afd7741c7a2d39b9
1,194
cpp
C++
BATS/code/BTHAIModule/Source/NexusAgent.cpp
Senth/bats
51d4ec39f3a118ed0eb90ec27a1864c0ceef3898
[ "Apache-2.0" ]
null
null
null
BATS/code/BTHAIModule/Source/NexusAgent.cpp
Senth/bats
51d4ec39f3a118ed0eb90ec27a1864c0ceef3898
[ "Apache-2.0" ]
null
null
null
BATS/code/BTHAIModule/Source/NexusAgent.cpp
Senth/bats
51d4ec39f3a118ed0eb90ec27a1864c0ceef3898
[ "Apache-2.0" ]
null
null
null
#include "NexusAgent.h" #include "AgentManager.h" #include "WorkerAgent.h" #include "PFManager.h" #include "BatsModule/include/BuildPlanner.h" #include "ResourceManager.h" using namespace BWAPI; using namespace std; NexusAgent::NexusAgent(Unit* mUnit) : StructureAgent(mUnit) { agentType = "NexusAgent"; hasSentWorkers = false; if (AgentManager::getInstance()->countNoUnits(UnitTypes::Protoss_Nexus) == 0) { //We dont do this for the first Nexus. hasSentWorkers = true; } } void NexusAgent::computeActions() { if (!hasSentWorkers) { if (!unit->isBeingConstructed()) { sendWorkers(); hasSentWorkers = true; bats::BuildPlanner::getInstance()->addRefinery(); if (AgentManager::getInstance()->countNoUnits(UnitTypes::Protoss_Forge) > 0) { bats::BuildPlanner::getInstance()->addItemFirst(UnitTypes::Protoss_Pylon); bats::BuildPlanner::getInstance()->addItemFirst(UnitTypes::Protoss_Photon_Cannon); } } } if (!unit->isIdle()) { //Already doing something return; } if (ResourceManager::getInstance()->needWorker()) { UnitType worker = Broodwar->self()->getRace().getWorker(); if (canBuild(worker)) { unit->train(worker); } } }
20.947368
86
0.701005
Senth
ae1c06878dbfac75a332fd6c4f0ac34da9229d79
19
cpp
C++
src/DlibDotNet.Native.Dnn/dlib/dnn/tensor.cpp
ejoebstl/DlibDotNet
47436a573c931fc9c9107442b10cf32524805378
[ "MIT" ]
387
2017-10-14T23:08:59.000Z
2022-03-28T05:26:44.000Z
src/DlibDotNet.Native.Dnn/dlib/dnn/tensor.cpp
ejoebstl/DlibDotNet
47436a573c931fc9c9107442b10cf32524805378
[ "MIT" ]
246
2017-10-09T11:40:20.000Z
2022-03-22T08:04:08.000Z
src/DlibDotNet.Native.Dnn/dlib/dnn/tensor.cpp
ejoebstl/DlibDotNet
47436a573c931fc9c9107442b10cf32524805378
[ "MIT" ]
113
2017-10-18T12:04:53.000Z
2022-03-28T09:05:27.000Z
#include "tensor.h"
19
19
0.736842
ejoebstl
ae1df20fd6c4d4f350682072ec4175a62b66a344
6,242
cc
C++
bwidgets/widgets/bwNumberSlider.cc
julianeisel/bWidgets
35695df104f77b35992013a5602adf2723ab1022
[ "MIT" ]
72
2018-03-26T20:13:47.000Z
2022-03-08T15:59:55.000Z
bwidgets/widgets/bwNumberSlider.cc
julianeisel/bWidgets
35695df104f77b35992013a5602adf2723ab1022
[ "MIT" ]
12
2018-03-30T12:54:15.000Z
2021-05-30T23:33:01.000Z
bwidgets/widgets/bwNumberSlider.cc
julianeisel/bWidgets
35695df104f77b35992013a5602adf2723ab1022
[ "MIT" ]
10
2018-03-26T23:04:06.000Z
2021-11-17T21:04:27.000Z
#include <algorithm> #include <cassert> #include <cmath> #include <iomanip> #include <iostream> #include <sstream> #include "bwEvent.h" #include "bwPainter.h" #include "bwStyle.h" #include "bwNumberSlider.h" namespace bWidgets { bwNumberSlider::bwNumberSlider(std::optional<unsigned int> width_hint, std::optional<unsigned int> height_hint) : bwTextBox(width_hint, height_hint), precision(2) { } auto bwNumberSlider::getTypeIdentifier() const -> std::string_view { return "bwNumberSlider"; } void bwNumberSlider::draw(bwStyle& style) { bwPainter painter; bwRectanglePixel inner_rect = rectangle; const float radius = base_style.corner_radius * style.dpi_fac; // Inner - "inside" of outline, so scale down inner_rect.resize(-1); painter.setContentMask(inner_rect); painter.enableGradient( bwGradient(base_style.backgroundColor(), base_style.shadeTop(), base_style.shadeBottom())); painter.drawRoundbox(inner_rect, base_style.roundbox_corners, radius - 1.0f); painter.active_drawtype = bwPainter::DrawType::FILLED; // Text editing if (is_text_editing) { // Selection drawing painter.setActiveColor(base_style.decorationColor()); painter.drawRectangle(selection_rectangle); } else { drawValueIndicator(painter, style); } // Outline painter.setActiveColor(base_style.borderColor()); painter.active_drawtype = bwPainter::DrawType::OUTLINE; painter.drawRoundbox(rectangle, base_style.roundbox_corners, radius); painter.setActiveColor(base_style.textColor()); if (!is_text_editing) { painter.drawText(text, rectangle, base_style.text_alignment); } painter.drawText(valueToString(precision), rectangle, is_text_editing ? TextAlignment::LEFT : TextAlignment::RIGHT); } void bwNumberSlider::drawValueIndicator(bwPainter& painter, bwStyle& style) const { bwGradient gradient = bwGradient(base_style.decorationColor(), // shadeTop/Bottom intentionally inverted base_style.shadeBottom(), base_style.shadeTop()); bwRectanglePixel indicator_offset_rect = rectangle; bwRectanglePixel indicator_rect = rectangle; unsigned int roundbox_corners = base_style.roundbox_corners; const float radius = base_style.corner_radius * style.dpi_fac; float right_side_radius = radius; indicator_offset_rect.xmax = indicator_offset_rect.xmin + right_side_radius; indicator_rect.xmin = indicator_offset_rect.xmax; indicator_rect.xmax = indicator_rect.xmin + calcValueIndicatorWidth(style); if (indicator_rect.xmax > (rectangle.xmax - right_side_radius)) { right_side_radius *= (indicator_rect.xmax + right_side_radius - rectangle.xmax) / right_side_radius; } else { roundbox_corners &= ~(TOP_RIGHT | BOTTOM_RIGHT); } painter.enableGradient(gradient); painter.drawRoundbox( indicator_offset_rect, roundbox_corners & ~(TOP_RIGHT | BOTTOM_RIGHT), radius); painter.drawRoundbox( indicator_rect, roundbox_corners & ~(TOP_LEFT | BOTTOM_LEFT), right_side_radius); } auto bwNumberSlider::setValue(float _value) -> bwNumberSlider& { const int precision_fac = std::pow(10, precision); const float unclamped_value = std::max(min, std::min(max, _value)); value = std::roundf(unclamped_value * precision_fac) / precision_fac; return *this; } auto bwNumberSlider::getValue() const -> float { return value; } auto bwNumberSlider::setMinMax(float _min, float _max) -> bwNumberSlider& { min = _min; max = _max; return *this; } auto bwNumberSlider::valueToString(unsigned int precision) const -> std::string { std::stringstream string_stream; string_stream << std::fixed << std::setprecision(precision) << value; return string_stream.str(); } auto bwNumberSlider::calcValueIndicatorWidth(bwStyle& style) const -> float { const float range = max - min; const float radius = base_style.corner_radius * style.dpi_fac; assert(max > min); return ((value - min) * (rectangle.width() - radius)) / range; } // ------------------ Handling ------------------ class bwNumberSliderHandler : public bwTextBoxHandler { public: bwNumberSliderHandler(bwNumberSlider& numberslider); ~bwNumberSliderHandler() = default; void onMousePress(bwMouseButtonEvent&) override; void onMouseRelease(bwMouseButtonEvent&) override; void onMouseClick(bwMouseButtonEvent&) override; void onMouseDrag(bwMouseButtonDragEvent&) override; private: bwNumberSlider& numberslider; // Initial value before starting to edit. float initial_value; }; bwNumberSliderHandler::bwNumberSliderHandler(bwNumberSlider& numberslider) : bwTextBoxHandler(numberslider), numberslider(numberslider) { } auto bwNumberSlider::createHandler() -> std::unique_ptr<bwScreenGraph::EventHandler> { return std::make_unique<bwNumberSliderHandler>(*this); } void bwNumberSliderHandler::onMousePress(bwMouseButtonEvent& event) { if (event.button == bwMouseButtonEvent::Button::LEFT) { initial_value = numberslider.value; numberslider.setState(bwWidget::State::SUNKEN); event.swallow(); } else if (event.button == bwMouseButtonEvent::Button::RIGHT) { if (numberslider.is_text_editing) { endTextEditing(); } else if (is_dragging) { numberslider.value = initial_value; } event.swallow(); } } void bwNumberSliderHandler::onMouseRelease(bwMouseButtonEvent& event) { if (is_dragging) { numberslider.setState(bwWidget::State::NORMAL); } is_dragging = false; event.swallow(); } void bwNumberSliderHandler::onMouseClick(bwMouseButtonEvent& event) { if (event.button == bwMouseButtonEvent::Button::LEFT) { startTextEditing(); } event.swallow(); } void bwNumberSliderHandler::onMouseDrag(bwMouseButtonDragEvent& event) { if (event.button == bwMouseButtonEvent::Button::LEFT) { numberslider.setValue(initial_value + (event.drag_distance.x / (float)numberslider.rectangle.width())); if (numberslider.apply_functor) { (*numberslider.apply_functor)(); } is_dragging = true; event.swallow(); } } } // namespace bWidgets
28.372727
97
0.716437
julianeisel
ae1f29f88c6f05e3560317369e6deaca5e2fb449
324
cpp
C++
Sirul_Retardat/Sirul_Retardat.cpp
EneRgYCZ/Problems
e8bf9aa4bba2b5ead25fc5ce482a36c861501f46
[ "MIT" ]
null
null
null
Sirul_Retardat/Sirul_Retardat.cpp
EneRgYCZ/Problems
e8bf9aa4bba2b5ead25fc5ce482a36c861501f46
[ "MIT" ]
null
null
null
Sirul_Retardat/Sirul_Retardat.cpp
EneRgYCZ/Problems
e8bf9aa4bba2b5ead25fc5ce482a36c861501f46
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main () { int n, x, y, z, v[10001]; cin >> n >> x >> y >> z; v[1] = x; v[2] = y; v[3] = z; for (int i = 4; i <= n; ++i) { v[i] = v[i - 1] + v[i - 2] - v[i - 3]; } for (int i = n; i >= 1; --i) { cout << v[i] << " "; } }
17.052632
46
0.330247
EneRgYCZ
ae1fcacb9a1c8125da9eda8a38dbe2fb5d748bfa
95,361
cpp
C++
v3d_main/neuron_annotator/gui/NaMainWindow.cpp
hanchuan/vaa3d_external
d6381572dec4079705ac5d3e39c9556b50472403
[ "MIT" ]
null
null
null
v3d_main/neuron_annotator/gui/NaMainWindow.cpp
hanchuan/vaa3d_external
d6381572dec4079705ac5d3e39c9556b50472403
[ "MIT" ]
null
null
null
v3d_main/neuron_annotator/gui/NaMainWindow.cpp
hanchuan/vaa3d_external
d6381572dec4079705ac5d3e39c9556b50472403
[ "MIT" ]
null
null
null
// Fix windows compile problem with windows.h being included too late. // I wish it wasn't included at all... #ifdef _MSC_VER #define NOMINMAX //added by PHC, 2010-05-20 to overcome VC min max macro #include <windows.h> #endif #include <QDir> #include <QFileInfo> #include <QDebug> #include <iostream> #include <cmath> #include <cassert> #include "NaMainWindow.h" #include "Na3DWidget.h" #include "ui_NaMainWindow.h" #include "../../basic_c_fun/v3d_message.h" #include "../../v3d/v3d_application.h" #include "../DataFlowModel.h" #include "../MultiColorImageStackNode.h" #include "../NeuronAnnotatorResultNode.h" #include "../TimebasedIdentifierGenerator.h" #include "RendererNeuronAnnotator.h" #include "GalleryButton.h" #include "../../cell_counter/CellCounter3D.h" #include "../NeuronSelector.h" #include "FragmentGalleryWidget.h" #include "AnnotationWidget.h" #include "../utility/loadV3dFFMpeg.h" #include "PreferencesDialog.h" #include "../utility/FooDebug.h" #include "../utility/url_tools.h" #include <cstdlib> // getenv using namespace std; using namespace jfrc; ////////////////// // NutateThread // ////////////////// NutateThread::NutateThread(qreal cyclesPerSecond, QObject * parentObj /* = NULL */) : QThread(parentObj) , speed(cyclesPerSecond) , interval(0.200) // update every 200 milliseconds , currentAngle(0.0) { deltaAngle = 2.0 * 3.14159 * cyclesPerSecond * interval; } void NutateThread::run() { while(true) { if (paused) { msleep(500); continue; } // qDebug() << "nutation angle = " << currentAngle; rot = deltaNutation(currentAngle, deltaAngle); emit nutate(rot); currentAngle += deltaAngle; while (currentAngle > 2.0 * 3.14159) currentAngle -= 2.0 * 3.14159; msleep( (1000.0 * deltaAngle) / (2.0 * 3.14159 * speed) ); } } void NutateThread::pause() {paused = true;} void NutateThread::unpause() {paused = false;} ////////////////// // NaMainWindow // ////////////////// inline const char * getConsolePort() { const char *port; port = getenv("WORKSTATION_SERVICE_PORT"); if(NULL == port) port = "30001"; return port; } NaMainWindow::NaMainWindow(QWidget * parent, Qt::WindowFlags flags) : QMainWindow(parent, flags) , ui(new Ui::NaMainWindow) , nutateThread(NULL) , statusProgressBar(NULL) , neuronSelector(this) , undoStack(NULL) , showAllNeuronsInEmptySpaceAction(NULL) , hideAllAction(NULL) , selectNoneAction(NULL) , neuronContextMenu(NULL) , viewerContextMenu(NULL) , recentViewer(VIEWER_3D) , dynamicRangeTool(NULL) , isInCustomCutMode(false) , bShowCrosshair(true) // default to on , viewMode(VIEW_SINGLE_STACK) , cutPlanner(NULL) { const char* port = getConsolePort(); qDebug() << "Using console port: " << port; QString qport(port); QString url = QString("http://localhost:%1/axis2/services/cds").arg(port); consoleUrl = new char[url.length() + 1]; QByteArray ba = url.toUtf8(); strcpy(consoleUrl, ba.data()); qDebug() << "Using console URL: " << consoleUrl; // Set up potential 3D stereo modes before creating QGLWidget. #ifdef ENABLE_STEREO QGLFormat glFormat = QGLFormat::defaultFormat(); glFormat.setStereo(true); glFormat.setDoubleBuffer(true); if (glFormat.stereo()) { // qDebug() << "Attempting to set 3D stereo format"; } else { // qDebug() << "Failed to make stereo 3D default QGLFormat"; } QGLFormat::setDefaultFormat(glFormat); #endif recentFileActions.fill(NULL, NaMainWindow::maxRecentFiles); ui->setupUi(this); setAcceptDrops(true); // Z value comes from camera model qRegisterMetaType<Vector3D>("Vector3D"); // hide neuron gallery until there are neurons to show setViewMode(VIEW_SINGLE_STACK); // ui->mipsFrame->setVisible(false); // hide compartment map until it works correctly and is not so slow on Mac ui->compartmentSelectGroupBox->hide(); dataFlowModel=0; // TODO - neuronSelector should probably be a member of Na3DViewer, not of NaMainWindow // neuronSelector = new NeuronSelector(this); // Create stubs for recent file menu for (int i = 0; i < maxRecentFiles; ++i) { recentFileActions[i] = new OpenFileAction(this); ui->menuOpen_Recent->addAction(recentFileActions[i]); recentFileActions[i]->setVisible(false); connect(recentFileActions[i], SIGNAL(openFileRequested(QString)), this, SLOT(openFileOrUrl(QString))); } updateRecentFileActions(); // Create an area in the status bar for progress messages. statusProgressMessage = new QLabel(NULL); statusBar()->addWidget(statusProgressMessage); statusProgressBar = new QProgressBar(NULL); statusProgressBar->setValue(0); statusProgressBar->setMinimum(0); statusProgressBar->setMaximum(100); statusBar()->addWidget(statusProgressBar); statusProgressBar->hide(); statusProgressMessage->hide(); // hide progress bar for 3d viewer until it is needed ui->widget_progress3d->hide(); // hide the File->Open 3D Image stack menu item ui->menuFile->removeAction(ui->actionLoad_Tiff); ui->menuFile->removeAction(ui->actionCell_Counter_3D_2ch_lsm); // hide dev-version rotate-X movie maker, until it become more user-friendly ui->menuExport->removeAction(ui->actionX_Rotation_Movie); // hide fps option: it's for debugging ui->menuView->removeAction(ui->actionMeasure_Frame_Rate); // hide octree test item ui->menuFile->removeAction(ui->actionOpen_Octree_Volume); #ifdef USE_FFMPEG ui->actionLoad_movie_as_texture->setVisible(true); ui->actionLoad_fast_separation_result->setVisible(true); #else ui->actionLoad_movie_as_texture->setVisible(false); ui->actionLoad_fast_separation_result->setVisible(false); #endif // visualize compartment map //QDockWidget *dock = new QDockWidget(tr("Compartment Map"), this); //dock->setWidget( ui->compartmentMapWidget); qRegisterMetaType<QList<LabelSurf> >("QList<LabelSurf>"); ui->compartmentMapWidget->setComboBox(ui->compartmentMapComboBox); connect(ui->compartmentMapComboBox, SIGNAL(currentIndexChanged(int)), ui->compartmentMapWidget, SLOT(switchCompartment(int))); //connect(ui->compartmentMapWidget, SIGNAL(viscomp3dview(QList<LabelSurf>)), (Renderer_gl1*)(ui->v3dr_glwidget->getRenderer()), SLOT(setListLabelSurf(QList<LabelSurf>))); // vis compartments in Na3Dviewer // Wire up MIP viewer // Status bar message connect(ui->naLargeMIPWidget, SIGNAL(statusMessage(const QString&)), statusBar(), SLOT(showMessage(const QString&))); connect(ui->naZStackWidget, SIGNAL(statusMessage(const QString&)), statusBar(), SLOT(showMessage(const QString&))); ui->progressWidgetMip->hide(); connect(ui->naLargeMIPWidget, SIGNAL(showProgress()), ui->progressWidgetMip, SLOT(show())); connect(ui->naLargeMIPWidget, SIGNAL(hideProgress()), ui->progressWidgetMip, SLOT(hide())); connect(ui->naLargeMIPWidget, SIGNAL(setProgressMax(int)), ui->progressBarMip, SLOT(setMaximum(int))); connect(ui->naLargeMIPWidget, SIGNAL(setProgress(int)), ui->progressBarMip, SLOT(setValue(int))); ui->progressWidgetZ->hide(); // ui->gammaWidget_Zstack->hide(); // Distinguish the two gamma sliders ui->sharedGammaWidget->gamma_label->setText("N "); // "neurons" ui->sharedGammaWidget->setToolTip(tr("Brightness/gamma of data")); ui->referenceGammaWidget->gamma_label->setText("R "); // "reference" ui->referenceGammaWidget->setToolTip(tr("Brightness/gamma of reference channel")); ui->BoxSize_spinBox->setMinimum(NaZStackWidget::minHdrBoxSize); // Wire up Z-stack / HDR viewer connect(ui->HDR_checkBox, SIGNAL(toggled(bool)), ui->naZStackWidget, SLOT(setHDRCheckState(bool))); connect(ui->naZStackWidget, SIGNAL(changedHDRCheckState(bool)), ui->HDR_checkBox, SLOT(setChecked(bool))); connect(ui->HDRRed_pushButton, SIGNAL(clicked()), ui->naZStackWidget, SLOT(setRedChannel())); connect(ui->HDRGreen_pushButton, SIGNAL(clicked()), ui->naZStackWidget, SLOT(setGreenChannel())); connect(ui->HDRBlue_pushButton, SIGNAL(clicked()), ui->naZStackWidget, SLOT(setBlueChannel())); connect(ui->HDRNc82_pushButton, SIGNAL(clicked()), ui->naZStackWidget, SLOT(setNc82Channel())); connect(ui->naZStackWidget, SIGNAL(curColorChannelChanged(NaZStackWidget::Color)), this, SLOT(onHdrChannelChanged(NaZStackWidget::Color))); ui->naZStackWidget->setHDRCheckState(false); connect(ui->ZSlice_horizontalScrollBar, SIGNAL(valueChanged(int)), ui->naZStackWidget, SLOT(setCurrentZSlice(int))); connect(ui->naZStackWidget, SIGNAL(curZsliceChanged(int)), ui->ZSlice_horizontalScrollBar, SLOT(setValue(int))); connect(ui->BoxSize_spinBox, SIGNAL(valueChanged(int)), ui->naZStackWidget, SLOT(setHdrBoxSize(int))); connect(ui->naZStackWidget, SIGNAL(hdrBoxSizeChanged(int)), ui->BoxSize_spinBox, SLOT(setValue(int))); // 3D viewer connect(ui->rotationResetButton, SIGNAL(clicked()), ui->v3dr_glwidget, SLOT(resetRotation())); connect(ui->nutateButton, SIGNAL(toggled(bool)), this, SLOT(setNutate(bool))); connect(this, SIGNAL(nutatingChanged(bool)), ui->nutateButton, SLOT(setChecked(bool))); connect(ui->actionAnimate_3D_nutation, SIGNAL(toggled(bool)), this, SLOT(setNutate(bool))); connect(this, SIGNAL(nutatingChanged(bool)), ui->actionAnimate_3D_nutation, SLOT(setChecked(bool))); connect(ui->v3dr_glwidget, SIGNAL(signalTextureLoaded()), this, SLOT(onDataLoadFinished())); /* obsolete. now we toggle channels. connect(ui->redToggleButton, SIGNAL(toggled(bool)), ui->v3dr_glwidget, SLOT(setChannelR(bool))); connect(ui->greenToggleButton, SIGNAL(toggled(bool)), ui->v3dr_glwidget, SLOT(setChannelG(bool))); connect(ui->blueToggleButton, SIGNAL(toggled(bool)), ui->v3dr_glwidget, SLOT(setChannelB(bool))); */ // 3D rotation // synchronize compartment map connect(&sharedCameraModel, SIGNAL(rotationChanged(const Rotation3D&)), ui->compartmentMapWidget, SLOT(setRotation(const Rotation3D&))); // connect(&sharedCameraModel, SIGNAL(focusChanged(const Vector3D&)), // ui->compartmentMapWidget, SLOT(setFocus(const Vector3D&))); connect(&(ui->v3dr_glwidget->cameraModel), SIGNAL(rotationChanged(const Rotation3D&)), this, SLOT(on3DViewerRotationChanged(const Rotation3D&))); connect(ui->rotXWidget, SIGNAL(angleChanged(int)), this, SLOT(update3DViewerXYZBodyRotation())); connect(ui->rotYWidget, SIGNAL(angleChanged(int)), this, SLOT(update3DViewerXYZBodyRotation())); connect(ui->rotZWidget, SIGNAL(angleChanged(int)), this, SLOT(update3DViewerXYZBodyRotation())); connect(ui->v3dr_glwidget, SIGNAL(progressValueChanged(int)), this, SLOT(set3DProgress(int))); connect(ui->v3dr_glwidget, SIGNAL(progressComplete()), this, SLOT(complete3DProgress())); connect(ui->v3dr_glwidget, SIGNAL(progressMessageChanged(QString)), this, SLOT(set3DProgressMessage(QString))); connect(ui->v3dr_glwidget, SIGNAL(progressAborted(QString)), this, SLOT(complete3DProgress())); // 3D volume cut connect(ui->v3dr_glwidget, SIGNAL(changeXCut0(int)), ui->XcminSlider, SLOT(setValue(int))); // x-cut connect(ui->XcminSlider, SIGNAL(valueChanged(int)), ui->v3dr_glwidget, SLOT(setXCut0(int))); connect(ui->v3dr_glwidget, SIGNAL(changeXCut1(int)), ui->XcmaxSlider, SLOT(setValue(int))); connect(ui->XcmaxSlider, SIGNAL(valueChanged(int)), ui->v3dr_glwidget, SLOT(setXCut1(int))); connect(ui->v3dr_glwidget, SIGNAL(changeYCut0(int)), ui->YcminSlider, SLOT(setValue(int))); // y-cut connect(ui->YcminSlider, SIGNAL(valueChanged(int)), ui->v3dr_glwidget, SLOT(setYCut0(int))); connect(ui->v3dr_glwidget, SIGNAL(changeYCut1(int)), ui->YcmaxSlider, SLOT(setValue(int))); connect(ui->YcmaxSlider, SIGNAL(valueChanged(int)), ui->v3dr_glwidget, SLOT(setYCut1(int))); connect(ui->v3dr_glwidget, SIGNAL(changeZCut0(int)), ui->ZcminSlider, SLOT(setValue(int))); // z-cut connect(ui->ZcminSlider, SIGNAL(valueChanged(int)), ui->v3dr_glwidget, SLOT(setZCut0(int))); connect(ui->v3dr_glwidget, SIGNAL(changeZCut1(int)), ui->ZcmaxSlider, SLOT(setValue(int))); connect(ui->ZcmaxSlider, SIGNAL(valueChanged(int)), ui->v3dr_glwidget, SLOT(setZCut1(int))); connect(ui->XCutCB, SIGNAL(stateChanged(int)), ui->v3dr_glwidget, SLOT(setXCutLock(int))); connect(ui->YCutCB, SIGNAL(stateChanged(int)), ui->v3dr_glwidget, SLOT(setYCutLock(int))); connect(ui->ZCutCB, SIGNAL(stateChanged(int)), ui->v3dr_glwidget, SLOT(setZCutLock(int))); connect(ui->slabThicknessSlider, SIGNAL(valueChanged(int)), ui->v3dr_glwidget, SLOT(setSlabThickness(int))); connect(ui->slabPositionSlider, SIGNAL(valueChanged(int)), ui->v3dr_glwidget, SLOT(setSlabPosition(int))); connect(ui->v3dr_glwidget, SIGNAL(slabThicknessChanged(int)), this, SLOT(onSlabThicknessChanged(int))); // ui->slabThicknessSlider, SLOT(setValue(int))); connect(ui->v3dr_glwidget, SIGNAL(slabPositionChanged(int)), ui->slabPositionSlider, SLOT(setValue(int))); connect(ui->freezeFrontBackButton, SIGNAL(clicked()), ui->v3dr_glwidget, SLOT(clipSlab())); // alpha blending connect(ui->action3D_alpha_blending, SIGNAL(toggled(bool)), ui->v3dr_glwidget, SLOT(setAlphaBlending(bool))); connect(ui->v3dr_glwidget, SIGNAL(alphaBlendingChanged(bool)), ui->action3D_alpha_blending, SLOT(setChecked(bool))); // show axes connect(ui->actionShow_Axes, SIGNAL(toggled(bool)), ui->v3dr_glwidget, SLOT(setShowCornerAxes(bool))); // Whether to use common zoom and focus in MIP, ZStack and 3D viewers connect(ui->actionLink_viewers, SIGNAL(toggled(bool)), this, SLOT(unifyCameras(bool))); unifyCameras(true); // Start with cameras linked connect(ui->resetViewButton, SIGNAL(clicked()), this, SLOT(resetView())); connect(ui->zoomWidget, SIGNAL(zoomValueChanged(qreal)), &sharedCameraModel, SLOT(setScale(qreal))); connect(&sharedCameraModel, SIGNAL(scaleChanged(qreal)), ui->zoomWidget, SLOT(setZoomValue(qreal))); connect(&sharedCameraModel, SIGNAL(scaleChanged(qreal)), this, SLOT(updateViewers())); // Colors connect(ui->redToggleButton, SIGNAL(toggled(bool)), this, SLOT(setChannelZeroVisibility(bool))); connect(ui->greenToggleButton, SIGNAL(toggled(bool)), this, SLOT(setChannelOneVisibility(bool))); connect(ui->blueToggleButton, SIGNAL(toggled(bool)), this, SLOT(setChannelTwoVisibility(bool))); // Crosshair connect(ui->actionShow_Crosshair, SIGNAL(toggled(bool)), this, SLOT(setCrosshairVisibility(bool))); connect(this, SIGNAL(crosshairVisibilityChanged(bool)), ui->actionShow_Crosshair, SLOT(setChecked(bool))); connect(this, SIGNAL(crosshairVisibilityChanged(bool)), ui->naLargeMIPWidget, SLOT(showCrosshair(bool))); connect(this, SIGNAL(crosshairVisibilityChanged(bool)), ui->v3dr_glwidget, SLOT(showCrosshair(bool))); connect(this, SIGNAL(crosshairVisibilityChanged(bool)), ui->naZStackWidget, SLOT(showCrosshair(bool))); retrieveCrosshairVisibilitySetting(); // Axes // TODO I want a small set of axes that sits in the lower left corner. The gigantic axes are less useful. // connect(ui->actionShow_Axes, SIGNAL(toggled(bool)), // ui->v3dr_glwidget, SLOT(enableShowAxes(bool))); // Clear status message when viewer changes connect(ui->viewerStackedWidget, SIGNAL(currentChanged(int)), this, SLOT(onViewerChanged(int))); // Create "Undo" menu options // TODO - figure out which of these variables to expose once we have a QUndoCommand to work with. QUndoGroup * undoGroup = new QUndoGroup(this); QAction * undoAction = undoGroup->createUndoAction(this); undoAction->setShortcuts(QKeySequence::Undo); QAction * redoAction = undoGroup->createRedoAction(this); redoAction->setShortcuts(QKeySequence::Redo); ui->menuEdit->insertAction(ui->menuEdit->actions().at(0), redoAction); ui->menuEdit->insertAction(redoAction, undoAction); // expose undoStack undoStack = new QUndoStack(undoGroup); undoGroup->setActiveStack(undoStack); ui->v3dr_glwidget->setUndoStack(*undoStack); // Connect sort buttons to gallery widget connect(ui->gallerySortBySizeButton, SIGNAL(clicked()), ui->fragmentGalleryWidget, SLOT(sortBySize())); connect(ui->gallerySortByColorButton, SIGNAL(clicked()), ui->fragmentGalleryWidget, SLOT(sortByColor())); connect(ui->gallerySortByIndexButton, SIGNAL(clicked()), ui->fragmentGalleryWidget, SLOT(sortByIndex())); connect(ui->gallerySortByNameButton, SIGNAL(clicked()), ui->fragmentGalleryWidget, SLOT(sortByName())); // Allow cross-thread signals/slots that pass QList<int> qRegisterMetaType< QList<int> >("QList<int>"); // Set up the annotation widget ui->annotationFrame->setMainWindow(this); ui->centralwidget->installEventFilter(ui->annotationFrame); ui->annotationFrame->consoleConnect(3); // NeuronSelector helper class for selecting neurons connect(&neuronSelector, SIGNAL(neuronSelected(int)), ui->annotationFrame, SLOT(selectNeuron(int))); connect(ui->v3dr_glwidget, SIGNAL(neuronSelected(double,double,double)), &neuronSelector, SLOT(updateSelectedPosition(double,double,double))); connect(ui->actionDynamic_range, SIGNAL(triggered(bool)), this, SLOT(showDynamicRangeTool())); connect(ui->actionFull_Screen, SIGNAL(toggled(bool)), this, SLOT(setFullScreen(bool))); connect(this, SIGNAL(benchmarkTimerResetRequested()), this, SLOT(resetBenchmarkTimer())); connect(this, SIGNAL(benchmarkTimerPrintRequested(QString)), this, SLOT(printBenchmarkTimer(QString))); connect(ui->v3dr_glwidget, SIGNAL(benchmarkTimerPrintRequested(QString)), this, SIGNAL(benchmarkTimerPrintRequested(QString))); connect(ui->v3dr_glwidget, SIGNAL(benchmarkTimerResetRequested()), this, SIGNAL(benchmarkTimerResetRequested())); initializeContextMenus(); initializeStereo3DOptions(); connectCustomCut(); } /* slot */ void NaMainWindow::onSlabThicknessChanged(int t) { // qDebug() << "NaMainWindow::onSlabThicknessChanged()" << t << __FILE__ << __LINE__; if (t > ui->slabThicknessSlider->maximum()) { ui->slabThicknessSlider->setMaximum(t); ui->slabPositionSlider->setMaximum(t/2); ui->slabPositionSlider->setMinimum(-t/2); } ui->slabThicknessSlider->setValue(t); } /* slot */ void NaMainWindow::resetBenchmarkTimer() { mainWindowStopWatch.restart(); } /* slot */ void NaMainWindow::printBenchmarkTimer(QString message) { // qDebug() << "BENCHMARK" << message << "at" << mainWindowStopWatch.elapsed()/1000.0 << "seconds"; } /* virtual */ void NaMainWindow::keyPressEvent(QKeyEvent *event) { // Press <ESC> to exit full screen mode if (event->key() == Qt::Key_Escape) { // qDebug() << "escape pressed in main window"; exitFullScreen(); } QMainWindow::keyPressEvent(event); } /* slot */ void NaMainWindow::setViewMode(ViewMode mode) { // if (mode == viewMode) // return; // no change viewMode = mode; if (mode == VIEW_SINGLE_STACK) { ui->mipsFrame->setVisible(false); ui->annotationFrame->setVisible(true); ui->referenceGammaWidget->setVisible(false); // qDebug() << "Changing to single stack mode" << __FILE__ << __LINE__; } if (mode == VIEW_NEURON_SEPARATION) { ui->mipsFrame->setVisible(true); ui->annotationFrame->setVisible(true); ui->referenceGammaWidget->setVisible(true); // qDebug() << "Changing to separation result mode" << __FILE__ << __LINE__; } update(); } /* slot */ void NaMainWindow::exitFullScreen() { if (! isFullScreen()) return; if (viewMode == VIEW_NEURON_SEPARATION) { ui->mipsFrame->show(); } ui->annotationFrame->show(); ui->viewerSelectorAndControlFrame->show(); statusBar()->show(); showNormal(); } /* slot */ void NaMainWindow::setFullScreen(bool b) { if (isFullScreen() == b) return; if (b) { ui->annotationFrame->hide(); ui->mipsFrame->hide(); ui->viewerSelectorAndControlFrame->hide(); statusBar()->hide(); showFullScreen(); } else { exitFullScreen(); } } QString NaMainWindow::getDataDirectoryPathWithDialog() { QString initialDialogPath = QDir::currentPath(); // Use previous annotation path as initial file browser location QSettings settings(QSettings::UserScope, "HHMI", "Vaa3D"); QString previousAnnotationDirString = settings.value("NeuronAnnotatorPreviousAnnotationPath").toString(); if (! previousAnnotationDirString.isEmpty()) { QDir previousAnnotationDir(previousAnnotationDirString); if (previousAnnotationDir.exists() && previousAnnotationDir.isReadable()) { initialDialogPath = previousAnnotationDir.path(); // qDebug() << "Annotation directory path = " << initialDialogPath; } } QString dirName = QFileDialog::getExistingDirectory( this, "Select neuron separation directory", initialDialogPath, QFileDialog::ShowDirsOnly); if (dirName.isEmpty()) return ""; QDir dir(dirName); if (! dir.exists() ) { QMessageBox::warning(this, tr("No such directory"), QString("'%1'\n No such directory.\nIs the file share mounted?\nHas the directory moved?").arg(dirName)); return ""; } // Remember parent directory to ease browsing next time if (dir.cdUp()) { if (dir.exists()) { // qDebug() << "Saving annotation dir parent path " << parentDir.path(); settings.setValue("NeuronAnnotatorPreviousAnnotationPath", dir.path()); } else { // qDebug() << "Problem saving parent directory of " << dirName; } } return dirName; } QString NaMainWindow::getStackPathWithDialog() { QString initialDialogPath = QDir::currentPath(); // Use previous annotation path as initial file browser location QSettings settings(QSettings::UserScope, "HHMI", "Vaa3D"); QString previousAnnotationDirString = settings.value("NeuronAnnotatorPreviousAnnotationPath").toString(); if (! previousAnnotationDirString.isEmpty()) { QDir previousAnnotationDir(previousAnnotationDirString); if (previousAnnotationDir.exists() && previousAnnotationDir.isReadable()) { initialDialogPath = previousAnnotationDir.path(); // qDebug() << "Annotation directory path = " << initialDialogPath; } } QString fileName = QFileDialog::getOpenFileName(this, "Select volume file", initialDialogPath, tr("Stacks (*.lsm *.tif *.tiff *.mp4 *.v3draw *.v3dpbd)")); if (fileName.isEmpty()) // Silently do nothing when user presses Cancel. No error dialogs please! return ""; QFile movieFile(fileName); if (! movieFile.exists() ) { QMessageBox::warning(this, tr("No such file"), QString("'%1'\n No such file.\nIs the file share mounted?\nHas the directory moved?").arg(fileName)); return ""; } // Remember parent directory to ease browsing next time QDir parentDir = QFileInfo(movieFile).dir(); if (parentDir.exists()) { // qDebug() << "Saving annotation dir parent path " << parentDir.path(); settings.setValue("NeuronAnnotatorPreviousAnnotationPath", parentDir.path()); } else { // qDebug() << "Problem saving parent directory of " << fileName; } return fileName; } /* slot */ void NaMainWindow::on_action1280x720_triggered() { int w = ui->v3dr_glwidget->width(); int h = ui->v3dr_glwidget->height(); int dw = 1280 - w; int dh = 720 - h; resize(width() + dw, height() + dh); } /* slot */ void NaMainWindow::on_actionAdd_landmark_at_cursor_triggered() { // qDebug() << "add landmark"; RendererNeuronAnnotator * rna = ui->v3dr_glwidget->getRendererNa(); if (rna != NULL) { float radius = 20.0; Vector3D focus = sharedCameraModel.focus(); // Shape comes from type not shape argument. whatever // 0 - dodecahedron // 1 - cube ImageMarker landmark = ImageMarker(2, 0, focus.x(), rna->dim2 - focus.y(), rna->dim3 - focus.z(), radius); // cycle colors red->green->blue int c = viewerLandmarks3D.size() % 3; if (c == 0) landmark.color.i = 0xff5050ff; else if (c == 1) landmark.color.i = 0xff50ff50; else if (c == 2) landmark.color.i = 0xffff5050; viewerLandmarks3D << landmark; rna->sShowMarkers = true; rna->markerSize = (int) radius; rna->setLandmarks(viewerLandmarks3D); rna->b_showMarkerLabel = false; rna->b_showMarkerName = false; // rna->updateLandmark(); // deletes markerList! } } /* slot */ void NaMainWindow::on_actionAppend_key_frame_at_current_view_triggered() { // qDebug() << "append frame"; KeyFrame newFrame(4.0); newFrame.storeCameraSettings(sharedCameraModel); newFrame.storeLandmarkVisibility(viewerLandmarks3D); if (dataFlowModel != NULL) { DataColorModel::Reader reader(dataFlowModel->getDataColorModel()); newFrame.storeChannelColorModel(reader); } currentMovie.appendKeyFrame(newFrame); } /* slot */ void NaMainWindow::on_actionLoad_movie_as_texture_triggered() { #ifdef USE_FFMPEG QString fileName = getStackPathWithDialog(); if (fileName.isEmpty()) return; if (! dataFlowModel) return; dataFlowModel->getFast3DTexture().loadFile(fileName); #endif } void NaMainWindow::on_actionClear_landmarks_triggered() { viewerLandmarks3D.clear(); RendererNeuronAnnotator * rna = ui->v3dr_glwidget->getRendererNa(); if (rna != NULL) { rna->clearLandmarks(); } } void NaMainWindow::on_actionClear_movie_triggered() { currentMovie.clear(); } /* slot */ void NaMainWindow::on_actionMeasure_Frame_Rate_triggered() { cout << "Measuring frame rate..." << endl; Rotation3D currentRotation = sharedCameraModel.rotation(); Rotation3D dRot; const int numSteps = 30; dRot.setRotationFromAngleAboutUnitVector( 2.0 * 3.14159 / numSteps, UnitVector3D(0, 1, 0)); QElapsedTimer timer; timer.start(); for (int deg = 0; deg < numSteps; ++deg) { // cout << "step " << deg << endl; currentRotation = dRot * currentRotation; sharedCameraModel.setRotation(currentRotation); QCoreApplication::processEvents(); ui->v3dr_glwidget->updateGL(); QCoreApplication::processEvents(); } qint64 msTime = timer.elapsed(); double meanFrameTime = msTime / (double)(numSteps); double frameRate = 1000.0 / meanFrameTime; cout << meanFrameTime << " ms per frame; " << frameRate << " frames per second" << endl; // cout << timer.elapsed() << endl; } /* slot */ void NaMainWindow::on_actionOpen_Octree_Volume_triggered() { QString fileName = getStackPathWithDialog(); if (fileName.isEmpty()) return; loadSingleStack(fileName, false); // TODO - actually do something clever } /* slot */ void NaMainWindow::on_actionOpen_Single_Movie_Stack_triggered() { // qDebug() << "NaMainWindow::on_actionOpen_Single_Movie_Stack_triggered"; QString initialDialogPath = QDir::currentPath(); // Use previous annotation path as initial file browser location QSettings settings(QSettings::UserScope, "HHMI", "Vaa3D"); QString previousAnnotationDirString = settings.value("NeuronAnnotatorPreviousAnnotationPath").toString(); if (! previousAnnotationDirString.isEmpty()) { QDir previousAnnotationDir(previousAnnotationDirString); if (previousAnnotationDir.exists() && previousAnnotationDir.isReadable()) { initialDialogPath = previousAnnotationDir.path(); // qDebug() << "Annotation directory path = " << initialDialogPath; } } QString fileName = QFileDialog::getOpenFileName(this, "Select MPEG4 format volume data", initialDialogPath); // qDebug() << dirName; // If user presses cancel, QFileDialog::getOpenFileName returns a null string if (fileName.isEmpty()) // Silently do nothing when user presses Cancel. No error dialogs please! return; QFile movieFile(fileName); if (! movieFile.exists() ) { QMessageBox::warning(this, tr("No such file"), QString("'%1'\n No such file.\nIs the file share mounted?\nHas the directory moved?").arg(fileName)); return; } // Remember parent directory to ease browsing next time QDir parentDir = QFileInfo(movieFile).dir(); if (parentDir.exists()) { // qDebug() << "Saving annotation dir parent path " << parentDir.path(); settings.setValue("NeuronAnnotatorPreviousAnnotationPath", parentDir.path()); } else { // qDebug() << "Problem saving parent directory of " << fileName; } loadSingleStack(fileName, false); } void NaMainWindow::on_actionPlay_movie_triggered() { // qDebug() << "Play movie"; currentMovie.rewind(); QTime movieTimer; movieTimer.start(); double movieElapsedTime = 0.0; AnimationFrame frame; bool bPlayRealTime = true; while (currentMovie.hasMoreFrames()) { frame = currentMovie.getNextFrame(); // Skip frames to catch up, if behind schedule movieElapsedTime += currentMovie.secondsPerFrame; if (bPlayRealTime && (movieElapsedTime < movieTimer.elapsed()/1000.0)) continue; // race to next frame // animateToFrame(frame); } // Alway finish in final frame. if (bPlayRealTime) animateToFrame(frame); } void NaMainWindow::animateToFrame(const AnimationFrame& frame) { frame.retrieveCameraSettings(sharedCameraModel); frame.retrieveLandmarkVisibility(viewerLandmarks3D); RendererNeuronAnnotator * rna = ui->v3dr_glwidget->getRendererNa(); if (rna != NULL) { rna->clearLandmarks(); rna->setLandmarks(viewerLandmarks3D); rna->sShowMarkers = true; } // One channel visibility at a time // Test for positive comparisons, to avoid NaN values if (frame.channelZeroVisibility >= 0.5) emit setChannelZeroVisibility(true); else if (frame.channelZeroVisibility < 0.5) emit setChannelZeroVisibility(false); // if (frame.channelOneVisibility >= 0.5) emit setChannelOneVisibility(true); else if (frame.channelOneVisibility < 0.5) emit setChannelOneVisibility(false); // if (frame.channelTwoVisibility >= 0.5) emit setChannelTwoVisibility(true); else if (frame.channelTwoVisibility < 0.5) emit setChannelTwoVisibility(false); // if (frame.channelThreeVisibility >= 0.5) emit setChannelThreeVisibility(true); else if (frame.channelThreeVisibility < 0.5) emit setChannelThreeVisibility(false); ui->v3dr_glwidget->update(); QApplication::processEvents(); } void NaMainWindow::on_actionSave_movie_frames_triggered() { // Get output folder static QString startFolder; QString sf; if (! startFolder.isEmpty()) sf = startFolder; QString folderName = QFileDialog::getExistingDirectory(this, tr("Choose folder to store movie frame images"), sf); if (folderName.isEmpty()) return; QDir folder(folderName); if (! folder.exists()) { QMessageBox::warning(this, "No such folder", "Folder " +folderName+ " does not exist"); return; } currentMovie.rewind(); double secondsElapsed = 0.0; int frameIndex = 0; int savedCount = 0; while (currentMovie.hasMoreFrames()) { animateToFrame(currentMovie.getNextFrame()); QImage grabbedFrame = ui->v3dr_glwidget->grabFrameBuffer(true); // true->with alpha frameIndex += 1; QString fileName; fileName.sprintf("frame_%05d.png", frameIndex); fileName = folder.absoluteFilePath(fileName); qDebug() << fileName; if (grabbedFrame.save(fileName)) { savedCount += 1; } else { // TODO - better error handling qDebug() << "Failed to save frame" << fileName; } } QMessageBox::information(this, "Finished saving frames", QString("Saved %1 frames").arg(savedCount)); // Remember this folder next time startFolder = folderName; } void NaMainWindow::on_zThicknessDoubleSpinBox_valueChanged(double val) { ui->v3dr_glwidget->setThickness(val); } static bool isFolder(QString path) { if (path.isEmpty()) return false; if (path.endsWith("/")) return true; if (QFileInfo(path).suffix().isEmpty()) return true; return false; } void NaMainWindow::openFileOrUrl(QString name) { // qDebug() << "NaMainWindow::openFileOrUrl" << name << __FILE__ << __LINE__; if (name.isEmpty()) return; QUrl url(name); if (! url.isValid()) url = QUrl::fromLocalFile(name); bool isDir = true; if (url.isValid() && (!url.isRelative()) && url.toLocalFile().isEmpty()) isDir = isFolder(url.path()); // non-file URL else isDir = QFileInfo(url.toLocalFile()).isDir(); // local file if (isDir) openMulticolorImageStack(url); else loadSingleStack(url); } /* slot */ void NaMainWindow::setCrosshairVisibility(bool b) { if (bShowCrosshair == b) return; // no change bShowCrosshair = b; QSettings settings(QSettings::UserScope, "HHMI", "Vaa3D"); settings.setValue("NaCrosshairVisibility", bShowCrosshair); emit crosshairVisibilityChanged(bShowCrosshair); } void NaMainWindow::retrieveCrosshairVisibilitySetting() { QSettings settings(QSettings::UserScope, "HHMI", "Vaa3D"); bool bVisible = true; // default to "on" QVariant val = settings.value("NaCrosshairVisibility"); if (! val.isNull()) bVisible = val.toBool(); setCrosshairVisibility(bVisible); } ///////////////////////////////////////////////////// // Drop volume files onto main window to view them // ///////////////////////////////////////////////////// // Return file name if the dragged item can be usefully dropped into the NeuronAnnotator main window QUrl checkDragEvent(QDropEvent* event) { QList<QUrl> urls; if (event->mimeData()->hasUrls()) urls = event->mimeData()->urls(); // Maybe the user dragged a string with a filename or url else if (event->mimeData()->hasText()) { QString text = event->mimeData()->text(); QUrl url(text); if (url.isValid() && ! url.isEmpty()) urls.append(url); else { if (QFileInfo(text).exists()) urls.append(QUrl::fromLocalFile(text)); } } if (urls.isEmpty()) return QUrl(); /* Switch to use URLs, not files Jan 2013 QString fileName = urls.first().toLocalFile(); if (fileName.isEmpty()) return ""; */ QUrl url = urls.first(); if (url.isEmpty()) return QUrl(); QString urlPath = url.path(); if (url.host() == "") url.setHost("localhost"); // check for recognized file extensions QString fileExtension = QFileInfo(urlPath).suffix().toLower(); if (fileExtension == "lsm") return url; if (fileExtension.startsWith("tif")) // tif or tiff return url; if (fileExtension.startsWith("v3d")) // v3draw or v3dpdb return url; #ifdef USE_FFMPEG if (fileExtension.startsWith("mp4")) // v3draw or v3dpdb return url; #endif bool isDir = isFolder(url.path()); if (isDir) return url; // neuron separation folder return QUrl(); } void NaMainWindow::dragEnterEvent(QDragEnterEvent * event) { QUrl url = checkDragEvent(event); if (! url.isEmpty()) event->acceptProposedAction(); // qDebug() << "NaMainWindow::dragEnterEvent" << fileName << __FILE__ << __LINE__; } void NaMainWindow::dropEvent(QDropEvent * event) { QUrl url = checkDragEvent(event); if (url.isEmpty()) return; openFileOrUrl(url.toString()); } void NaMainWindow::moveEvent ( QMoveEvent * event ) { // qDebug() << "NaMainWindow::moveEvent()" << __FILE__ << __LINE__; ui->v3dr_glwidget->updateScreenPosition(); QMainWindow::moveEvent(event); } void NaMainWindow::loadSingleStack(QUrl url) { // Default to NeuronAnnotator, not Vaa3D classic, when URL is given loadSingleStack(url, false); } /* slot */ void NaMainWindow::loadSingleStack(QString fileName) { QUrl url = QUrl::fromLocalFile(fileName); loadSingleStack(url, true); // default to classic mode } /* slot */ void NaMainWindow::loadSingleStack(QUrl url, bool useVaa3dClassic) { if (url.isEmpty()) return; if (! url.isValid()) return; mainWindowStopWatch.start(); if (useVaa3dClassic) { // Open in Vaa3D classic mode ui->actionV3DDefault->trigger(); // switch mode QString fileName = url.toLocalFile(); if (! fileName.isEmpty()) emit defaultVaa3dFileLoadRequested(fileName); else emit defaultVaa3dUrlLoadRequested(url); } else { setViewMode(VIEW_SINGLE_STACK); onDataLoadStarted(); createNewDataFlowModel(); VolumeTexture& volumeTexture = dataFlowModel->getVolumeTexture(); volumeTexture.queueVolumeData(); QString baseName = QFileInfo(url.path()).fileName(); setTitle(baseName); emit singleStackLoadRequested(url); addUrlToRecentFilesList(url); } } /////////////////////////////////// // User clip planes in 3D viewer // /////////////////////////////////// void NaMainWindow::connectCustomCut() { connect(ui->customCutButton, SIGNAL(pressed()), this, SLOT(applyCustomCut())); connect(ui->defineClipPlaneButton, SIGNAL(pressed()), this, SLOT(toggleCustomCutMode())); } /* slot */ void NaMainWindow::applyCustomCut() { // assert(isInCustomCutMode); ui->v3dr_glwidget->applyCustomCut(); if (isInCustomCutMode) toggleCustomCutMode(); } /* slot */ void NaMainWindow::applyCustomKeepPlane() { // qDebug() << "NaMainWindow::applyCustomKeepPlane()" << __FILE__ << __LINE__; // assert(isInCustomCutMode); ui->v3dr_glwidget->applyCustomKeepPlane(); if (isInCustomCutMode) toggleCustomCutMode(); } /* slot */ void NaMainWindow::setCustomCutMode(bool doCustom) { if (doCustom) { // Activate custom cut mode ui->defineClipPlaneButton->setText(tr("Cancel")); ui->customCutButton->setEnabled(true); ui->v3dr_glwidget->setCustomCutMode(); } else { // Turn off custom cut mode ui->defineClipPlaneButton->setText(tr("Custom...")); ui->customCutButton->setEnabled(false); ui->v3dr_glwidget->cancelCustomCutMode(); } isInCustomCutMode = doCustom; } /* slot */ void NaMainWindow::toggleCustomCutMode() { setCustomCutMode(!isInCustomCutMode); } /* slot */ void NaMainWindow::showDynamicRangeTool() { // qDebug() << "NaMainWindow::showDynamicRangeTool"; if (! dynamicRangeTool) { dynamicRangeTool = new DynamicRangeTool(this); if (dataFlowModel) dynamicRangeTool->setColorModel(&dataFlowModel->getDataColorModel()); else dynamicRangeTool->setColorModel(NULL); } dynamicRangeTool->show(); } void NaMainWindow::onDataLoadStarted() { // Give strong indication to user that load is in progress ui->viewerControlTabWidget->setEnabled(false); ViewerIndex currentIndex = (ViewerIndex)ui->viewerStackedWidget->currentIndex(); if (currentIndex != VIEWER_WAIT_LOADING_SCREEN) recentViewer = currentIndex; ui->viewerStackedWidget->setCurrentIndex(VIEWER_WAIT_LOADING_SCREEN); update(); } void NaMainWindow::onDataLoadFinished() { if (undoStack) undoStack->clear(); ui->viewerStackedWidget->setCurrentIndex(recentViewer); ui->viewerControlTabWidget->setEnabled(true); // qDebug() << "Data load took" << mainWindowStopWatch.elapsed()/1000.0 << "seconds"; update(); } void NaMainWindow::initializeStereo3DOptions() { // Only check one stereo format at a time QActionGroup* stereoModeGroup = new QActionGroup(this); stereoModeGroup->setExclusive(true); stereoModeGroup->addAction(ui->actionMono_Off); stereoModeGroup->addAction(ui->actionLeft_eye_view); stereoModeGroup->addAction(ui->actionRight_eye_view); stereoModeGroup->addAction(ui->actionQuadro_120_Hz); stereoModeGroup->addAction(ui->actionAnaglyph_Red_Cyan); stereoModeGroup->addAction(ui->actionAnaglyph_Green_Magenta); stereoModeGroup->addAction(ui->actionRow_Interleaved_Zalman); stereoModeGroup->addAction(ui->actionChecker_Interleaved_3DTV); stereoModeGroup->addAction(ui->actionColumn_Interleaved); connect(ui->actionMono_Off, SIGNAL(toggled(bool)), ui->v3dr_glwidget, SLOT(setStereoOff(bool))); connect(ui->actionLeft_eye_view, SIGNAL(toggled(bool)), ui->v3dr_glwidget, SLOT(setStereoLeftEye(bool))); connect(ui->actionRight_eye_view, SIGNAL(toggled(bool)), ui->v3dr_glwidget, SLOT(setStereoRightEye(bool))); connect(ui->actionQuadro_120_Hz, SIGNAL(toggled(bool)), ui->v3dr_glwidget, SLOT(setStereoQuadBuffered(bool))); connect(ui->actionAnaglyph_Red_Cyan, SIGNAL(toggled(bool)), ui->v3dr_glwidget, SLOT(setStereoAnaglyphRedCyan(bool))); connect(ui->actionAnaglyph_Green_Magenta, SIGNAL(toggled(bool)), ui->v3dr_glwidget, SLOT(setStereoAnaglyphGreenMagenta(bool))); connect(ui->actionRow_Interleaved_Zalman, SIGNAL(toggled(bool)), ui->v3dr_glwidget, SLOT(setStereoRowInterleaved(bool))); connect(ui->actionChecker_Interleaved_3DTV, SIGNAL(toggled(bool)), ui->v3dr_glwidget, SLOT(setStereoCheckerInterleaved(bool))); connect(ui->actionColumn_Interleaved, SIGNAL(toggled(bool)), ui->v3dr_glwidget, SLOT(setStereoColumnInterleaved(bool))); connect(ui->v3dr_glwidget, SIGNAL(quadStereoSupported(bool)), this, SLOT(supportQuadStereo(bool))); } /* slot */ void NaMainWindow::supportQuadStereo(bool b) { ui->actionQuadro_120_Hz->setEnabled(b); if ( (!b) && ui->actionQuadro_120_Hz->isChecked() ) ui->actionMono_Off->setChecked(true); } void NaMainWindow::connectContextMenus(const NeuronSelectionModel& neuronSelectionModel) { connect(showAllNeuronsInEmptySpaceAction, SIGNAL(triggered()), &neuronSelectionModel, SLOT(showAllNeuronsInEmptySpace())); connect(selectNoneAction, SIGNAL(triggered()), &neuronSelectionModel, SLOT(clearSelection())); connect(hideAllAction, SIGNAL(triggered()), &neuronSelectionModel, SLOT(showNothing())); neuronContextMenu->connectActions(neuronSelectionModel); } void NaMainWindow::initializeContextMenus() { viewerContextMenu = new QMenu(this); neuronContextMenu = new NeuronContextMenu(this); // Some QActions were already made in Qt Designer showAllNeuronsInEmptySpaceAction = ui->actionShow_all_neurons_in_empty_space; hideAllAction = ui->actionClear_Hide_All; selectNoneAction = ui->actionSelect_None; // viewerContextMenu->addAction(showAllNeuronsInEmptySpaceAction); viewerContextMenu->addAction(hideAllAction); viewerContextMenu->addAction(selectNoneAction); // neuronContextMenu->addSeparator(); neuronContextMenu->addAction(showAllNeuronsInEmptySpaceAction); neuronContextMenu->addAction(hideAllAction); neuronContextMenu->addAction(selectNoneAction); // ui->naLargeMIPWidget->setContextMenus(viewerContextMenu, neuronContextMenu); ui->naZStackWidget->setContextMenus(viewerContextMenu, neuronContextMenu); ui->v3dr_glwidget->setContextMenus(viewerContextMenu, neuronContextMenu); } /* slot */ void NaMainWindow::onHdrChannelChanged(NaZStackWidget::Color channel) { switch(channel) { // Due to exclusive group, checking one button unchecks the others. case NaZStackWidget::COLOR_RED: ui->HDRRed_pushButton->setChecked(true); break; case NaZStackWidget::COLOR_GREEN: ui->HDRGreen_pushButton->setChecked(true); break; case NaZStackWidget::COLOR_BLUE: ui->HDRBlue_pushButton->setChecked(true); break; case NaZStackWidget::COLOR_NC82: ui->HDRNc82_pushButton->setChecked(true); break; } } /* slot */ void NaMainWindow::onColorModelChanged() { // For historical reasons, reference channel is denormalized into both NeuronSelectionModel and DataColorModel bool bReferenceColorIsVisible; bool bReferenceOverlayIsVisible; { DataColorModel::Reader colorReader(dataFlowModel->getDataColorModel()); if (dataFlowModel->getDataColorModel().readerIsStale(colorReader)) return; ui->redToggleButton->setChecked(colorReader.getChannelVisibility(0)); ui->greenToggleButton->setChecked(colorReader.getChannelVisibility(1)); ui->blueToggleButton->setChecked(colorReader.getChannelVisibility(2)); // Gamma ui->sharedGammaWidget->setGammaBrightness(colorReader.getSharedGamma()); const int refIndex = 3; NaVolumeData::Reader volumeReader(dataFlowModel->getVolumeData()); if (volumeReader.hasReadLock() && volumeReader.hasReferenceImage()) ui->referenceGammaWidget->setGammaBrightness(colorReader.getChannelGamma(refIndex)); // Communicate reference channel changes between NeuronSelectionModel and DataColorModel bReferenceColorIsVisible = colorReader.getChannelVisibility(refIndex); NeuronSelectionModel::Reader selectionReader(dataFlowModel->getNeuronSelectionModel()); if (! selectionReader.hasReadLock()) return; if (selectionReader.getMaskStatusList().size() < 1) return; // selection model is not active, single stack being viewed? bReferenceOverlayIsVisible = selectionReader.getOverlayStatusList()[DataFlowModel::REFERENCE_MIP_INDEX]; } // release read locks // Communicate reference visibility change, if any, to NeuronSelectionModel if (bReferenceColorIsVisible != bReferenceOverlayIsVisible) dataFlowModel->getNeuronSelectionModel().updateOverlay(DataFlowModel::REFERENCE_MIP_INDEX, bReferenceColorIsVisible); } /* slot */ void NaMainWindow::onSelectionModelVisibilityChanged() { // For historical reasons, reference channel is denormalized into both NeuronSelectionModel and DataColorModel bool bReferenceColorIsVisible; bool bReferenceOverlayIsVisible; { DataColorModel::Reader colorReader(dataFlowModel->getDataColorModel()); if (dataFlowModel->getDataColorModel().readerIsStale(colorReader)) return; bReferenceColorIsVisible = colorReader.getChannelVisibility(3); NeuronSelectionModel::Reader selectionReader(dataFlowModel->getNeuronSelectionModel()); if (! selectionReader.hasReadLock()) return; bReferenceOverlayIsVisible = selectionReader.getOverlayStatusList()[DataFlowModel::REFERENCE_MIP_INDEX]; } if (bReferenceColorIsVisible != bReferenceOverlayIsVisible) // TODO - this causes a fork of data color model // dataFlowModel->getDataColorModel().setChannelVisibility(3, bReferenceOverlayIsVisible); emit channelVisibilityChanged(3, bReferenceOverlayIsVisible); } /* slot */ void NaMainWindow::setChannelZeroVisibility(bool v) { // qDebug() << "NaMainWindow::setChannelZeroVisibility" << v; emit channelVisibilityChanged(0, v); } /* slot */ void NaMainWindow::setChannelOneVisibility(bool v) { emit channelVisibilityChanged(1, v); } /* slot */ void NaMainWindow::setChannelTwoVisibility(bool v) { emit channelVisibilityChanged(2, v); } /* slot */ void NaMainWindow::setChannelThreeVisibility(bool v) // reference channel { // For reference channel, update both DataColorModel AND "overlay" of NeuronSelectionModel if (dataFlowModel) dataFlowModel->getNeuronSelectionModel().updateOverlay(DataFlowModel::REFERENCE_MIP_INDEX, v); emit channelVisibilityChanged(3, v); } void NaMainWindow::onViewerChanged(int viewerIndex) { QString msg(" viewer selected."); switch(viewerIndex) { case VIEWER_MIP: msg = "Maximum intensity projection" + msg; break; case VIEWER_ZSTACK: msg = "Z-stack" + msg; break; case VIEWER_3D: msg = "3D" + msg; break; default: return; // wait window gets no message break; } ui->statusbar->showMessage(msg); } void NaMainWindow::setRotation(Rotation3D r) { sharedCameraModel.setRotation(r); ui->v3dr_glwidget->update(); } void NaMainWindow::setNutate(bool bDoNutate) { if (bDoNutate) { // qDebug() << "nutate"; if (! nutateThread) { nutateThread = new NutateThread(0.2, this); qRegisterMetaType<Rotation3D>("Rotation3D"); connect(nutateThread, SIGNAL(nutate(const Rotation3D&)), this, SLOT(nutate(const Rotation3D&))); } if (! nutateThread->isRunning()) nutateThread->start(QThread::IdlePriority); if (nutateThread->isRunning() && nutateThread->isPaused()) { nutateThread->unpause(); emit nutatingChanged(bDoNutate); } } else { // qDebug() << "stop nutating"; if (!nutateThread) return; if (nutateThread->isRunning() && (!nutateThread->isPaused())) { nutateThread->pause(); emit nutatingChanged(bDoNutate); } } } void NaMainWindow::nutate(const Rotation3D& R) { // qDebug() << "nutate!"; // std::cout << R << std::endl; CameraModel& cam = ui->v3dr_glwidget->cameraModel; if (!ui->v3dr_glwidget->mouseIsDragging()) { cam.setRotation(R * cam.rotation()); // TODO - use a signal here instead of processEvents QCoreApplication::processEvents(); // keep responsive during nutation ui->v3dr_glwidget->update(); } } void NaMainWindow::resetView() { // TODO - might not work if cameras are not linked Vector3D newFocus = ui->v3dr_glwidget->getDefaultFocus(); // cerr << newFocus << __LINE__ << __FILE__; sharedCameraModel.setFocus(newFocus); sharedCameraModel.setRotation(Rotation3D()); // identity rotation sharedCameraModel.setScale(1.0); // fit to window ui->viewerStackedWidget->update(); // whichever viewer is shown } void NaMainWindow::updateViewers() { ui->naLargeMIPWidget->update(); ui->naZStackWidget->update(); ui->v3dr_glwidget->update(); } void NaMainWindow::unifyCameras(bool bDoUnify) { // TODO - explicitly copy parameters from active displayed viewer if (bDoUnify) { ui->naLargeMIPWidget->synchronizeWithCameraModel(&sharedCameraModel); ui->naZStackWidget->synchronizeWithCameraModel(&sharedCameraModel); ui->v3dr_glwidget->synchronizeWithCameraModel(&sharedCameraModel); // qDebug() << "unify cameras"; } else { ui->naLargeMIPWidget->decoupleCameraModel(&sharedCameraModel); ui->naZStackWidget->decoupleCameraModel(&sharedCameraModel); ui->v3dr_glwidget->decoupleCameraModel(&sharedCameraModel); // qDebug() << "disband cameras"; } } void NaMainWindow::setZRange(int minZ, int maxZ) { // qDebug() << "minZ = " << minZ << "; maxZ = " << maxZ; QString text = QString("of %1").arg(maxZ); // qDebug() << text; ui->ZSliceTotal_label->setText(text); ui->ZSlice_horizontalScrollBar->setMaximum(maxZ); ui->ZSlice_spinBox->setMaximum(maxZ); ui->ZSlice_horizontalScrollBar->setMinimum(minZ); ui->ZSlice_spinBox->setMinimum(minZ); } void NaMainWindow::handleCoordinatedCloseEvent(QCloseEvent *e) { if (isVisible()) { // Remember window size for next time. // These settings affect both NaMainWindow and classic V3D MainWindows. So only use // NaMainWindow settings if the NaMainWindow is visible. // qDebug() << "Saving NaMainWindow size and position"; QSettings settings(QSettings::UserScope, "HHMI", "Vaa3D"); settings.setValue("pos", pos()); settings.setValue("size", size()); } e->accept(); } void NaMainWindow::closeEvent(QCloseEvent *e) { V3dApplication::handleCloseEvent(e); } void NaMainWindow::on_actionQuit_triggered() { close(); } void NaMainWindow::on_actionV3DDefault_triggered() { V3dApplication::deactivateNaMainWindow(); V3dApplication::activateMainWindow(); } void NaMainWindow::on_actionNeuronAnnotator_triggered() { V3dApplication::activateNaMainWindow(); V3dApplication::deactivateMainWindow(); } void NaMainWindow::setV3DDefaultModeCheck(bool checkState) { QAction* ui_actionV3DDefault = this->findChild<QAction*>("actionV3DDefault"); ui_actionV3DDefault->setChecked(checkState); } void NaMainWindow::setNeuronAnnotatorModeCheck(bool checkState) { QAction* ui_actionNeuronAnnotator = this->findChild<QAction*>("actionNeuronAnnotator"); ui_actionNeuronAnnotator->setChecked(checkState); } void NaMainWindow::on_actionOpen_microCT_Cut_Planner_triggered() { if (cutPlanner == NULL) { cutPlanner = new CutPlanner(sharedCameraModel, *ui->v3dr_glwidget, this); connect(cutPlanner, SIGNAL(rotationAdjusted(Rotation3D)), this, SLOT(setRotation(Rotation3D))); connect(cutPlanner, SIGNAL(clipPlaneRequested()), this, SLOT(applyCustomCut())); connect(cutPlanner, SIGNAL(keepPlaneRequested()), this, SLOT(applyCustomKeepPlane())); connect(cutPlanner, SIGNAL(cutGuideRequested(bool)), this, SLOT(setCustomCutMode(bool))); connect(cutPlanner, SIGNAL(compartmentNamingRequested()), this, SLOT(labelNeuronsAsFlyBrainCompartments())); } setCustomCutMode(true); cutPlanner->show(); } void NaMainWindow::on_actionOpen_triggered() { QString dirName = getDataDirectoryPathWithDialog(); openMulticolorImageStack(dirName); } bool NaMainWindow::openMulticolorImageStack(QString dirName) { // qDebug() << "NaMainWindow::openMulticolorImageStack" << dirName << __FILE__ << __LINE__; // string could be a folder name or a URL string // Try for folder name QDir imageDir(dirName); if (imageDir.exists()) { QUrl url = QUrl::fromLocalFile(imageDir.absolutePath()); return openMulticolorImageStack(url); } // Path is always a folder, so make it explicit if (! dirName.endsWith("/")) dirName = dirName + "/"; // That didn't work: try for a URL QUrl url(dirName); if (! url.isValid()) { QMessageBox::warning(this, tr("No such directory or URL"), QString("'%1'\n No such directory or URL.\nIs the file share mounted?\nHas the directory moved?").arg(dirName)); return false; } // qDebug() << url; bool result = openMulticolorImageStack(url); if (! result) { QMessageBox::warning(this, tr("Error opening directory or URL"), QString("'%1'\n Could not open directory or URL.\nIs the file share mounted?\nHas the directory moved?").arg(dirName)); } return result; } bool NaMainWindow::openMulticolorImageStack(QUrl url) { // qDebug() << "NaMainWindow::openMulticolorImageStack" << url << __FILE__ << __LINE__; mainWindowStopWatch.start(); // std::cout << "Selected directory=" << imageDir.absolutePath().toStdString() << endl; emit benchmarkTimerResetRequested(); emit benchmarkTimerPrintRequested("openMulticolorImageStack called"); if (! tearDownOldDataFlowModel()) { QMessageBox::warning(this, tr("Could not close previous Annotation Session"), "Error saving previous session and/or clearing memory - please exit application"); return false; } // Try to avoid Dec 2013 crash ui->v3dr_glwidget->clearImage(); createNewDataFlowModel(); // reset front/back clip slab ui->v3dr_glwidget->resetSlabThickness(); emit initializeColorModelRequested(); VolumeTexture& volumeTexture = dataFlowModel->getVolumeTexture(); // Queue up the various volumes to load, using StageFileLoaders // delegated to VolumeTexture (3D viewer) and NaVolumeTexture (all viewers) onDataLoadStarted(); if (! volumeTexture.queueSeparationFolder(url)) { onDataLoadFinished(); return false; } // Make sure 3D viewer is showing if fast loading is enabled if(volumeTexture.hasFastVolumesQueued()) { // Fast loading is only interesting if 3D viewer is selected. // So show the 3D viewer ui->viewerControlTabWidget->setCurrentIndex(2); setViewMode(VIEW_SINGLE_STACK); // no gallery yet. } // MulticolorImageStackNode setup is required for loadLsmMetadata call to succeed. MultiColorImageStackNode* multiColorImageStackNode = new MultiColorImageStackNode(url.toString()); QUrl fileUrl = url; QString path = fileUrl.path(); if (! path.endsWith("/")) path = path + "/"; // These file names will be overridden by Staged loader fileUrl.setPath(path + "ConsolidatedSignal"); multiColorImageStackNode->setPathToOriginalImageStackFile(fileUrl.toString()); fileUrl.setPath(path + "Reference"); multiColorImageStackNode->setPathToReferenceStackFile(fileUrl.toString()); fileUrl.setPath(path + "ConsolidatedLabel"); multiColorImageStackNode->setPathToMulticolorLabelMaskFile(fileUrl.toString()); dataFlowModel->setMultiColorImageStackNode(multiColorImageStackNode); if (! dataFlowModel->getVolumeData().queueSeparationFolder(url)) { onDataLoadFinished(); return false; } // Correct Z-thickness dataFlowModel->loadLsmMetadata(); // Kick off loading sequence emit stagedLoadRequested(); // volumeTexture.loadNextVolume(); addUrlToRecentFilesList(url); return true; } bool NaMainWindow::loadSeparationDirectoryV1Pbd(QUrl imageInputDirectory) { onDataLoadStarted(); // Need to construct (temporary until backend implemented) MultiColorImageStackNode from this directory // This code will be redone when the node/filestore is implemented. QUrl originalImageStackFilePath = appendPath(imageInputDirectory, MultiColorImageStackNode::IMAGE_STACK_BASE_FILENAME); QUrl maskLabelFilePath = appendPath(imageInputDirectory, MultiColorImageStackNode::IMAGE_MASK_BASE_FILENAME); QUrl referenceStackFilePath = appendPath(imageInputDirectory, MultiColorImageStackNode::IMAGE_REFERENCE_BASE_FILENAME); // Create input nodes MultiColorImageStackNode* multiColorImageStackNode = new MultiColorImageStackNode(imageInputDirectory); multiColorImageStackNode->setPathToMulticolorLabelMaskFile(maskLabelFilePath); multiColorImageStackNode->setPathToOriginalImageStackFile(originalImageStackFilePath); multiColorImageStackNode->setPathToReferenceStackFile(referenceStackFilePath); dataFlowModel->setMultiColorImageStackNode(multiColorImageStackNode); // Create result node long resultNodeId=TimebasedIdentifierGenerator::getSingleId(); NeuronAnnotatorResultNode* resultNode = new NeuronAnnotatorResultNode(resultNodeId); if (!resultNode->ensureDirectoryExists()) { QMessageBox::warning(this, tr("Could not create NeuronAnnotationResultNode"), "Error creating directory="+resultNode->getDirectoryPath()); return false; } dataFlowModel->setNeuronAnnotatorResultNode(resultNode); // Opposite of fast loading behavior dataFlowModel->getVolumeData().doFlipY = true; dataFlowModel->getVolumeData().bDoUpdateSignalTexture = true; // fooDebug() << __FILE__ << __LINE__; // Load session setViewMode(VIEW_NEURON_SEPARATION); if (! dataFlowModel->loadVolumeData()) return false; // dataChanged() signal will be emitted if load succeeds return true; } // Recent files list void NaMainWindow::addDirToRecentFilesList(QDir imageDir) { QString fileName = imageDir.absolutePath(); addFileNameToRecentFilesList(QUrl::fromLocalFile(fileName).toString()); } void NaMainWindow::addUrlToRecentFilesList(QUrl url) { addFileNameToRecentFilesList(url.toString()); } void NaMainWindow::addFileNameToRecentFilesList(QString fileName) { // fooDebug() << fileName << __FILE__ << __LINE__; if (fileName.isEmpty()) return; QSettings settings(QSettings::UserScope, "HHMI", "Vaa3D"); QVariant filesVariant = settings.value("NeuronAnnotatorRecentFileList"); QStringList files = filesVariant.toStringList(); if ( (files.size() > 0) && (files[0] == fileName) ) return; // this dir is already the top entry as is files.removeAll(fileName); files.removeAll(QString()); files.prepend(fileName); while (files.size() > maxRecentFiles) files.removeLast(); settings.setValue("NeuronAnnotatorRecentFileList", files); updateRecentFileActions(); } void NaMainWindow::updateRecentFileActions() { QSettings settings(QSettings::UserScope, "HHMI", "Vaa3D"); QStringList files = settings.value("NeuronAnnotatorRecentFileList").toStringList(); ui->menuOpen_Recent->setEnabled(files.size() > 0); for (int i = 0; i < maxRecentFiles; ++i) { if ( (i < files.size() && (! files[i].isEmpty())) ) { // active recentFileActions[i]->setFileName(files[i]); recentFileActions[i]->setVisible(true); } else { // inactive recentFileActions[i]->setFileName(QString()); recentFileActions[i]->setVisible(false); } } } QString NaMainWindow::suggestedExportFilenameFromCurrentState(const NeuronSelectionModel::Reader& selectionReader) { MultiColorImageStackNode* multiColorImageStackNode=this->dataFlowModel->getMultiColorImageStackNode(); QStringList lsmFilePathsList=multiColorImageStackNode->getLsmFilePathList(); if (lsmFilePathsList.size()>0) { // First get filename prefix QString firstFilePath=lsmFilePathsList.at(0); QStringList components=firstFilePath.split(QRegExp("/")); QString name=components.at(components.size()-1); QStringList extComponents=name.split(QRegExp("\\.")); QString filenamePrefix=extComponents.at(0); // Next, add current state if(selectionReader.getOverlayStatusList().at(DataFlowModel::REFERENCE_MIP_INDEX)) { filenamePrefix.append("_R"); } if (selectionReader.getOverlayStatusList().at(DataFlowModel::BACKGROUND_MIP_INDEX)) { filenamePrefix.append("_B"); } const QList<bool> neuronStatusList = selectionReader.getMaskStatusList(); int activeCount=0; QString neuronStatusString; for (int i=0;i<neuronStatusList.size();i++) { if (neuronStatusList.at(i)) { neuronStatusString.append("_"); QString number=QString("%1").arg(i); neuronStatusString.append(number); activeCount++; } } if (activeCount==neuronStatusList.size()) { filenamePrefix.append("_all"); } else if (activeCount<6) { filenamePrefix.append(neuronStatusString); } else { filenamePrefix.append("_multiple"); } return filenamePrefix; } else { return QString(""); } } void expressRegretsAboutVolumeWriting(QString message) { QMessageBox::warning(NULL, "Volume export failed", message); } void NaMainWindow::on_action3D_Volume_triggered() { if (! dataFlowModel) { expressRegretsAboutVolumeWriting("No data available to save"); return; } QString suggestedFile; { NeuronSelectionModel::Reader selectionReader(dataFlowModel->getNeuronSelectionModel()); if (! selectionReader.hasReadLock()) { expressRegretsAboutVolumeWriting("Could not access selection data"); return; } suggestedFile=suggestedExportFilenameFromCurrentState(selectionReader); } QString fileTypes = "*.v3dpbd *.v3draw *.tif"; #ifdef USE_FFMPEG fileTypes += " *.mp4"; #endif fileTypes = "3D Volumes ("+fileTypes+")"; QString filename = QFileDialog::getSaveFileName( 0, QObject::tr("Save 3D Volume to a file"), suggestedFile, QObject::tr(fileTypes.toStdString().c_str())); if (filename.isEmpty()) return; // user pressed "Cancel" QFileInfo fi(filename); if (fi.suffix().isEmpty()) filename = filename + ".v3dpbd"; fooDebug() << filename; ExportFile *pExport = new ExportFile( filename, dataFlowModel->getVolumeData(), dataFlowModel->getNeuronSelectionModel(), dataFlowModel->getDataColorModel(), sharedCameraModel); connect(pExport, SIGNAL(finished()), pExport, SLOT(deleteLater())); connect(pExport, SIGNAL(exportFinished(QString)), this, SLOT(onExportFinished(QString))); connect(pExport, SIGNAL(exportFailed(QString, QString)), this, SLOT(onExportFinished(QString, QString))); pExport->start(); } /* slot */ void NaMainWindow::onExportFinished(QString fileName) { QMessageBox::information(this, "Volume export succeeded", "Saved file " + fileName); } /* slot */ void NaMainWindow::onExportFailed(QString fileName, QString message) { QMessageBox::warning(this, "Volume export failed", message + ": " + fileName); } void NaMainWindow::on_action2D_MIP_triggered() { QString filename = QFileDialog::getSaveFileName(0, QObject::tr("Save 2D MIP to an .tif file"), ".", QObject::tr("2D MIP (*.tif)")); if (!(filename.isEmpty())){ // bool saved = ui->naLargeMIPWidget->saveImage(filename); // REPLACING WITH 3D MIP USING ROTATION and CUT PLANES ExportFile *pExport = new ExportFile( filename, dataFlowModel->getVolumeData(), dataFlowModel->getNeuronSelectionModel(), dataFlowModel->getDataColorModel(), sharedCameraModel, true /* is2D */); connect(pExport, SIGNAL(finished()), pExport, SLOT(deleteLater())); connect(pExport, SIGNAL(exportFinished(QString)), this, SLOT(onExportFinished(QString))); connect(pExport, SIGNAL(exportFailed(QString, QString)), this, SLOT(onExportFinished(QString, QString))); pExport->start(); } } void NaMainWindow::on_actionScreenShot_triggered() { static QString dirname = "."; QString filename = QFileDialog::getSaveFileName( ui->v3dr_glwidget, QObject::tr("Save 3D View to an image file"), dirname, QObject::tr("Images (*.tif *.png *.jpg *.ppm *.xpm)")); if (filename.isEmpty()) return; // User cancelled bool saved = ui->v3dr_glwidget->screenShot(filename); if (saved) { QMessageBox::information(ui->v3dr_glwidget, "Successfully saved screen shot", "Successfully saved screen shot to file " + filename); // Remember this directory next time // TODO - use QSettings for more persistent memory dirname = filename; } else { QMessageBox::critical(this, "Failed to save screen shot", "Failed to save screen shot to file " + filename + " \nDo you have write permission in that folder?" + " \nMaybe a different image format would work better?"); } } void NaMainWindow::on_actionPreferences_triggered() { PreferencesDialog dlg(this); dlg.loadPreferences(); int result = dlg.exec(); if (result == QDialog::Accepted) { dlg.savePreferences(); } } void NaMainWindow::on_actionX_Rotation_Movie_triggered() { QString fileName = QFileDialog::getSaveFileName( this, tr("Save movie frame images"), "", tr("Images (*.png *.jpg *.ppm)")); if (fileName.isEmpty()) return; QFileInfo fi(fileName); QDir dir = fi.absoluteDir(); QString base = fi.completeBaseName(); QString suffix = fi.suffix(); int frameCount = 540; Rotation3D dRot; dRot.setRotationFromAngleAboutUnitVector( 2.0 * 3.14159 / frameCount, UnitVector3D(1, 0, 0)); Rotation3D currentRotation = sharedCameraModel.rotation(); ui->v3dr_glwidget->resize(1280, 720); for (int f = 0; f < frameCount; ++f) { QString fnum = QString("_%1.").arg(f, 5, 10, QChar('0')); QString fName = dir.absoluteFilePath(base + fnum + suffix); fooDebug() << fName; currentRotation = dRot * currentRotation; sharedCameraModel.setRotation(currentRotation); ui->v3dr_glwidget->repaint(); QCoreApplication::processEvents(); QImage frameImage = ui->v3dr_glwidget->grabFrameBuffer(); frameImage.save(fName, NULL, 95); } } // June 27, 2012 modify to accept "NULL" during data flow replacement void NaMainWindow::setDataFlowModel(DataFlowModel* dataFlowModelParam) { if (dataFlowModel == dataFlowModelParam) return; // no change if ( (dataFlowModelParam != NULL) // we are not currently tearing down && (dataFlowModel != NULL) ) // there is another different model in existence { qDebug() << "WARNING: setDataFlowModel() should not be tearing down old models" << __FILE__ << __LINE__; tearDownOldDataFlowModel(); } dataFlowModel = dataFlowModelParam; ui->v3dr_glwidget->setDataFlowModel(dataFlowModel); ui->naLargeMIPWidget->setDataFlowModel(dataFlowModel); ui->naZStackWidget->setDataFlowModel(dataFlowModel); ui->fragmentGalleryWidget->setDataFlowModel(dataFlowModel); neuronSelector.setDataFlowModel(dataFlowModel); // was in loadAnnotationSessionFromDirectory June 27, 2012 if (dynamicRangeTool) { if (NULL == dataFlowModel) dynamicRangeTool->setColorModel(NULL); else dynamicRangeTool->setColorModel(&dataFlowModel->getDataColorModel()); } // No connecting if the model is NULL if (NULL == dataFlowModel) { ui->naLargeMIPWidget->setMipMergedData(NULL); return; } connect(this, SIGNAL(subsampleLabelPbdFileNamed(QUrl)), &dataFlowModel->getVolumeTexture(), SLOT(setLabelPbdFileUrl(QUrl))); connect(dataFlowModel, SIGNAL(benchmarkTimerPrintRequested(QString)), this, SIGNAL(benchmarkTimerPrintRequested(QString))); connect(dataFlowModel, SIGNAL(benchmarkTimerResetRequested()), this, SIGNAL(benchmarkTimerResetRequested())); // Connect mip viewer to data flow model ui->naLargeMIPWidget->setMipMergedData(&dataFlowModel->getMipMergedData()); connectContextMenus(dataFlowModel->getNeuronSelectionModel()); connect(dataFlowModel, SIGNAL(scrollBarFocus(NeuronSelectionModel::NeuronIndex)), ui->fragmentGalleryWidget, SLOT(scrollToFragment(NeuronSelectionModel::NeuronIndex))); connect(&dataFlowModel->getVolumeData(), SIGNAL(channelsLoaded(int)), this, SLOT(processUpdatedVolumeData())); // Both mip images and selection model need to be in place to update gallery connect(&dataFlowModel->getGalleryMipImages(), SIGNAL(dataChanged()), this, SLOT(updateGalleries())); connect(&dataFlowModel->getNeuronSelectionModel(), SIGNAL(initialized()), this, SLOT(initializeGalleries())); // Z value comes from camera model connect(&sharedCameraModel, SIGNAL(focusChanged(Vector3D)), &dataFlowModel->getZSliceColors(), SLOT(onCameraFocusChanged(Vector3D))); connect(&dataFlowModel->getNeuronSelectionModel(), SIGNAL(selectionCleared()), ui->annotationFrame, SLOT(deselectNeurons())); connect(ui->annotationFrame, SIGNAL(neuronSelected(int)), &dataFlowModel->getNeuronSelectionModel(), SLOT(selectExactlyOneNeuron(int))); connect(ui->annotationFrame, SIGNAL(neuronsDeselected()), &dataFlowModel->getNeuronSelectionModel(), SLOT(clearSelection())); connect(this, SIGNAL(initializeSelectionModelRequested()), &dataFlowModel->getNeuronSelectionModel(), SLOT(initializeSelectionModel())); connect(&dataFlowModel->getNeuronSelectionModel(), SIGNAL(visibilityChanged()), this, SLOT(onSelectionModelVisibilityChanged())); // Progress if NaVolumeData file load // TODO - this is a lot of connection boilerplate code. This should be abstracted into a single call or specialized ProgressManager class. connect(&dataFlowModel->getVolumeData(), SIGNAL(progressMessageChanged(QString)), this, SLOT(setProgressMessage(QString))); connect(&dataFlowModel->getVolumeData(), SIGNAL(progressValueChanged(int)), this, SLOT(setProgressValue(int))); connect(&dataFlowModel->getVolumeData(), SIGNAL(progressCompleted()), this, SLOT(completeProgress())); connect(&dataFlowModel->getVolumeData(), SIGNAL(progressAborted(QString)), this, SLOT(abortProgress(QString))); // Loading single stack connect(this, SIGNAL(singleStackLoadRequested(QUrl)), &dataFlowModel->getVolumeData(), SLOT(loadChannels(QUrl))); connect(&dataFlowModel->getVolumeData(), SIGNAL(channelsLoaded(int)), this, SLOT(onDataLoadFinished())); // Loading a series of separation result stacks connect(this, SIGNAL(stagedLoadRequested()), &dataFlowModel->getVolumeTexture(), SLOT(loadStagedVolumes())); // Color toggling connect(this, SIGNAL(channelVisibilityChanged(int,bool)), &dataFlowModel->getDataColorModel(), SLOT(setChannelVisibility(int,bool))); connect(ui->resetColorsButton, SIGNAL(clicked()), &dataFlowModel->getDataColorModel(), SLOT(resetColors())); connect(ui->sharedGammaWidget, SIGNAL(gammaBrightnessChanged(qreal)), &dataFlowModel->getDataColorModel(), SLOT(setSharedGamma(qreal))); connect(ui->referenceGammaWidget, SIGNAL(gammaBrightnessChanged(qreal)), &dataFlowModel->getDataColorModel(), SLOT(setReferenceGamma(qreal))); connect(&dataFlowModel->getDataColorModel(), SIGNAL(dataChanged()), this, SLOT(onColorModelChanged())); connect(ui->naZStackWidget, SIGNAL(hdrRangeChanged(int,qreal,qreal)), &dataFlowModel->getDataColorModel(), SLOT(setChannelHdrRange(int,qreal,qreal))); connect(this, SIGNAL(initializeColorModelRequested()), &dataFlowModel->getDataColorModel(), SLOT(resetColors())); } bool NaMainWindow::tearDownOldDataFlowModel() { ui->v3dr_glwidget->clearImage(); if (NULL == dataFlowModel) return true; // TODO - orderly shut down of old data flow model DataFlowModel* dfm = dataFlowModel; // save pointer // TODO - make sure clients respect setting to null // TODO - make sure this does not yet delete dataFlowModel setDataFlowModel(NULL); delete dfm; return true; } bool NaMainWindow::createNewDataFlowModel() { if (NULL != dataFlowModel) { bool result = tearDownOldDataFlowModel(); if (!result) return false; } DataFlowModel* dfm = new DataFlowModel(); setDataFlowModel(dfm); ui->v3dr_glwidget->invalidate(); ui->naZStackWidget->invalidate(); ui->naLargeMIPWidget->invalidate(); ui->v3dr_glwidget->clearImage(); ui->v3dr_glwidget->initializeDefaultTextures(); // <- this is how to reset the label texture return true; } void NaMainWindow::setTitle(QString title) { setWindowTitle(QString("%1 - V3D Neuron Annotator").arg(title)); } /* slot */ void NaMainWindow::processUpdatedVolumeData() // activated by volumeData::dataChanged() signal { onDataLoadFinished(); // TODO -- install separate listeners for dataChanged() in the various display widgets dataFlowModel->loadLsmMetadata(); int img_sc, img_sz, ref_sc; { NaVolumeData::Reader volumeReader(dataFlowModel->getVolumeData()); if (! volumeReader.hasReadLock()) return; const Image4DProxy<My4DImage>& imgProxy = volumeReader.getOriginalImageProxy(); const Image4DProxy<My4DImage>& refProxy = volumeReader.getReferenceImageProxy(); img_sc = imgProxy.sc; img_sz = imgProxy.sz; ref_sc = refProxy.sc; } // release read locks setZRange(0, img_sz - 1); // Ensure z-stack viewer gets enabled dataFlowModel->getZSliceColors().onCameraFocusChanged(sharedCameraModel.focus()); // Start in middle of volume // No, initial position should be set in 3D viewer // ui->naZStackWidget->setCurrentZSlice(img_sz / 2 + 1); // Need at least two colors for use of the color buttons to make sense ui->HDRRed_pushButton->setEnabled(img_sc > 1); ui->HDRGreen_pushButton->setEnabled(img_sc > 1); ui->HDRBlue_pushButton->setEnabled(img_sc > 2); ui->HDRNc82_pushButton->setEnabled(ref_sc > 0); resetVolumeCutRange(); } /* slot */ void NaMainWindow::resetVolumeCutRange() { int mx, my, mz; mx = my = mz = 0; // first try VolumeTexture to get dimensions { VolumeTexture::Reader textureReader(dataFlowModel->getVolumeTexture()); if (! dataFlowModel->getVolumeTexture().readerIsStale(textureReader)) { Dimension size = textureReader.originalImageSize(); mx = (int)size.x() - 1; my = (int)size.y() - 1; mz = (int)size.z() - 1; } } // if that fails, try VolumeData if (mx <= 0) { NaVolumeData::Reader volumeReader(dataFlowModel->getVolumeData()); if (volumeReader.hasReadLock()) { const Image4DProxy<My4DImage>& imgProxy = volumeReader.getOriginalImageProxy(); mx = imgProxy.sx - 1; my = imgProxy.sy - 1; mz = imgProxy.sz - 1; } } if (mx <= 0) return; // volume cut update ui->XcminSlider->setRange(0, mx); ui->XcminSlider->setValue(0); ui->XcmaxSlider->setRange(0, mx); ui->XcmaxSlider->setValue(mx); ui->YcminSlider->setRange(0, my); ui->YcminSlider->setValue(0); ui->YcmaxSlider->setRange(0, my); ui->YcmaxSlider->setValue(my); ui->ZcminSlider->setRange(0, my); ui->ZcminSlider->setValue(0); ui->ZcmaxSlider->setRange(0, my); ui->ZcmaxSlider->setValue(my); } // release lock DataFlowModel* NaMainWindow::getDataFlowModel() const { return dataFlowModel; } void NaMainWindow::initializeGalleries() { initializeOverlayGallery(); initializeNeuronGallery(); } void NaMainWindow::updateGalleries() { updateOverlayGallery(); updateNeuronGallery(); // Show or hide galleries depending on data structures // In particular, hide galleries when there is no reference, nor any neurons. bool bShowGalleries = false; if (NULL == dataFlowModel) ; // bShowGalleries = false; else { NaVolumeData::Reader volumeReader(dataFlowModel->getVolumeData()); if (volumeReader.hasReadLock()) { if ( (volumeReader.getNumberOfNeurons() > 0) || (volumeReader.hasReferenceImage()) ) { bShowGalleries = true; } } } // ui->mipsFrame->setVisible(bShowGalleries); if (bShowGalleries) setViewMode(VIEW_NEURON_SEPARATION); } void NaMainWindow::initializeOverlayGallery() { // qDebug() << "NaMainWindow::initializeOverlayGallery()" << __FILE__ << __LINE__; // Create layout, only if needed. QFrame* ui_maskFrame = this->findChild<QFrame*>("maskFrame"); if (! ui_maskFrame->layout()) { ui_maskFrame->setLayout(new QHBoxLayout()); assert(ui_maskFrame->layout()); } QLayout *managementLayout = ui_maskFrame->layout(); // Create new buttons, only if needed. if (overlayGalleryButtonList.size() != 2) { // Delete any old contents from the layout, such as previous thumbnails QLayoutItem * item; while ( ( item = managementLayout->takeAt(0)) != NULL ) { delete item->widget(); delete item; } QImage initialImage(100, 140, QImage::Format_ARGB32); initialImage.fill(Qt::gray); GalleryButton* referenceButton = new GalleryButton( initialImage, "Reference", DataFlowModel::REFERENCE_MIP_INDEX, GalleryButton::OVERLAY_BUTTON); managementLayout->addWidget(referenceButton); overlayGalleryButtonList.append(referenceButton); GalleryButton* backgroundButton = new GalleryButton( initialImage, "Background", DataFlowModel::BACKGROUND_MIP_INDEX, GalleryButton::OVERLAY_BUTTON); managementLayout->addWidget(backgroundButton); overlayGalleryButtonList.append(backgroundButton); } // Initialize signals whether the buttons were already there or not for (int i = 0; i < 2; ++i) { overlayGalleryButtonList[i]->setNeuronSelectionModel(dataFlowModel->getNeuronSelectionModel()); } updateOverlayGallery(); } void NaMainWindow::updateOverlayGallery() { if (overlayGalleryButtonList.size() != 2) return; // not initialized if (NULL == dataFlowModel) return; { NeuronSelectionModel::Reader selectionReader(dataFlowModel->getNeuronSelectionModel()); if (selectionReader.getOverlayStatusList().size() < 2) return; if (selectionReader.hasReadLock()) { for (int i = 0; i < 2; ++i) overlayGalleryButtonList[i]->setChecked(selectionReader.getOverlayStatusList().at(i)); } } { GalleryMipImages::Reader mipReader(dataFlowModel->getGalleryMipImages()); // acquire read lock if (mipReader.hasReadLock() && (mipReader.getNumberOfOverlays() == 2)) { for (int i = 0; i < 2; ++i) overlayGalleryButtonList[i]->setThumbnailIcon(*mipReader.getOverlayMip(i)); } } for (int i = 0; i < 2; ++i) overlayGalleryButtonList[i]->update(); } void NaMainWindow::initializeNeuronGallery() { GalleryMipImages::Reader mipReader(dataFlowModel->getGalleryMipImages()); // acquire read lock if (! mipReader.hasReadLock()) return; NeuronSelectionModel::Reader selectionReader(dataFlowModel->getNeuronSelectionModel()); if (! selectionReader.hasReadLock()) return; if (neuronGalleryButtonList.size() != mipReader.getNumberOfNeurons()) { neuronGalleryButtonList.clear(); ui->fragmentGalleryWidget->clear(); // deletes buttons // qDebug() << "Number of neuron masks = " << mipReader.getNumberOfNeurons(); for (int i = 0; i < mipReader.getNumberOfNeurons(); ++i) { GalleryButton* button = new GalleryButton( *mipReader.getNeuronMip(i), QString("Neuron fragment %1").arg(i), i, GalleryButton::NEURON_BUTTON); button->setContextMenu(neuronContextMenu); neuronGalleryButtonList.append(button); ui->fragmentGalleryWidget->appendFragment(button); } // qDebug() << "createMaskGallery() end size=" << mipReader.getNumberOfNeurons(); } // Update signals whether the buttons were already there or not for (int i = 0; i < mipReader.getNumberOfNeurons(); ++i) { neuronGalleryButtonList[i]->setThumbnailIcon(*mipReader.getNeuronMip(i)); neuronGalleryButtonList[i]->setChecked(selectionReader.getMaskStatusList().at(i)); neuronGalleryButtonList[i]->update(); neuronGalleryButtonList[i]->setNeuronSelectionModel( dataFlowModel->getNeuronSelectionModel()); } ui->fragmentGalleryWidget->updateButtonsGeometry(); } // For microCT mode /* slot */ void NaMainWindow::labelNeuronsAsFlyBrainCompartments() { // If a second renaming scheme is ever needed, refactor this to load names from an // external data source. QList<QString> compartmentNames; compartmentNames << "FB (Fan-shaped Body)"; compartmentNames << "EB (Ellipsoid Body)"; compartmentNames << "SAD (Saddle)"; compartmentNames << "NO (Noduli)"; compartmentNames << "SOG (Suboesophageal Ganglion)"; compartmentNames << "PB (Protocerebral Bridge)"; compartmentNames << "CRE_R (Crepine)"; compartmentNames << "EPA_R (Epaulette)"; compartmentNames << "VES_R (Vesta)"; compartmentNames << "ATL_R (Antler)"; compartmentNames << "PLP_R (Posterior Lateral Protocerebrum)"; compartmentNames << "AVLP_R (Anterior Ventro-lateral protocerebrum)"; compartmentNames << "AL_R (Antennal Lobe)"; compartmentNames << "GOR_R (Gorget)"; compartmentNames << "SCL_R (Superior Clamp)"; compartmentNames << "FLA (Flange)"; compartmentNames << "ICL_R (Inferior Clamp)"; compartmentNames << "ME_R (Medulla)"; compartmentNames << "LOP_R (Lobula Plate)"; compartmentNames << "LO_R (Lobula)"; compartmentNames << "MB_R (Mushroom Body)"; compartmentNames << "PVLP_R (Posterior Ventro-lateral Protocerebrum)"; compartmentNames << "OTU_R (Optic Tubercle)"; compartmentNames << "WED_R (Wedge)"; compartmentNames << "SMP_R (Superior Medial Protocerebrum)"; compartmentNames << "LH_R (Lateral Horn)"; compartmentNames << "SLP_R (Superior Lateral Protocerebrum)"; compartmentNames << "LB_R (Lateral Bulb)"; compartmentNames << "SIP_R (Superior Intermediate Protocerebrum)"; compartmentNames << "IB_R (Inferior Bridge)"; compartmentNames << "IVLP_R (Inferior Ventro-lateral Protocerebrum)"; compartmentNames << "IPS_R (Inferior Posterior Slope)"; compartmentNames << "SPS_R (Superior Posterior Slope)"; compartmentNames << "LAL_R (Lateral Accessory Lobe)"; compartmentNames << "PRW (Prow)"; compartmentNames << "AME_R (Accessory Medulla)"; compartmentNames << "GA_R (Gall)"; compartmentNames << "CRE_L (Crepine)"; compartmentNames << "EPA_L (Epaulette)"; compartmentNames << "VES_L (Vesta)"; compartmentNames << "ATL_L (Antler)"; compartmentNames << "PLP_L (Posterior Lateral Protocerebrum)"; compartmentNames << "AVLP_L (Anterior Ventro-lateral protocerebrum)"; compartmentNames << "AL_L (Antennal Lobe)"; compartmentNames << "GOR_L (Gorget)"; compartmentNames << "SCL_L (Superior Clamp)"; compartmentNames << "ICL_L (Inferior Clamp)"; compartmentNames << "ME_L (Medulla)"; compartmentNames << "LOP_L (Lobula Plate)"; compartmentNames << "LO_L (Lobula)"; compartmentNames << "MB_L (Mushroom Body)"; compartmentNames << "PVLP_L (Posterior Ventro-lateral Protocerebrum)"; compartmentNames << "OTU_L (Optic Tubercle)"; compartmentNames << "WED_L (Wedge)"; compartmentNames << "SMP_L (Superior Medial Protocerebrum)"; compartmentNames << "LH_L (Lateral Horn)"; compartmentNames << "SLP_L (Superior Lateral Protocerebrum)"; compartmentNames << "LB_L (Lateral Bulb)"; compartmentNames << "SIP_L (Superior Intermediate Protocerebrum)"; compartmentNames << "IB_L (Inferior Bridge)"; compartmentNames << "IVLP_L (Inferior Ventro-lateral Protocerebrum)"; compartmentNames << "IPS_L (Inferior Posterior Slope)"; compartmentNames << "SPS_L (Superior Posterior Slope)"; compartmentNames << "LAL_L (Lateral Accessory Lobe)"; compartmentNames << "AME_L (Accessory Medulla)"; compartmentNames << "GA_L (Gall)"; compartmentNames << "AMMC_L (Antennal Mechanosensory and Motor Centre)"; compartmentNames << "AMMC_R (Antennal Mechanosensory and Motor Centre)"; for (int i = 0; i < neuronGalleryButtonList.size(); ++ i) { if (i >= compartmentNames.size()) break; neuronGalleryButtonList[i]->setLabelText(compartmentNames[i]); } ui->fragmentGalleryWidget->updateNameSortTable(); } void NaMainWindow::updateNeuronGallery() { GalleryMipImages::Reader mipReader(dataFlowModel->getGalleryMipImages()); // acquire read lock if (! mipReader.hasReadLock()) return; NeuronSelectionModel::Reader selectionReader(dataFlowModel->getNeuronSelectionModel()); if (! selectionReader.hasReadLock()) return; if (neuronGalleryButtonList.size() != mipReader.getNumberOfNeurons()) initializeNeuronGallery(); else { for (int i = 0; i < mipReader.getNumberOfNeurons(); ++i) { neuronGalleryButtonList[i]->setThumbnailIcon(*mipReader.getNeuronMip(i)); neuronGalleryButtonList[i]->setChecked(selectionReader.getMaskStatusList().at(i)); neuronGalleryButtonList[i]->update(); } ui->fragmentGalleryWidget->updateButtonsGeometry(); } } void NaMainWindow::on3DViewerRotationChanged(const Rotation3D& rot) { Vector3D angles = rot.convertBodyFixedXYZRotationToThreeAngles(); int rotX = Na3DWidget::radToDeg(angles.x()); int rotY = Na3DWidget::radToDeg(angles.y()); int rotZ = Na3DWidget::radToDeg(angles.z()); int oldRotX = ui->rotXWidget->spinBox->value(); int oldRotY = ui->rotYWidget->spinBox->value(); int oldRotZ = ui->rotZWidget->spinBox->value(); if (Na3DWidget::eulerAnglesAreEquivalent(rotX, rotY, rotZ, oldRotX, oldRotY, oldRotZ)) return; // Block signals from individual rot widgets until we update them all ui->rotXWidget->blockSignals(true); ui->rotYWidget->blockSignals(true); ui->rotZWidget->blockSignals(true); ui->rotXWidget->setAngle(rotX); ui->rotYWidget->setAngle(rotY); ui->rotZWidget->setAngle(rotZ); ui->rotXWidget->blockSignals(false); ui->rotYWidget->blockSignals(false); ui->rotZWidget->blockSignals(false); } void NaMainWindow::update3DViewerXYZBodyRotation() { int rotX = ui->rotXWidget->spinBox->value(); int rotY = ui->rotYWidget->spinBox->value(); int rotZ = ui->rotZWidget->spinBox->value(); // qDebug() << rotX << ", " << rotY << ", " << rotZ; ui->v3dr_glwidget->setXYZBodyRotationInt(rotX, rotY, rotZ); } // update neuron selected status void NaMainWindow::synchronizeGalleryButtonsToAnnotationSession(QString updateString) { NeuronSelectionModel::Reader selectionReader( dataFlowModel->getNeuronSelectionModel()); if (! selectionReader.hasReadLock()) return; // We are not using the update string in this case, which is from the modelUpdated() signal, // because we are doing a total update. int maskStatusListSize=selectionReader.getMaskStatusList().size(); int neuronGalleryButtonSize=neuronGalleryButtonList.size(); assert(neuronGalleryButtonSize == maskStatusListSize); for (int i = 0; i < maskStatusListSize; i++) { neuronGalleryButtonList.at(i)->setChecked( selectionReader.neuronMaskIsChecked(i)); } // Reference toggle if (selectionReader.getOverlayStatusList().at(DataFlowModel::REFERENCE_MIP_INDEX)) { overlayGalleryButtonList.at(DataFlowModel::REFERENCE_MIP_INDEX)->setChecked(true); } else { overlayGalleryButtonList.at(DataFlowModel::REFERENCE_MIP_INDEX)->setChecked(false); } // Background toggle if (selectionReader.getOverlayStatusList().at(DataFlowModel::BACKGROUND_MIP_INDEX)) { overlayGalleryButtonList.at(DataFlowModel::BACKGROUND_MIP_INDEX)->setChecked(true); } else { overlayGalleryButtonList.at(DataFlowModel::BACKGROUND_MIP_INDEX)->setChecked(false); } } /* slot */ void NaMainWindow::setProgressValue(int progressValueParam) { if (progressValueParam >= 100) { completeProgress(); return; } statusProgressBar->setValue(progressValueParam); statusProgressBar->show(); } /* slot */ void NaMainWindow::setProgressMessage(QString msg) { statusBar()->showMessage(""); // avoid overlap of temporary messages with progress message statusProgressMessage->setText(msg); statusProgressMessage->show(); } /* slot */ void NaMainWindow::completeProgress() { statusProgressBar->hide(); statusProgressMessage->hide(); statusBar()->showMessage("", 500); } /* slot */ void NaMainWindow::abortProgress(QString msg) { statusProgressBar->hide(); statusProgressMessage->hide(); statusBar()->showMessage(msg, 1000); } static const bool use3DProgress = false; void NaMainWindow::set3DProgress(int prog) { if (prog >= 100) { complete3DProgress(); return; } if (use3DProgress) { ui->progressBar3d->setValue(prog); // ui->v3dr_glwidget->setResizeEnabled(false); // don't show ugly brief resize behavior ui->widget_progress3d->show(); } else setProgressValue(prog); } void NaMainWindow::complete3DProgress() { if (use3DProgress) { ui->widget_progress3d->hide(); // avoid jerky resize to accomodated progress widget QCoreApplication::processEvents(); // flush pending resize events ui->v3dr_glwidget->resizeEvent(NULL); ui->v3dr_glwidget->setResizeEnabled(true); // ui->v3dr_glwidget->update(); } else completeProgress(); } void NaMainWindow::set3DProgressMessage(QString msg) { if (use3DProgress) { ui->progressLabel3d->setText(msg); ui->v3dr_glwidget->setResizeEnabled(false); // don't show ugly brief resize behavior ui->widget_progress3d->show(); } else setProgressMessage(msg); } char* NaMainWindow::getConsoleURL() { return consoleUrl; } // NutateThread
37.425824
208
0.672696
hanchuan
ae223da69d12a8042f518d725fe23972111e156a
580
cpp
C++
contest/AOJ/0035.cpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
7
2018-04-14T14:55:51.000Z
2022-01-31T10:49:49.000Z
contest/AOJ/0035.cpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
5
2018-04-14T14:28:49.000Z
2019-05-11T02:22:10.000Z
contest/AOJ/0035.cpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
null
null
null
#include "geometry/polygon.hpp" #include "string.hpp" int main() { setBoolName("YES", "NO"); for (String line; line = in, !in.eof;) { auto v = line.split(',').transform(cast<String, long double>()); Polygon polygon(4); for (int i = 0; i < 4; ++i) { polygon[i] = Point(v[2 * i], v[2 * i + 1]); } if (polygon.area() < 0) { polygon.reverse(); } auto is_convex = [](const Vector<Point> &corner) { return ccw(Segment(corner[0], corner[1]), corner[2]) != RIGHT; }; cout << polygon.getCorners().all_of(is_convex) << endl; } }
27.619048
68
0.555172
not522
ae264600552d13c8335eae879cf3250abfc1074d
5,203
cpp
C++
ass2/Ass2_3.cpp
krishna-akula/OSLab
09ea00eb9b346a2a51b39a0948d05b4f3b414342
[ "MIT" ]
null
null
null
ass2/Ass2_3.cpp
krishna-akula/OSLab
09ea00eb9b346a2a51b39a0948d05b4f3b414342
[ "MIT" ]
null
null
null
ass2/Ass2_3.cpp
krishna-akula/OSLab
09ea00eb9b346a2a51b39a0948d05b4f3b414342
[ "MIT" ]
null
null
null
#include<unistd.h> #include<stdlib.h> #include<fcntl.h> #include<stdio.h> #include<sys/types.h> #include<sys/wait.h> #include<sys/stat.h> #include<string> #include<cstring> #include<sstream> #include<vector> #include<iostream> using namespace std; struct cmd_info{ int type; string infilename,outfilename,filename; string cmd; string fcmd; string path; char *argv[1024]; int size; cmd_info() { size=0; } }; void run_internal_cmd(cmd_info &rd) { int status=-1; if(rd.fcmd=="mkdir") { status=mkdir((rd.path).c_str(),0777); } else if(rd.fcmd=="rm") { status=rmdir((rd.path).c_str()); } else if(rd.fcmd=="cd") { char cwd[256]; getcwd(cwd,sizeof(cwd)); cout<<"Original directory:\t"<<cwd<<"\n"; status=chdir((rd.path).c_str()); getcwd(cwd,sizeof(cwd)); cout<<"Changed directory:\t"<<cwd<<"\n"; } if(status==-1) cout<<"enter correct command\n"; else cout<<"command executed successfully\n"; } void run_exec(cmd_info &rd) { pid_t id_child; int cstatus=0; pid_t c; int in,out; id_child=fork(); if(id_child==0) { if(rd.type==3) { in = open(rd.filename.c_str(), O_RDONLY); dup2(in,0); } else if(rd.type==4) { out = open(rd.filename.c_str(), O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IRGRP | S_IWGRP | S_IWUSR); dup2(out,1); } // execlp("/bin/sh",argc); // if(rd.type==5) // { // //setpgid(0,0); // fclose(stdin); // } // setpgid(0,0); execvp((rd.cmd).c_str(),rd.argv); cout<<"Child process could not do execlp.\n";//error if the child process is not executed exit(2); } else if(id_child==-1) { //if forking is failed cout<<"Fork failed\n"; } else { if(rd.type==5) waitpid(id_child,&cstatus,WNOHANG); else waitpid(id_child,&cstatus,0); } } void get_tokens(cmd_info &rd,string command_line) { istringstream iss(command_line); string word; iss>>rd.cmd; if((rd.cmd).size()>0){ rd.argv[rd.size]=new char[(rd.cmd).length()+1]; strcpy(rd.argv[rd.size],(rd.cmd).c_str()); rd.size++; } else rd.cmd=" "; while(iss >> word) { if(word==">" or word=="<") { iss>>rd.filename; rd.type=word==">"?4:3; break; } else if(word=="&") { break; } rd.argv[rd.size]=new char[word.length()+1]; strcpy(rd.argv[rd.size],word.c_str()); rd.size++; } if(rd.size==0) { rd.argv[0]=" "; rd.size++; } rd.argv[rd.size]='\0'; } void connect_cmds(int in,int out,cmd_info & rd,int last) { pid_t id_child; pid_t c; int cstatus; id_child=fork(); if(id_child==0) { if(in!=0) { dup2(in,0); close(in); } if(out!=1 and !last) { // close(in); dup2(out,1); close(out); } execvp((rd.cmd).c_str(),rd.argv); cout<<" chld process could not be constructed\n"; exit(1); } else { c=wait(&cstatus); close(in); close(out); return; } } void run_pipe_cmds(vector<cmd_info> &rds) { int n=rds.size(); int pipes[n-1][2]; int in=0; // pipe(pipes); int stdo,stdi; stdi=dup(0); stdo=dup(1); for(int i=0;i<n-1;i++) { pipe(pipes[i]); } for(int i=0;i<n;i++) { if(i==n-1) { connect_cmds(in,1,rds[i],1); dup2(stdi,0); dup2(stdo,1); } else { dup2(in,0); connect_cmds(in,pipes[i][1],rds[i],0); in = pipes[i][0]; } } } int main() { cout<<"----------------------------------------------------------------------------------------------\n"; cout<<"select the option for excecution\n"; cout<<"1.\tInternal command\n"; cout<<"2:\tExternal command\n"; cout<<"3:\tExternal command by redirectting standard input\n"; cout<<"4:\tExternal command by redirectting standard output\n"; cout<<"5:\tExternal command in the background\n"; cout<<"6:\tExternal command by for pipelining execution\n"; cout<<"7:\tQuit the program\n"; while(1) { int choice; pid_t par; par=getpid(); cmd_info rd; cout<<">option\t\t:"; cin>>choice; cout<<"\n"; if(choice<1 or choice>=7) break; string command_line,word; cin.ignore(256, '\n'); cout<<">command\t:"; getline(cin,command_line); cout<<"\n"; rd.type=choice; if(choice==1) { istringstream iss(command_line); iss>>rd.fcmd; iss>>rd.path; run_internal_cmd(rd); } else if( (choice>=2 and choice <=4) or choice==5) { get_tokens(rd,command_line); run_exec(rd); } else if(choice==6) { vector<string>pipe_cmds; string delim="|"; size_t pos = 0; string token; while ((pos = command_line.find(delim)) != string::npos) { token = command_line.substr(0, pos); pipe_cmds.push_back(token); command_line.erase(0, pos + delim.length()); } if(command_line.size()!=0) { pipe_cmds.push_back(command_line); } vector< cmd_info >rds(pipe_cmds.size()); for(int i=0;i<pipe_cmds.size();i++) { rds[i].type=2; get_tokens(rds[i],pipe_cmds[i]); } // cout<<rds.size()<<endl; run_pipe_cmds(rds); } if(getpid()!=par) { exit(1); } } }
17.171617
106
0.55641
krishna-akula
ae26a8066b1380a0d36c6e3d5e87ca7977f0762f
506
cpp
C++
6.ExceptionHandling/i-Assess/HallBookingBO.cpp
Concept-Team/e-box-UTA018
a6caf487c9f27a5ca30a00847ed49a163049f67e
[ "MIT" ]
26
2021-03-17T03:15:22.000Z
2021-06-09T13:29:41.000Z
6.ExceptionHandling/i-Assess/HallBookingBO.cpp
Servatom/e-box-UTA018
a6caf487c9f27a5ca30a00847ed49a163049f67e
[ "MIT" ]
6
2021-03-16T19:04:05.000Z
2021-06-03T13:41:04.000Z
6.ExceptionHandling/i-Assess/HallBookingBO.cpp
Concept-Team/e-box-UTA018
a6caf487c9f27a5ca30a00847ed49a163049f67e
[ "MIT" ]
42
2021-03-17T03:16:22.000Z
2021-06-14T21:11:20.000Z
#include<iostream> #include<list> #include"HallBooking.cpp" #include<iterator> using namespace std; class HallBookingBO{ public: bool validateHallBooking(list<HallBooking> lst,HallBooking hallObj){ try{ for(HallBooking h: lst){ if(h.getHall()==hallObj.getHall()&&h.getDateOfBooking()==hallObj.getDateOfBooking()){ throw 1; } } }catch(...){ return false; } return true; } };
24.095238
101
0.551383
Concept-Team
ae2a6ab82e3b1a653467db1256731298173dee6a
268
cpp
C++
LastHope Engine/Component.cpp
rohomedesrius/LastHopeEngine
5a73a0a3cf00fbcd2fa48f0ec1ce2c9bc1057bc0
[ "MIT" ]
1
2018-10-03T14:01:40.000Z
2018-10-03T14:01:40.000Z
LastHope Engine/Component.cpp
rohomedesrius/LastHopeEngine
5a73a0a3cf00fbcd2fa48f0ec1ce2c9bc1057bc0
[ "MIT" ]
null
null
null
LastHope Engine/Component.cpp
rohomedesrius/LastHopeEngine
5a73a0a3cf00fbcd2fa48f0ec1ce2c9bc1057bc0
[ "MIT" ]
null
null
null
#include "Component.h" GameObject* Component::GetGameObject() const { return game_object; } bool Component::IsActive() const { return active; } void Component::SetActive(bool value) { active = value; } ComponentType Component::GetType() const { return type; }
12.181818
44
0.727612
rohomedesrius
ae2c515406c9ae9c65d4a3b150e08c2c989fafc9
2,598
hpp
C++
include/multi_sync_replayer.hpp
dabinkim-LGOM/lsc_planner
88dcb1de59bac810d1b1fd194fe2b8d24d1860c9
[ "MIT" ]
9
2021-09-04T15:14:57.000Z
2022-03-29T04:34:13.000Z
include/multi_sync_replayer.hpp
dabinkim-LGOM/lsc_planner
88dcb1de59bac810d1b1fd194fe2b8d24d1860c9
[ "MIT" ]
null
null
null
include/multi_sync_replayer.hpp
dabinkim-LGOM/lsc_planner
88dcb1de59bac810d1b1fd194fe2b8d24d1860c9
[ "MIT" ]
4
2021-09-29T11:32:54.000Z
2022-03-06T05:24:33.000Z
#pragma once #include <ros/ros.h> #include <param.hpp> #include <mission.hpp> #include <obstacle_generator.hpp> #include <visualization_msgs/MarkerArray.h> #include <std_msgs/Float64.h> #include <std_msgs/Float64MultiArray.h> #include <util.hpp> namespace DynamicPlanning { class MultiSyncReplayer { public: MultiSyncReplayer(const ros::NodeHandle& _nh, Param _param, Mission _mission); void initializeReplay(); void replay(double t); void readCSVFile(const std::string& file_name); void setOctomap(std::string file_name); private: ros::NodeHandle nh; ros::Publisher pub_agent_trajectories; ros::Publisher pub_obstacle_trajectories; ros::Publisher pub_collision_model; ros::Publisher pub_start_goal_points; // ros::Publisher pub_safety_margin_to_agents; // ros::Publisher pub_safety_margin_to_obstacles; ros::Publisher pub_agent_velocities_x; ros::Publisher pub_agent_velocities_y; ros::Publisher pub_agent_velocities_z; ros::Publisher pub_agent_accelerations_x; ros::Publisher pub_agent_accelerations_y; ros::Publisher pub_agent_accelerations_z; ros::Publisher pub_agent_vel_limits; ros::Publisher pub_agent_acc_limits; ros::Publisher pub_world_boundary; ros::Publisher pub_collision_alert; Param param; Mission mission; std::shared_ptr<DynamicEDTOctomap> distmap_obj; ObstacleGenerator obstacle_generator; visualization_msgs::MarkerArray msg_agent_trajectories_replay; visualization_msgs::MarkerArray msg_obstacle_trajectories_replay; std::vector<std::vector<State>> agent_state_history; std::vector<std::vector<State>> obstacle_state_history; // std_msgs::Float64MultiArray safety_margin_to_agents_replay; // std_msgs::Float64MultiArray safety_margin_to_obstacles_replay; // std::vector<std::vector<double>> safety_margin_to_agents_history; // std::vector<std::vector<double>> safety_margin_to_obstacles_history; double timeStep, makeSpan; void doReplay(double t); void publish_agent_trajectories(double t); void publish_obstacle_trajectories(double t); void publish_collision_model(); void publish_start_goal_points(); // void publish_safety_margin(double t); void publish_collision_alert(); void publish_agent_vel_acc(double t); static std::vector<std::string> csv_read_row(std::istream& in, char delimiter); }; }
33.307692
87
0.711316
dabinkim-LGOM
ae2d3ee25a6ac1b5bde055317dabe97eabc70e44
1,764
cpp
C++
CF R405/B.cpp
parthlathiya/Codeforces_Submissions
6c8f40dbeea31a3c3c7d37b799b78f6af4bbcf68
[ "MIT" ]
null
null
null
CF R405/B.cpp
parthlathiya/Codeforces_Submissions
6c8f40dbeea31a3c3c7d37b799b78f6af4bbcf68
[ "MIT" ]
null
null
null
CF R405/B.cpp
parthlathiya/Codeforces_Submissions
6c8f40dbeea31a3c3c7d37b799b78f6af4bbcf68
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define forall(i,a,b) for(int i=a;i<b;i++) #define ll long long int #define llu long long unsigned #define vll vector<ll> #define vllu vector<llu> #define sll set<ll> #define sllu set<llu> #define pb push_back #define mll map<ll,ll> #define mllu map<llu,llu> #define miN(a,b) ( (a) < (b) ? (a) : (b)) #define maX(a,b) ( (a) > (b) ? (a) : (b)) #define mod 1000000007 int main() { #ifndef ONLINE_JUDGE freopen("B_in.txt","r",stdin); #endif int n,m; cin>>n>>m; int a[n][n]; forall(i,0,n) forall(j,0,n) a[i][j]=0; forall(i,0,m) { ll p, q; cin>>p>>q; a[p-1][q-1]=1; } int c[n][n]; forall(i,0,n) { forall(j,0,n) { c[i][j]=0; forall(k,0,n){ c[i][j]=c[i][j]+(a[i][k]*a[k][j]); if(c[i][j]>0) break; } } } int ans=1; int i,j; // for(i=0;i<n;++i) // { // for(j=0;j<n;++j) // { // cout<<a[i][j]<<" "; // } // cout<<"\n"; // } // for(i=0;i<n;++i) // { // for(j=0;j<n;++j) // { // cout<<c[i][j]<<" "; // } // cout<<"\n"; // } forall(i,0,n) { forall(j,0,n) { if(c[i][j]>0 && a[i][j]!=1) { ans=0; break; } } if(!ans)break; } if(ans) cout<<"YES"; else cout<<"NO"; return 0; }
19.173913
61
0.3322
parthlathiya
ae2d8775f8329e8e9c17bff4ec195a3d69b6d59f
32,224
cpp
C++
DRE2008OS_plugins/DRE2008_OS_Callback.cpp
GreatCong/GUI_EC_PluginSrc
9194e67b76f3707f782f1fc17ba6e6dcb712c2a5
[ "MIT" ]
1
2019-12-25T13:36:01.000Z
2019-12-25T13:36:01.000Z
DRE2008OS_plugins/DRE2008_OS_Callback.cpp
GreatCong/GUI_EC_PluginSrc
9194e67b76f3707f782f1fc17ba6e6dcb712c2a5
[ "MIT" ]
null
null
null
DRE2008OS_plugins/DRE2008_OS_Callback.cpp
GreatCong/GUI_EC_PluginSrc
9194e67b76f3707f782f1fc17ba6e6dcb712c2a5
[ "MIT" ]
1
2020-08-05T14:05:15.000Z
2020-08-05T14:05:15.000Z
#include "DRE2008_OS_Callback.h" #include <QDebug> //int slave_num = 1; //int16_t Normal_AD_Input[8] = { 0,0,0,0,0,0,0,0 }; char file[500]; //需要保存数据的文件 DRE2008_OS_Callback::DRE2008_OS_Callback(QObject *parent) : QObject(parent),Ethercat_Callback() { m_isOS_Reset = false;//超采样初始化 m_isOS_Run = false; pre_OverSampling_CycleCount = 0; output_ptr = nullptr; input_ptr = nullptr; m_measure_Q = new QQueue<int16_t>(); m_OS_Channel = OS_CH1; //超采样通道设置 m_SamplingRate = 20; //采样率设置(最大40Khz) m_AD_Channel = AD_CH1; m_ErrState = Error_None; memset(m_Normal_AD_Input,0,sizeof(m_Normal_AD_Input)); } void DRE2008_OS_Callback::Master_AppLoop_callback() { static int reset_num = 0; if(m_isOS_Run){ if(!m_isOS_Reset){//这里貌似是需要按顺序执行,稍后再改 //超采样设置 if(reset_num < 3){//先Reset,再进行其他操作 reset_num++; // DRE2008_OS_Reset(slave_num); //DRE2008-OS复位(禁止超采样) // pre_OverSampling_CycleCount = 0; DRE2008_OS_Reset(output_ptr); //DRE2008-OS复位(禁止超采样) pre_OverSampling_CycleCount = 0; } else{ DRE2008_OS_SamplingRateSet(output_ptr, m_SamplingRate); //设置采样率 DRE2008_OS_Enable(output_ptr, m_OS_Channel); //设置超采样通道并使能超采样 m_isOS_Reset = true; reset_num = 0; } } else{ DRE2008_OS_NormalInputRead(input_ptr, m_Normal_AD_Input); //普通模式数据采集 // qDebug() << Normal_AD_Input[0]; m_ErrState = DRE2008_OS_OverSamplingInputLog(input_ptr, m_OS_Channel, 0, file, m_AD_Channel); //超采样数据log // if(m_ErrState != Error_None){ // qDebug() << m_ErrState; // } } } else{ pre_OverSampling_CycleCount = 0; DRE2008_OS_SamplingRateSet(output_ptr, 50); DRE2008_OS_Disable(output_ptr); // printf("required %d data log complete!\n", num_of_samples); // TestKillTimer(1); } } void DRE2008_OS_Callback::Master_AppStart_callback() { // qDebug() << "Index1:" << this->Master_getSlaveChooseIndex(); output_ptr = (uint8_t *)(m_Master_addressBase + this->Master_getAddressList().at(this->Master_getSlaveChooseIndex()).outputs_offset);//这里需要根据扫描到的地址替换 input_ptr = (uint8_t *)(m_Master_addressBase + this->Master_getAddressList().at(this->Master_getSlaveChooseIndex()).inputs_offset); m_isOS_Reset = false;//超采样初始化 pre_OverSampling_CycleCount = 0;//超采样获取中的参数 m_isOS_Run = false; // initQueue(&my_ecQueue.my_ecQueue_ch1); m_measure_Q->clear(); emit Master_RunStateChanged(true); } void DRE2008_OS_Callback::Master_AppStop_callback() { m_isOS_Reset = false;//超采样初始化 m_isOS_Run = false; // clearQueue(&my_ecQueue.my_ecQueue_ch1); m_measure_Q->clear(); emit Master_RunStateChanged(false); } void DRE2008_OS_Callback::Master_AppScan_callback() { emit Sig_MasterScanChanged(); } void DRE2008_OS_Callback::Master_ReleaseAddress() { m_Master_addressBase = NULL; output_ptr = NULL; input_ptr = NULL; } int DRE2008_OS_Callback::Master_setAdressBase(char *address) { m_Master_addressBase = address; return 0; } void DRE2008_OS_Callback::Set_OverSampling_run(bool isRun) { m_isOS_Run = isRun; } void DRE2008_OS_Callback::Set_OverSampling_Reset(bool isReset) { m_isOS_Reset = isReset; } const QString DRE2008_OS_Callback::ErrorState_ToString() { QString str; switch(m_ErrState){ case Error_None: str = "Error_None"; break; case Error_NoFile: str = "Error_NoFile"; break; case Error_File_WriteOver: str = "Error_File_WriteOver"; break; case Error_TimeOut: str = "Error_TimeOut"; break; case Error_Channel_Invalid: str = "Error_Channel_Invalid"; break; default: str = "ErrorCode:"+QString::number(m_ErrState); break; } return str; } /* DRE2008 */ void DRE2008_OS_Callback::DRE2008_OS_Reset(uint8_t *data_OutPtr) { // int i = 0; DRE2008_OS_SamplingRateSet(data_OutPtr, 50); DRE2008_OS_Disable(data_OutPtr); // while(i < 50) // { // ec_send_processdata(); // ec_receive_processdata(EC_TIMEOUTRET); // osal_usleep(2000); // i++; // } // printf("RESET OVER......\n"); // qDebug() << "RESET OVER......"; } void DRE2008_OS_Callback::DRE2008_OS_SamplingRateSet(uint8_t *data_Outptr, int SamplingRate) { uint8_t *data_out; // data_out = ec_slave[slave_num].outputs; data_out = data_Outptr; *data_out++ = SamplingRate & 0xFF; *data_out++ = SamplingRate >> 8; } void DRE2008_OS_Callback::DRE2008_OS_Enable(uint8_t *data_Outptr, int channel) { uint8_t *data_out; // data_out = ec_slave[slave_num].outputs; data_out = data_Outptr; *data_out++; *data_out++; *data_out++ = channel & 0xFF; *data_out++ = channel >> 8; } void DRE2008_OS_Callback::DRE2008_OS_Disable(uint8_t *data_Outptr) { uint8_t *data_out; int channel = OS_NONE; // data_out = ec_slave[slave_num].outputs; data_out = data_Outptr; *data_out++; *data_out++; *data_out++ = channel & 0xFF; *data_out++ = channel >> 8; } void DRE2008_OS_Callback::DRE2008_OS_NormalInputRead(uint8_t *data_Inptr, int16_t *NormalInput) { uint8_t *data_in; int16_t temp1, temp2; // data_in = ec_slave[slave_num].inputs; data_in = data_Inptr; temp1 = *data_in++; temp2 = *data_in++; NormalInput[0] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; NormalInput[1] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; NormalInput[2] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; NormalInput[3] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; NormalInput[4] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; NormalInput[5] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; NormalInput[6] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; NormalInput[7] = temp1 + (temp2 << 8); } void DRE2008_OS_Callback::DRE2008_OS_OverSamplingInputRead(uint8_t *data_Inptr, int32_t *CycleCount, int16_t *OverSamplingInput) { uint8_t *data_in; int16_t temp1, temp2, temp3, temp4; // data_in = ec_slave[slave_num].inputs; data_in = data_Inptr; *data_in++; *data_in++; *data_in++; *data_in++; *data_in++; *data_in++; *data_in++; *data_in++; *data_in++; *data_in++; *data_in++; *data_in++; *data_in++; *data_in++; *data_in++; *data_in++; *data_in++; *data_in++; temp1 = *data_in++; temp2 = *data_in++; temp3 = *data_in++; temp4 = *data_in++; *CycleCount = temp1 + (temp2 << 8) + (temp3 << 16) + (temp4 << 24); temp1 = *data_in++; temp2 = *data_in++; OverSamplingInput[0] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; OverSamplingInput[1] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; OverSamplingInput[2] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; OverSamplingInput[3] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; OverSamplingInput[4] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; OverSamplingInput[5] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; OverSamplingInput[6] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; OverSamplingInput[7] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; OverSamplingInput[8] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; OverSamplingInput[9] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; OverSamplingInput[10] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; OverSamplingInput[11] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; OverSamplingInput[12] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; OverSamplingInput[13] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; OverSamplingInput[14] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; OverSamplingInput[15] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; OverSamplingInput[16] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; OverSamplingInput[17] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; OverSamplingInput[18] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; OverSamplingInput[19] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; OverSamplingInput[20] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; OverSamplingInput[21] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; OverSamplingInput[22] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; OverSamplingInput[23] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; OverSamplingInput[24] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; OverSamplingInput[25] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; OverSamplingInput[26] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; OverSamplingInput[27] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; OverSamplingInput[28] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; OverSamplingInput[29] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; OverSamplingInput[30] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; OverSamplingInput[31] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; OverSamplingInput[32] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; OverSamplingInput[33] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; OverSamplingInput[34] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; OverSamplingInput[35] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; OverSamplingInput[36] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; OverSamplingInput[37] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; OverSamplingInput[38] = temp1 + (temp2 << 8); temp1 = *data_in++; temp2 = *data_in++; OverSamplingInput[39] = temp1 + (temp2 << 8); } int DRE2008_OS_Callback::DRE2008_OS_OverSamplingInputLog(uint8_t *data_Inptr, int channel, int num_of_samples, char *file, int dis_channel) { // FILE *fpWrite; (void*)(&num_of_samples); (void*)file; int32_t OverSampling_CycleCount = 0; int16_t OverSampling_AD_Input[40] = { 0 }; // static int32_t pre_OverSampling_CycleCount = 0; int circlecount_error = 3;//当前周期读取到的circlrcount与上一周期的差值,理论为1,将该值设置大于1可提高容错率但会造成部分数据丢失 int ret = Error_None; // int channelDis_temp = 0; // channelDis_temp = dis_channel -1;//C语言数组从0开始,而参数是从1开始 int channelDis_temp = dis_channel;//dis_channel本身从0开始 DRE2008_OS_OverSamplingInputRead(data_Inptr, &OverSampling_CycleCount, OverSampling_AD_Input);//读取40个数据 switch (channel) { case OS_CH1://CH1超采样 { if((OverSampling_CycleCount > pre_OverSampling_CycleCount) && ((OverSampling_CycleCount - pre_OverSampling_CycleCount) < circlecount_error + 1)) { // printf("CycleCount: %d PreCycleCount: %d\n", OverSampling_CycleCount, pre_OverSampling_CycleCount); pre_OverSampling_CycleCount = OverSampling_CycleCount; // fpWrite = fopen(file, "a+"); // if (fpWrite == NULL) // { // return Error_NoFile; // } // fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 1, OverSampling_AD_Input[0]); // fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 2, OverSampling_AD_Input[1]); // fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 3, OverSampling_AD_Input[2]); // fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 4, OverSampling_AD_Input[3]); // fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 5, OverSampling_AD_Input[4]); // fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 6, OverSampling_AD_Input[5]); // fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 7, OverSampling_AD_Input[6]); // fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 8, OverSampling_AD_Input[7]); // fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 9, OverSampling_AD_Input[8]); // fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 10, OverSampling_AD_Input[9]); // fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 11, OverSampling_AD_Input[10]); // fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 12, OverSampling_AD_Input[11]); // fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 13, OverSampling_AD_Input[12]); // fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 14, OverSampling_AD_Input[13]); // fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 15, OverSampling_AD_Input[14]); // fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 16, OverSampling_AD_Input[15]); // fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 17, OverSampling_AD_Input[16]); // fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 18, OverSampling_AD_Input[17]); // fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 19, OverSampling_AD_Input[18]); // fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 20, OverSampling_AD_Input[19]); // fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 21, OverSampling_AD_Input[20]); // fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 22, OverSampling_AD_Input[21]); // fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 23, OverSampling_AD_Input[22]); // fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 24, OverSampling_AD_Input[23]); // fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 25, OverSampling_AD_Input[24]); // fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 26, OverSampling_AD_Input[25]); // fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 27, OverSampling_AD_Input[26]); // fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 28, OverSampling_AD_Input[27]); // fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 29, OverSampling_AD_Input[28]); // fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 30, OverSampling_AD_Input[29]); // fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 31, OverSampling_AD_Input[30]); // fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 32, OverSampling_AD_Input[31]); // fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 33, OverSampling_AD_Input[32]); // fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 34, OverSampling_AD_Input[33]); // fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 35, OverSampling_AD_Input[34]); // fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 36, OverSampling_AD_Input[35]); // fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 37, OverSampling_AD_Input[36]); // fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 38, OverSampling_AD_Input[37]); // fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 39, OverSampling_AD_Input[38]); // fprintf(fpWrite, "%d %d\n", (OverSampling_CycleCount - 1) * 40 + 40, OverSampling_AD_Input[39]); // fclose(fpWrite); if(channelDis_temp < 1){ for(int index=0,loop_num = 0;loop_num < 40;index++,loop_num++){ m_measure_Q->enqueue(OverSampling_AD_Input[index]); // enQueue(&my_ecQueue.my_ecQueue_ch1, OverSampling_AD_Input[index]); // qDebug() << OverSampling_AD_Input[index]; // enQueue(&my_ecQueue.my_ecQueue_ch2, OverSampling_AD_Input[index]); } } else { ret = Error_Channel_Invalid;//通道不匹配 } // if (((OverSampling_CycleCount - 1) * 40 + 40) >= num_of_samples) // { // pre_OverSampling_CycleCount = 0; // DRE2008_OS_SamplingRateSet(slave_num, 50); // DRE2008_OS_Disable(slave_num); // printf("required %d data log complete!\n", num_of_samples); // ret = Error_File_WriteOver;//表示满了 // } } else{ ret = Error_TimeOut; } break; } case OS_CH1_CH2://CH1-CH2超采样 { if ((OverSampling_CycleCount > pre_OverSampling_CycleCount) && ((OverSampling_CycleCount - pre_OverSampling_CycleCount) < circlecount_error + 1)) { // printf("CycleCount: %d PreCycleCount: %d\n", OverSampling_CycleCount, pre_OverSampling_CycleCount); pre_OverSampling_CycleCount = OverSampling_CycleCount; // fpWrite = fopen(file, "a+"); // if (fpWrite == NULL) // { // return Error_NoFile; // } // fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 1, OverSampling_AD_Input[0], OverSampling_AD_Input[20]); // fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 2, OverSampling_AD_Input[1], OverSampling_AD_Input[21]); // fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 3, OverSampling_AD_Input[2], OverSampling_AD_Input[22]); // fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 4, OverSampling_AD_Input[3], OverSampling_AD_Input[23]); // fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 5, OverSampling_AD_Input[4], OverSampling_AD_Input[24]); // fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 6, OverSampling_AD_Input[5], OverSampling_AD_Input[25]); // fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 7, OverSampling_AD_Input[6], OverSampling_AD_Input[26]); // fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 8, OverSampling_AD_Input[7], OverSampling_AD_Input[27]); // fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 9, OverSampling_AD_Input[8], OverSampling_AD_Input[28]); // fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 10, OverSampling_AD_Input[9], OverSampling_AD_Input[29]); // fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 11, OverSampling_AD_Input[10], OverSampling_AD_Input[30]); // fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 12, OverSampling_AD_Input[11], OverSampling_AD_Input[31]); // fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 13, OverSampling_AD_Input[12], OverSampling_AD_Input[32]); // fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 14, OverSampling_AD_Input[13], OverSampling_AD_Input[33]); // fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 15, OverSampling_AD_Input[14], OverSampling_AD_Input[34]); // fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 16, OverSampling_AD_Input[15], OverSampling_AD_Input[35]); // fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 17, OverSampling_AD_Input[16], OverSampling_AD_Input[36]); // fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 18, OverSampling_AD_Input[17], OverSampling_AD_Input[37]); // fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 19, OverSampling_AD_Input[18], OverSampling_AD_Input[38]); // fprintf(fpWrite, "%d %d %d\n", (OverSampling_CycleCount - 1) * 20 + 20, OverSampling_AD_Input[19], OverSampling_AD_Input[39]); // fclose(fpWrite); // if (((OverSampling_CycleCount - 1) * 20 + 20) >= num_of_samples) // { // pre_OverSampling_CycleCount = 0; // DRE2008_OS_SamplingRateSet(slave_num, 50); // DRE2008_OS_Disable(slave_num); // printf("required %d data log complete!\n", num_of_samples); // ret = Error_File_WriteOver; // } if(channelDis_temp < 2){ for(int index = channelDis_temp*20,loop_num = 0;loop_num < 20;index++,loop_num++){ // enQueue(&my_ecQueue.my_ecQueue_ch1, OverSampling_AD_Input[index]); m_measure_Q->enqueue(OverSampling_AD_Input[index]); // enQueue(&my_ecQueue.my_ecQueue_ch2, OverSampling_AD_Input[index]); } } else { ret = Error_Channel_Invalid; } } else{ ret = Error_TimeOut; } break; } case OS_CH1_CH4://CH1-CH4超采样 { if ((OverSampling_CycleCount > pre_OverSampling_CycleCount) && ((OverSampling_CycleCount - pre_OverSampling_CycleCount) < circlecount_error + 1)) { // printf("CycleCount: %d PreCycleCount: %d\n", OverSampling_CycleCount, pre_OverSampling_CycleCount); pre_OverSampling_CycleCount = OverSampling_CycleCount; // fpWrite = fopen(file, "a+"); // if (fpWrite == NULL) // { // return -1; // } // fprintf(fpWrite, "%d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 10 + 1, OverSampling_AD_Input[0], OverSampling_AD_Input[10], \ // OverSampling_AD_Input[20], OverSampling_AD_Input[30]); // fprintf(fpWrite, "%d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 10 + 2, OverSampling_AD_Input[1], OverSampling_AD_Input[11], \ // OverSampling_AD_Input[21], OverSampling_AD_Input[31]); // fprintf(fpWrite, "%d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 10 + 3, OverSampling_AD_Input[2], OverSampling_AD_Input[12], \ // OverSampling_AD_Input[22], OverSampling_AD_Input[32]); // fprintf(fpWrite, "%d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 10 + 4, OverSampling_AD_Input[3], OverSampling_AD_Input[13], \ // OverSampling_AD_Input[23], OverSampling_AD_Input[33]); // fprintf(fpWrite, "%d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 10 + 5, OverSampling_AD_Input[4], OverSampling_AD_Input[14], \ // OverSampling_AD_Input[24], OverSampling_AD_Input[34]); // fprintf(fpWrite, "%d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 10 + 6, OverSampling_AD_Input[5], OverSampling_AD_Input[15], \ // OverSampling_AD_Input[25], OverSampling_AD_Input[35]); // fprintf(fpWrite, "%d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 10 + 7, OverSampling_AD_Input[6], OverSampling_AD_Input[16], \ // OverSampling_AD_Input[26], OverSampling_AD_Input[36]); // fprintf(fpWrite, "%d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 10 + 8, OverSampling_AD_Input[7], OverSampling_AD_Input[17], \ // OverSampling_AD_Input[27], OverSampling_AD_Input[37]); // fprintf(fpWrite, "%d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 10 + 9, OverSampling_AD_Input[8], OverSampling_AD_Input[18], \ // OverSampling_AD_Input[28], OverSampling_AD_Input[38]); // fprintf(fpWrite, "%d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 10 + 10, OverSampling_AD_Input[9], OverSampling_AD_Input[19], \ // OverSampling_AD_Input[29], OverSampling_AD_Input[39]); // fclose(fpWrite); if(channelDis_temp < 4){ for(int index = channelDis_temp*10,loop_num = 0;loop_num < 10;index++,loop_num++){ // enQueue(&my_ecQueue.my_ecQueue_ch1, OverSampling_AD_Input[index]); m_measure_Q->enqueue(OverSampling_AD_Input[index]); // enQueue(&my_ecQueue.my_ecQueue_ch2, OverSampling_AD_Input[index]); } } else{ ret = Error_Channel_Invalid; } // if (((OverSampling_CycleCount - 1) * 10 + 10) >= num_of_samples) // { // pre_OverSampling_CycleCount = 0; // DRE2008_OS_SamplingRateSet(slave_num, 50); // DRE2008_OS_Disable(slave_num); // printf("required %d data log complete!\n", num_of_samples); // ret = Error_File_WriteOver; // } } else{ ret = Error_TimeOut; } break; } case OS_CH1_CH8://CH1-CH8超采样 { if ((OverSampling_CycleCount > pre_OverSampling_CycleCount) && ((OverSampling_CycleCount - pre_OverSampling_CycleCount) < circlecount_error + 1)) { // printf("CycleCount: %d PreCycleCount: %d\n", OverSampling_CycleCount, pre_OverSampling_CycleCount); pre_OverSampling_CycleCount = OverSampling_CycleCount; // fpWrite = fopen(file, "a+"); // if (fpWrite == NULL) // { // return Error_NoFile; // } // fprintf(fpWrite, "%d %d %d %d %d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 5 + 1, OverSampling_AD_Input[0], OverSampling_AD_Input[5], \ // OverSampling_AD_Input[10], OverSampling_AD_Input[15], \ // OverSampling_AD_Input[20], OverSampling_AD_Input[25], \ // OverSampling_AD_Input[30], OverSampling_AD_Input[35]); // fprintf(fpWrite, "%d %d %d %d %d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 5 + 2, OverSampling_AD_Input[1], OverSampling_AD_Input[6], \ // OverSampling_AD_Input[11], OverSampling_AD_Input[16], \ // OverSampling_AD_Input[21], OverSampling_AD_Input[26], \ // OverSampling_AD_Input[31], OverSampling_AD_Input[36]); // fprintf(fpWrite, "%d %d %d %d %d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 5 + 3, OverSampling_AD_Input[2], OverSampling_AD_Input[7], \ // OverSampling_AD_Input[12], OverSampling_AD_Input[17], \ // OverSampling_AD_Input[22], OverSampling_AD_Input[27], \ // OverSampling_AD_Input[32], OverSampling_AD_Input[37]); // fprintf(fpWrite, "%d %d %d %d %d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 5 + 4, OverSampling_AD_Input[3], OverSampling_AD_Input[8], \ // OverSampling_AD_Input[13], OverSampling_AD_Input[18], \ // OverSampling_AD_Input[23], OverSampling_AD_Input[28], \ // OverSampling_AD_Input[33], OverSampling_AD_Input[38]); // fprintf(fpWrite, "%d %d %d %d %d %d %d %d %d\n", (OverSampling_CycleCount - 1) * 5 + 5, OverSampling_AD_Input[4], OverSampling_AD_Input[9], \ // OverSampling_AD_Input[14], OverSampling_AD_Input[19], \ // OverSampling_AD_Input[24], OverSampling_AD_Input[29], \ // OverSampling_AD_Input[34], OverSampling_AD_Input[39]); // fclose(fpWrite); if(channelDis_temp < 8){ for(int index = channelDis_temp*5,loop_num = 0;loop_num < 5;index++,loop_num++){ // enQueue(&my_ecQueue.my_ecQueue_ch1, OverSampling_AD_Input[index]); m_measure_Q->enqueue(OverSampling_AD_Input[index]); // enQueue(&my_ecQueue.my_ecQueue_ch2, OverSampling_AD_Input[index]); } } else{ ret = Error_Channel_Invalid; } // if (((OverSampling_CycleCount - 1) * 5 + 5) >= num_of_samples) // { // pre_OverSampling_CycleCount = 0; // DRE2008_OS_SamplingRateSet(slave_num, 50); // DRE2008_OS_Disable(slave_num); // printf("The required %d data log complete!\n", num_of_samples); // ret = Error_File_WriteOver; // } } else{ ret = Error_TimeOut; } break; } default: break; } return ret; }
43.961801
172
0.543105
GreatCong
ae2d8c0a1f4465bf6b72f7b7cc39561f4ef0ad19
1,798
hpp
C++
include/np/ndarray/dynamic/NDArrayDynamicSortImpl.hpp
mgorshkov/np
75c7adff38e7260371135839b547d5340f3ca367
[ "MIT" ]
null
null
null
include/np/ndarray/dynamic/NDArrayDynamicSortImpl.hpp
mgorshkov/np
75c7adff38e7260371135839b547d5340f3ca367
[ "MIT" ]
null
null
null
include/np/ndarray/dynamic/NDArrayDynamicSortImpl.hpp
mgorshkov/np
75c7adff38e7260371135839b547d5340f3ca367
[ "MIT" ]
null
null
null
/* C++ numpy-like template-based array implementation Copyright (c) 2022 Mikhail Gorshkov (mikhail.gorshkov@gmail.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include <np/ndarray/dynamic/NDArrayDynamicDecl.hpp> namespace np::ndarray::array_dynamic { // Sort an array template<typename DType, typename Storage> inline void NDArrayDynamic<DType, Storage>::sort() { m_ArrayImpl.sort(); auto shape = m_ArrayImpl.shape(); shape.flatten(); m_ArrayImpl.setShape(shape); } // Sort the elements of an array's axis // TODO // template<typename DType, typename Storage> // template<std::size_t N> // inline void NDArrayDynamic<DType, Storage>::sort(std::optional<Axis<N>> axis) { // } } // namespace np::ndarray::array_dynamic
36.693878
86
0.74861
mgorshkov
ae3120a1f2b602611be0945168db439e9cd8076f
35
cpp
C++
NotifyServer/SQLThreadConPool.cpp
lijialong1234/TeachNotice
27ec630d1a8e669bd30df406ea6618d8fbce8c3b
[ "MIT" ]
2
2019-05-25T13:25:33.000Z
2019-06-03T06:48:24.000Z
NotifyServer/SQLThreadConPool.cpp
lijialong1234/TeachNotice
27ec630d1a8e669bd30df406ea6618d8fbce8c3b
[ "MIT" ]
null
null
null
NotifyServer/SQLThreadConPool.cpp
lijialong1234/TeachNotice
27ec630d1a8e669bd30df406ea6618d8fbce8c3b
[ "MIT" ]
null
null
null
#include "SQLThreadConPool.h"
8.75
30
0.685714
lijialong1234
ae38f72c78ef42f31273498ba0aa14853c32c46e
8,622
cpp
C++
Cpp/Docker/OBJ.cpp
Gabidal/GAC
f36b76bceb6a39a87b50c393eb3540f4085bd879
[ "MIT" ]
5
2019-08-19T18:18:08.000Z
2019-12-13T19:26:03.000Z
Cpp/Docker/OBJ.cpp
Gabidal/GAC
f36b76bceb6a39a87b50c393eb3540f4085bd879
[ "MIT" ]
3
2019-04-15T19:24:36.000Z
2020-02-29T13:09:07.000Z
Cpp/Docker/OBJ.cpp
Gabidal/GAC
f36b76bceb6a39a87b50c393eb3540f4085bd879
[ "MIT" ]
2
2019-10-08T23:16:05.000Z
2019-12-18T22:58:04.000Z
#include "../../H/Docker/OBJ.h" #include "../../H/BackEnd/Selector.h" #include "../../H/Nodes/Node.h" #include "../../H/Assembler/Assembler_Types.h" #include "../../H/UI/Usr.h" #include "../../H/UI/Safe.h" #include "../../H/Assembler/Assembler.h" #include "../../H/Docker/Docker.h" extern Selector* selector; extern Node* Global_Scope; extern Usr* sys; extern Assembler* assembler; vector<OBJ::Section> OBJ::Gather_All_Sections(vector<char> buffer, int Section_Count) { vector<Section> Result; for (int i = sizeof(Header); i < Section_Count; i += sizeof(Section)) { Result.push_back(*(Section*)&(buffer[i])); } return Result; } vector<string> OBJ::Get_Symbol_Table_Content(Header h, vector<char> buffer) { vector<string> Result; vector<Symbol> Symbols; for (int i = *(int*)h.Pointer_To_Symbol_Table; i < buffer.size(); i++) { Symbols.push_back(*(Symbol*)&(buffer[i])); } for (auto& S : Symbols) { if (S.Name.Header == 0) { string Name = ""; for (int i = *(int*)S.Name.Offset; i < buffer.size(); i++) { if (buffer[i] == '\0') break; Name += buffer[i]; } Result.push_back(Name); } else Result.push_back(string(S.Full_Name, 8)); } return Result; } void OBJ::OBJ_Analyser(vector<string>& Output) { //get the header and then start up the section suckup syste 2000 :D //read the file vector<uint8_t> tmp = DOCKER::Get_Char_Buffer_From_File(DOCKER::Working_Dir.back().second + DOCKER::FileName.back(), ""); vector<char> Buffer = vector<char>(*(char*)tmp.data(), tmp.size()); //read the header of this obj file Header header = *(Header*)&Buffer; DOCKER::Append(Output, Get_Symbol_Table_Content(header, Buffer)); } vector<unsigned char> OBJ::Create_Obj(vector<Byte_Map_Section*> Input){ OBJ::Header header; header.Machine = selector->OBJ_Machine_ID; header.Number_OF_Sections = Input.size(); header.Date_Time = time_t(time(NULL)); header.Pointer_To_Symbol_Table = offsetof(OBJ::Header, Characteristics) + sizeof(Header::Characteristics) + sizeof(OBJ::Section) * Input.size(); //calculate the exports and import functions from global scope for (auto s : Global_Scope->Defined){ if (s->Has(vector<string>{"export", "import"}) > 0){ header.Number_Of_Symbols++; } } header.Size_Of_Optional_Header = 0; header.Characteristics = _IMAGE_FILE_LARGE_ADDRESS_AWARE; // header.Magic = _MAGIC_PE32_PlUS; // header.Linker_Version = 0x0000; // for (auto i : Input){ // header.Size_Of_Code += i->Calculated_Size; // } // for (auto i : Input){ // if (i->Is_Data_Section) // header.Size_Of_Initialized_Data += i->Calculated_Size; // } // header.Size_Of_Uninitialized_Data = 0; // if (sys->Info.Format == "lib"){ // header.Address_Of_Entry_Point = 0; // } // else{ // string Unmangled_Starting_Function_Name = sys->Info.Start_Function_Name; // Node* Function = Global_Scope->Find(Unmangled_Starting_Function_Name, Global_Scope, FUNCTION_NODE); // if (Function == nullptr){ // Report(Observation(ERROR, "Function " + Unmangled_Starting_Function_Name + " not found in the global scope", LINKER_MISSING_STARTING_FUNCTION)); // return vector<unsigned char>(); // } // string Mangled_Starting_Function_Name = Function->Mangled_Name; // header.Address_Of_Entry_Point = assembler->Symbol_Table.at(Mangled_Starting_Function_Name); // } // header.Base_Of_Code = Input.size() * sizeof(Section) + header.Number_Of_Symbols * sizeof(Symbol) + sizeof(Header); // header.Base_Of_Data = header.Base_Of_Code + header.Size_Of_Code; // if (sys->Info.OS == "win"){ // if (sys->Info.Format == "exe"){ // header.Image_Base = _WINDOWS_PE_EXE_BASE_IMAGE; // } // else if (sys->Info.Format == "dll"){ // header.Image_Base = _WINDOWS_PE_DLL_BASE_IMAGE; // } // } // header.Section_Alignment = _FILE_ALIGNMENT; // header.File_Alignment = _FILE_ALIGNMENT; // header.Operating_System_Version = 0x0006; // header.Image_Version = 0; // header.Subsystem_Version = 0; // header.Win32_Version_Value = 0; // header.Size_Of_Image = header.Size_Of_Code + header.Size_Of_Initialized_Data + header.Size_Of_Uninitialized_Data + sizeof(Section) * Input.size() + header.Number_Of_Symbols * sizeof(Symbol) + sizeof(Header); // header.Size_Of_Headers = sizeof(Header) + sizeof(Section) * Input.size() + header.Number_Of_Symbols * sizeof(Symbol); // header.Check_Sum = 0; // header.Subsystem = 0; // header.Dll_Characteristics = 0; // header.Size_Of_Stack_Reserve = 0x100000; // header.Size_Of_Stack_Commit = 0x1000; // //Allocate for one bucket + bucket buffer for the Evie allocator. // header.Size_Of_Heap_Reserve = _BUCKET_SIZE; // header.Size_Of_Heap_Commit = _ALLOCATOR_BUCKET_COUNT + _BUCKET_SIZE; // header.Loader_Flags = 0; // header.Number_Of_Rva_And_Sizes = 0; vector<OBJ::Symbol> Symbols = Generate_Symbol_Table(); vector<string> Symbol_Names = Generate_Name_Section_For_Symbol_Table(); unsigned long long Symbol_Name_Size = 0; for (auto i : Symbol_Names){ //add the null terminator Symbol_Name_Size += i.size() + 1; } vector<OBJ::Section> Sections = Generate_Section_Table(Input, header.Pointer_To_Symbol_Table + sizeof(header.Pointer_To_Symbol_Table) + sizeof(OBJ::Symbol) * Symbols.size() + Symbol_Name_Size); //Now inline all the data into one humongus buffer vector<unsigned char> Buffer; //Remove the optional headers from the buffer unsigned char* Header_Start_Address = (unsigned char*)&header; unsigned char* Header_End_Address = (unsigned char*)&header.Characteristics + sizeof(header.Characteristics); Buffer.insert(Buffer.end(), (unsigned char*)&header, Header_End_Address); Buffer.insert(Buffer.end(), (unsigned char*)Sections.data(), (unsigned char*)Sections.data() + sizeof(OBJ::Section) * Input.size()); Buffer.insert(Buffer.end(), (unsigned char*)Symbols.data(), (unsigned char*)Symbols.data() + sizeof(OBJ::Symbol) * Symbols.size()); int s = sizeof(OBJ::Symbol); unsigned int String_Table_Size = 0; vector<unsigned char> String_Table_Buffer; for (auto i : Symbol_Names){ String_Table_Buffer.insert(String_Table_Buffer.end(), i.begin(), i.end()); String_Table_Buffer.push_back(0); } String_Table_Size = String_Table_Buffer.size() + sizeof(String_Table_Size); Buffer.insert(Buffer.end(), (unsigned char*)&String_Table_Size, (unsigned char*)&String_Table_Size + sizeof(String_Table_Size)); Buffer.insert(Buffer.end(), String_Table_Buffer.begin(), String_Table_Buffer.end()); for (auto i : Input){ for (auto& j : i->Byte_Maps){ vector<unsigned char> Data = selector->Assemble(j); Buffer.insert(Buffer.end(), Data.begin(), Data.end()); } } //transform the return Buffer; } vector<OBJ::Section> OBJ::Generate_Section_Table(vector<Byte_Map_Section*> Input, unsigned long long Origo){ vector<OBJ::Section> Result; for (auto i : Input){ Section tmp; memcpy(&tmp.Name, i->Name.data(), i->Name.size()); tmp.Virtual_Size = i->Calculated_Size; tmp.Virtual_Address = i->Calculated_Address; tmp.Size_Of_Raw_Data = i->Calculated_Size; tmp.Pointer_To_Raw_Data = i->Calculated_Address + Origo; tmp.Pointer_To_Relocations = 0; tmp.Pointer_To_Line_Numbers = 0; tmp.Number_Of_Relocations = 0; tmp.Number_Of_Line_Numbers = 0; if (i->Is_Data_Section){ tmp.Characteristics = _IMAGE_SCN_CNT_INITIALIZED_DATA | _IMAGE_SCN_MEM_READ | _IMAGE_SCN_MEM_WRITE; } else{ tmp.Characteristics = _IMAGE_SCN_CNT_CODE | _IMAGE_SCN_MEM_EXECUTE | _IMAGE_SCN_MEM_READ; } Result.push_back(tmp); } return Result; } vector<OBJ::Symbol> OBJ::Generate_Symbol_Table(){ vector<OBJ::Symbol> Result; //Skip the String_Table_Size identifier long long Current_Symbol_Offset = sizeof(unsigned int); for (auto i : assembler->Symbol_Table){ OBJ::Symbol Current; //Generate the offset for the name redies in, transform it to text Current.Full_Name = Current_Symbol_Offset << 32; Current.Value = i.second; Current.Section_Number = 0; Current.Type = 0; Current.Storage_Class = _IMAGE_SYM_CLASS_LABEL; Current.Number_Of_Aux_Symbols = 0; Result.push_back(Current); Current_Symbol_Offset += i.first.size() + 1; } return Result; } vector<string> OBJ::Generate_Name_Section_For_Symbol_Table(){ vector<string> Result; for (auto symbol : assembler->Symbol_Table){ Result.push_back(symbol.first); } return Result; }
31.933333
212
0.694734
Gabidal
ae38f7dc7a43cd38e41341504420dbacb7158e09
9,567
cc
C++
chrome/browser/autofill/form_structure_browsertest.cc
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
2
2017-09-02T19:08:28.000Z
2021-11-15T15:15:14.000Z
chrome/browser/autofill/form_structure_browsertest.cc
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
null
null
null
chrome/browser/autofill/form_structure_browsertest.cc
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
1
2020-04-13T05:45:10.000Z
2020-04-13T05:45:10.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 <vector> #include "base/file_path.h" #include "base/path_service.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/autofill/autofill_manager.h" #include "chrome/browser/autofill/form_structure.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "googleurl/src/gurl.h" namespace { FilePath GetInputFileDirectory() { FilePath test_data_dir_; PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir_); test_data_dir_ = test_data_dir_.AppendASCII("autofill_heuristics") .AppendASCII("input"); return test_data_dir_; } FilePath GetOutputFileDirectory() { FilePath test_data_dir_; PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir_); test_data_dir_ = test_data_dir_.AppendASCII("autofill_heuristics") .AppendASCII("output"); return test_data_dir_; } // Write |content| to |file|. Returns true on success. bool WriteFile(const FilePath& file, const std::string& content) { int write_size = file_util::WriteFile(file, content.c_str(), content.length()); return write_size == static_cast<int>(content.length()); } // Convert |html| to URL format, and return the converted string. const std::string ConvertToURLFormat(const std::string& html) { return std::string("data:text/html;charset=utf-8,") + html; } // Compare |output_file_source| with |form_string|. Returns true when they are // identical. bool CompareText(const std::string& output_file_source, const std::string& form_string) { std::string output_file = output_file_source; std::string form = form_string; ReplaceSubstringsAfterOffset(&output_file, 0, "\r\n", " "); ReplaceSubstringsAfterOffset(&output_file, 0, "\r", " "); ReplaceSubstringsAfterOffset(&output_file, 0, "\n", " "); ReplaceSubstringsAfterOffset(&form, 0, "\n", " "); return (output_file == form); } } // namespace // Test class for verifying proper form structure as determined by AutoFill // heuristics. A test inputs each form file(e.g. form_[language_code].html), // loads its HTML content with a call to |NavigateToURL|, the |AutoFillManager| // associated with the tab contents is queried for the form structures that // were loaded and parsed. These form structures are serialized to string form. // If this is the first time test is run, a gold test result file is generated // in output directory, else the form structures are compared against the // existing result file. class FormStructureBrowserTest : public InProcessBrowserTest { public: FormStructureBrowserTest() {} virtual ~FormStructureBrowserTest() {} protected: // Returns a vector of form structure objects associated with the given // |autofill_manager|. const std::vector<FormStructure*>& GetFormStructures( const AutoFillManager& autofill_manager); // Serializes the given form structures in |forms| to string form. const std::string FormStructuresToString( const std::vector<FormStructure*>& forms); private: // A helper utility for converting an |AutoFillFieldType| to string form. const std::string AutoFillFieldTypeToString(AutoFillFieldType type); DISALLOW_COPY_AND_ASSIGN(FormStructureBrowserTest); }; const std::vector<FormStructure*>& FormStructureBrowserTest::GetFormStructures( const AutoFillManager& autofill_manager) { return autofill_manager.form_structures_.get(); } const std::string FormStructureBrowserTest::FormStructuresToString( const std::vector<FormStructure*>& forms) { std::string forms_string; for (std::vector<FormStructure*>::const_iterator iter = forms.begin(); iter != forms.end(); ++iter) { for (std::vector<AutoFillField*>::const_iterator field_iter = (*iter)->begin(); field_iter != (*iter)->end(); ++field_iter) { // The field list is NULL-terminated. Exit loop when at the end. if (!*field_iter) break; forms_string += AutoFillFieldTypeToString((*field_iter)->type()); forms_string += "\n"; } } return forms_string; } const std::string FormStructureBrowserTest::AutoFillFieldTypeToString( AutoFillFieldType type) { switch (type) { case NO_SERVER_DATA: return "NO_SERVER_DATA"; case UNKNOWN_TYPE: return "UNKNOWN_TYPE"; case EMPTY_TYPE: return "EMPTY_TYPE"; case NAME_FIRST: return "NAME_FIRST"; case NAME_MIDDLE: return "NAME_MIDDLE"; case NAME_LAST: return "NAME_LAST"; case NAME_MIDDLE_INITIAL: return "NAME_MIDDLE_INITIAL"; case NAME_FULL: return "NAME_FULL"; case NAME_SUFFIX: return "NAME_SUFFIX"; case EMAIL_ADDRESS: return "EMAIL_ADDRESS"; case PHONE_HOME_NUMBER: return "PHONE_HOME_NUMBER"; case PHONE_HOME_CITY_CODE: return "PHONE_HOME_CITY_CODE"; case PHONE_HOME_COUNTRY_CODE: return "PHONE_HOME_COUNTRY_CODE"; case PHONE_HOME_CITY_AND_NUMBER: return "PHONE_HOME_CITY_AND_NUMBER"; case PHONE_HOME_WHOLE_NUMBER: return "PHONE_HOME_WHOLE_NUMBER"; case PHONE_FAX_NUMBER: return "PHONE_FAX_NUMBER"; case PHONE_FAX_CITY_CODE: return "PHONE_FAX_CITY_CODE"; case PHONE_FAX_COUNTRY_CODE: return "PHONE_FAX_COUNTRY_CODE"; case PHONE_FAX_CITY_AND_NUMBER: return "PHONE_FAX_CITY_AND_NUMBER"; case PHONE_FAX_WHOLE_NUMBER: return "PHONE_FAX_WHOLE_NUMBER"; case ADDRESS_HOME_LINE1: return "ADDRESS_HOME_LINE1"; case ADDRESS_HOME_LINE2: return "ADDRESS_HOME_LINE2"; case ADDRESS_HOME_APT_NUM: return "ADDRESS_HOME_APT_NUM"; case ADDRESS_HOME_CITY: return "ADDRESS_HOME_CITY"; case ADDRESS_HOME_STATE: return "ADDRESS_HOME_STATE"; case ADDRESS_HOME_ZIP: return "ADDRESS_HOME_ZIP"; case ADDRESS_HOME_COUNTRY: return "ADDRESS_HOME_COUNTRY"; case ADDRESS_BILLING_LINE1: return "ADDRESS_BILLING_LINE1"; case ADDRESS_BILLING_LINE2: return "ADDRESS_BILLING_LINE2"; case ADDRESS_BILLING_APT_NUM: return "ADDRESS_BILLING_APT_NUM"; case ADDRESS_BILLING_CITY: return "ADDRESS_BILLING_CITY"; case ADDRESS_BILLING_STATE: return "ADDRESS_BILLING_STATE"; case ADDRESS_BILLING_ZIP: return "ADDRESS_BILLING_ZIP"; case ADDRESS_BILLING_COUNTRY: return "ADDRESS_BILLING_COUNTRY"; case CREDIT_CARD_NAME: return "CREDIT_CARD_NAME"; case CREDIT_CARD_NUMBER: return "CREDIT_CARD_NUMBER"; case CREDIT_CARD_EXP_MONTH: return "CREDIT_CARD_EXP_MONTH"; case CREDIT_CARD_EXP_2_DIGIT_YEAR: return "CREDIT_CARD_EXP_2_DIGIT_YEAR"; case CREDIT_CARD_EXP_4_DIGIT_YEAR: return "CREDIT_CARD_EXP_4_DIGIT_YEAR"; case CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR: return "CREDIT_CARD_EXP_DATE_2_DIGIT_YEAR"; case CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR: return "CREDIT_CARD_EXP_DATE_4_DIGIT_YEAR"; case CREDIT_CARD_TYPE: return "CREDIT_CARD_TYPE"; case CREDIT_CARD_VERIFICATION_CODE: return "CREDIT_CARD_VERIFICATION_CODE"; case COMPANY_NAME: return "COMPANY_NAME"; default: NOTREACHED() << "Invalid AutoFillFieldType value."; } return std::string(); } IN_PROC_BROWSER_TEST_F(FormStructureBrowserTest, HTMLFiles) { FilePath input_file_path = GetInputFileDirectory(); file_util::FileEnumerator input_file_enumerator(input_file_path, false, file_util::FileEnumerator::FILES, FILE_PATH_LITERAL("*.html")); for (input_file_path = input_file_enumerator.Next(); !input_file_path.empty(); input_file_path = input_file_enumerator.Next()) { std::string input_file_source; ASSERT_TRUE(file_util::ReadFileToString(input_file_path, &input_file_source)); input_file_source = ConvertToURLFormat(input_file_source); ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser())); ASSERT_NO_FATAL_FAILURE(ui_test_utils::NavigateToURL( browser(), GURL(input_file_source))); ASSERT_NO_FATAL_FAILURE(ui_test_utils::ClickOnView(browser(), VIEW_ID_TAB_CONTAINER)); ASSERT_TRUE(ui_test_utils::IsViewFocused( browser(), VIEW_ID_TAB_CONTAINER_FOCUS_VIEW)); AutoFillManager* autofill_manager = browser()->GetSelectedTabContents()->GetAutoFillManager(); ASSERT_NE(static_cast<AutoFillManager*>(NULL), autofill_manager); std::vector<FormStructure*> forms = GetFormStructures(*autofill_manager); FilePath output_file_directory = GetOutputFileDirectory(); FilePath output_file_path = output_file_directory.Append( input_file_path.BaseName().StripTrailingSeparators().ReplaceExtension( FILE_PATH_LITERAL(".out"))); std::string output_file_source; if (file_util::ReadFileToString(output_file_path, &output_file_source)) { ASSERT_TRUE(CompareText( output_file_source, FormStructureBrowserTest::FormStructuresToString(forms))); } else { ASSERT_TRUE(WriteFile( output_file_path, FormStructureBrowserTest::FormStructuresToString(forms))); } } }
35.831461
79
0.720184
Gitman1989
ae3ab6bc4f88c37f0fa5090dce0cf138c035c01c
308
hpp
C++
pythran/pythonic/include/cmath/log.hpp
artas360/pythran
66dad52d52be71693043e9a7d7578cfb9cb3d1da
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/include/cmath/log.hpp
artas360/pythran
66dad52d52be71693043e9a7d7578cfb9cb3d1da
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/include/cmath/log.hpp
artas360/pythran
66dad52d52be71693043e9a7d7578cfb9cb3d1da
[ "BSD-3-Clause" ]
null
null
null
#ifndef PYTHONIC_INCLUDE_CMATH_LOG_HPP #define PYTHONIC_INCLUDE_CMATH_LOG_HPP #include "pythonic/include/utils/proxy.hpp" #include <cmath> namespace pythonic { namespace cmath { ALIAS_DECL(log, std::log); double log(double x, double base); PROXY_DECL(pythonic::cmath, log); } } #endif
15.4
43
0.733766
artas360
ae3b50e593a3c8dd1c8b912c6cbdc593f6ebe381
883
cc
C++
remoting/signaling/signaling_tracker_impl.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
remoting/signaling/signaling_tracker_impl.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
remoting/signaling/signaling_tracker_impl.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.000Z
// Copyright 2020 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 "remoting/signaling/signaling_tracker_impl.h" namespace remoting { SignalingTrackerImpl::SignalingTrackerImpl() = default; SignalingTrackerImpl::~SignalingTrackerImpl() = default; void SignalingTrackerImpl::OnChannelActive() { channel_last_active_time_ = base::TimeTicks::Now(); } bool SignalingTrackerImpl::IsChannelActive() const { return GetLastReportedChannelActiveDuration() < SignalingTracker::kChannelInactiveTimeout; } base::TimeDelta SignalingTrackerImpl::GetLastReportedChannelActiveDuration() const { if (channel_last_active_time_.is_null()) { return base::TimeDelta::Max(); } return base::TimeTicks::Now() - channel_last_active_time_; } } // namespace remoting
28.483871
76
0.772367
sarang-apps
ae3ca7324c166c72a93c09bd7aa727976348a3cf
9,203
hpp
C++
stm32-jl/include/common/uart.hpp
serjzimmerman/mipt-rt-stm32-f0-labs
561f363ec5c4dece92b2a14c36343aaa9d713785
[ "MIT" ]
null
null
null
stm32-jl/include/common/uart.hpp
serjzimmerman/mipt-rt-stm32-f0-labs
561f363ec5c4dece92b2a14c36343aaa9d713785
[ "MIT" ]
null
null
null
stm32-jl/include/common/uart.hpp
serjzimmerman/mipt-rt-stm32-f0-labs
561f363ec5c4dece92b2a14c36343aaa9d713785
[ "MIT" ]
null
null
null
#pragma once #include <cstdarg> #include <cstring> #include "gpio.hpp" #include "stm32f051/rcc.hpp" namespace JL { enum StopBits { stopBit1 = 0b00, stopBit05 = 0b01, stopBit2 = 0b10, stopBit15 = 0b11, }; enum WordLength { wordLength8 = 0b00, wordLength9 = 0b01, wordLength7 = 0b10, }; template <uint32_t addr, typename tx, typename rx, PinAlternateFunction txaf, PinAlternateFunction rxaf, typename clock> struct UartBase { static constexpr uint32_t addr_ = addr; using Tx = tx; using Rx = rx; struct CR1 : RegisterBase<addr_ + 0x00, RegisterReadWriteMode> { using UE = RegisterField<UartBase::CR1, 0, 1, RegisterReadWriteMode>; using UESM = RegisterField<UartBase::CR1, 1, 1, RegisterReadWriteMode>; using RE = RegisterField<UartBase::CR1, 2, 1, RegisterReadWriteMode>; using TE = RegisterField<UartBase::CR1, 3, 1, RegisterReadWriteMode>; using IDLEIE = RegisterField<UartBase::CR1, 4, 1, RegisterReadWriteMode>; using EXNEIE = RegisterField<UartBase::CR1, 5, 1, RegisterReadWriteMode>; using TCIE = RegisterField<UartBase::CR1, 6, 1, RegisterReadWriteMode>; using TXEIE = RegisterField<UartBase::CR1, 7, 1, RegisterReadWriteMode>; using PEIE = RegisterField<UartBase::CR1, 8, 1, RegisterReadWriteMode>; using PS = RegisterField<UartBase::CR1, 9, 1, RegisterReadWriteMode>; using PCE = RegisterField<UartBase::CR1, 10, 1, RegisterReadWriteMode>; using WAKE = RegisterField<UartBase::CR1, 11, 1, RegisterReadWriteMode>; using M0 = RegisterField<UartBase::CR1, 12, 1, RegisterReadWriteMode>; using MME = RegisterField<UartBase::CR1, 13, 1, RegisterReadWriteMode>; using CMIE = RegisterField<UartBase::CR1, 14, 1, RegisterReadWriteMode>; using OVER8 = RegisterField<UartBase::CR1, 15, 1, RegisterReadWriteMode>; using DEDT = RegisterField<UartBase::CR1, 16, 4, RegisterReadWriteMode>; using DEAT = RegisterField<UartBase::CR1, 21, 4, RegisterReadWriteMode>; using RTOIE = RegisterField<UartBase::CR1, 26, 1, RegisterReadWriteMode>; using EOBIE = RegisterField<UartBase::CR1, 27, 1, RegisterReadWriteMode>; using M1 = RegisterField<UartBase::CR1, 28, 1, RegisterReadWriteMode>; }; struct CR2 : RegisterBase<addr_ + 0x04, RegisterReadWriteMode> { using ADDM7 = RegisterField<UartBase::CR2, 4, 1, RegisterReadWriteMode>; using LBDL = RegisterField<UartBase::CR2, 5, 1, RegisterReadWriteMode>; using LBDIE = RegisterField<UartBase::CR2, 6, 1, RegisterReadWriteMode>; using LBCL = RegisterField<UartBase::CR2, 8, 1, RegisterReadWriteMode>; using CPHA = RegisterField<UartBase::CR2, 9, 1, RegisterReadWriteMode>; using CPOL = RegisterField<UartBase::CR2, 10, 1, RegisterReadWriteMode>; using CLKEN = RegisterField<UartBase::CR2, 11, 1, RegisterReadWriteMode>; using STOP = RegisterField<UartBase::CR2, 12, 2, RegisterReadWriteMode>; using LINEN = RegisterField<UartBase::CR2, 14, 1, RegisterReadWriteMode>; using SWAP = RegisterField<UartBase::CR2, 15, 1, RegisterReadWriteMode>; using RXINV = RegisterField<UartBase::CR2, 16, 1, RegisterReadWriteMode>; using TXINV = RegisterField<UartBase::CR2, 17, 1, RegisterReadWriteMode>; using DATAINV = RegisterField<UartBase::CR2, 18, 1, RegisterReadWriteMode>; using MSBFIRST = RegisterField<UartBase::CR2, 19, 1, RegisterReadWriteMode>; using ABREN = RegisterField<UartBase::CR2, 20, 1, RegisterReadWriteMode>; using ABRMOD = RegisterField<UartBase::CR2, 21, 2, RegisterReadWriteMode>; using RTOEN = RegisterField<UartBase::CR2, 23, 1, RegisterReadWriteMode>; using ADD = RegisterField<UartBase::CR2, 24, 8, RegisterReadWriteMode>; }; struct CR3 : RegisterBase<addr_ + 0x08, RegisterReadWriteMode> { using EIE = RegisterField<UartBase::CR3, 0, 1, RegisterReadWriteMode>; using IREN = RegisterField<UartBase::CR3, 1, 1, RegisterReadWriteMode>; using IRLP = RegisterField<UartBase::CR3, 2, 1, RegisterReadWriteMode>; using HDSEL = RegisterField<UartBase::CR3, 3, 1, RegisterReadWriteMode>; using NACK = RegisterField<UartBase::CR3, 4, 1, RegisterReadWriteMode>; using SCEN = RegisterField<UartBase::CR3, 5, 1, RegisterReadWriteMode>; using DMAR = RegisterField<UartBase::CR3, 6, 1, RegisterReadWriteMode>; using DMAT = RegisterField<UartBase::CR3, 7, 2, RegisterReadWriteMode>; using RTSE = RegisterField<UartBase::CR3, 8, 1, RegisterReadWriteMode>; using CTSE = RegisterField<UartBase::CR3, 9, 1, RegisterReadWriteMode>; using CTSIE = RegisterField<UartBase::CR3, 10, 1, RegisterReadWriteMode>; using ONEBIT = RegisterField<UartBase::CR3, 11, 1, RegisterReadWriteMode>; using OVRDIS = RegisterField<UartBase::CR3, 12, 1, RegisterReadWriteMode>; using DDRE = RegisterField<UartBase::CR3, 13, 1, RegisterReadWriteMode>; using DEM = RegisterField<UartBase::CR3, 14, 1, RegisterReadWriteMode>; using DEP = RegisterField<UartBase::CR3, 15, 1, RegisterReadWriteMode>; using SCARCNT = RegisterField<UartBase::CR3, 17, 3, RegisterReadWriteMode>; using WUS = RegisterField<UartBase::CR3, 20, 2, RegisterReadWriteMode>; using WUFIE = RegisterField<UartBase::CR3, 22, 1, RegisterReadWriteMode>; }; struct BRR : RegisterBase<addr_ + 0x0c, RegisterReadWriteMode> { using BRR16 = RegisterField<UartBase::BRR, 0, 16, RegisterReadWriteMode>; using FRAC8 = RegisterField<UartBase::BRR, 0, 3, RegisterReadWriteMode>; using BRR8 = RegisterField<UartBase::BRR, 4, 12, RegisterReadWriteMode>; }; struct RDRREG : RegisterBase<addr_ + 0x24, RegisterReadMode> { using RDR = RegisterField<UartBase::RDRREG, 0, 9, RegisterReadMode>; }; struct TDRREG : RegisterBase<addr_ + 0x28, RegisterReadWriteMode> { using TDR = RegisterField<UartBase::TDRREG, 0, 9, RegisterReadWriteMode>; }; struct ISR : RegisterBase<addr_ + 0x1c, RegisterReadMode> { using PE = RegisterField<UartBase::ISR, 0, 1, RegisterReadMode>; using FE = RegisterField<UartBase::ISR, 1, 1, RegisterReadMode>; using NF = RegisterField<UartBase::ISR, 2, 1, RegisterReadMode>; using ORE = RegisterField<UartBase::ISR, 3, 1, RegisterReadMode>; using IDLE = RegisterField<UartBase::ISR, 4, 1, RegisterReadMode>; using RXNE = RegisterField<UartBase::ISR, 5, 1, RegisterReadMode>; using TC = RegisterField<UartBase::ISR, 6, 1, RegisterReadMode>; using TXE = RegisterField<UartBase::ISR, 7, 1, RegisterReadMode>; using LBDF = RegisterField<UartBase::ISR, 8, 1, RegisterReadMode>; using CTSIF = RegisterField<UartBase::ISR, 9, 1, RegisterReadMode>; using CTS = RegisterField<UartBase::ISR, 10, 1, RegisterReadMode>; using RTOF = RegisterField<UartBase::ISR, 11, 1, RegisterReadMode>; using EOBF = RegisterField<UartBase::ISR, 12, 1, RegisterReadMode>; using ABRE = RegisterField<UartBase::ISR, 14, 1, RegisterReadMode>; using ABRF = RegisterField<UartBase::ISR, 15, 1, RegisterReadMode>; using BUSY = RegisterField<UartBase::ISR, 16, 1, RegisterReadMode>; using CMF = RegisterField<UartBase::ISR, 17, 1, RegisterReadMode>; using SBKF = RegisterField<UartBase::ISR, 18, 1, RegisterReadMode>; using RWU = RegisterField<UartBase::ISR, 19, 1, RegisterReadMode>; using WUF = RegisterField<UartBase::ISR, 20, 1, RegisterReadMode>; using TEACK = RegisterField<UartBase::ISR, 21, 1, RegisterReadMode>; using REACK = RegisterField<UartBase::ISR, 22, 1, RegisterReadMode>; }; /* Only for oversampling 16 */ static inline void SetFrequency(uint32_t baudrate) { BRR::BRR16::Set(APBClock / baudrate); } static inline void Config(uint32_t baudrate, StopBits stop, WordLength length, PinType type) { /* Enable clock for USART and tx and rx PORT */ ClockPack<typename rx::PinPort::Clock, typename tx::PinPort::Clock>::Enable(); ClockPack<clock>::Enable(); PinPack<rx, tx>::Config(modeAlternate, speedMid); rx::SetAlternateFunction(rxaf); tx::SetAlternateFunction(txaf); CR1::Set(0); CR2::Set(0); CR3::Set(0); PinPack<rx, tx>::SetOutputType(type); /* If type and open-drain, then USART is configured in half-duplex mode */ if (type == typeOpdr) { CR3::HDSEL::Set(1); } SetFrequency(baudrate); CR1::UE::Set(1); /* Configure word length and number of stop bits */ RegisterFieldPack<typename CR1::M0, typename CR1::M1>::Set(CR1::M0::GetIndividualValue(length & 1) | CR1::M1::GetIndividualValue((length >> 1) & 1)); RegisterFieldPack<typename CR2::STOP>::Set(CR2::STOP::GetIndividualValue(stop)); /* Enable USART, transmitter and receiver */ } static void PutChar(char tosend) { TDRREG::TDR::Set(tosend); /* Todo: implement timeout */ while (ISR::TC::Get() != 1) ; } static char GetChar() { while (ISR::RXNE::Get() != 1) ; return RDRREG::RDR::Get(); } static void Print(const char *s) { while (*s) { PutChar(*s++); } } }; } // namespace JL
48.183246
120
0.693144
serjzimmerman
ae3cec7f20f8fdb8d588ff4460e5e882697b33d1
9,676
cpp
C++
src/modules/hip/kernel/median_filter.cpp
shobana-mcw/rpp
e4a5eb622b9abd0a5a936bf7174a84a5e2470b59
[ "MIT" ]
26
2019-09-04T17:48:41.000Z
2022-02-23T17:04:24.000Z
src/modules/hip/kernel/median_filter.cpp
shobana-mcw/rpp
e4a5eb622b9abd0a5a936bf7174a84a5e2470b59
[ "MIT" ]
57
2019-09-06T21:37:34.000Z
2022-03-09T02:13:46.000Z
src/modules/hip/kernel/median_filter.cpp
shobana-mcw/rpp
e4a5eb622b9abd0a5a936bf7174a84a5e2470b59
[ "MIT" ]
24
2019-09-04T23:12:07.000Z
2022-03-30T02:06:22.000Z
#include <hip/hip_runtime.h> #include "rpp_hip_host_decls.hpp" #define saturate_8u(value) ((value) > 255 ? 255 : ((value) < 0 ? 0 : (value))) #define SIZE 7*7 extern "C" __global__ void median_filter_pkd(unsigned char *input, unsigned char *output, const unsigned int height, const unsigned int width, const unsigned int channel, const unsigned int kernelSize) { int id_x = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x; int id_y = hipBlockIdx_y * hipBlockDim_y + hipThreadIdx_y; int id_z = hipBlockIdx_z * hipBlockDim_z + hipThreadIdx_z; if (id_x >= width || id_y >= height || id_z >= channel) { return; } int c[SIZE]; int counter = 0; int pixIdx = id_y * channel * width + id_x * channel + id_z; int bound = (kernelSize - 1) / 2; for(int i = -bound ; i <= bound; i++) { for(int j = -bound; j <= bound; j++) { if(id_x + j >= 0 && id_x + j <= width - 1 && id_y + i >= 0 && id_y + i <= height - 1) { unsigned int index = pixIdx + (j * channel) + (i * width * channel); c[counter] = input[index]; } else { c[counter] = 0; counter++; } } } int pos; int max = 0; for (int i = 0; i < counter; i++) { for (int j = i; j < counter; j++) { if (max < c[j]) { max = c[j]; pos = j; } } max = 0; int temp = c[pos]; c[pos] = c[i]; c[i] = temp; } counter = kernelSize * bound + bound + 1; output[pixIdx] = c[counter]; } extern "C" __global__ void median_filter_pln(unsigned char *input, unsigned char *output, const unsigned int height, const unsigned int width, const unsigned int channel, const unsigned int kernelSize) { int id_x = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x; int id_y = hipBlockIdx_y * hipBlockDim_y + hipThreadIdx_y; int id_z = hipBlockIdx_z * hipBlockDim_z + hipThreadIdx_z; if (id_x >= width || id_y >= height || id_z >= channel) { return; } int c[SIZE]; int counter = 0; int pixIdx = id_y * width + id_x + id_z * width * height; int bound = (kernelSize - 1) / 2; unsigned char pixel = input[pixIdx]; for(int i = -bound; i <= bound; i++) { for(int j = -bound; j <= bound; j++) { if(id_x + j >= 0 && id_x + j <= width - 1 && id_y + i >= 0 && id_y + i <= height - 1) { unsigned int index = pixIdx + j + (i * width); c[counter] = input[index]; } else { c[counter] = 0; counter++; } } } int pos; int max = 0; for (int i = 0; i < counter; i++) { for (int j = i; j < counter; j++) { if (max < c[j]) { max = c[j]; pos = j; } } max = 0; int temp = c[pos]; c[pos] = c[i]; c[i] = temp; } counter = kernelSize * bound + bound + 1; output[pixIdx] = c[counter]; } extern "C" __global__ void median_filter_batch(unsigned char *input, unsigned char *output, unsigned int *kernelSize, unsigned int *xroi_begin, unsigned int *xroi_end, unsigned int *yroi_begin, unsigned int *yroi_end, unsigned int *height, unsigned int *width, unsigned int *max_width, unsigned long long *batch_index, const unsigned int channel, unsigned int *inc, // use width * height for pln and 1 for pkd const int plnpkdindex) // use 1 pln 3 for pkd { int id_x = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x; int id_y = hipBlockIdx_y * hipBlockDim_y + hipThreadIdx_y; int id_z = hipBlockIdx_z * hipBlockDim_z + hipThreadIdx_z; unsigned char valuer, valuer1, valueg, valueg1, valueb, valueb1; int kernelSizeTemp = kernelSize[id_z]; int indextmp = 0; long pixIdx = 0; int temp; // printf("%d", id_x); int value = 0; int value1 = 0; int counter = 0; int r[SIZE], g[SIZE], b[SIZE], maxR = 0, maxG = 0, maxB = 0, posR, posG, posB; int bound = (kernelSizeTemp - 1) / 2; pixIdx = batch_index[id_z] + (id_x + id_y * max_width[id_z]) * plnpkdindex; if((id_y >= yroi_begin[id_z]) && (id_y <= yroi_end[id_z]) && (id_x >= xroi_begin[id_z]) && (id_x <= xroi_end[id_z])) { for(int i = -bound; i <= bound; i++) { for(int j = -bound; j <= bound; j++) { if(id_x + j >= 0 && id_x + j <= width[id_z] - 1 && id_y + i >= 0 && id_y + i <= height[id_z] - 1) { unsigned int index = pixIdx + (j + (i * max_width[id_z])) * plnpkdindex; r[counter] = input[index]; if(channel == 3) { index = pixIdx + (j + (i * max_width[id_z])) * plnpkdindex + inc[id_z]; g[counter] = input[index]; index = pixIdx + (j + (i * max_width[id_z])) * plnpkdindex + inc[id_z] * 2; b[counter] = input[index]; } } else { r[counter] = 0; if(channel == 3) { g[counter] = 0; b[counter] = 0; } } counter++; } } for (int i = 0; i < counter; i++) { posB = i; posG = i; posR = i; for (int j = i; j < counter; j++) { if (maxR < r[j]) { maxR = r[j]; posR = j; } if (maxG < g[j]) { maxG = g[j]; posG = j; } if (maxB < b[j]) { maxB = b[j]; posB = j; } } maxR = 0; maxG = 0; maxB = 0; int temp; temp = r[posR]; r[posR] = r[i]; r[i] = temp; temp = g[posG]; g[posG] = g[i]; g[i] = temp; temp = b[posB]; b[posB] = b[i]; b[i] = temp; } counter = kernelSizeTemp * bound + bound + 1; output[pixIdx] = r[counter]; if(channel == 3) { output[pixIdx + inc[id_z]] = g[counter]; output[pixIdx + inc[id_z] * 2] = b[counter]; } } else if((id_x < width[id_z]) && (id_y < height[id_z])) { for(indextmp = 0; indextmp < channel; indextmp++) { output[pixIdx] = input[pixIdx]; pixIdx += inc[id_z]; } } } RppStatus hip_exec_median_filter_batch(Rpp8u *srcPtr, Rpp8u *dstPtr, rpp::Handle& handle, RppiChnFormat chnFormat, Rpp32u channel, Rpp32s plnpkdind, Rpp32u max_height, Rpp32u max_width) { int localThreads_x = 32; int localThreads_y = 32; int localThreads_z = 1; int globalThreads_x = (max_width + 31) & ~31; int globalThreads_y = (max_height + 31) & ~31; int globalThreads_z = handle.GetBatchSize(); hipLaunchKernelGGL(median_filter_batch, dim3(ceil((float)globalThreads_x/localThreads_x), ceil((float)globalThreads_y/localThreads_y), ceil((float)globalThreads_z/localThreads_z)), dim3(localThreads_x, localThreads_y, localThreads_z), 0, handle.GetStream(), srcPtr, dstPtr, handle.GetInitHandle()->mem.mgpu.uintArr[0].uintmem, handle.GetInitHandle()->mem.mgpu.roiPoints.x, handle.GetInitHandle()->mem.mgpu.roiPoints.roiWidth, handle.GetInitHandle()->mem.mgpu.roiPoints.y, handle.GetInitHandle()->mem.mgpu.roiPoints.roiHeight, handle.GetInitHandle()->mem.mgpu.srcSize.height, handle.GetInitHandle()->mem.mgpu.srcSize.width, handle.GetInitHandle()->mem.mgpu.maxSrcSize.width, handle.GetInitHandle()->mem.mgpu.srcBatchIndex, channel, handle.GetInitHandle()->mem.mgpu.inc, plnpkdind); return RPP_SUCCESS; }
35.185455
185
0.423625
shobana-mcw
ae3d5347e2294cddba00ceea4f9349c14fcfe64f
2,859
cc
C++
src/swganh/object/group/group.cc
JohnShandy/swganh
d20d22a8dca2e9220a35af0f45f7935ca2eda531
[ "MIT" ]
1
2015-03-25T16:02:17.000Z
2015-03-25T16:02:17.000Z
src/swganh/object/group/group.cc
JohnShandy/swganh
d20d22a8dca2e9220a35af0f45f7935ca2eda531
[ "MIT" ]
null
null
null
src/swganh/object/group/group.cc
JohnShandy/swganh
d20d22a8dca2e9220a35af0f45f7935ca2eda531
[ "MIT" ]
null
null
null
// This file is part of SWGANH which is released under the MIT license. // See file LICENSE or go to http://swganh.com/LICENSE #include "swganh/object/group/group.h" #include "swganh/object/tangible/tangible.h" using namespace std; using namespace swganh::messages; using namespace swganh::object; using namespace swganh::object::group; using namespace swganh::object::tangible; Group::Group() : member_list_(5) , difficulty_(0) , loot_master_(0) , loot_mode_(FREE_LOOT) { } Group::Group(uint32_t max_member_size) : member_list_(max_member_size) , difficulty_(0) , loot_master_(0) , loot_mode_(FREE_LOOT) { } Group::~Group() { } void Group::AddGroupMember(uint64_t member, std::string name) { boost::lock_guard<boost::mutex> lock(group_mutex_); member_list_.Add(Member(member, name)); GetEventDispatcher()->Dispatch(make_shared<GroupEvent> ("Group::Member",static_pointer_cast<Group>(shared_from_this()))); } void Group::RemoveGroupMember(uint64_t member) { boost::lock_guard<boost::mutex> lock(group_mutex_); auto iter = std::find_if(begin(member_list_), end(member_list_), [=](const Member& x)->bool { return member == x.object_id; }); if(iter == end(member_list_)) { return; } member_list_.Remove(iter); GetEventDispatcher()->Dispatch(make_shared<GroupEvent> ("Group::Member",static_pointer_cast<Group>(shared_from_this()))); } swganh::messages::containers::NetworkSortedVector<Member> Group::GetGroupMembers() { boost::lock_guard<boost::mutex> lock(group_mutex_); return member_list_; } void Group::SetLootMode(LootMode loot_mode) { loot_mode_ = loot_mode; GetEventDispatcher()->Dispatch(make_shared<GroupEvent> ("Group::LootMode",static_pointer_cast<Group>(shared_from_this()))); } LootMode Group::GetLootMode(void) { uint32_t loot_mode = loot_mode_; return (LootMode)loot_mode; } void Group::SetDifficulty(uint16_t difficulty) { difficulty_ = difficulty; GetEventDispatcher()->Dispatch(make_shared<GroupEvent> ("Group::Difficulty",static_pointer_cast<Group>(shared_from_this()))); } uint16_t Group::GetDifficulty(void) { return difficulty_; } void Group::SetLootMaster(uint64_t loot_master) { loot_master_ = loot_master; GetEventDispatcher()->Dispatch(make_shared<GroupEvent> ("Group::LootMaster",static_pointer_cast<Group>(shared_from_this()))); } uint64_t Group::GetLootMaster(void) { return loot_master_; } uint16_t Group::GetCapacity(void) { boost::lock_guard<boost::mutex> lock(group_mutex_); return member_list_.Capacity(); } uint16_t Group::GetSize(void) { boost::lock_guard<boost::mutex> lock(group_mutex_); return member_list_.Size(); } void Group::GetBaseline3() { } void Group::GetBaseline6() { }
22.872
97
0.70794
JohnShandy
ae3dc01e1073dba6d10405d3e51257864cf466be
3,743
hpp
C++
src/libraries/fvOptions/sources/derived/rotorDiskSource/bladeModel/bladeModel.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/fvOptions/sources/derived/rotorDiskSource/bladeModel/bladeModel.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/fvOptions/sources/derived/rotorDiskSource/bladeModel/bladeModel.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
/*---------------------------------------------------------------------------*\ Copyright (C) 2011-2013 OpenFOAM Foundation ------------------------------------------------------------------------------- License This file is part of Caelus. Caelus is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Caelus 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 Caelus. If not, see <http://www.gnu.org/licenses/>. Class CML::bladeModel Description Blade model class SourceFiles bladeModel.cpp \*---------------------------------------------------------------------------*/ #ifndef bladeModel_HPP #define bladeModel_HPP #include "List.hpp" #include "dictionary.hpp" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace CML { /*---------------------------------------------------------------------------*\ Class bladeModel Declaration \*---------------------------------------------------------------------------*/ class bladeModel { protected: // Protected data //- Corresponding profile name per section List<word> profileName_; //- Corresponding profile ID per section List<label> profileID_; //- Radius [m] List<scalar> radius_; //- Twist [deg] on input, converted to [rad] List<scalar> twist_; //- Chord [m] List<scalar> chord_; //- File name (optional) fileName fName_; // Protected Member Functions //- Return ture if file name is set bool readFromFile() const; //- Return the interpolation indices and gradient void interpolateWeights ( const scalar& xIn, const List<scalar>& values, label& i1, label& i2, scalar& ddx ) const; public: //- Constructor bladeModel(const dictionary& dict); //- Destructor virtual ~bladeModel(); // Member functions // Access //- Return const access to the profile name list const List<word>& profileName() const; //- Return const access to the profile ID list const List<label>& profileID() const; //- Return const access to the radius list const List<scalar>& radius() const; //- Return const access to the twist list const List<scalar>& twist() const; //- Return const access to the chord list const List<scalar>& chord() const; // Edit //- Return non-const access to the profile ID list List<label>& profileID(); // Evaluation //- Return the twist and chord for a given radius virtual void interpolate ( const scalar radius, scalar& twist, scalar& chord, label& i1, label& i2, scalar& invDr ) const; }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace CML // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
25.290541
79
0.47689
MrAwesomeRocks
ae41976ffdc4f430861d25c818f7ef3d17a23a23
2,092
cpp
C++
Competitive Programming/Searching & Sorting/maximum sum such that no 2 elements are adjacent.cpp
shreejitverma/GeeksforGeeks
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
2
2022-02-18T05:14:28.000Z
2022-03-08T07:00:08.000Z
Competitive Programming/Searching & Sorting/maximum sum such that no 2 elements are adjacent.cpp
shivaniverma1/Competitive-Programming-1
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
6
2022-01-13T04:31:04.000Z
2022-03-12T01:06:16.000Z
Competitive Programming/Searching & Sorting/maximum sum such that no 2 elements are adjacent.cpp
shivaniverma1/Competitive-Programming-1
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
2
2022-02-14T19:53:53.000Z
2022-02-18T05:14:30.000Z
/* https://practice.geeksforgeeks.org/problems/stickler-theif-1587115621/1 Stickler Thief Easy Accuracy: 50.32% Submissions: 43113 Points: 2 Stickler the thief wants to loot money from a society having n houses in a single line. He is a weird person and follows a certain rule when looting the houses. According to the rule, he will never loot two consecutive houses. At the same time, he wants to maximize the amount he loots. The thief knows which house has what amount of money but is unable to come up with an optimal looting strategy. He asks for your help to find the maximum money he can get if he strictly follows the rule. Each house has a[i] amount of money present in it. Example 1: Input: n = 6 a[] = {5,5,10,100,10,5} Output: 110 Explanation: 5+100+5=110 Example 2: Input: n = 3 a[] = {1,2,3} Output: 4 Explanation: 1+3=4 Your Task: Complete the function FindMaxSum() which takes an array arr[] and n as input which returns the maximum money he can get following the rules Expected Time Complexity: O(N). Expected Space Complexity: O(N). Constraints: 1 ≤ n ≤ 104 1 ≤ a[i] ≤ 104 */ // { Driver Code Starts #include <bits/stdc++.h> using namespace std; typedef long long int ll; // } Driver Code Ends class Solution { public: //Function to find the maximum money the thief can get. int FindMaxSum(int arr[], int n) { // Your code here { int dp[n]; dp[0] = arr[0]; dp[1] = max(arr[1], arr[0]); for (int i = 2; i < n; i++) dp[i] = max(dp[i - 1], arr[i] + dp[i - 2]); return dp[n - 1]; } } }; // { Driver Code Starts. int main() { //taking total testcases int t; cin >> t; while (t--) { //taking number of houses int n; cin >> n; int a[n]; //inserting money of each house in the array for (int i = 0; i < n; ++i) cin >> a[i]; Solution ob; //calling function FindMaxSum() cout << ob.FindMaxSum(a, n) << endl; } return 0; } // } Driver Code Ends
25.82716
541
0.616635
shreejitverma
ae41cb5076286b79fd7b17737b07b0d2febfd7f3
1,687
hpp
C++
thirdparty/libgenerator/inc/generator/utils.hpp
ppiecuch/godot
ff2098b324b814a0d1bd9d5722aa871fc5214fab
[ "MIT", "Apache-2.0", "CC-BY-4.0", "Unlicense" ]
null
null
null
thirdparty/libgenerator/inc/generator/utils.hpp
ppiecuch/godot
ff2098b324b814a0d1bd9d5722aa871fc5214fab
[ "MIT", "Apache-2.0", "CC-BY-4.0", "Unlicense" ]
null
null
null
thirdparty/libgenerator/inc/generator/utils.hpp
ppiecuch/godot
ff2098b324b814a0d1bd9d5722aa871fc5214fab
[ "MIT", "Apache-2.0", "CC-BY-4.0", "Unlicense" ]
null
null
null
// Copyright 2015 Markus Ilmola // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. #ifndef GENERATOR_UTILS_HPP #define GENERATOR_UTILS_HPP namespace generator { /// Will have a type named "Type" that has same type as value returned by method /// generate() of type Generator. template <typename Generator> class GeneratedType { public: using Type = decltype(static_cast<const Generator *>(nullptr)->generate()); }; /// Will have a type named "Type" that has same type as value returned by method /// edges() for type Primitive. template <typename Primitive> class EdgeGeneratorType { public: using Type = decltype(static_cast<const Primitive *>(nullptr)->edges()); }; /// Will have a type named "Type" that has same type as value returned by method /// triangles() for type Primitive. template <typename Primitive> class TriangleGeneratorType { public: using Type = decltype(static_cast<const Primitive *>(nullptr)->triangles()); }; /// Will have a type named "Type" that has same type as value returned by method /// vertices() for type Primitive. template <typename Primitive> class VertexGeneratorType { public: using Type = decltype(static_cast<const Primitive *>(nullptr)->vertices()); }; /// Counts the number of steps left in the generator. template <typename Generator> int count(const Generator &generator) noexcept { Generator temp{ generator }; int c = 0; while (!temp.done()) { ++c; temp.next(); } return c; } } // namespace generator #endif
28.116667
80
0.739775
ppiecuch
ae441a8c950165c356976067cadacc904641a35c
1,526
cpp
C++
lib/CMakeTargetMachine.cpp
akemimadoka/LLVMCMakeBackend
64513885876ad81d932eeb06464aa7caa5f5843b
[ "MIT" ]
40
2020-04-04T09:16:28.000Z
2021-12-10T14:03:40.000Z
lib/CMakeTargetMachine.cpp
akemimadoka/LLVMCMakeBackend
64513885876ad81d932eeb06464aa7caa5f5843b
[ "MIT" ]
1
2020-04-07T10:44:48.000Z
2020-04-16T17:02:48.000Z
lib/CMakeTargetMachine.cpp
akemimadoka/LLVMCMakeBackend
64513885876ad81d932eeb06464aa7caa5f5843b
[ "MIT" ]
null
null
null
#include "CMakeTargetMachine.h" #include "CMakeBackend.h" #include "CheckNeedGotoPass.h" #include <llvm/CodeGen/TargetPassConfig.h> #include <llvm/Support/TargetRegistry.h> #include <llvm/Transforms/Utils.h> using namespace llvm; Target CMakeBackendTarget{}; extern "C" void LLVMInitializeCMakeBackendTarget() { RegisterTargetMachine<LLVMCMakeBackend::CMakeTargetMachine> X(CMakeBackendTarget); } extern "C" void LLVMInitializeCMakeBackendTargetInfo() { RegisterTarget<> X(CMakeBackendTarget, "cmake", "CMake backend", "CMake"); } extern "C" void LLVMInitializeCMakeBackendTargetMC() { } bool LLVMCMakeBackend::CMakeTargetSubtargetInfo::enableAtomicExpand() const { return true; } const llvm::TargetLowering* LLVMCMakeBackend::CMakeTargetSubtargetInfo::getTargetLowering() const { return &Lowering; } bool LLVMCMakeBackend::CMakeTargetMachine::addPassesToEmitFile( llvm::PassManagerBase& PM, llvm::raw_pwrite_stream& Out, llvm::raw_pwrite_stream* DwoOut, llvm::CodeGenFileType FileType, bool DisableVerify, llvm::MachineModuleInfoWrapperPass* MMIWP) { if (FileType != CodeGenFileType::CGFT_AssemblyFile) { return true; } const auto reg = PassRegistry::getPassRegistry(); const auto passConfig = createPassConfig(PM); PM.add(passConfig); PM.add(createLowerSwitchPass()); PM.add(new CheckNeedGotoPass()); PM.add(new CMakeBackend(Out)); return false; } const llvm::TargetSubtargetInfo* LLVMCMakeBackend::CMakeTargetMachine::getSubtargetImpl(const Function&) const { return &SubtargetInfo; }
24.612903
98
0.787025
akemimadoka
ae4e5b3ae84f0a27adcc7442fc4f8cd1a6f576eb
3,660
cpp
C++
Haru/hpdf/hpdf_image.cpp
miyako/4d-plugin-haru
749599d7ec9f21a2071ebef3859eb3fce8c59754
[ "MIT" ]
null
null
null
Haru/hpdf/hpdf_image.cpp
miyako/4d-plugin-haru
749599d7ec9f21a2071ebef3859eb3fce8c59754
[ "MIT" ]
1
2020-02-13T03:34:38.000Z
2020-06-01T21:08:11.000Z
Haru/hpdf/hpdf_image.cpp
miyako/4d-plugin-haru
749599d7ec9f21a2071ebef3859eb3fce8c59754
[ "MIT" ]
2
2016-06-07T08:28:17.000Z
2016-08-03T10:53:05.000Z
#include "hpdf_image.h" // ------------------------------------- Image ------------------------------------ void PDF_Image_AddSMask(sLONG_PTR *pResult, PackagePtr pParams) { C_TEXT Param1; C_TEXT Param2; C_LONGINT returnValue; Param1.fromParamAtIndex(pParams, 1); Param2.fromParamAtIndex(pParams, 2); HPDF_Image image = (HPDF_Image)_fromHex(Param1); HPDF_Image smask = (HPDF_Image)_fromHex(Param2); returnValue.setIntValue(HPDF_Image_AddSMask(image, smask)); returnValue.setReturn(pResult); } void PDF_Image_GetSize(sLONG_PTR *pResult, PackagePtr pParams) { C_TEXT Param1; C_REAL Param2; C_REAL Param3; C_LONGINT returnValue; Param1.fromParamAtIndex(pParams, 1); HPDF_Image image = (HPDF_Image)_fromHex(Param1); HPDF_Point size; returnValue.setIntValue(HPDF_Image_GetSize2(image, &size)); Param2.setDoubleValue(size.x); Param3.setDoubleValue(size.y); Param2.toParamAtIndex(pParams, 2); Param3.toParamAtIndex(pParams, 3); returnValue.setReturn(pResult); } void PDF_Image_GetWidth(sLONG_PTR *pResult, PackagePtr pParams) { C_TEXT Param1; C_LONGINT returnValue; Param1.fromParamAtIndex(pParams, 1); HPDF_Image image = (HPDF_Image)_fromHex(Param1); returnValue.setIntValue(HPDF_Image_GetWidth(image)); returnValue.setReturn(pResult); } void PDF_Image_GetHeight(sLONG_PTR *pResult, PackagePtr pParams) { C_TEXT Param1; C_LONGINT returnValue; Param1.fromParamAtIndex(pParams, 1); HPDF_Image image = (HPDF_Image)_fromHex(Param1); returnValue.setIntValue(HPDF_Image_GetHeight(image)); returnValue.setReturn(pResult); } void PDF_Image_GetBitsPerComponent(sLONG_PTR *pResult, PackagePtr pParams) { C_TEXT Param1; C_LONGINT returnValue; Param1.fromParamAtIndex(pParams, 1); HPDF_Image image = (HPDF_Image)_fromHex(Param1); returnValue.setIntValue(HPDF_Image_GetBitsPerComponent(image)); returnValue.setReturn(pResult); } void PDF_Image_GetColorSpace(sLONG_PTR *pResult, PackagePtr pParams) { C_TEXT Param1; C_TEXT returnValue; Param1.fromParamAtIndex(pParams, 1); HPDF_Image image = (HPDF_Image)_fromHex(Param1); CUTF8String u = CUTF8String((const uint8_t *)HPDF_Image_GetColorSpace(image)); returnValue.setUTF8String(&u); returnValue.setReturn(pResult); } void PDF_Image_SetColorMask(sLONG_PTR *pResult, PackagePtr pParams) { C_TEXT Param1; C_LONGINT Param2; C_LONGINT Param3; C_LONGINT Param4; C_LONGINT Param5; C_LONGINT Param6; C_LONGINT Param7; C_LONGINT returnValue; Param1.fromParamAtIndex(pParams, 1); Param2.fromParamAtIndex(pParams, 2); Param3.fromParamAtIndex(pParams, 3); Param4.fromParamAtIndex(pParams, 4); Param5.fromParamAtIndex(pParams, 5); Param6.fromParamAtIndex(pParams, 6); Param7.fromParamAtIndex(pParams, 7); HPDF_Image image = (HPDF_Image)_fromHex(Param1); HPDF_UINT rmin = (HPDF_UINT)Param2.getIntValue(); HPDF_UINT rmax = (HPDF_UINT)Param3.getIntValue(); HPDF_UINT gmin = (HPDF_UINT)Param4.getIntValue(); HPDF_UINT gmax = (HPDF_UINT)Param5.getIntValue(); HPDF_UINT bmin = (HPDF_UINT)Param6.getIntValue(); HPDF_UINT bmax = (HPDF_UINT)Param7.getIntValue(); returnValue.setIntValue(HPDF_Image_SetColorMask(image, rmin, rmax, gmin, gmax, bmin, bmax)); returnValue.setReturn(pResult); } void PDF_Image_SetMaskImage(sLONG_PTR *pResult, PackagePtr pParams) { C_TEXT Param1; C_TEXT Param2; C_LONGINT returnValue; Param1.fromParamAtIndex(pParams, 1); Param2.fromParamAtIndex(pParams, 2); HPDF_Image image = (HPDF_Image)_fromHex(Param1); HPDF_Image mask_image = (HPDF_Image)_fromHex(Param2); returnValue.setIntValue(HPDF_Image_SetMaskImage(image, mask_image)); returnValue.setReturn(pResult); }
24.4
93
0.764208
miyako
ae4f4b4e979772284c486e8ee37fad05527ab9d8
3,071
cxx
C++
osf-to-esf/dborl/dborl_image_description.cxx
wenhanshi/lemsvxl-shock-computation
1208e5f6a0c9fddbdffcc20f2c1d914e07015b45
[ "MIT" ]
1
2022-01-01T20:43:47.000Z
2022-01-01T20:43:47.000Z
osf-to-esf/dborl/dborl_image_description.cxx
wenhanshi/lemsvxl-shock-computation
1208e5f6a0c9fddbdffcc20f2c1d914e07015b45
[ "MIT" ]
null
null
null
osf-to-esf/dborl/dborl_image_description.cxx
wenhanshi/lemsvxl-shock-computation
1208e5f6a0c9fddbdffcc20f2c1d914e07015b45
[ "MIT" ]
null
null
null
//: // \file // \brief // \author Ozge Can Ozcanli (ozge@lems.brown.edu) // \date 010/03/07 #include "dborl_image_description.h" #include "dborl_image_data_description_base.h" #include "dborl_image_bbox_description.h" #include "dborl_image_polygon_description.h" #include "dborl_image_mask_description.h" #include <vcl_iostream.h> dborl_image_description::dborl_image_description(dborl_image_bbox_description_sptr box_data) { vcl_map<vcl_string, vcl_vector<vsol_box_2d_sptr> >& map = box_data->get_category_map(); //: add each category and counts one by one for (vcl_map<vcl_string, vcl_vector<vsol_box_2d_sptr> >::iterator i = map.begin(); i != map.end(); i++) category_list_[i->first] = (i->second).size(); category_data_ = box_data->cast_to_image_data_description_base(); } dborl_image_description::dborl_image_description(dborl_image_polygon_description_sptr poly_data) { vcl_map<vcl_string, vcl_vector<vsol_polygon_2d_sptr> >& map = poly_data->get_category_map(); //: add each category and counts one by one for (vcl_map<vcl_string, vcl_vector<vsol_polygon_2d_sptr> >::iterator i = map.begin(); i != map.end(); i++) category_list_[i->first] = (i->second).size(); category_data_ = poly_data->cast_to_image_data_description_base(); } //: assuming the names in the vector are names of categories for corresponding indices // (the vector may contain way more cats than that exists in the mask) dborl_image_description::dborl_image_description(dborl_image_mask_description_sptr mask_data, vcl_vector<vcl_string>& cats) { category_data_ = mask_data->cast_to_image_data_description_base(); for (unsigned i = 0; i < cats.size(); i++) { if (category_exists(cats[i])) add_to_category_cnt(cats[i], 1); // increments the count by 1 else add_category(cats[i]); // sets the count to 1 } } unsigned dborl_image_description::version() { return 0; } void dborl_image_description::b_read() { vcl_cout << "IMPLEMENT: dborl_image_description::b_read()\n"; } void dborl_image_description::b_write() { vcl_cout << "IMPLEMENT: dborl_image_description::b_write()\n"; } unsigned dborl_image_description::get_object_type() { return dborl_object_type::image; } void dborl_image_description::write_xml(vcl_ostream& os) { os << "<type name = \"image\">\n"; os << "\t<description>\n"; if (category_data_->cast_to_image_polygon_description()) { category_data_->cast_to_image_polygon_description()->write_xml(os); } else if (category_data_->cast_to_image_bbox_description()) { category_data_->cast_to_image_bbox_description()->write_xml(os); } else if (category_data_->cast_to_image_mask_description()) { for (vcl_map<vcl_string, int>::iterator iter = category_list_.begin(); iter != category_list_.end(); iter++) { for (int i = 0; i < iter->second; i++) { os << "\t\t<instance>\n"; os << "\t\t\t<category>" << iter->first << "</category>\n"; os << "\t\t</instance>\n"; } } } os << "\t</description>\n"; os << "</type>\n"; }
34.122222
123
0.713123
wenhanshi
ae52889679352218af67833e2b1ae882b3353939
2,650
cpp
C++
src/sol_scip_kbest.cpp
aurtg/david
26922b8b9f35ee749f44e56a599aa5e7136024e2
[ "MIT" ]
null
null
null
src/sol_scip_kbest.cpp
aurtg/david
26922b8b9f35ee749f44e56a599aa5e7136024e2
[ "MIT" ]
null
null
null
src/sol_scip_kbest.cpp
aurtg/david
26922b8b9f35ee749f44e56a599aa5e7136024e2
[ "MIT" ]
null
null
null
#include <mutex> #include <algorithm> #include "./kernel.h" #include "./lhs.h" #include "./cnv.h" #include "./sol.h" #include "./json.h" namespace dav { namespace sol { #ifdef USE_SCIP string_t code2str(SCIP_RETCODE c); #endif scip_k_best_t::scip_k_best_t(const kernel_t *m, bool cpi) : scip_t(m, cpi), m_max_num(param()->geti("max-solution-num", 5)), m_max_delta(param()->getf("max-eval-delta", 5.0)), m_margin(param()->geti("eval-margin", 3)) {} void scip_k_best_t::validate() const { scip_t::validate(); if (not m_max_num.valid()) throw exception_t("The value \"max-solution-num\" must not be a minus value."); if (m_margin < 0) throw exception_t("The valud \"margin\" must not be a minus value."); } void scip_k_best_t::solve(std::shared_ptr<ilp::problem_t> prob) { #ifdef USE_SCIP model_t m(this, prob); auto exe = [](SCIP_RETCODE c) { if (c <= 0) throw exception_t(format( "SCIP error-code: \"%s\"", code2str(c).c_str())); }; exe(m.initialize()); while (m_max_num.do_accept(out.size() + 1)) { console_t::auto_indent_t ai; if (console()->is(verboseness_e::ROUGH)) { console()->print_fmt("Optimization #%d", out.size() + 1); console()->add_indent(); } if (out.empty()) exe(m.solve(&out)); else { ilp::constraint_t c = prohibit(out.back(), m_margin); exe(m.free_transform()); exe(m.add_constraint(c)); exe(m.solve(&out)); if (out.empty()) break; else if (out.back()->type() == ilp::SOL_NOT_AVAILABLE) { out.pop_back(); break; } else if (m_max_delta.valid()) { // IF DELTA IS BIGGER THAN THRESHOLD, THIS SOLUTION IS NOT ACCEPTABLE. double delta = out.back()->objective_value() - out.front()->objective_value(); if (!m_max_delta.do_accept(std::abs(delta))) { out.pop_back(); break; } } } if (has_timed_out()) break; } #endif } void scip_k_best_t::write_json(json::object_writer_t &wr) const { scip_t::write_json(wr); wr.write_field<int>("max-num", m_max_num.get()); wr.write_field<double>("max-delta", m_max_delta.get()); wr.write_field<int>("margin", m_margin); } ilp_solver_t* scip_k_best_t::generator_t::operator()(const kernel_t *m) const { return new sol::scip_k_best_t(m, do_use_cpi); } } }
22.457627
94
0.551698
aurtg
ae5289e95ee89e9358178fefeafc955aca22fb10
11,663
cpp
C++
Computer Graphics/src/scene_texture.cpp
sergio5405/Computer-Graphics-Project
829cd1f25caaa88070a0aeccd2b7cdcb5007fbcc
[ "MIT" ]
null
null
null
Computer Graphics/src/scene_texture.cpp
sergio5405/Computer-Graphics-Project
829cd1f25caaa88070a0aeccd2b7cdcb5007fbcc
[ "MIT" ]
null
null
null
Computer Graphics/src/scene_texture.cpp
sergio5405/Computer-Graphics-Project
829cd1f25caaa88070a0aeccd2b7cdcb5007fbcc
[ "MIT" ]
null
null
null
#include "scene_texture.h" #include "ifile.h" #include "time.h" #include "cgmath.h" #include "vec2.h" #include "vec3.h" #include "mat3.h" #include "mat4.h" #include <string> #include <vector> scene_texture::~scene_texture() { glDeleteProgram(shader_program); } void scene_texture::init() { std::vector<cgmath::vec3> positions; //Front positions.push_back(cgmath::vec3(3.0f, -3.0f, 3.0f)); positions.push_back(cgmath::vec3(3.0f, 3.0f, 3.0f)); positions.push_back(cgmath::vec3(-3.0f, -3.0f, 3.0f)); positions.push_back(cgmath::vec3(-3.0f, 3.0f, 3.0f)); //Top positions.push_back(cgmath::vec3(3.0f, 3.0f, 3.0f)); positions.push_back(cgmath::vec3(3.0f, 3.0f, -3.0f)); positions.push_back(cgmath::vec3(-3.0f, 3.0f, 3.0f)); positions.push_back(cgmath::vec3(-3.0f, 3.0f, -3.0f)); //Right positions.push_back(cgmath::vec3(3.0f, -3.0f, -3.0f)); positions.push_back(cgmath::vec3(3.0f, 3.0f, -3.0f)); positions.push_back(cgmath::vec3(3.0f, -3.0f, 3.0f)); positions.push_back(cgmath::vec3(3.0f, 3.0f, 3.0f)); //Left positions.push_back(cgmath::vec3(-3.0f, -3.0f, 3.0f)); positions.push_back(cgmath::vec3(-3.0f, 3.0f, 3.0f)); positions.push_back(cgmath::vec3(-3.0f, -3.0f, -3.0f)); positions.push_back(cgmath::vec3(-3.0f, 3.0f, -3.0f)); //Down positions.push_back(cgmath::vec3(3.0f, -3.0f, -3.0f)); positions.push_back(cgmath::vec3(3.0f, -3.0f, 3.0f)); positions.push_back(cgmath::vec3(-3.0f, -3.0f, -3.0f)); positions.push_back(cgmath::vec3(-3.0f, -3.0f, 3.0f)); //Back positions.push_back(cgmath::vec3(-3.0f, -3.0f, -3.0f)); positions.push_back(cgmath::vec3(-3.0f, 3.0f, -3.0f)); positions.push_back(cgmath::vec3(3.0f, -3.0f, -3.0f)); positions.push_back(cgmath::vec3(3.0f, 3.0f, -3.0f)); std::vector<unsigned int> indices{ 0, 1, 2, //front 1, 3, 2, 4, 5, 6, //top 5, 7, 6, 8, 9, 10, //right 9, 11, 10, 12, 13, 14, //left 13, 15, 14, 16, 17, 18, //down 17, 19, 18, 20, 21, 22, //back 21, 23, 22 }; glGenVertexArrays(1, &vao); glBindVertexArray(vao); glGenBuffers(1, &positionsVBO); glBindBuffer(GL_ARRAY_BUFFER, positionsVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(cgmath::vec3) * positions.size(), positions.data(), GL_DYNAMIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr); glBindBuffer(GL_ARRAY_BUFFER, 0); glGenBuffers(1, &positionsIndicesBuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, positionsIndicesBuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * indices.size(), indices.data(), GL_STATIC_DRAW); std::vector<cgmath::vec3> colors; for (int i = 0; i < 4; i++) colors.push_back(cgmath::vec3(1.0f, 0.0f, 0.0f));//red for (int i = 0; i < 4; i++) colors.push_back(cgmath::vec3(0.0f, 1.0f, 0.0f));//green for (int i = 0; i < 4; i++) colors.push_back(cgmath::vec3(0.0f, 0.0f, 1.0f));//blue for (int i = 0; i < 4; i++) colors.push_back(cgmath::vec3(1.0f, 0.0f, 1.0f));//pink for (int i = 0; i < 4; i++) colors.push_back(cgmath::vec3(1.0f, 1.0f, 0.0f));//yellow for (int i = 0; i < 4; i++) colors.push_back(cgmath::vec3(0.0f, 1.0f, 1.0f));//cyan //std::vector<unsigned int> indicesColors{ 0, 0, 0, 0, 0, 0, //front // 1, 1, 1, 1, 1, 1, //top // 2, 2, 2, 2, 2, 2, //right // 3, 3, 3, 3, 3, 3, //left // 4, 4, 4, 4, 4, 4, //down // 5, 5, 5, 5, 5, 5, //back //}; glGenBuffers(1, &colorBuffer); glBindBuffer(GL_ARRAY_BUFFER, colorBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(cgmath::vec3) * colors.size(), colors.data(), GL_DYNAMIC_DRAW); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, nullptr); glBindBuffer(GL_ARRAY_BUFFER, 0); /*glGenBuffers(1, &indicesColorBuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indicesColorBuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * indicesColors.size(), indicesColors.data(), GL_STATIC_DRAW); glBindVertexArray(0);*/ std::vector<cgmath::vec3> normals; for (int i = 0; i < 4; i++) normals.push_back(cgmath::vec3(0.0f, 0.0f, 1.0f));//front for (int i = 0; i < 4; i++) normals.push_back(cgmath::vec3(0.0f, 1.0f, 0.0f));//top for (int i = 0; i < 4; i++) normals.push_back(cgmath::vec3(1.0f, 0.0f, 0.0f));//right for (int i = 0; i < 4; i++) normals.push_back(cgmath::vec3(-1.0f, 0.0f, 0.0f));//left for (int i = 0; i < 4; i++) normals.push_back(cgmath::vec3(0.0f, -1.0f, 0.0f));//down for (int i = 0; i < 4; i++) normals.push_back(cgmath::vec3(0.0f, 0.0f, -1.0f));//back glGenBuffers(1, &normalBuffer); glBindBuffer(GL_ARRAY_BUFFER, normalBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(cgmath::vec3) * normals.size(), normals.data(), GL_DYNAMIC_DRAW); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, nullptr); glBindBuffer(GL_ARRAY_BUFFER, 0); std::vector<cgmath::vec2> texCoords; for (int i = 0; i < 6; i++) { texCoords.push_back(cgmath::vec2(1.0f, 0.0f)); texCoords.push_back(cgmath::vec2(1.0f, 1.0f)); texCoords.push_back(cgmath::vec2(0.0f, 0.0f)); texCoords.push_back(cgmath::vec2(0.0f, 1.0f)); } glGenBuffers(1, &texCoordsBuffer); glBindBuffer(GL_ARRAY_BUFFER, texCoordsBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(cgmath::vec2) * texCoords.size(), texCoords.data(), GL_DYNAMIC_DRAW); glEnableVertexAttribArray(3); glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, 0, nullptr); glBindBuffer(GL_ARRAY_BUFFER, 0); ilGenImages(1, &pigImageId); ilBindImage(pigImageId); ilLoadImage("images/pig.png"); glGenTextures(2, textureId); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, textureId[0]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, ilGetInteger(IL_IMAGE_FORMAT), ilGetInteger(IL_IMAGE_WIDTH), ilGetInteger(IL_IMAGE_HEIGHT), 0, ilGetInteger(IL_IMAGE_FORMAT), ilGetInteger(IL_IMAGE_TYPE), ilGetData()); glGenerateMipmap(GL_TEXTURE_2D); ilDeleteImages(1, &pigImageId); ILenum Error; while ((Error = ilGetError()) != IL_NO_ERROR) { printf("%d: /n", Error); } ilGenImages(1, &crateImageId); ilBindImage(crateImageId); ilLoadImage("images/crate.png"); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, textureId[1]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, ilGetInteger(IL_IMAGE_FORMAT), ilGetInteger(IL_IMAGE_WIDTH), ilGetInteger(IL_IMAGE_HEIGHT), 0, ilGetInteger(IL_IMAGE_FORMAT), ilGetInteger(IL_IMAGE_TYPE), ilGetData()); glGenerateMipmap(GL_TEXTURE_2D); ilDeleteImages(1, &crateImageId); while ((Error = ilGetError()) != IL_NO_ERROR) { printf("%d: /n", Error); } glBindTexture(GL_TEXTURE_2D, 0); ifile shader_file; shader_file.read("shaders/cubeTex.vert"); std::string vertex_source = shader_file.get_contents(); const GLchar* vertex_source_c = (const GLchar*)vertex_source.c_str(); GLuint vertex_shader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex_shader, 1, &vertex_source_c, nullptr); glCompileShader(vertex_shader); GLint Result = GL_FALSE; int InfoLogLength; // Check Vertex Shader glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &Result); glGetShaderiv(vertex_shader, GL_INFO_LOG_LENGTH, &InfoLogLength); if (InfoLogLength > 0) { std::vector<char> VertexShaderErrorMessage(InfoLogLength + 1); glGetShaderInfoLog(vertex_shader, InfoLogLength, NULL, &VertexShaderErrorMessage[0]); printf("%s\n", &VertexShaderErrorMessage[0]); } shader_file.read("shaders/cubeColorsTex.frag"); std::string fragment_source = shader_file.get_contents(); const GLchar* fragment_source_c = (const GLchar*)fragment_source.c_str(); GLuint fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment_shader, 1, &fragment_source_c, nullptr); glCompileShader(fragment_shader); Result = GL_FALSE; InfoLogLength; // Check Frag Shader glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &Result); glGetShaderiv(fragment_shader, GL_INFO_LOG_LENGTH, &InfoLogLength); if (InfoLogLength > 0) { std::vector<char> FragShaderErrorMessage(InfoLogLength + 1); glGetShaderInfoLog(fragment_shader, InfoLogLength, NULL, &FragShaderErrorMessage[0]); printf("%s\n", &FragShaderErrorMessage[0]); } shader_program = glCreateProgram(); glAttachShader(shader_program, vertex_shader); glAttachShader(shader_program, fragment_shader); glBindAttribLocation(shader_program, 0, "VertexPosition"); glBindAttribLocation(shader_program, 1, "Color"); glBindAttribLocation(shader_program, 2, "VertexNormal"); glBindAttribLocation(shader_program, 3, "TexC"); glLinkProgram(shader_program); glDeleteShader(vertex_shader); glDeleteShader(fragment_shader); glUseProgram(0); } void scene_texture::awake() { glClearColor(1.0f, 1.0f, 1.0f, 1.0f); glEnable(GL_PROGRAM_POINT_SIZE); } void scene_texture::sleep() { glClearColor(1.0f, 1.0f, 1.0f, 1.0f); glDisable(GL_PROGRAM_POINT_SIZE); } void scene_texture::mainLoop() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(shader_program); float t = time::elapsed_time().count(); ////Vmath library from http://www.openglsuperbible.com/example-code/ //Model matrix cgmath::mat4 rotationMatrix = cgmath::mat4::rotateMatrix(t*30.0f, t*60.0f, t*30.0f); cgmath::mat4 modelMatrix = rotationMatrix; // View Matrix cgmath::mat4 viewMatrix(1.0f); viewMatrix[3][2] = 20.0f; viewMatrix = cgmath::mat4::inverse(viewMatrix); // Projection Matrix float far = 1000.0f; float near = 1.0f; float half_fov = cgmath::radians(30.0f); cgmath::mat4 projectionMatrix; projectionMatrix[0][0] = 1.0f / (1.0f * tan(half_fov)); projectionMatrix[1][1] = 1.0f / tan(half_fov); projectionMatrix[2][2] = -((far + near) / (far - near)); projectionMatrix[2][3] = -1.0f; projectionMatrix[3][2] = -((2 * far * near) / (far - near)); cgmath::mat4 mvpMatrix = projectionMatrix * viewMatrix * modelMatrix; cgmath::mat3 esqSupIzq = cgmath::mat3(); for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) esqSupIzq[i][j] = modelMatrix[i][j]; cgmath::mat3 normalMatrix = cgmath::mat3::transpose(cgmath::mat3::inverse(esqSupIzq)); GLuint mvp_location = glGetUniformLocation(shader_program, "MVPMatrix"); glUniformMatrix4fv(mvp_location, 1, GL_FALSE, &mvpMatrix[0][0]); GLuint normal_location = glGetUniformLocation(shader_program, "NormalMatrix"); glUniformMatrix3fv(normal_location, 1, GL_FALSE, &normalMatrix[0][0]); GLuint model_location = glGetUniformLocation(shader_program, "ModelMatrix"); glUniformMatrix4fv(model_location, 1, GL_FALSE, &modelMatrix[0][0]); cgmath::vec3 lightVector = cgmath::vec3(-3, 6, 10); GLuint light_location = glGetUniformLocation(shader_program, "LightPosition"); glUniform3fv(light_location, 1, &lightVector[0]); cgmath::vec3 cameraPos = cgmath::vec3(0, 0, 10); GLuint camera_loc = glGetUniformLocation(shader_program, "CameraPosition"); glUniform3fv(camera_loc, 1, &cameraPos[0]); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, textureId[0]); GLint pig_tex_location = glGetUniformLocation(shader_program, "PigTex"); glUniform1i(pig_tex_location, 0); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, textureId[1]); GLint crate_tex_location = glGetUniformLocation(shader_program, "CrateTex"); glUniform1i(crate_tex_location, 1); glBindVertexArray(vao); glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, nullptr); glBindVertexArray(0); glUseProgram(0); } void scene_texture::resize(int width, int height) { glViewport(0, 0, width, height); }
32.307479
87
0.717311
sergio5405
ae551ceeabbd4f32ea97ede9162edf49c11e9545
2,054
cpp
C++
bazaar/PixRaster/UppLept.cpp
dreamsxin/ultimatepp
41d295d999f9ff1339b34b43c99ce279b9b3991c
[ "BSD-2-Clause" ]
2
2016-04-07T07:54:26.000Z
2020-04-14T12:37:34.000Z
bazaar/PixRaster/UppLept.cpp
dreamsxin/ultimatepp
41d295d999f9ff1339b34b43c99ce279b9b3991c
[ "BSD-2-Clause" ]
null
null
null
bazaar/PixRaster/UppLept.cpp
dreamsxin/ultimatepp
41d295d999f9ff1339b34b43c99ce279b9b3991c
[ "BSD-2-Clause" ]
null
null
null
#include "PixRaster.h" #include <Draw/Draw.h> NAMESPACE_UPP /////////////////////////////////////////////////////////////////////////////// // All Leptonica routines operates on Pix data structures; here 2 conversion // routines are provided to go to/from Upp Images /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // Creation of Pix image from an Upp Image // As Upp Image is in RGBA format, it's simply converted // to an RGB Leptonica Pix; alpha channel is discarded PIX *Image2Pix(const Image &img) { PIX *pix; // Get image sizes int width = img.GetWidth(); int height = img.GetHeight(); // Get image sizes in dots int sizeX = img.GetDots().cx; int sizeY = img.GetDots().cy; // Allocates the Pix structure pix = pixCreateNoInit(width, height, 32); if(!pix) return NULL; // sets image resolution (if any) // don't know if it's correct, yet.... pixSetResolution(pix, sizeX / width, sizeY / height); // transfer the image bytes memcpy(pixGetData(pix), ~img, 4*width*height); return pix; } // END Image2Pix() /////////////////////////////////////////////////////////////////////////////// // Creation of Upp Image from Pix // Pix is first converted to an RGB format, then to Upp Image Image Pix2Image(PIX * pix) { bool destroyCopy = false; // colormapped and non-32 bit depth pixs need conversion before if(pixGetColormap(pix) || pixGetDepth(pix) != 32) { // we need to destroy converted pix on exit destroyCopy = true; // convert pix to 32 bit format pix = pixConvertTo32(pix); if(!pix) return Image(); } // just copy data buffer to a new imagebuffer int width = pixGetWidth(pix); int height = pixGetHeight(pix); ImageBuffer img(width, height); memcpy(~img, pixGetData(pix), 4*width*height); // sets image type to opaque // not sure if we must set alpha bit to 255...... img.SetKind(IMAGE_OPAQUE); if(destroyCopy) pixDestroy(&pix); return img; } END_UPP_NAMESPACE
25.675
79
0.588121
dreamsxin
ae5542944f061d0fc74cb545b84b0d4b3d8b6986
448
cpp
C++
src/get_texture_colour.cpp
jackys-95/computer-graphics-final-image-competition
65e7c041530f319d10faba177ef03963aad16e56
[ "MIT" ]
null
null
null
src/get_texture_colour.cpp
jackys-95/computer-graphics-final-image-competition
65e7c041530f319d10faba177ef03963aad16e56
[ "MIT" ]
null
null
null
src/get_texture_colour.cpp
jackys-95/computer-graphics-final-image-competition
65e7c041530f319d10faba177ef03963aad16e56
[ "MIT" ]
null
null
null
#include "get_texture_colour.h" #include <iostream> Eigen::Vector3d get_texture_colour(const std::vector<unsigned char> &rgb, const int height, const int width, const int offset) { int new_height = 0; if (offset == 247) { new_height = 360 - height; } else { new_height = height; } int start_index = 3 * (width + 640 * new_height); return Eigen::Vector3d(rgb[0 + start_index],rgb[1 +start_index], rgb[2+start_index]); }
24.888889
92
0.676339
jackys-95
ae5b4d125742c200e4661b8418e7cdd46ff338a4
958
hpp
C++
fsc/include/fsx/sim_event.hpp
gbucknell/fsc-sdk
11b7cda4eea35ec53effbe37382f4b28020cd59d
[ "MIT" ]
null
null
null
fsc/include/fsx/sim_event.hpp
gbucknell/fsc-sdk
11b7cda4eea35ec53effbe37382f4b28020cd59d
[ "MIT" ]
null
null
null
fsc/include/fsx/sim_event.hpp
gbucknell/fsc-sdk
11b7cda4eea35ec53effbe37382f4b28020cd59d
[ "MIT" ]
null
null
null
// (c) Copyright 2008 Samuel Debionne. // // Distributed under the MIT Software License. (See accompanying file // license.txt) or copy at http://www.opensource.org/licenses/mit-license.php) // // See http://code.google.com/p/fsc-sdk/ for the library home page. // // $Revision: $ // $History: $ /// \file sim_event.hpp /// Events of the Sim Connect API #if !defined(__FSX_SIM_EVENT_HPP__) #define __FSX_SIM_EVENT_HPP__ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include <cassert> #include <windows.h> #include <SimConnect.h> namespace fsx { /// Sim connect event. class sim_event { public: sim_event(SIMCONNECT_CLIENT_EVENT_ID _id, const DWORD& _data) : id_(_id), data_(_data) {} private: SIMCONNECT_CLIENT_EVENT_ID id_; DWORD data_; }; //template <class T> //struct sim_data_traits //{ // int //}; } //namespace fsx #endif //__FSX_SIM_EVENT_HPP__
17.418182
94
0.656576
gbucknell
ae609a38d49a1719bae957c603e67db286fac184
20,403
cpp
C++
hackathon/XuanZhao/TraceNeuronBasedLine/branchtree.cpp
MoritzNegwer/vaa3d_tools
bdb2dc95bc13e9a31e1d416cc341c00d97153968
[ "MIT" ]
null
null
null
hackathon/XuanZhao/TraceNeuronBasedLine/branchtree.cpp
MoritzNegwer/vaa3d_tools
bdb2dc95bc13e9a31e1d416cc341c00d97153968
[ "MIT" ]
null
null
null
hackathon/XuanZhao/TraceNeuronBasedLine/branchtree.cpp
MoritzNegwer/vaa3d_tools
bdb2dc95bc13e9a31e1d416cc341c00d97153968
[ "MIT" ]
null
null
null
#include "branchtree.h" #include <queue> void adjustRalationForSplitBranches(Branch *origin, vector<Branch *> target) { target.front()->parent = origin->parent; if (origin->parent) { auto it = origin->parent->children.begin(); for (; it != origin->parent->children.end(); ++it) { if (*it == origin) { origin->parent->children.erase(it); break; } } origin->parent->children.push_back(target.front()); } for (int k = 1; k < target.size(); ++k) { target[k]->parent = target[k - 1]; target[k - 1]->children.push_back(target[k]); } target.back()->children = origin->children; for (Branch* child : origin->children) { child->parent = target.back(); } } void adjustRalationForRemoveBranch(Branch *origin) { if (origin->parent) { auto it = origin->parent->children.begin(); for (; it != origin->parent->children.end(); ++it) { if (*it == origin) { origin->parent->children.erase(it); break; } } } for (Branch* child : origin->children) { if (origin->parent) { origin->parent->children.push_back(child); } child->parent = origin->parent; } } void PointFeature::getFeature(unsigned char *pdata, long long *sz, float x, float y, float z) { this->x = x; this->y = y; this->z = z; double *vec1 = new double[3]; double *vec2 = new double[3]; double *vec3 = new double[3]; double pc1, pc2, pc3; int xx = x + 0.5, yy = y + 0.5, zz = z + 0.5; xx = xx >= sz[0] ? sz[0] - 1 : xx; xx = xx < 0 ? 0 : xx; yy = yy >= sz[1] ? sz[1] - 1 : yy; yy = yy < 0 ? 0 : yy; zz = zz >= sz[2] ? sz[2] - 1 : zz; zz = zz < 0 ? 0 : zz; this->intensity = pdata[zz * sz[0]* sz[1] + yy * sz[0] + xx]; computeCubePcaEigVec(pdata, sz, xx, yy, zz, 3, 3, 3, pc1, pc2, pc3, vec1, vec2, vec3); this->linearity_3 = pc2 == 0 ? 0 : pc1 / pc2; computeCubePcaEigVec(pdata, sz, xx, yy, zz, 5, 5, 5, pc1, pc2, pc3, vec1, vec2, vec3); this->linearity_5 = pc2 == 0 ? 0 : pc1 / pc2; computeCubePcaEigVec(pdata, sz, xx, yy, zz, 8, 8, 8, pc1, pc2, pc3, vec1, vec2, vec3); this->linearity_8 = pc2 == 0 ? 0 : pc1 / pc2; if (x < 5 || x > sz[0] -5 || y < 5 || y > sz[1] - 5 || z < 5 || z > sz[2] - 5) { this->nearEdge = 1; } else { this->nearEdge = 0; } if(vec1){ delete[] vec1; vec1 = 0; } if(vec2){ delete[] vec2; vec2 = 0; } if(vec3){ delete[] vec3; vec3 = 0; } } void LineFeature::intial() { this->pointsFeature.clear(); this->pointsFeature = vector<PointFeature>(5); this->directions.clear(); this->directions = vector<XYZ>(5, XYZ()); this->intensity_mean = this->intensity_std = 0; this->intensity_mean_r5 = this->intensity_std_r5 = 0; this->linearity_3_mean = this->linearity_5_mean = this->linearity_8_mean = 0; } vector<Branch*> Branch::splitByInflectionPoint(float d, float cosAngleThres) { vector<Branch*> results; int pointSize = this->points.size(); float* path = new float[pointSize]; memset(path, 0, sizeof(float) * pointSize); if (pointSize < 2) { results.push_back(this); return results; } for (int i = 1; i < pointSize; ++i) { float tmpD = zx_dist(this->points[i], this->points[i - 1]); path[i] = path[i-1] + tmpD; } XYZ v1,v2; XYZ p1,p2; p1 = XYZ(this->points[0].x, this->points[0].y, this->points[0].z); float cosAngle; int startPoint = 0; int i,j,k; int ppIndex,ccIndex,curIndex; XYZ pp1,pp2; float inflectionPointCosAngle; int inflectionPointIndex = -1; for (i = 0; i < pointSize;) { for (j = i+1; j < pointSize; ++j) { if (path[j] - path[i] > d) { p2 = XYZ(this->points[j].x, this->points[j].y, this->points[j].z); if (i == startPoint) { v1 = p2 - p1; } else { v2 = p2 - p1; cosAngle = dot(normalize(v1), normalize(v2)); if (cosAngle < cosAngleThres) { inflectionPointCosAngle = 1; inflectionPointIndex = -1; for (k = startPoint + 1; k < j; ++k) { if ((path[k] - path[startPoint]) < d || (path[j] - path[k]) < d) { continue; } curIndex = k; ppIndex = startPoint; ccIndex = j; for (int ki = k - 1; ki >= startPoint; --ki) { if (path[k] - path[ki] > d) { ppIndex = ki; break; } } for (int ki = k + 1; ki <= j; ++ki) { if (path[ki] - path[k] > d) { ccIndex = ki; break; } } pp1 = XYZ(this->points[ppIndex].x, this->points[ppIndex].y, this->points[ppIndex].z); pp2 = XYZ(this->points[ccIndex].x, this->points[ccIndex].y, this->points[ccIndex].z); double tmpCosAngle = dot(normalize(pp1), normalize(pp2)); if (tmpCosAngle < inflectionPointCosAngle) { inflectionPointCosAngle = tmpCosAngle; inflectionPointIndex = k; } } if(cosAngle > (sqrt(2.0)/2) || inflectionPointIndex == -1){ inflectionPointIndex = (j + startPoint) / 2; } Branch* line = new Branch(); for (k = startPoint; k <= inflectionPointIndex; ++k) { line->points.push_back(this->points[k]); } results.push_back(line); startPoint = j; } } p1 = p2; break; } } i = j; } if (startPoint == 0) { results.push_back(this); return results; } else { Branch* line = new Branch(); for (k = inflectionPointIndex; k < pointSize; ++k) { line->points.push_back(this->points[k]); } results.push_back(line); } adjustRalationForSplitBranches(this, results); return results; } vector<Branch*> Branch::splitByLength(float l_thres) { vector<Branch*> results; this->calLength(); if (this->length < l_thres) { results.push_back(this); return results; } int length_mean = this->length / ceil(this->length / l_thres); int count_i = 1; float path_length = 0; int start_index = 0; for (int i = 1; i<this->points.size() - 1; ++i) { path_length += zx_dist(this->points[i], this->points[i - 1]); if (path_length > length_mean * count_i) { Branch* branch = new Branch(); branch->points.insert(branch->points.end(), this->points.begin() + start_index, this->points.begin() + i + 1); results.push_back(branch); start_index = i; count_i++; } } Branch* branch = new Branch(); branch->points.insert(branch->points.end(), this->points.begin() + start_index, this->points.end()); results.push_back(branch); adjustRalationForSplitBranches(this, results); return results; } void Branch::removePointsNearSoma(const NeuronSWC &soma, float ratio) { if (this->level > 2) { return; } auto it = this->points.begin(); for (; it != this->points.end(); ) { if (zx_dist(*it, soma) < soma.r * ratio) { this->points.erase(it); } else { break; } } } void Branch::removeTerminalPoints(float d) { auto it = this->points.begin(); float length = 0; for (; it != this->points.end() - 1; ) { if (length < d) { length += zx_dist(*it, *(it + 1)); this->points.erase(it); } else { break; } } it = this->points.end() - 1; length = 0; for (; it != this->points.begin(); ) { if (length < d) { length += zx_dist(*it, *(it - 1)); this->points.erase(it); --it; } else { break; } } } float Branch::calLength() { this->length = 0; auto it = this->points.begin(); for(; it != this->points.end() - 1; ++it) { this->length += zx_dist(*it, *(it + 1)); } return this->length; } float Branch::calDistance() { this->distance = this->points.size() ? zx_dist(this->points.front(), this->points.back()) : 0; return this->distance; } void Branch::getFeature(unsigned char *pdata, long long *sz) { this->line_feature.intial(); this->calLength(); this->calDistance(); int pointSize = this->points.size(); double *vec1 = new double[3]; double *vec2 = new double[3]; double *vec3 = new double[3]; int x,y,z; double pc1,pc2,pc3; vector<unsigned char> intensities; this->line_feature.pointsFeature[0].getFeature(pdata, sz, this->points.front().x, this->points.front().y, this->points.front().z); this->line_feature.intensity_mean += this->line_feature.pointsFeature.front().intensity; intensities.push_back(this->line_feature.pointsFeature.front().intensity); this->line_feature.linearity_3_mean += this->line_feature.pointsFeature.front().linearity_3; this->line_feature.linearity_5_mean += this->line_feature.pointsFeature.front().linearity_5; this->line_feature.linearity_8_mean += this->line_feature.pointsFeature.front().linearity_8; int point_i = 1; float cur_length = 0; for (int i = 1; i < pointSize - 1; ++i) { cur_length += zx_dist(this->points[i], this->points[i - 1]); if (cur_length > this->length / 5 * point_i) { this->line_feature.pointsFeature[point_i].getFeature(pdata, sz, this->points[i].x, this->points[i].y, this->points[i].z); this->line_feature.intensity_mean += this->line_feature.pointsFeature[point_i].intensity; intensities.push_back(this->line_feature.pointsFeature[point_i].intensity); this->line_feature.linearity_3_mean += this->line_feature.pointsFeature[point_i].linearity_3; this->line_feature.linearity_5_mean += this->line_feature.pointsFeature[point_i].linearity_5; this->line_feature.linearity_8_mean += this->line_feature.pointsFeature[point_i].linearity_8; point_i++; } else { x = this->points[i].x + 0.5; y = this->points[i].y + 0.5; z = this->points[i].z + 0.5; x = x >= sz[0] ? sz[0] - 1 : x; x = x < 0 ? 0 : x; y = y >= sz[1] ? sz[1] - 1 : y; y = y < 0 ? 0 : y; z = z >= sz[2] ? sz[2] - 1 : z; z = z < 0 ? 0 : z; this->line_feature.intensity_mean += pdata[z * sz[0] * sz[1] + y * sz[0] + x]; intensities.push_back(pdata[z * sz[0] * sz[1] + y * sz[0] + x]); computeCubePcaEigVec(pdata, sz, x, y, z, 3, 3, 3, pc1, pc2, pc3, vec1, vec2, vec3); this->line_feature.linearity_3_mean += (pc2 == 0 ? 0 : pc1 / pc2); computeCubePcaEigVec(pdata, sz, x, y, z, 5, 5, 5, pc1, pc2, pc3, vec1, vec2, vec3); this->line_feature.linearity_5_mean += (pc2 == 0 ? 0 : pc1 / pc2); computeCubePcaEigVec(pdata, sz, x, y, z, 8, 8, 8, pc1, pc2, pc3, vec1, vec2, vec3); this->line_feature.linearity_8_mean += (pc2 == 0 ? 0 : pc1 / pc2); } } this->line_feature.pointsFeature[4].getFeature(pdata, sz, this->points.back().x, this->points.back().y, this->points.back().z); this->line_feature.intensity_mean += this->line_feature.pointsFeature.back().intensity; intensities.push_back(this->line_feature.pointsFeature.front().intensity); this->line_feature.linearity_3_mean += this->line_feature.pointsFeature.back().linearity_3; this->line_feature.linearity_5_mean += this->line_feature.pointsFeature.back().linearity_5; this->line_feature.linearity_8_mean += this->line_feature.pointsFeature.back().linearity_8; this->line_feature.intensity_mean /= pointSize; this->line_feature.linearity_3_mean /= pointSize; this->line_feature.linearity_5_mean /= pointSize; this->line_feature.linearity_8_mean /= pointSize; for (auto intensity : intensities) { this->line_feature.intensity_std += pow((intensity - this->line_feature.intensity_mean), 2); } this->line_feature.intensity_std = sqrt(this->line_feature.intensity_std / pointSize); NeuronTree nt_r5; for (NeuronSWC s : this->points) { s.radius = 5; nt_r5.listNeuron.push_back(s); } setNeuronTreeHash(nt_r5); vector<MyMarker*> markers_r5 = swc_convert(nt_r5); unsigned char* mask_r5 = 0; swcTomask(mask_r5, markers_r5, sz[0], sz[1], sz[2]); V3DLONG total_sz = sz[0] * sz[1] * sz[2]; intensities.clear(); // qDebug()<<"origin: "<<"r5_mean: "<<this->line_feature.intensity_mean_r5<<" r5_std: "<<this->line_feature.intensity_std_r5; // qDebug()<<"intensity size: "<<intensities.size(); for (int i = 0; i < total_sz; ++i) { if (mask_r5[i] > 0) { this->line_feature.intensity_mean_r5 += pdata[i]; intensities.push_back(pdata[i]); } } // qDebug()<<"after intensity size: "<<intensities.size(); if (intensities.size() > 0) { this->line_feature.intensity_mean_r5 /= intensities.size(); } for (auto intensity : intensities) { this->line_feature.intensity_std_r5 += pow((intensity - this->line_feature.intensity_mean_r5), 2); } if (intensities.size() > 0) { this->line_feature.intensity_std_r5 = sqrt(this->line_feature.intensity_std_r5 / intensities.size()); } // qDebug()<<"r5_mean: "<<this->line_feature.intensity_mean_r5<<" r5_std: "<<this->line_feature.intensity_std_r5; if (this->line_feature.pointsFeature.front().x > this->line_feature.pointsFeature.back().x) { reverse(this->line_feature.pointsFeature.begin(), this->line_feature.pointsFeature.end()); } else if (this->line_feature.pointsFeature.front().x == this->line_feature.pointsFeature.back().x) { if (this->line_feature.pointsFeature.front().y > this->line_feature.pointsFeature.back().y) { reverse(this->line_feature.pointsFeature.begin(), this->line_feature.pointsFeature.end()); } else if (this->line_feature.pointsFeature.front().y == this->line_feature.pointsFeature.back().y){ if (this->line_feature.pointsFeature.front().z > this->line_feature.pointsFeature.back().z) { reverse(this->line_feature.pointsFeature.begin(), this->line_feature.pointsFeature.end()); } } } this->line_feature.directions[0] = XYZ(this->line_feature.pointsFeature.back().x - this->line_feature.pointsFeature.front().x, this->line_feature.pointsFeature.back().y - this->line_feature.pointsFeature.front().y, this->line_feature.pointsFeature.back().z - this->line_feature.pointsFeature.front().z); for (int i = 1; i < this->line_feature.pointsFeature.size(); ++i) { this->line_feature.directions[i] = XYZ(this->line_feature.pointsFeature[i].x - this->line_feature.pointsFeature[i - 1].x, this->line_feature.pointsFeature[i].y - this->line_feature.pointsFeature[i - 1].y, this->line_feature.pointsFeature[i].z - this->line_feature.pointsFeature[i - 1].z); } for (int i = 0; i < 5; ++i) { normalize(this->line_feature.directions[i]); } } bool BranchTree::initialize(NeuronTree &nt) { this->branches.clear(); vector<V3DLONG> rootIndex = vector<V3DLONG>(); V3DLONG size = nt.listNeuron.size(); vector<vector<V3DLONG> > children = vector<vector<V3DLONG> >(size,vector<V3DLONG>()); for (V3DLONG i = 0; i < size; ++i) { V3DLONG prt = nt.listNeuron[i].parent; if (nt.hashNeuron.contains(prt)) { V3DLONG prtIndex = nt.hashNeuron.value(prt); children[prtIndex].push_back(i); } else { rootIndex.push_back(i); } } queue<V3DLONG> q; if (rootIndex.size() != 1) { return false; } else { this->soma = nt.listNeuron[rootIndex.front()]; q.push(rootIndex.front()); if (soma.parent == -1) { this->hasSoma = true; } else { this->hasSoma = false; } } while (!q.empty()) { V3DLONG tmp = q.front(); q.pop(); vector<V3DLONG>& child = children[tmp]; for(int i = 0; i < child.size(); ++i) { Branch* branch = new Branch(); int cIndex = child[i]; branch->points.push_back(nt.listNeuron[tmp]); while(children[cIndex].size() == 1) { branch->points.push_back(nt.listNeuron[cIndex]); cIndex = children[cIndex][0]; } if(children.at(cIndex).size() >= 1) { q.push(cIndex); } branch->points.push_back(nt.listNeuron[cIndex]); this->branches.push_back(branch); } } //initial parent for(int i = 0; i < this->branches.size(); ++i) { if(this->branches[i]->points.front().parent == this->soma.parent) { this->branches[i]->parent = nullptr; } else { for(int j = 0; j < this->branches.size(); ++j) { if(this->branches[i]->points.front().n == this->branches[j]->points.back().n) { this->branches[i]->parent = this->branches[j]; break; } } } } //initial level for(int i = 0; i < this->branches.size(); ++i) { Branch* branch = this->branches[i]; int level=0; while(branch->parent != nullptr) { level++; branch = branch->parent; } this->branches[i]->level = level; } //initial children for(int i = 0; i < this->branches.size(); ++i){ if (this->branches[i]->parent) { this->branches[i]->parent->children.push_back(this->branches[i]); } } } void BranchTree::preProcess(float inflection_d, float cosAngleThres, float l_thres_max, float l_thres_min, float t_length, float soma_ratio) { vector<Branch*> tmp_results; for (Branch* branch : this->branches) { vector<Branch*> s_results = branch->splitByInflectionPoint(inflection_d, cosAngleThres); tmp_results.insert(tmp_results.end(), s_results.begin(), s_results.end()); } this->branches.clear(); for (Branch* branch : tmp_results) { vector<Branch*> s_results = branch->splitByLength(l_thres_max); this->branches.insert(this->branches.end(), s_results.begin(), s_results.end()); } if (this->hasSoma) { for (Branch* branch : this->branches) { branch->removePointsNearSoma(this->soma, soma_ratio); } } for (Branch* branch : this->branches) { branch->removeTerminalPoints(t_length); } auto it = this->branches.begin(); for (; it != this->branches.end();) { if ((*it)->calLength() < l_thres_min) { adjustRalationForRemoveBranch(*it); this->branches.erase(it); } else { ++it; } } } void BranchTree::getFeature(unsigned char *pdata, long long *sz) { for (Branch* branch : this->branches) { branch->getFeature(pdata, sz); } }
36.82852
134
0.538646
MoritzNegwer
ae615bac2d2f06e2f0a8f5674d924c2d6e7c1292
546
hh
C++
cs252/LABS/shell/command.hh
fshafi1997/PurdueComputerScience
673c56daf80f059f5064c3e096a9e27d9c84a7a5
[ "MIT" ]
null
null
null
cs252/LABS/shell/command.hh
fshafi1997/PurdueComputerScience
673c56daf80f059f5064c3e096a9e27d9c84a7a5
[ "MIT" ]
null
null
null
cs252/LABS/shell/command.hh
fshafi1997/PurdueComputerScience
673c56daf80f059f5064c3e096a9e27d9c84a7a5
[ "MIT" ]
null
null
null
#ifndef command_hh #define command_hh #include "simpleCommand.hh" // Command Data Structure struct Command { std::vector<SimpleCommand *> _simpleCommands; std::string * _outFile; std::string * _inFile; std::string * _errFile; bool _background; int _counterOut; int _counterIn; int appendFlag; Command(); void insertSimpleCommand( SimpleCommand * simpleCommand ); void expanding(); void clear(); void print(); void execute(); int checkForBuiltIn(int i); static SimpleCommand *_currentSimpleCommand; }; #endif
18.2
60
0.721612
fshafi1997
ae62f1acdcbd3b242c2ab531e9039846d26c5ebe
2,994
cpp
C++
src/Eos/SurfaceGroup/eossurfacegroupclient.cpp
sparkleholic/qml-webos-framework
dbf1f8608ae88b189dedd358acc97d9504425996
[ "Apache-2.0" ]
12
2018-03-17T12:35:32.000Z
2021-10-15T09:04:56.000Z
src/Eos/SurfaceGroup/eossurfacegroupclient.cpp
sparkleholic/qml-webos-framework
dbf1f8608ae88b189dedd358acc97d9504425996
[ "Apache-2.0" ]
2
2020-05-28T14:58:01.000Z
2022-02-04T04:03:07.000Z
src/Eos/SurfaceGroup/eossurfacegroupclient.cpp
sparkleholic/qml-webos-framework
dbf1f8608ae88b189dedd358acc97d9504425996
[ "Apache-2.0" ]
5
2018-03-22T18:54:18.000Z
2020-03-04T19:20:01.000Z
// Copyright (c) 2015-2018 LG Electronics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SPDX-License-Identifier: Apache-2.0 #include "eossurfacegroupclient.h" EosSurfaceGroupClient::EosSurfaceGroupClient(QObject *parent) : QObject (parent) , m_webOSWindow (0) , m_SurfaceGroup (0) { } EosSurfaceGroupClient::~EosSurfaceGroupClient() { if (m_SurfaceGroup) { delete m_SurfaceGroup; m_SurfaceGroup = 0; } } void EosSurfaceGroupClient::classBegin() { } void EosSurfaceGroupClient::componentComplete() { if (!m_webOSWindow) { qCritical("Need valid value for \"webOSWindow\" "); return; } if (m_groupName.isEmpty()) { qCritical("Need valid value for \"groupName\" "); return; } handleWindowVisibility(); } void EosSurfaceGroupClient::handleWindowVisibility() { if (m_SurfaceGroup) { return; } if (m_webOSWindow && m_webOSWindow->isVisible()) { WebOSSurfaceGroupCompositor* compositor = WebOSPlatform::instance()->surfaceGroupCompositor(); if (compositor) { if (!m_groupName.isEmpty()) { m_SurfaceGroup = compositor->getGroup(m_groupName); if (m_SurfaceGroup) { if (m_layerName.isEmpty()) { m_SurfaceGroup->attachAnonymousSurface(m_webOSWindow); } else { m_SurfaceGroup->attachSurface(m_webOSWindow, m_layerName); } } } } } } void EosSurfaceGroupClient::setGroupName(const QString& groupName) { if (m_groupName.isEmpty() && !groupName.isEmpty()) { m_groupName = groupName; } } void EosSurfaceGroupClient::setWebOSWindow(WebOSQuickWindow* webOSWindow) { if (!m_webOSWindow && webOSWindow) { m_webOSWindow = webOSWindow; QObject::connect(m_webOSWindow, SIGNAL(visibleChanged(bool)), this, SLOT(handleWindowVisibility())); } } void EosSurfaceGroupClient::setLayerName(const QString& layerName) { if (m_layerName.isEmpty() && !layerName.isEmpty()) { m_layerName = layerName; } } void EosSurfaceGroupClient::focusOwner() { if (m_SurfaceGroup) { m_SurfaceGroup->focusOwner(); } } void EosSurfaceGroupClient::focusLayer() { if (m_SurfaceGroup) { if (!m_layerName.isEmpty()) { m_SurfaceGroup->focusLayer(m_layerName); } } }
25.810345
102
0.642285
sparkleholic
ae6907210038d0f445acfc2d470f884aadd55ec4
802
hpp
C++
ql/experimental/templatemodels/hybrid/hybridmodels.hpp
sschlenkrich/quantlib
ff39ad2cd03d06d185044976b2e26ce34dca470c
[ "BSD-3-Clause" ]
null
null
null
ql/experimental/templatemodels/hybrid/hybridmodels.hpp
sschlenkrich/quantlib
ff39ad2cd03d06d185044976b2e26ce34dca470c
[ "BSD-3-Clause" ]
null
null
null
ql/experimental/templatemodels/hybrid/hybridmodels.hpp
sschlenkrich/quantlib
ff39ad2cd03d06d185044976b2e26ce34dca470c
[ "BSD-3-Clause" ]
null
null
null
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2019 Sebastian Schlenkrich */ /*! \file hybridmodels.hpp \brief bind template types to double */ #ifndef quantlib_hybridmodels_hpp #define quantlib_hybridmodels_hpp #include <ql/experimental/templatemodels/hybrid/assetmodelT.hpp> #include <ql/experimental/templatemodels/hybrid/hybridmodelT.hpp> #include <ql/experimental/templatemodels/hybrid/spreadmodelT.hpp> namespace QuantLib { typedef AssetModelT<QuantLib::Time, QuantLib::Real, QuantLib::Real> AssetModel; typedef HybridModelT<QuantLib::Time, QuantLib::Real, QuantLib::Real> HybridModel; typedef SpreadModelT<QuantLib::Time, QuantLib::Real, QuantLib::Real> SpreadModel; } #endif /* ifndef quantlib_hybridmodelshpp */
25.0625
85
0.753117
sschlenkrich
ae6a31d9655395ef70277c4e533cd2fd26227972
671
cpp
C++
src/ProjectileGraphicsComponent.cpp
filipecaixeta/NeonEdgeGame
7dbc825507d731d60a96b4a82975a70e6aa68d7e
[ "MIT" ]
6
2017-05-10T19:25:23.000Z
2021-04-08T23:55:17.000Z
src/ProjectileGraphicsComponent.cpp
filipecaixeta/NeonEdgeGame
7dbc825507d731d60a96b4a82975a70e6aa68d7e
[ "MIT" ]
1
2017-11-10T12:17:26.000Z
2017-11-10T12:17:26.000Z
src/ProjectileGraphicsComponent.cpp
filipecaixeta/NeonEdgeGame
7dbc825507d731d60a96b4a82975a70e6aa68d7e
[ "MIT" ]
5
2017-05-30T01:07:46.000Z
2021-04-08T23:55:19.000Z
// Copyright (c) 2017 Neon Edge Game. #include "ProjectileGraphicsComponent.h" #include "Projectile.h" #include "Rect.h" ProjectileGraphicsComponent::ProjectileGraphicsComponent(std::string baseNameParam): GraphicsComponent(baseNameParam) { AddSprite(baseName, "Projectile", 4, 80); sprite = sprites["Projectile"]; surface = surfaces["Projectile"]; } ProjectileGraphicsComponent::~ProjectileGraphicsComponent() { } void ProjectileGraphicsComponent::Update(GameObject *gameObject, float deltaTime) { characterLeftDirection = (gameObject->facing == GameObject::LEFT); sprite->Mirror(characterLeftDirection); sprite->Update(deltaTime); }
29.173913
84
0.755589
filipecaixeta
ae6b36b615553c52c30538243fca26525e741ce4
323
hxx
C++
inc/html5xx.d/Article.hxx
astrorigin/html5xx
cbaaeb232597a713630df7425752051036cf0cb2
[ "MIT" ]
null
null
null
inc/html5xx.d/Article.hxx
astrorigin/html5xx
cbaaeb232597a713630df7425752051036cf0cb2
[ "MIT" ]
null
null
null
inc/html5xx.d/Article.hxx
astrorigin/html5xx
cbaaeb232597a713630df7425752051036cf0cb2
[ "MIT" ]
null
null
null
/* * */ #ifndef _HTML5XX_ARTICLE_HXX_ #define _HTML5XX_ARTICLE_HXX_ #include "Element.hxx" using namespace std; namespace html { class Article: public Element { public: Article(): Element(Block, "article") {} }; } // end namespace html #endif // _HTML5XX_ARTICLE_HXX_ // vi: set ai et sw=2 sts=2 ts=2 :
10.766667
34
0.678019
astrorigin
ae6e20ab813074a83619a655aae7ccdca6126795
4,408
hpp
C++
common/array.hpp
ChaosGroup/cg2_2014_demo
fd7a70399321e9cdbc205ff1c74dd04ed7b922f0
[ "MIT" ]
1
2016-03-01T16:44:06.000Z
2016-03-01T16:44:06.000Z
common/array.hpp
ChaosGroup/cg2_2014_demo
fd7a70399321e9cdbc205ff1c74dd04ed7b922f0
[ "MIT" ]
null
null
null
common/array.hpp
ChaosGroup/cg2_2014_demo
fd7a70399321e9cdbc205ff1c74dd04ed7b922f0
[ "MIT" ]
null
null
null
#ifndef array_H__ #define array_H__ #include <assert.h> #include <stdlib.h> #include <stdint.h> #include "aligned_ptr.hpp" template < typename ELEMENT_T, size_t ALIGNMENT = 64 > class Array { enum { alignment = ALIGNMENT }; protected: uint32_t m_capacity; uint32_t m_count; aligned_ptr< ELEMENT_T, alignment > m_elem; // call only from copy ctors template < size_t SRC_ALIGNMENT > void actual_copy_ctor( const Array< ELEMENT_T, SRC_ALIGNMENT >& src); // call only from assignment operators template < size_t SRC_ALIGNMENT > Array& actual_assignment( const Array< ELEMENT_T, SRC_ALIGNMENT >& src); public: Array() : m_capacity(0) , m_count(0) { } Array( const Array& src) { actual_copy_ctor(src); } template < size_t SRC_ALIGNMENT > Array( const Array< ELEMENT_T, SRC_ALIGNMENT >& src) { actual_copy_ctor(src); } ~Array(); Array& operator =( const Array& src) { return actual_assignment(src); } template < size_t SRC_ALIGNMENT > Array& operator =( const Array< ELEMENT_T, SRC_ALIGNMENT >& src) { return actual_assignment(src); } bool setCapacity( const size_t n); size_t getCapacity() const { return m_capacity; } size_t getCount() const { return m_count; } void resetCount() { setCapacity(m_capacity); } bool addElement(); bool addElement( const ELEMENT_T &e); bool addMultiElement( const size_t count); const ELEMENT_T& getElement( const size_t i) const; ELEMENT_T& getMutable( const size_t i); }; template < typename ELEMENT_T, size_t ALIGNMENT > template < size_t SRC_ALIGNMENT > inline void Array< ELEMENT_T, ALIGNMENT >::actual_copy_ctor( const Array< ELEMENT_T, SRC_ALIGNMENT >& src) { m_capacity = 0; m_count = 0; if (0 == src.m_capacity) return; assert(!src.m_elem.is_null()); m_elem.malloc(src.m_capacity); if (m_elem.is_null()) return; for (size_t i = 0; i < src.m_count; ++i) new (m_elem + i) ELEMENT_T(src.m_elem[i]); m_capacity = src.m_capacity; m_count = src.m_count; } template < typename ELEMENT_T, size_t ALIGNMENT > inline Array< ELEMENT_T, ALIGNMENT >::~Array() { assert(0 == m_capacity || !m_elem.is_null()); for (size_t i = 0; i < m_count; ++i) m_elem[i].~ELEMENT_T(); #if !defined(NDEBUG) m_capacity = 0; m_count = 0; #endif } template < typename ELEMENT_T, size_t ALIGNMENT > template < size_t SRC_ALIGNMENT > inline Array< ELEMENT_T, ALIGNMENT >& Array< ELEMENT_T, ALIGNMENT >::actual_assignment( const Array< ELEMENT_T, SRC_ALIGNMENT >& src) { if (setCapacity(src.m_capacity)) { for (size_t i = 0; i < src.m_count; ++i) new (m_elem + i) ELEMENT_T(src.m_elem[i]); m_count = src.m_count; } return *this; } template < typename ELEMENT_T, size_t ALIGNMENT > inline bool Array< ELEMENT_T, ALIGNMENT >::setCapacity( const size_t n) { // setting the capacity resets the content for (size_t i = 0; i < m_count; ++i) m_elem[i].~ELEMENT_T(); m_count = 0; if (m_capacity == n) return true; m_capacity = 0; if (0 == n) { m_elem.free(); return true; } m_elem.malloc(n); if (m_elem.is_null()) return false; m_capacity = n; return true; } template < typename ELEMENT_T, size_t ALIGNMENT > inline bool Array< ELEMENT_T, ALIGNMENT >::addElement() { if (m_count == m_capacity) return false; assert(!m_elem.is_null()); new (m_elem + m_count++) ELEMENT_T(); return true; } template < typename ELEMENT_T, size_t ALIGNMENT > inline bool Array< ELEMENT_T, ALIGNMENT >::addElement( const ELEMENT_T& e) { if (m_count == m_capacity) return false; assert(!m_elem.is_null()); new (m_elem + m_count++) ELEMENT_T(e); return true; } template < typename ELEMENT_T, size_t ALIGNMENT > inline bool Array< ELEMENT_T, ALIGNMENT >::addMultiElement( const size_t count) { if (m_count + count > m_capacity) return false; assert(!m_elem.is_null()); for (size_t i = 0; i < count; ++i) new (m_elem + m_count + i) ELEMENT_T(); m_count += count; return true; } template < typename ELEMENT_T, size_t ALIGNMENT > inline const ELEMENT_T& Array< ELEMENT_T, ALIGNMENT >::getElement( const size_t i) const { assert(i < m_count); assert(!m_elem.is_null()); return m_elem[i]; } template < typename ELEMENT_T, size_t ALIGNMENT > inline ELEMENT_T& Array< ELEMENT_T, ALIGNMENT >::getMutable( const size_t i) { assert(i < m_count); assert(!m_elem.is_null()); return m_elem[i]; } #endif // array_H__
17.151751
60
0.690563
ChaosGroup
ae6e79bfa2356803e033cc0b24673eaff495daca
4,352
cpp
C++
conui/examples/Test5ValEdit.cpp
amalk/GUI-CLI
a08f3eed8d65c1cfef259397990f9e218a77d594
[ "MIT" ]
3
2016-08-17T09:35:16.000Z
2019-02-07T21:27:58.000Z
conui/examples/Test5ValEdit.cpp
amalk/GUI-CLI
a08f3eed8d65c1cfef259397990f9e218a77d594
[ "MIT" ]
null
null
null
conui/examples/Test5ValEdit.cpp
amalk/GUI-CLI
a08f3eed8d65c1cfef259397990f9e218a77d594
[ "MIT" ]
3
2016-08-17T09:35:21.000Z
2018-02-14T08:14:35.000Z
// Console Input Output Library Tester program for CValEdit // Test5ValEdit.cpp // // Fardad Soleimanloo, Chris Szalwinski // Oct 10 2012 // Version 0.9 #include "cuigh.h" #include "console.h" #include "cframe.h" #include "cdialog.h" #include "clabel.h" #include "cveditline.h" #include "cbutton.h" #include <cstring> #include <cctype> using namespace std; using namespace cui; bool Yes(const char* message, CDialog* owner); void Help(CDialog* owner, CDialog* helping); void PhoneHelp(MessageStatus st, CDialog& owner); void LastNameHelp(MessageStatus st, CDialog& owner); bool ValidPhone(const char* ph , CDialog& owner); int main() { int key = 0; int i = 1; bool done = false; bool insert = true; char str[81] = "I want to edit this thing!"; for(int k = 0; k < console.getRows(); k += 2) { for(int m = 0; m < console.getCols() - 10; m += 10) { console.strdsp((i = !i) ? "Hello" : "Hi", k, m); } } CDialog Screen; CDialog FD(&Screen, 5, 5, 70, 15, true); CLabel PhHelp(8, 34, 30); CLabel LnHelp(5, 37, 30); CLabel ErrMes(10, 2, 67); Screen << new CLabel("F1: HELP ", 0, 0); FD << new CLabel("Name:", 2, 2) << new CLineEdit(1, 10, 20, 40, &insert, true) << new CLabel("Lastname:", 5, 2) << new CValEdit(4, 13, 20, 40, &insert, NO_VALDFUNC, LastNameHelp, true) << new CLabel("Phone Number", 8, 2) << new CValEdit(7, 16, 15, 12, &insert, ValidPhone, PhoneHelp, true) << PhHelp << LnHelp << ErrMes << new CLabel("F1: help, ESCAPE: exit", 11, 2); FD.draw(); while(!done) { key = FD.edit(); switch(key) { case F(1): Help(&Screen, &FD); break; case ESCAPE: if(Yes("Do you really want to quit?", &Screen)) { done = true; } break; case F(6): FD.move(); break; } } return 0; } bool Yes(const char* message, CDialog* owner) { int key; bool res = false; bool done = false; CButton bt_yes("Yes", 4, 4 , true, " _ "); CButton bt_no("No", 4, 15 , true, " _ "); CDialog YesNo(owner, (console.getRows() - 10) / 2, (console.getCols() - 40) / 2, 40, 10, true); YesNo << new CLabel(2, 2, 36) << bt_yes << bt_no; YesNo[0].set(message); YesNo.draw(C_FULL_FRAME); while(!done) { key = YesNo.edit(); if(key == C_BUTTON_HIT) { res = &YesNo.curField() == &bt_yes; done = true; } else if(key == F(6)) { YesNo.move(); } } YesNo.hide(); return res; } void Help(CDialog* owner, CDialog* helping) { CDialog help(owner, (console.getRows() - 10) / 2, (console.getCols() - 40) / 2, 40, 10, true); help << new CLabel(2, 3, 36) << new CLabel("Escape Key: Exit the test program.", 4, 3) << new CLabel("F1 Key: Open this window.", 6, 3); switch(helping->curIndex()) { case 1: help[0].set("Enter the name here!"); break; case 3: help[0].set("Enter the Last name here!"); break; case 5: help[0].set("Enter Phone number: 999-999-9999"); } while(help.edit(C_FULL_FRAME) == F(6)) { help.move(); } help.hide(); } void PhoneHelp(MessageStatus st, CDialog& owner) { if(st == ClearMessage) { owner[6].set(""); } else { owner[6].set("Phone Format: 999-999-9999"); } owner.draw(7); } void LastNameHelp(MessageStatus st, CDialog& owner) { if(st == ClearMessage) { owner[7].set(""); } else { owner[7].set("i.e. Middle name and Surname"); } owner.draw(8); } bool ValidPhone(const char* ph , CDialog& owner) { bool ok = true; int i; for(i = 0; ok && i < 3; ok = (bool)isdigit(ph[i]), i++); ok = ph[i++] == '-'; for(; ok && i < 7; ok = (bool)isdigit(ph[i]), i++); ok = ph[i++] == '-'; for(; ok && i < 12; ok = (bool)isdigit(ph[i]), i++); if(ok) { owner[8].set(""); } else { owner[8].set("Invlid phone number, please use the specified phone number format!"); } owner.draw(9); return ok; }
21.544554
99
0.516774
amalk
ae6e8aa318c8889f6cca7de9f3eeb46bc5c3eb03
2,182
cpp
C++
test/libwebsocket-mock/mock_lws_minimal.cpp
costanic/mbed-edge
4900e950ff67f8974b7aeef955289ef56606c964
[ "Apache-2.0" ]
24
2018-03-27T16:44:18.000Z
2020-04-28T15:28:34.000Z
test/libwebsocket-mock/mock_lws_minimal.cpp
costanic/mbed-edge
4900e950ff67f8974b7aeef955289ef56606c964
[ "Apache-2.0" ]
19
2021-01-28T20:14:45.000Z
2021-11-23T13:08:59.000Z
test/libwebsocket-mock/mock_lws_minimal.cpp
costanic/mbed-edge
4900e950ff67f8974b7aeef955289ef56606c964
[ "Apache-2.0" ]
28
2018-04-02T02:36:48.000Z
2020-10-13T05:37:16.000Z
#include "CppUTestExt/MockSupport.h" #include "cpputest-custom-types/value_pointer.h" extern "C" { #include "libwebsockets.h" } int lws_callback_on_writable(struct lws *wsi) { return mock().actualCall("lws_callback_on_writable") .returnIntValueOrDefault(0); } size_t lws_remaining_packet_payload(struct lws *wsi) { return mock().actualCall("lws_remaining_packet_payload").returnUnsignedLongIntValue(); } int lws_is_final_fragment(struct lws *wsi) { return mock().actualCall("lws_is_final_fragment").returnIntValue(); } int lws_is_first_fragment(struct lws *wsi) { return mock().actualCall("lws_is_first_fragment").returnIntValue(); } void lws_close_reason(struct lws *wsi, enum lws_close_status status, unsigned char *buf, size_t len) { mock().actualCall("lws_close_reason"); } int lws_write(struct lws *wsi, unsigned char *buf, size_t len, enum lws_write_protocol protocol) { ValuePointer msg_param = ValuePointer(buf, len); return mock().actualCall("lws_write") .withParameterOfType("ValuePointer", "buf", &msg_param) .returnIntValue(); } struct lws_context *lws_create_context(const struct lws_context_creation_info *info) { return (struct lws_context*) mock().actualCall("lws_create_context").returnPointerValue(); } void lws_context_destroy(struct lws_context *ctx) { mock().actualCall("lws_context_destroy"); free(ctx); } LWS_VISIBLE LWS_EXTERN struct lws *lws_client_connect_via_info(const struct lws_client_connect_info *ccinfo) { return (struct lws*) mock().actualCall("lws_client_connect_via_info") .withStringParameter("path", ccinfo->path) .returnPointerValue(); } int lws_extension_callback_pm_deflate(struct lws_context *context, const struct lws_extension *ext, struct lws *wsi, enum lws_extension_callback_reasons reason, void *user, void *in, size_t len) { return mock().actualCall("lws_extension_callback_pm_deflate").returnIntValue(); }
31.623188
108
0.681027
costanic
ae6ed21530c39a8428342f0b94e687f912f25877
22,053
cpp
C++
tests/constraint/test_RnBoxConstraint.cpp
personalrobotics/r3
1303e3f3ef99a0c2249abc7415d19113f0026565
[ "BSD-3-Clause" ]
181
2016-04-22T15:11:23.000Z
2022-03-26T12:51:08.000Z
tests/constraint/test_RnBoxConstraint.cpp
personalrobotics/r3
1303e3f3ef99a0c2249abc7415d19113f0026565
[ "BSD-3-Clause" ]
514
2016-04-20T04:29:51.000Z
2022-02-10T19:46:21.000Z
tests/constraint/test_RnBoxConstraint.cpp
personalrobotics/r3
1303e3f3ef99a0c2249abc7415d19113f0026565
[ "BSD-3-Clause" ]
31
2017-03-17T09:53:02.000Z
2022-03-23T10:35:05.000Z
#include <dart/common/Memory.hpp> #include <gtest/gtest.h> #include <aikido/common/memory.hpp> #include <aikido/constraint/uniform/RnBoxConstraint.hpp> #include <aikido/distance/RnEuclidean.hpp> #include "SampleGeneratorCoverage.hpp" using aikido::common::RNG; using aikido::common::RNGWrapper; using aikido::constraint::ConstraintType; using aikido::constraint::SampleGenerator; using aikido::constraint::uniform::R2BoxConstraint; using aikido::constraint::uniform::RnBoxConstraint; using aikido::distance::R2Euclidean; using aikido::distance::RnEuclidean; using aikido::statespace::R2; using aikido::statespace::Rn; using Eigen::Matrix2d; using Eigen::Vector2d; class RnBoxConstraintTests : public ::testing::Test { protected: static constexpr std::size_t NUM_X_TARGETS{10}; static constexpr std::size_t NUM_Y_TARGETS{10}; static constexpr std::size_t NUM_SAMPLES{10000}; static constexpr double DISTANCE_THRESHOLD{0.15}; void SetUp() override { mR2StateSpace = std::make_shared<R2>(); mRxStateSpace = std::make_shared<Rn>(2); mR2Distance = std::make_shared<R2Euclidean>(mR2StateSpace); mRxDistance = std::make_shared<RnEuclidean>(mRxStateSpace); mRng = ::aikido::common::make_unique<RNGWrapper<std::default_random_engine>>( 0); mLowerLimits = Vector2d(-1., 1.); mUpperLimits = Vector2d(1., 2.); mGoodValues.resize(3); mGoodValues[0] = Vector2d(-0.9, 1.1); mGoodValues[1] = Vector2d(0.0, 1.5); mGoodValues[2] = Vector2d(0.9, 1.9); mBadValues.resize(8); mBadValues[0] = Vector2d(-1.1, 1.5); mBadValues[1] = Vector2d(1.1, 1.5); mBadValues[2] = Vector2d(0.0, 0.9); mBadValues[3] = Vector2d(0.0, 2.1); mBadValues[4] = Vector2d(-1.1, 0.9); mBadValues[5] = Vector2d(-1.1, 2.1); mBadValues[6] = Vector2d(1.1, 0.9); mBadValues[7] = Vector2d(1.1, 2.1); mTargets.clear(); mTargets.reserve(NUM_X_TARGETS * NUM_Y_TARGETS); for (std::size_t ix = 0; ix < NUM_X_TARGETS; ++ix) { auto xRatio = static_cast<double>(ix) / (NUM_X_TARGETS - 1); auto x = (1 - xRatio) * mLowerLimits[0] + xRatio * mUpperLimits[0]; for (std::size_t iy = 0; iy < NUM_Y_TARGETS; ++iy) { auto yRatio = static_cast<double>(iy) / (NUM_Y_TARGETS - 1); auto y = (1 - yRatio) * mLowerLimits[1] + yRatio * mUpperLimits[1]; auto state = mR2StateSpace->createState(); state.setValue(Vector2d(x, y)); mTargets.emplace_back(std::move(state)); } } } std::unique_ptr<RNG> mRng; std::shared_ptr<R2> mR2StateSpace; std::shared_ptr<Rn> mRxStateSpace; std::shared_ptr<R2Euclidean> mR2Distance; std::shared_ptr<RnEuclidean> mRxDistance; Eigen::Vector2d mLowerLimits; Eigen::Vector2d mUpperLimits; std::vector<Eigen::Vector2d, Eigen::aligned_allocator<Eigen::Vector2d>> mGoodValues; std::vector<Eigen::Vector2d, Eigen::aligned_allocator<Eigen::Vector2d>> mBadValues; std::vector<R2::ScopedState> mTargets; public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW }; //============================================================================== TEST_F(RnBoxConstraintTests, R2_constructor_StateSpaceIsNull_Throws) { EXPECT_THROW( { R2BoxConstraint(nullptr, mRng->clone(), mLowerLimits, mUpperLimits); }, std::invalid_argument); } //============================================================================== TEST_F(RnBoxConstraintTests, Rx_constructor_StateSpaceIsNull_Throws) { EXPECT_THROW( { RnBoxConstraint(nullptr, mRng->clone(), mLowerLimits, mUpperLimits); }, std::invalid_argument); } //============================================================================== TEST_F(RnBoxConstraintTests, R2_constructor_RNGIsNull_DoesNotThrow) { EXPECT_NO_THROW( { R2BoxConstraint(mR2StateSpace, nullptr, mLowerLimits, mUpperLimits); }); } //============================================================================== TEST_F(RnBoxConstraintTests, Rx_constructor_RNGIsNull_DoesNotThrow) { EXPECT_NO_THROW( { RnBoxConstraint(mRxStateSpace, nullptr, mLowerLimits, mUpperLimits); }); } //============================================================================== TEST_F( RnBoxConstraintTests, R2_constructor_LowersLimitExceedsUpperLimits_Throws) { Eigen::Vector2d badLowerLimits(1., 0.); Eigen::Vector2d badUpperLimits(0., 1.); EXPECT_THROW( { R2BoxConstraint( mR2StateSpace, mRng->clone(), badLowerLimits, badUpperLimits); }, std::invalid_argument); } //============================================================================== TEST_F( RnBoxConstraintTests, Rx_constructor_LowersLimitExceedsUpperLimits_Throws) { Eigen::Vector2d badLowerLimits(1., 0.); Eigen::Vector2d badUpperLimits(0., 1.); EXPECT_THROW( { RnBoxConstraint( mRxStateSpace, mRng->clone(), badLowerLimits, badUpperLimits); }, std::invalid_argument); } //============================================================================== TEST_F(RnBoxConstraintTests, R2_getStateSpace) { R2BoxConstraint constraint( mR2StateSpace, mRng->clone(), mLowerLimits, mUpperLimits); EXPECT_EQ(mR2StateSpace, constraint.getStateSpace()); } //============================================================================== TEST_F(RnBoxConstraintTests, Rx_getStateSpace) { RnBoxConstraint constraint( mRxStateSpace, mRng->clone(), mLowerLimits, mUpperLimits); EXPECT_EQ(mRxStateSpace, constraint.getStateSpace()); } //============================================================================== TEST_F(RnBoxConstraintTests, R2_getConstraintDimension) { R2BoxConstraint constraint( mR2StateSpace, mRng->clone(), mLowerLimits, mUpperLimits); EXPECT_EQ(2, constraint.getConstraintDimension()); } //============================================================================== TEST_F(RnBoxConstraintTests, Rx_getConstraintDimension) { RnBoxConstraint constraint( mRxStateSpace, mRng->clone(), mLowerLimits, mUpperLimits); EXPECT_EQ(2, constraint.getConstraintDimension()); } //============================================================================== TEST_F(RnBoxConstraintTests, R2_getConstraintTypes) { R2BoxConstraint constraint( mR2StateSpace, mRng->clone(), mLowerLimits, mUpperLimits); auto constraintTypes = constraint.getConstraintTypes(); ASSERT_EQ(2, constraintTypes.size()); EXPECT_EQ(ConstraintType::INEQUALITY, constraintTypes[0]); EXPECT_EQ(ConstraintType::INEQUALITY, constraintTypes[1]); } //============================================================================== TEST_F(RnBoxConstraintTests, Rx_getConstraintTypes) { RnBoxConstraint constraint( mRxStateSpace, mRng->clone(), mLowerLimits, mUpperLimits); auto constraintTypes = constraint.getConstraintTypes(); ASSERT_EQ(2, constraintTypes.size()); EXPECT_EQ(ConstraintType::INEQUALITY, constraintTypes[0]); EXPECT_EQ(ConstraintType::INEQUALITY, constraintTypes[1]); } //============================================================================== TEST_F(RnBoxConstraintTests, R2_isSatisfied_SatisfiesConstraint_ReturnsTrue) { R2BoxConstraint constraint( mR2StateSpace, mRng->clone(), mLowerLimits, mUpperLimits); auto state = mR2StateSpace->createState(); for (const auto& value : mGoodValues) { state.setValue(value); EXPECT_TRUE(constraint.isSatisfied(state)); } } //============================================================================== TEST_F(RnBoxConstraintTests, Rx_isSatisfied_SatisfiesConstraint_ReturnsTrue) { RnBoxConstraint constraint( mRxStateSpace, mRng->clone(), mLowerLimits, mUpperLimits); auto state = mRxStateSpace->createState(); for (const auto& value : mGoodValues) { state.setValue(value); EXPECT_TRUE(constraint.isSatisfied(state)); } } //============================================================================== TEST_F( RnBoxConstraintTests, R2_isSatisfied_DoesNotSatisfyConstraint_ReturnsFalse) { R2BoxConstraint constraint( mR2StateSpace, mRng->clone(), mLowerLimits, mUpperLimits); auto state = mR2StateSpace->createState(); for (const auto& value : mBadValues) { state.setValue(value); EXPECT_FALSE(constraint.isSatisfied(state)); } } //============================================================================== TEST_F( RnBoxConstraintTests, Rx_isSatisfied_DoesNotSatisfyConstraint_ReturnsFalse) { RnBoxConstraint constraint( mRxStateSpace, mRng->clone(), mLowerLimits, mUpperLimits); auto state = mRxStateSpace->createState(); for (const auto& value : mBadValues) { state.setValue(value); EXPECT_FALSE(constraint.isSatisfied(state)); } } //============================================================================== TEST_F(RnBoxConstraintTests, R2_project_SatisfiesConstraint_DoesNothing) { R2BoxConstraint constraint( mR2StateSpace, mRng->clone(), mLowerLimits, mUpperLimits); auto inState = mR2StateSpace->createState(); auto outState = mR2StateSpace->createState(); for (const auto& value : mGoodValues) { inState.setValue(value); EXPECT_TRUE(constraint.project(inState, outState)); EXPECT_TRUE(value.isApprox(outState.getValue())); } } //============================================================================== TEST_F(RnBoxConstraintTests, Rx_project_SatisfiesConstraint_DoesNothing) { RnBoxConstraint constraint( mRxStateSpace, mRng->clone(), mLowerLimits, mUpperLimits); auto inState = mRxStateSpace->createState(); auto outState = mRxStateSpace->createState(); for (const auto& value : mGoodValues) { inState.setValue(value); EXPECT_TRUE(constraint.project(inState, outState)); EXPECT_TRUE(value.isApprox(outState.getValue())); } } //============================================================================== TEST_F(RnBoxConstraintTests, R2_project_DoesNotSatisfyConstraint_Projects) { R2BoxConstraint constraint( mR2StateSpace, mRng->clone(), mLowerLimits, mUpperLimits); auto inState = mR2StateSpace->createState(); auto outState = mR2StateSpace->createState(); for (const auto& value : mBadValues) { inState.setValue(value); EXPECT_TRUE(constraint.project(inState, outState)); EXPECT_TRUE(constraint.isSatisfied(outState)); } } //============================================================================== TEST_F(RnBoxConstraintTests, Rx_project_DoesNotSatisfyConstraint_Projects) { RnBoxConstraint constraint( mRxStateSpace, mRng->clone(), mLowerLimits, mUpperLimits); auto inState = mRxStateSpace->createState(); auto outState = mRxStateSpace->createState(); for (const auto& value : mBadValues) { inState.setValue(value); EXPECT_TRUE(constraint.project(inState, outState)); EXPECT_TRUE(constraint.isSatisfied(outState)); } } //============================================================================== TEST_F(RnBoxConstraintTests, R2_getValue_SatisfiesConstraint_ReturnsZero) { R2BoxConstraint constraint( mR2StateSpace, mRng->clone(), mLowerLimits, mUpperLimits); auto state = mR2StateSpace->createState(); for (const auto& value : mGoodValues) { state.setValue(value); Eigen::VectorXd constraintValue; constraint.getValue(state, constraintValue); EXPECT_TRUE(Vector2d::Zero().isApprox(constraintValue)); } } //============================================================================== TEST_F(RnBoxConstraintTests, Rx_getValue_SatisfiesConstraint_ReturnsZero) { RnBoxConstraint constraint( mRxStateSpace, mRng->clone(), mLowerLimits, mUpperLimits); auto state = mRxStateSpace->createState(); for (const auto& value : mGoodValues) { state.setValue(value); Eigen::VectorXd constraintValue; constraint.getValue(state, constraintValue); EXPECT_TRUE(Vector2d::Zero().isApprox(constraintValue)); } } //============================================================================== TEST_F( RnBoxConstraintTests, R2_getValue_DoesNotSatisfyConstraint_ReturnsNonZero) { R2BoxConstraint constraint( mR2StateSpace, mRng->clone(), mLowerLimits, mUpperLimits); auto state = mR2StateSpace->createState(); // TODO: Check the sign. // TODO: Check which elements are non-zero. for (const auto& value : mBadValues) { state.setValue(value); Eigen::VectorXd constraintValue; constraint.getValue(state, constraintValue); EXPECT_FALSE(Vector2d::Zero().isApprox(constraintValue)); } } //============================================================================== TEST_F( RnBoxConstraintTests, Rx_getValue_DoesNotSatisfyConstraint_ReturnsNonZero) { RnBoxConstraint constraint( mRxStateSpace, mRng->clone(), mLowerLimits, mUpperLimits); auto state = mRxStateSpace->createState(); // TODO: Check the sign. // TODO: Check which elements are non-zero. for (const auto& value : mBadValues) { state.setValue(value); Eigen::VectorXd constraintValue; constraint.getValue(state, constraintValue); EXPECT_FALSE(Vector2d::Zero().isApprox(constraintValue)); } } //============================================================================== TEST_F(RnBoxConstraintTests, R2_getJacobian_SatisfiesConstraint_ReturnsZero) { R2BoxConstraint constraint( mR2StateSpace, mRng->clone(), mLowerLimits, mUpperLimits); auto state = mR2StateSpace->createState(); for (const auto& value : mGoodValues) { state.setValue(value); Eigen::MatrixXd jacobian; constraint.getJacobian(state, jacobian); EXPECT_TRUE(Matrix2d::Zero().isApprox(jacobian)); } } //============================================================================== TEST_F(RnBoxConstraintTests, Rx_getJacobian_SatisfiesConstraint_ReturnsZero) { RnBoxConstraint constraint( mRxStateSpace, mRng->clone(), mLowerLimits, mUpperLimits); auto state = mRxStateSpace->createState(); for (const auto& value : mGoodValues) { state.setValue(value); Eigen::MatrixXd jacobian; constraint.getJacobian(state, jacobian); EXPECT_TRUE(Matrix2d::Zero().isApprox(jacobian)); } } //============================================================================== TEST_F( RnBoxConstraintTests, R2_getJacobian_DoesNotSatisfyConstraint_ReturnsNonZero) { R2BoxConstraint constraint( mR2StateSpace, mRng->clone(), mLowerLimits, mUpperLimits); // TODO: Check the sign. // TODO: Check which elements are non-zero. auto state = mR2StateSpace->createState(); for (const auto& value : mBadValues) { state.setValue(value); Eigen::MatrixXd jacobian; constraint.getJacobian(state, jacobian); EXPECT_FALSE(Matrix2d::Zero().isApprox(jacobian)); } } //============================================================================== TEST_F( RnBoxConstraintTests, Rx_getJacobian_DoesNotSatisfyConstraint_ReturnsNonZero) { RnBoxConstraint constraint( mRxStateSpace, mRng->clone(), mLowerLimits, mUpperLimits); // TODO: Check the sign. // TODO: Check which elements are non-zero. auto state = mRxStateSpace->createState(); for (const auto& value : mBadValues) { state.setValue(value); Eigen::MatrixXd jacobian; constraint.getJacobian(state, jacobian); EXPECT_FALSE(Matrix2d::Zero().isApprox(jacobian)); } } //============================================================================== TEST_F( RnBoxConstraintTests, R2_getValueAndJacobian_SatisfiesConstraint_ReturnsZero) { R2BoxConstraint constraint( mR2StateSpace, mRng->clone(), mLowerLimits, mUpperLimits); auto state = mR2StateSpace->createState(); for (const auto& value : mGoodValues) { state.setValue(value); Eigen::VectorXd constraintValue; Eigen::MatrixXd constraintJac; constraint.getValueAndJacobian(state, constraintValue, constraintJac); EXPECT_TRUE(Vector2d::Zero().isApprox(constraintValue)); EXPECT_TRUE(Matrix2d::Zero().isApprox(constraintJac)); } } //============================================================================== TEST_F( RnBoxConstraintTests, Rx_getValueAndJacobian_SatisfiesConstraint_ReturnsZero) { RnBoxConstraint constraint( mRxStateSpace, mRng->clone(), mLowerLimits, mUpperLimits); auto state = mRxStateSpace->createState(); for (const auto& value : mGoodValues) { state.setValue(value); Eigen::VectorXd constraintValue; Eigen::MatrixXd constraintJac; constraint.getValueAndJacobian(state, constraintValue, constraintJac); EXPECT_TRUE(Vector2d::Zero().isApprox(constraintValue)); EXPECT_TRUE(Matrix2d::Zero().isApprox(constraintJac)); } } //============================================================================== TEST_F( RnBoxConstraintTests, R2_getValueAndJacobian_DoesNotSatisfyConstraint_ReturnsNonZero) { R2BoxConstraint constraint( mR2StateSpace, mRng->clone(), mLowerLimits, mUpperLimits); auto state = mR2StateSpace->createState(); for (const auto& value : mBadValues) { state.setValue(value); Eigen::VectorXd constraintValue; Eigen::MatrixXd constraintJac; constraint.getValueAndJacobian(state, constraintValue, constraintJac); EXPECT_FALSE(Vector2d::Zero().isApprox(constraintValue)); EXPECT_FALSE(Matrix2d::Zero().isApprox(constraintJac)); } } //============================================================================== TEST_F( RnBoxConstraintTests, Rx_getValueAndJacobian_DoesNotSatisfyConstraint_ReturnsNonZero) { RnBoxConstraint constraint( mRxStateSpace, mRng->clone(), mLowerLimits, mUpperLimits); auto state = mRxStateSpace->createState(); for (const auto& value : mBadValues) { state.setValue(value); Eigen::VectorXd constraintValue; Eigen::MatrixXd constraintJac; constraint.getValueAndJacobian(state, constraintValue, constraintJac); EXPECT_FALSE(Vector2d::Zero().isApprox(constraintValue)); EXPECT_FALSE(Matrix2d::Zero().isApprox(constraintJac)); } } //============================================================================== TEST_F(RnBoxConstraintTests, R2_createSampleGenerator) { auto constraint = dart::common::make_aligned_shared<R2BoxConstraint>( mR2StateSpace, mRng->clone(), mLowerLimits, mUpperLimits); auto generator = constraint->createSampleGenerator(); EXPECT_EQ(mR2StateSpace, generator->getStateSpace()); auto result = SampleGeneratorCoverage( *generator, *mR2Distance, std::begin(mTargets), std::end(mTargets), DISTANCE_THRESHOLD, NUM_SAMPLES); ASSERT_TRUE(result); } //============================================================================== TEST_F(RnBoxConstraintTests, Rx_createSampleGenerator) { auto constraint = std::make_shared<RnBoxConstraint>( mRxStateSpace, mRng->clone(), mLowerLimits, mUpperLimits); auto generator = constraint->createSampleGenerator(); EXPECT_EQ(mRxStateSpace, generator->getStateSpace()); auto result = SampleGeneratorCoverage( *generator, *mRxDistance, std::begin(mTargets), std::end(mTargets), DISTANCE_THRESHOLD, NUM_SAMPLES); ASSERT_TRUE(result); } //============================================================================== TEST_F(RnBoxConstraintTests, R2_createSampleGenerator_RNGIsNull_Throws) { // We need to use make_shared here because createSampleGenerator calls // shared_from_this, provided by enable_shared_from_this. auto constraint = dart::common::make_aligned_shared<R2BoxConstraint>( mR2StateSpace, nullptr, mLowerLimits, mUpperLimits); EXPECT_THROW({ constraint->createSampleGenerator(); }, std::invalid_argument); } //============================================================================== TEST_F(RnBoxConstraintTests, Rx_createSampleGenerator_RNGIsNull_Throws) { // We need to use make_shared here because createSampleGenerator calls // shared_from_this, provided by enable_shared_from_this. auto constraint = std::make_shared<RnBoxConstraint>( mRxStateSpace, nullptr, mLowerLimits, mUpperLimits); EXPECT_THROW({ constraint->createSampleGenerator(); }, std::invalid_argument); } //============================================================================== TEST_F(RnBoxConstraintTests, R2_createSampleGenerator_Unbounded_Throws) { Vector2d noLowerBound = mLowerLimits; noLowerBound[0] = -std::numeric_limits<double>::infinity(); Vector2d noUpperBound = mUpperLimits; noUpperBound[1] = std::numeric_limits<double>::infinity(); // We need to use make_shared here because createSampleGenerator calls // shared_from_this, provided by enable_shared_from_this. auto unbounded1 = dart::common::make_aligned_shared<R2BoxConstraint>( mR2StateSpace, mRng->clone(), noLowerBound, mUpperLimits); EXPECT_THROW({ unbounded1->createSampleGenerator(); }, std::runtime_error); auto unbounded2 = dart::common::make_aligned_shared<R2BoxConstraint>( mR2StateSpace, mRng->clone(), mLowerLimits, noUpperBound); EXPECT_THROW({ unbounded2->createSampleGenerator(); }, std::runtime_error); } //============================================================================== TEST_F(RnBoxConstraintTests, Rx_createSampleGenerator_Unbounded_Throws) { Vector2d noLowerBound = mLowerLimits; noLowerBound[0] = -std::numeric_limits<double>::infinity(); Vector2d noUpperBound = mUpperLimits; noUpperBound[1] = std::numeric_limits<double>::infinity(); // We need to use make_shared here because createSampleGenerator calls // shared_from_this, provided by enable_shared_from_this. auto unbounded1 = std::make_shared<RnBoxConstraint>( mRxStateSpace, mRng->clone(), noLowerBound, mUpperLimits); EXPECT_THROW({ unbounded1->createSampleGenerator(); }, std::runtime_error); auto unbounded2 = std::make_shared<RnBoxConstraint>( mRxStateSpace, mRng->clone(), mLowerLimits, noUpperBound); EXPECT_THROW({ unbounded2->createSampleGenerator(); }, std::runtime_error); }
31.730935
80
0.635378
personalrobotics
ae706494abacc4054ca1c640a0e4f4f245f031c0
17,359
cpp
C++
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/view/InputDevice.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/view/InputDevice.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/view/InputDevice.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos 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 <Elastos.CoreLibrary.Utility.h> #include "Elastos.Droid.Accounts.h" #include "Elastos.Droid.App.h" #include "Elastos.Droid.Content.h" #include "Elastos.Droid.Location.h" #include "Elastos.Droid.Widget.h" #include "elastos/droid/os/NullVibrator.h" #include "elastos/droid/view/InputDevice.h" #include "elastos/droid/view/CKeyCharacterMap.h" #include "elastos/droid/view/MotionEvent.h" #include "elastos/droid/hardware/input/CInputManager.h" #include "elastos/droid/hardware/input/CInputDeviceIdentifier.h" #include "elastos/droid/hardware/input/CInputManagerHelper.h" #include <elastos/core/AutoLock.h> using Elastos::Core::AutoLock; using Elastos::Utility::CArrayList; using Elastos::Droid::Os::NullVibrator; using Elastos::Droid::Hardware::Input::CInputManager; using Elastos::Droid::Hardware::Input::CInputDeviceIdentifier; using Elastos::Droid::Hardware::Input::IInputManagerHelper; using Elastos::Droid::Hardware::Input::CInputManagerHelper; using Elastos::Droid::Hardware::Input::IInputManager; namespace Elastos { namespace Droid { namespace View { CAR_INTERFACE_IMPL(InputDevice::MotionRange, Object, IMotionRange) CAR_INTERFACE_IMPL_2(InputDevice, Object, IInputDevice, IParcelable) InputDevice::MotionRange::MotionRange( /* [in] */ Int32 axis, /* [in] */ Int32 source, /* [in] */ Float min, /* [in] */ Float max, /* [in] */ Float flat, /* [in] */ Float fuzz, /* [in] */ Float resolution) : mAxis(axis) , mSource(source) , mMin(min) , mMax(max) , mFlat(flat) , mFuzz(fuzz) , mResolution(resolution) { } ECode InputDevice::MotionRange::GetAxis( /* [out] */ Int32* axis) { VALIDATE_NOT_NULL(axis) *axis = mAxis; return NOERROR; } ECode InputDevice::MotionRange::GetSource( /* [out] */ Int32* source) { VALIDATE_NOT_NULL(source) *source = mSource; return NOERROR; } ECode InputDevice::MotionRange::IsFromSource( /* [in] */ Int32 source, /* [out] */ Boolean* rst) { VALIDATE_NOT_NULL(rst) *rst = (mSource & source) == source; return NOERROR; } ECode InputDevice::MotionRange::GetMin( /* [out] */ Float* minimum) { VALIDATE_NOT_NULL(minimum); *minimum = mMin; return NOERROR; } ECode InputDevice::MotionRange::GetMax( /* [out] */ Float* maximum) { VALIDATE_NOT_NULL(maximum); *maximum = mMax; return NOERROR; } ECode InputDevice::MotionRange::GetRange( /* [out] */ Float* range) { VALIDATE_NOT_NULL(range); *range = mMax - mMin; return NOERROR; } ECode InputDevice::MotionRange::GetFlat( /* [out] */ Float* flat) { VALIDATE_NOT_NULL(flat); *flat = mFlat; return NOERROR; } ECode InputDevice::MotionRange::GetFuzz( /* [out] */ Float* fuzz) { VALIDATE_NOT_NULL(fuzz); *fuzz = mFuzz; return NOERROR; } ECode InputDevice::MotionRange::GetResolution( /* [out] */ Float* resolution) { VALIDATE_NOT_NULL(resolution); *resolution = mResolution; return NOERROR; } InputDevice::InputDevice() : mId(0) , mGeneration(0) , mControllerNumber(0) , mVendorId(0) , mProductId(0) , mIsExternal(FALSE) , mSources(0) , mKeyboardType(0) , mHasVibrator(FALSE) , mHasButtonUnderPad(FALSE) { } InputDevice::~InputDevice() { } ECode InputDevice::constructor() { CArrayList::New((IArrayList**)&mMotionRanges); return NOERROR; } ECode InputDevice::constructor( /* [in] */ Int32 id, /* [in] */ Int32 generation, /* [in] */ Int32 controllerNumber, /* [in] */ const String& name, /* [in] */ Int32 vendorId, /* [in] */ Int32 productId, /* [in] */ const String& descriptor, /* [in] */ Boolean isExternal, /* [in] */ Int32 sources, /* [in] */ Int32 keyboardType, /* [in] */ IKeyCharacterMap* keyCharacterMap, /* [in] */ Boolean hasVibrator, /* [in] */ Boolean hasButtonUnderPad) { CArrayList::New((IArrayList**)&mMotionRanges); mId = id; mGeneration = generation; mControllerNumber = controllerNumber; mName = name; mVendorId = vendorId; mProductId = productId; mDescriptor = descriptor; mIsExternal = isExternal; mSources = sources; mKeyboardType = keyboardType; mKeyCharacterMap = keyCharacterMap; mHasVibrator = hasVibrator; mHasButtonUnderPad = hasButtonUnderPad; CInputDeviceIdentifier::New(descriptor, vendorId, productId, (IInputDeviceIdentifier**)&mIdentifier); return NOERROR; } ECode InputDevice::GetDevice( /* [in] */ Int32 id, /* [out] */ IInputDevice** device) { return CInputManager::GetInstance()->GetInputDevice(id, device); } ECode InputDevice::GetDeviceIds( /* [out, callee] */ ArrayOf<Int32>** deviceIds) { return CInputManager::GetInstance()->GetInputDeviceIds(deviceIds); } ECode InputDevice::GetId( /* [out] */ Int32* id) { VALIDATE_NOT_NULL(id); *id = mId; return NOERROR; } ECode InputDevice::GetControllerNumber( /* [out] */ Int32* number) { VALIDATE_NOT_NULL(number) *number = mControllerNumber; return NOERROR; } ECode InputDevice::GetIdentifier( /* [out] */ IInputDeviceIdentifier** identifier) { VALIDATE_NOT_NULL(identifier) *identifier = mIdentifier; REFCOUNT_ADD(*identifier) return NOERROR; } ECode InputDevice::GetGeneration( /* [out] */ Int32* generation) { VALIDATE_NOT_NULL(generation); *generation = mGeneration; return NOERROR; } ECode InputDevice::GetVendorId( /* [out] */ Int32* id) { VALIDATE_NOT_NULL(id) *id = mVendorId; return NOERROR; } ECode InputDevice::GetProductId( /* [out] */ Int32* id) { VALIDATE_NOT_NULL(id) *id = mProductId; return NOERROR; } ECode InputDevice::GetDescriptor( /* [out] */ String* descriptor) { VALIDATE_NOT_NULL(descriptor); *descriptor = mDescriptor; return NOERROR; } ECode InputDevice::IsVirtual( /* [out] */ Boolean* isVirtual) { VALIDATE_NOT_NULL(isVirtual); *isVirtual = mId < 0; return NOERROR; } ECode InputDevice::IsExternal( /* [out] */ Boolean* isExternal) { VALIDATE_NOT_NULL(isExternal); *isExternal = mIsExternal; return NOERROR; } ECode InputDevice::IsFullKeyboard( /* [out] */ Boolean* isFullKeyboard) { VALIDATE_NOT_NULL(isFullKeyboard); *isFullKeyboard = (mSources & SOURCE_KEYBOARD) == SOURCE_KEYBOARD && mKeyboardType == KEYBOARD_TYPE_ALPHABETIC; return NOERROR; } ECode InputDevice::GetName( /* [out] */ String* name) { VALIDATE_NOT_NULL(name); *name = mName; return NOERROR; } ECode InputDevice::GetSources( /* [out] */ Int32* sources) { VALIDATE_NOT_NULL(sources); *sources = mSources; return NOERROR; } ECode InputDevice::SupportsSource( /* [in] */ Int32 source, /* [out] */ Boolean* rst) { VALIDATE_NOT_NULL(rst); *rst = (mSources & source) == source; return NOERROR; } ECode InputDevice::GetKeyboardType( /* [out] */ Int32* type) { VALIDATE_NOT_NULL(type); *type = mKeyboardType; return NOERROR; } ECode InputDevice::GetKeyCharacterMap( /* [out] */ IKeyCharacterMap** keyCharacterMap) { VALIDATE_NOT_NULL(keyCharacterMap); *keyCharacterMap = mKeyCharacterMap; REFCOUNT_ADD(*keyCharacterMap); return NOERROR; } ECode InputDevice::GetHasVibrator( /* [out] */ Boolean* hasVibrator) { VALIDATE_NOT_NULL(hasVibrator) *hasVibrator = mHasVibrator; return NOERROR; } ECode InputDevice::GetHasButtonUnderPad( /* [out] */ Boolean* hasButtonUnderPad) { VALIDATE_NOT_NULL(hasButtonUnderPad) *hasButtonUnderPad = mHasButtonUnderPad; return NOERROR; } ECode InputDevice::HasKeys( /* [in] */ ArrayOf<Int32>* keys, /* [out, calleee] */ ArrayOf<Boolean>** rsts) { VALIDATE_NOT_NULL(rsts) AutoPtr<IInputManagerHelper> helper; CInputManagerHelper::AcquireSingleton((IInputManagerHelper**)&helper); AutoPtr<IInputManager> manager; helper->GetInstance((IInputManager**)&manager); AutoPtr<ArrayOf<Int32> > param = ArrayOf<Int32>::Alloc(keys->GetLength() + 1); param->Set(0, mId); param->Copy(1, keys); return manager->DeviceHasKeys(*param, rsts); } ECode InputDevice::GetMotionRange( /* [in] */ Int32 axis, /* [out] */ IMotionRange** montionRange) { VALIDATE_NOT_NULL(montionRange); Int32 size; mMotionRanges->GetSize(&size); for (Int32 i = 0; i < size; ++i) { AutoPtr<IInterface> tmp; mMotionRanges->Get(i, (IInterface**)&tmp); AutoPtr<IMotionRange> rangeItf = IMotionRange::Probe(tmp); MotionRange* range = (MotionRange*)(rangeItf.Get()); if (range->mAxis == axis) { *montionRange = range; REFCOUNT_ADD(*montionRange); return NOERROR; } } *montionRange = NULL; return NOERROR; } ECode InputDevice::GetMotionRange( /* [in] */ Int32 axis, /* [in] */ Int32 source, /* [out] */ IMotionRange** montionRange) { VALIDATE_NOT_NULL(montionRange); Int32 size; mMotionRanges->GetSize(&size); for (Int32 i = 0; i < size; ++i) { AutoPtr<IInterface> tmp; mMotionRanges->Get(i, (IInterface**)&tmp); AutoPtr<IMotionRange> rangeItf = IMotionRange::Probe(tmp); MotionRange* range = (MotionRange*)(rangeItf.Get()); if (range->mAxis == axis && range->mSource == source) { *montionRange = range; REFCOUNT_ADD(*montionRange); return NOERROR; } } *montionRange = NULL; return NOERROR; } ECode InputDevice::GetMotionRanges( /* [out] */ IList** motionRanges) { VALIDATE_NOT_NULL(motionRanges); *motionRanges = IList::Probe(mMotionRanges); REFCOUNT_ADD(*motionRanges) return NOERROR; } ECode InputDevice::AddMotionRange( /* [in] */ Int32 axis, /* [in] */ Int32 source, /* [in] */ Float min, /* [in] */ Float max, /* [in] */ Float flat, /* [in] */ Float fuzz, /* [in] */ Float resolution) { AutoPtr<MotionRange> range = new MotionRange(axis, source, min, max, flat, fuzz, resolution); mMotionRanges->Add((IMotionRange*)range.Get()); return NOERROR; } ECode InputDevice::GetVibrator( /* [out] */ IVibrator** vibrator) { VALIDATE_NOT_NULL(vibrator); ISynchronize* sync = ISynchronize::Probe(mMotionRanges); AutoLock lock(sync); if (mVibrator == NULL) { if (mHasVibrator) { CInputManager::GetInstance()->GetInputDeviceVibrator( mId, (IVibrator**)&mVibrator); } else { mVibrator = (IVibrator*)NullVibrator::GetInstance().Get(); } } *vibrator = mVibrator; REFCOUNT_ADD(*vibrator); return NOERROR; } ECode InputDevice::HasButtonUnderPad( /* [in] */ Boolean* rst) { VALIDATE_NOT_NULL(rst) *rst = mHasButtonUnderPad; return NOERROR; } ECode InputDevice::ReadFromParcel( /* [in] */ IParcel* in) { in->ReadInt32(&mId); in->ReadInt32(&mGeneration); in->ReadInt32(&mControllerNumber); in->ReadString(&mName); in->ReadInt32(&mVendorId); in->ReadInt32(&mProductId); in->ReadString(&mDescriptor); in->ReadBoolean(&mIsExternal); in->ReadInt32(&mSources); in->ReadInt32(&mKeyboardType); CKeyCharacterMap::New((IKeyCharacterMap**)&mKeyCharacterMap); IParcelable::Probe(mKeyCharacterMap)->ReadFromParcel(in); in->ReadBoolean(&mHasVibrator); in->ReadBoolean(&mHasButtonUnderPad); CInputDeviceIdentifier::New(mDescriptor, mVendorId, mProductId, (IInputDeviceIdentifier**)&mIdentifier); Int32 size; in->ReadInt32(&size); for (Int32 i = 0; i < size; ++i) { Int32 axis, source; Float min, max, flat, fuzz, resolution; in->ReadInt32(&axis); in->ReadInt32(&source); in->ReadFloat(&min); in->ReadFloat(&max); in->ReadFloat(&flat); in->ReadFloat(&fuzz); in->ReadFloat(&resolution); AddMotionRange(axis, source, min, max, flat, fuzz, resolution); } return NOERROR; } ECode InputDevice::WriteToParcel( /* [in] */ IParcel* out) { out->WriteInt32(mId); out->WriteInt32(mGeneration); out->WriteInt32(mControllerNumber); out->WriteString(mName); out->WriteInt32(mVendorId); out->WriteInt32(mProductId); out->WriteString(mDescriptor); out->WriteBoolean(mIsExternal); out->WriteInt32(mSources); out->WriteInt32(mKeyboardType); IParcelable::Probe(mKeyCharacterMap)->WriteToParcel(out); out->WriteBoolean(mHasVibrator); out->WriteBoolean(mHasButtonUnderPad); Int32 size; mMotionRanges->GetSize(&size); out->WriteInt32(size); for (Int32 i = 0; i < size; ++i) { AutoPtr<IInterface> tmp; mMotionRanges->Get(i, (IInterface**)&tmp); AutoPtr<IMotionRange> rangeItf = IMotionRange::Probe(tmp); MotionRange* range = (MotionRange*)(rangeItf.Get()); assert(range != NULL); out->WriteInt32(range->mAxis); out->WriteInt32(range->mSource); out->WriteFloat(range->mMin); out->WriteFloat(range->mMax); out->WriteFloat(range->mFlat); out->WriteFloat(range->mFuzz); out->WriteFloat(range->mResolution); } return NOERROR; } ECode InputDevice::ToString( /* [out] */ String* str) { VALIDATE_NOT_NULL(str) StringBuilder description; ((((description += "Input Device ") += mId) += ": ") += mName) += "\n"; ((description += " Descriptor: ") += mDescriptor) += "\n"; ((description += " Generation: ") += " Generation: ") += "\n"; ((description += " Generation: ") += mGeneration) += "\n"; ((description += " Location: ") += mIsExternal ? "external" : "built-in") += "\n"; description += " Keyboard Type: "; switch (mKeyboardType) { case IInputDevice::KEYBOARD_TYPE_NONE: description += "none"; break; case IInputDevice::KEYBOARD_TYPE_NON_ALPHABETIC: description += "non-alphabetic"; break; case IInputDevice::KEYBOARD_TYPE_ALPHABETIC: description += "alphabetic"; break; } description += "\n"; ((description += " Has Vibrator: ") += " Has Vibrator: ") += "\n"; ((description += " Sources: 0x") += StringUtils::ToString(mSources, 16)) += " ("; AppendSourceDescriptionIfApplicable(description, IInputDevice::SOURCE_KEYBOARD, String("keyboard")); AppendSourceDescriptionIfApplicable(description, IInputDevice::SOURCE_DPAD, String("dpad")); AppendSourceDescriptionIfApplicable(description, IInputDevice::SOURCE_TOUCHSCREEN, String("touchscreen")); AppendSourceDescriptionIfApplicable(description, IInputDevice::SOURCE_MOUSE, String("mouse")); AppendSourceDescriptionIfApplicable(description, IInputDevice::SOURCE_STYLUS, String("stylus")); AppendSourceDescriptionIfApplicable(description, IInputDevice::SOURCE_TRACKBALL, String("trackball")); AppendSourceDescriptionIfApplicable(description, IInputDevice::SOURCE_TOUCHPAD, String("touchpad")); AppendSourceDescriptionIfApplicable(description, IInputDevice::SOURCE_JOYSTICK, String("joystick")); AppendSourceDescriptionIfApplicable(description, IInputDevice::SOURCE_GAMEPAD, String("gamepad")); AppendSourceDescriptionIfApplicable(description, IInputDevice::SOURCE_GESTURE_SENSOR, String("gesture")); description += " )\n"; Int32 size; mMotionRanges->GetSize(&size); for (Int32 i = 0; i < size; ++i) { AutoPtr<IInterface> tmp; mMotionRanges->Get(i, (IInterface**)&tmp); AutoPtr<IMotionRange> rangeItf = IMotionRange::Probe(tmp); MotionRange* range = (MotionRange*)(rangeItf.Get()); (description += " ") += MotionEvent::AxisToString(range->mAxis); (description += ": source=0x") += StringUtils::ToString(range->mSource, 16); (description += " min=") += range->mMin; (description += " max=") += range->mMax; (description += " flat=") += range->mFlat; (description += " fuzz=") += range->mFuzz; (description += " resolution=") += range->mResolution; description += "\n"; } *str = description.ToString(); return NOERROR; } ECode InputDevice::AppendSourceDescriptionIfApplicable( /* [in] */ StringBuilder& description, /* [in] */ Int32 source, /* [in] */ const String& sourceName) { if ((mSources & source) == source) { description += " "; description += sourceName; } return NOERROR; } } //namespace View } //namespace Droid } //namespace Elastos
27.953301
110
0.645832
jingcao80
ae71a4ef975ed4a1f28cc8068cf32da4b32e4d2b
3,722
hpp
C++
src/mge/core/GameObject.hpp
mtesseracttech/CustomEngine
1a9ed564408ae29fe49681a810b851403d71f486
[ "Apache-2.0" ]
null
null
null
src/mge/core/GameObject.hpp
mtesseracttech/CustomEngine
1a9ed564408ae29fe49681a810b851403d71f486
[ "Apache-2.0" ]
null
null
null
src/mge/core/GameObject.hpp
mtesseracttech/CustomEngine
1a9ed564408ae29fe49681a810b851403d71f486
[ "Apache-2.0" ]
null
null
null
#ifndef GAMEOBJECT_H #define GAMEOBJECT_H #include <vector> #include <string> #include <iostream> #include <glm/glm.hpp> #include "LinearMath/btDefaultMotionState.h" #include "BulletCollision/CollisionShapes/btSphereShape.h" #include "BulletDynamics/Vehicle/btRaycastVehicle.h" class RigidBody; class AbstractBehaviour; class AbstractMaterial; class World; class Mesh; /** * A GameObject wraps all data required to display an (interactive / dynamic) object, but knows nothing about OpenGL or rendering. * You will need to alter this class to add colliders etc. */ class GameObject { public: GameObject(std::string pName = NULL, glm::vec3 pPosition = glm::vec3(0.0f, 0.0f, 0.0f)); virtual ~GameObject(); void setName(std::string pName); std::string getName() const; //contains local rotation, scale, position const glm::mat4& getTransform() const; void setTransform(const glm::mat4& pTransform); //access just the local position glm::vec3 getLocalPosition() const; glm::quat getLocalRotation() const; glm::quat getLocalRotationSlow() const; void setLocalPosition(const glm::vec3 pPosition); void setLocalRotation(const glm::quat rotation); glm::vec3 getTransformRight() const; glm::vec3 getTransformUp() const; glm::vec3 getTransformForward() const; void setTransformForward(glm::vec3 fwd); //get the objects world position by combining transforms //expensive operations!! Improvement would be to cache these transforms! glm::vec3 getWorldPosition() const; glm::quat getWorldRotation() const; glm::mat4 getWorldTransform() const; glm::vec3 getWorldTransformRight() const; glm::vec3 getWorldTransformUp() const; glm::vec3 getWorldTransformForward() const; //change local position, rotation, scaling void translate(glm::vec3 pTranslation); void rotate(float pAngle, glm::vec3 pAxis); //DO NOT USE IN FINAL GAME, ROTATION FUNCTIONS MAKE GAMEOBJECT LOSE SCALE! void scale(glm::vec3 pScale); //mesh and material should be shared as much as possible void setMesh(Mesh* pMesh); Mesh* getMesh() const; void setMaterial(AbstractMaterial* pMaterial); AbstractMaterial* getMaterial() const; btDefaultMotionState* getDefaultMotionState() const; void setRigidBody(btCollisionShape* shape, float mass, btDynamicsWorld* world); void setMeshRigidBody(btDynamicsWorld* world); RigidBody* getRigidBody() const; void removeRigidBody() const; virtual void update(float pStep); void AddBehaviour(AbstractBehaviour* behaviour); void RemoveBehaviour(AbstractBehaviour* behaviour); void ClearBehaviours(); void DeleteBehaviours(); //child management //shortcut to set the parent of pChild to ourselves void add(GameObject* pChild); //shortcut to set the parent of pChild to NULL void remove(GameObject* pChild); virtual void setParent(GameObject* pGameObject); GameObject* getParent(); int getChildCount(); GameObject* getChildAt(int pIndex); void enableDebugging(); void printDebug(); void deleteObject(const GameObject* pObject); //light void AdjustPosition(); virtual void OnCollision(const btCollisionObject* other); protected: std::string _name; glm::mat4 _transform; GameObject* _parent; std::vector<GameObject*> _children; Mesh* _mesh; AbstractMaterial* _material; RigidBody* _rigidBody; btDefaultMotionState* _defaultMotionState; std::vector<AbstractBehaviour*> _behaviours; //update children list administration void _innerAdd(GameObject* pChild); void _innerRemove(GameObject* pChild); private: GameObject(const GameObject&); GameObject& operator=(const GameObject&); bool _debug; glm::mat4 floatToMat4(float* Pmatrix); }; #endif // GAMEOBJECT_H
29.776
129
0.754164
mtesseracttech
ae72d619789f6f135889a6b73e3309bce505c65c
783
cc
C++
examples/cli-subcommands/greetings.cc
jfjlaros/userIO
21e32a80ed3c652fb983780de0936a1aaec67b0c
[ "MIT" ]
2
2021-11-09T11:25:55.000Z
2021-12-08T18:47:53.000Z
examples/cli-subcommands/greetings.cc
jfjlaros/commandIO
21e32a80ed3c652fb983780de0936a1aaec67b0c
[ "MIT" ]
null
null
null
examples/cli-subcommands/greetings.cc
jfjlaros/commandIO
21e32a80ed3c652fb983780de0936a1aaec67b0c
[ "MIT" ]
null
null
null
/* * Example CLI interface for multiple functions. */ #include <commandIO.h> string hi(bool shout) { if (shout) { return "HELLO WORLD!"; } return "Hello world."; } string greet(string name) { return "Hello " + name + "."; } string flood(string name, int times) { string greeting = ""; int i; for (i = 0; i < times; i++) { greeting += "Hi " + name + ".\n"; } return greeting; } int main(int argc, char** argv) { CliIO io(argc, argv); interface( io, func(hi, "hi", "simple greeting", param("-s", false, "shout")), func(greet, "greet", "personal greeting", param("name", "name")), func(flood, "flood", "multiple personal greetings", param("name", "name"), param("-n", 1, "multiplier"))); return 0; }
17.021739
55
0.563218
jfjlaros
ae74218f8cb2aabee96af40c71347623f1a9343e
945
cpp
C++
C++/Maximum Element/Solution.cpp
chessmastersan/HackerRank
850319e6f79e7473afbb847d28edde7b2cdfc37d
[ "MIT" ]
2
2019-08-07T19:58:20.000Z
2019-08-27T00:06:09.000Z
C++/Maximum Element/Solution.cpp
chessmastersan/HackerRank
850319e6f79e7473afbb847d28edde7b2cdfc37d
[ "MIT" ]
1
2020-06-11T19:09:48.000Z
2020-06-11T19:09:48.000Z
C++/Maximum Element/Solution.cpp
chessmastersan/HackerRank
850319e6f79e7473afbb847d28edde7b2cdfc37d
[ "MIT" ]
7
2019-08-27T00:06:11.000Z
2021-12-11T10:01:45.000Z
/** * @author SANKALP SAXENA */ #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ long int n, i=1, ch, item, top=-1; scanf("%ld",&n); long int stack[n]; for(i=1; i<=n; i++) { scanf("%ld",&ch); switch(ch) { case 1: scanf("%ld",&item); stack[++(top)] = item; break; case 2: stack[(top)--]; break; case 3: long int i=0, max=stack[0]; for( ; i<=top ; i++) { if(stack[i] > max) max = stack[i]; } printf("%ld\n", max); } } return 0; }
21
80
0.373545
chessmastersan
ae7ad77f8d25919d3349cddc6fd908c972de005b
13,697
cpp
C++
sources/VS/ThirdParty/wxWidgets/samples/widgets/gauge.cpp
Sasha7b9Work/S8-53M2
fdc9cb5e3feb8055fd3f7885a6f6362f62ff6b6e
[ "MIT" ]
null
null
null
sources/VS/ThirdParty/wxWidgets/samples/widgets/gauge.cpp
Sasha7b9Work/S8-53M2
fdc9cb5e3feb8055fd3f7885a6f6362f62ff6b6e
[ "MIT" ]
null
null
null
sources/VS/ThirdParty/wxWidgets/samples/widgets/gauge.cpp
Sasha7b9Work/S8-53M2
fdc9cb5e3feb8055fd3f7885a6f6362f62ff6b6e
[ "MIT" ]
null
null
null
///////////////////////////////////////////////////////////////////////////// // Program: wxWidgets Widgets Sample // Name: gauge.cpp // Purpose: Part of the widgets sample showing wxGauge // Author: Vadim Zeitlin // Created: 27.03.01 // Copyright: (c) 2001 Vadim Zeitlin // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// // ============================================================================ // declarations // ============================================================================ // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- // for compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" // for all others, include the necessary headers #ifndef WX_PRECOMP #include "wx/log.h" #include "wx/timer.h" #include "wx/bitmap.h" #include "wx/button.h" #include "wx/checkbox.h" #include "wx/combobox.h" #include "wx/gauge.h" #include "wx/radiobox.h" #include "wx/statbox.h" #include "wx/textctrl.h" #endif #include "wx/sizer.h" #include "widgets.h" #if wxUSE_GAUGE #include "icons/gauge.xpm" // ---------------------------------------------------------------------------- // constants // ---------------------------------------------------------------------------- // control ids enum { GaugePage_Reset = wxID_HIGHEST, GaugePage_Progress, GaugePage_IndeterminateProgress, GaugePage_Clear, GaugePage_SetValue, GaugePage_SetRange, GaugePage_CurValueText, GaugePage_ValueText, GaugePage_RangeText, GaugePage_Timer, GaugePage_IndeterminateTimer, GaugePage_Gauge }; // ---------------------------------------------------------------------------- // GaugeWidgetsPage // ---------------------------------------------------------------------------- class GaugeWidgetsPage : public WidgetsPage { public: GaugeWidgetsPage(WidgetsBookCtrl *book, wxImageList *imaglist); virtual ~GaugeWidgetsPage(); virtual wxWindow *GetWidget() const wxOVERRIDE { return m_gauge; } virtual void RecreateWidget() wxOVERRIDE { CreateGauge(); } // lazy creation of the content virtual void CreateContent() wxOVERRIDE; protected: // event handlers void OnButtonReset(wxCommandEvent& event); void OnButtonProgress(wxCommandEvent& event); void OnButtonIndeterminateProgress(wxCommandEvent& event); void OnButtonClear(wxCommandEvent& event); void OnButtonSetValue(wxCommandEvent& event); void OnButtonSetRange(wxCommandEvent& event); void OnCheckOrRadioBox(wxCommandEvent& event); void OnUpdateUIValueButton(wxUpdateUIEvent& event); void OnUpdateUIRangeButton(wxUpdateUIEvent& event); void OnUpdateUIResetButton(wxUpdateUIEvent& event); void OnUpdateUICurValueText(wxUpdateUIEvent& event); void OnProgressTimer(wxTimerEvent& event); void OnIndeterminateProgressTimer(wxTimerEvent& event); // reset the gauge parameters void Reset(); // (re)create the gauge void CreateGauge(); // start progress timer void StartTimer(wxButton*); // stop the progress timer void StopTimer(wxButton*); // the gauge range unsigned long m_range; // the controls // ------------ // the checkboxes for styles wxCheckBox *m_chkVert, *m_chkSmooth, *m_chkProgress; // the gauge itself and the sizer it is in wxGauge *m_gauge; wxSizer *m_sizerGauge; // the text entries for set value/range wxTextCtrl *m_textValue, *m_textRange; // the timer for simulating gauge progress wxTimer *m_timer; private: wxDECLARE_EVENT_TABLE(); DECLARE_WIDGETS_PAGE(GaugeWidgetsPage) }; // ---------------------------------------------------------------------------- // event tables // ---------------------------------------------------------------------------- wxBEGIN_EVENT_TABLE(GaugeWidgetsPage, WidgetsPage) EVT_BUTTON(GaugePage_Reset, GaugeWidgetsPage::OnButtonReset) EVT_BUTTON(GaugePage_Progress, GaugeWidgetsPage::OnButtonProgress) EVT_BUTTON(GaugePage_IndeterminateProgress, GaugeWidgetsPage::OnButtonIndeterminateProgress) EVT_BUTTON(GaugePage_Clear, GaugeWidgetsPage::OnButtonClear) EVT_BUTTON(GaugePage_SetValue, GaugeWidgetsPage::OnButtonSetValue) EVT_BUTTON(GaugePage_SetRange, GaugeWidgetsPage::OnButtonSetRange) EVT_UPDATE_UI(GaugePage_SetValue, GaugeWidgetsPage::OnUpdateUIValueButton) EVT_UPDATE_UI(GaugePage_SetRange, GaugeWidgetsPage::OnUpdateUIRangeButton) EVT_UPDATE_UI(GaugePage_Reset, GaugeWidgetsPage::OnUpdateUIResetButton) EVT_UPDATE_UI(GaugePage_CurValueText, GaugeWidgetsPage::OnUpdateUICurValueText) EVT_CHECKBOX(wxID_ANY, GaugeWidgetsPage::OnCheckOrRadioBox) EVT_RADIOBOX(wxID_ANY, GaugeWidgetsPage::OnCheckOrRadioBox) EVT_TIMER(GaugePage_Timer, GaugeWidgetsPage::OnProgressTimer) EVT_TIMER(GaugePage_IndeterminateTimer, GaugeWidgetsPage::OnIndeterminateProgressTimer) wxEND_EVENT_TABLE() // ============================================================================ // implementation // ============================================================================ #if defined(__WXUNIVERSAL__) #define FAMILY_CTRLS UNIVERSAL_CTRLS #else #define FAMILY_CTRLS NATIVE_CTRLS #endif IMPLEMENT_WIDGETS_PAGE(GaugeWidgetsPage, "Gauge", FAMILY_CTRLS ); GaugeWidgetsPage::GaugeWidgetsPage(WidgetsBookCtrl *book, wxImageList *imaglist) :WidgetsPage(book, imaglist, gauge_xpm) { // init everything m_range = 100; m_timer = (wxTimer *)NULL; m_chkVert = m_chkSmooth = m_chkProgress = (wxCheckBox *)NULL; m_gauge = (wxGauge *)NULL; m_sizerGauge = (wxSizer *)NULL; } void GaugeWidgetsPage::CreateContent() { wxSizer *sizerTop = new wxBoxSizer(wxHORIZONTAL); // left pane wxStaticBox *box = new wxStaticBox(this, wxID_ANY, "&Set style"); wxSizer *sizerLeft = new wxStaticBoxSizer(box, wxVERTICAL); m_chkVert = CreateCheckBoxAndAddToSizer(sizerLeft, "&Vertical"); m_chkSmooth = CreateCheckBoxAndAddToSizer(sizerLeft, "&Smooth"); m_chkProgress = CreateCheckBoxAndAddToSizer(sizerLeft, "&Progress"); sizerLeft->Add(5, 5, 0, wxGROW | wxALL, 5); // spacer wxButton *btn = new wxButton(this, GaugePage_Reset, "&Reset"); sizerLeft->Add(btn, 0, wxALIGN_CENTRE_HORIZONTAL | wxALL, 15); // middle pane wxStaticBox *box2 = new wxStaticBox(this, wxID_ANY, "&Change gauge value"); wxSizer *sizerMiddle = new wxStaticBoxSizer(box2, wxVERTICAL); wxTextCtrl *text; wxSizer *sizerRow = CreateSizerWithTextAndLabel("Current value", GaugePage_CurValueText, &text); text->SetEditable(false); sizerMiddle->Add(sizerRow, 0, wxALL | wxGROW, 5); sizerRow = CreateSizerWithTextAndButton(GaugePage_SetValue, "Set &value", GaugePage_ValueText, &m_textValue); sizerMiddle->Add(sizerRow, 0, wxALL | wxGROW, 5); sizerRow = CreateSizerWithTextAndButton(GaugePage_SetRange, "Set &range", GaugePage_RangeText, &m_textRange); m_textRange->SetValue( wxString::Format("%lu", m_range) ); sizerMiddle->Add(sizerRow, 0, wxALL | wxGROW, 5); btn = new wxButton(this, GaugePage_Progress, "Simulate &progress"); sizerMiddle->Add(btn, 0, wxALL | wxGROW, 5); btn = new wxButton(this, GaugePage_IndeterminateProgress, "Simulate &indeterminate job"); sizerMiddle->Add(btn, 0, wxALL | wxGROW, 5); btn = new wxButton(this, GaugePage_Clear, "&Clear"); sizerMiddle->Add(btn, 0, wxALL | wxGROW, 5); // right pane wxSizer *sizerRight = new wxBoxSizer(wxHORIZONTAL); m_gauge = new wxGauge(this, GaugePage_Gauge, m_range); sizerRight->Add(m_gauge, 1, wxCENTRE | wxALL, 5); sizerRight->SetMinSize(150, 0); m_sizerGauge = sizerRight; // save it to modify it later // the 3 panes panes compose the window sizerTop->Add(sizerLeft, 0, wxGROW | (wxALL & ~wxLEFT), 10); sizerTop->Add(sizerMiddle, 1, wxGROW | wxALL, 10); sizerTop->Add(sizerRight, 1, wxGROW | (wxALL & ~wxRIGHT), 10); // final initializations Reset(); SetSizer(sizerTop); } GaugeWidgetsPage::~GaugeWidgetsPage() { delete m_timer; } // ---------------------------------------------------------------------------- // operations // ---------------------------------------------------------------------------- void GaugeWidgetsPage::Reset() { m_chkVert->SetValue(false); m_chkSmooth->SetValue(false); m_chkProgress->SetValue(false); } void GaugeWidgetsPage::CreateGauge() { int flags = GetAttrs().m_defaultFlags; if ( m_chkVert->GetValue() ) flags |= wxGA_VERTICAL; else flags |= wxGA_HORIZONTAL; if ( m_chkSmooth->GetValue() ) flags |= wxGA_SMOOTH; if ( m_chkProgress->GetValue() ) flags |= wxGA_PROGRESS; int val = 0; if ( m_gauge ) { val = m_gauge->GetValue(); m_sizerGauge->Detach( m_gauge ); delete m_gauge; } m_gauge = new wxGauge(this, GaugePage_Gauge, m_range, wxDefaultPosition, wxDefaultSize, flags); m_gauge->SetValue(val); if ( flags & wxGA_VERTICAL ) m_sizerGauge->Add(m_gauge, 0, wxGROW | wxALL, 5); else m_sizerGauge->Add(m_gauge, 1, wxCENTRE | wxALL, 5); m_sizerGauge->Layout(); } void GaugeWidgetsPage::StartTimer(wxButton *clicked) { static const int INTERVAL = 300; wxLogMessage("Launched progress timer (interval = %d ms)", INTERVAL); m_timer = new wxTimer(this, clicked->GetId() == GaugePage_Progress ? GaugePage_Timer : GaugePage_IndeterminateTimer); m_timer->Start(INTERVAL); clicked->SetLabel("&Stop timer"); if (clicked->GetId() == GaugePage_Progress) FindWindow(GaugePage_IndeterminateProgress)->Disable(); else FindWindow(GaugePage_Progress)->Disable(); } void GaugeWidgetsPage::StopTimer(wxButton *clicked) { wxCHECK_RET( m_timer, "shouldn't be called" ); m_timer->Stop(); wxDELETE(m_timer); if (clicked->GetId() == GaugePage_Progress) { clicked->SetLabel("Simulate &progress"); FindWindow(GaugePage_IndeterminateProgress)->Enable(); } else { clicked->SetLabel("Simulate indeterminate job"); FindWindow(GaugePage_Progress)->Enable(); } wxLogMessage("Progress finished."); } // ---------------------------------------------------------------------------- // event handlers // ---------------------------------------------------------------------------- void GaugeWidgetsPage::OnButtonReset(wxCommandEvent& WXUNUSED(event)) { Reset(); CreateGauge(); } void GaugeWidgetsPage::OnButtonProgress(wxCommandEvent& event) { wxButton *b = (wxButton *)event.GetEventObject(); if ( !m_timer ) { StartTimer(b); } else // stop the running timer { StopTimer(b); wxLogMessage("Stopped the timer."); } } void GaugeWidgetsPage::OnButtonIndeterminateProgress(wxCommandEvent& event) { wxButton *b = (wxButton *)event.GetEventObject(); if ( !m_timer ) { StartTimer(b); } else // stop the running timer { StopTimer(b); m_gauge->SetValue(0); wxLogMessage("Stopped the timer."); } } void GaugeWidgetsPage::OnButtonClear(wxCommandEvent& WXUNUSED(event)) { m_gauge->SetValue(0); } void GaugeWidgetsPage::OnButtonSetRange(wxCommandEvent& WXUNUSED(event)) { unsigned long val; if ( !m_textRange->GetValue().ToULong(&val) ) return; m_range = val; m_gauge->SetRange(val); } void GaugeWidgetsPage::OnButtonSetValue(wxCommandEvent& WXUNUSED(event)) { unsigned long val; if ( !m_textValue->GetValue().ToULong(&val) ) return; m_gauge->SetValue(val); } void GaugeWidgetsPage::OnUpdateUIValueButton(wxUpdateUIEvent& event) { unsigned long val; event.Enable( m_textValue->GetValue().ToULong(&val) && (val <= m_range) ); } void GaugeWidgetsPage::OnUpdateUIRangeButton(wxUpdateUIEvent& event) { unsigned long val; event.Enable( m_textRange->GetValue().ToULong(&val) ); } void GaugeWidgetsPage::OnUpdateUIResetButton(wxUpdateUIEvent& event) { event.Enable( m_chkVert->GetValue() || m_chkSmooth->GetValue() || m_chkProgress->GetValue() ); } void GaugeWidgetsPage::OnCheckOrRadioBox(wxCommandEvent& WXUNUSED(event)) { CreateGauge(); } void GaugeWidgetsPage::OnProgressTimer(wxTimerEvent& WXUNUSED(event)) { int val = m_gauge->GetValue(); if ( (unsigned)val < m_range ) { m_gauge->SetValue(val + 1); } else // reached the end { wxButton *btn = (wxButton *)FindWindow(GaugePage_Progress); wxCHECK_RET( btn, "no progress button?" ); StopTimer(btn); } } void GaugeWidgetsPage::OnIndeterminateProgressTimer(wxTimerEvent& WXUNUSED(event)) { m_gauge->Pulse(); } void GaugeWidgetsPage::OnUpdateUICurValueText(wxUpdateUIEvent& event) { event.SetText( wxString::Format("%d", m_gauge->GetValue())); } #endif // wxUSE_GAUGE
28.835789
97
0.599036
Sasha7b9Work
ae814fd9c69ec00895489e21e847958a7a75a14d
410
cc
C++
poj/2/2591.cc
eagletmt/procon
adbe503eb3c1bbcc1538b2ee8988aa353937e8d4
[ "MIT" ]
1
2015-04-17T09:54:23.000Z
2015-04-17T09:54:23.000Z
poj/2/2591.cc
eagletmt/procon
adbe503eb3c1bbcc1538b2ee8988aa353937e8d4
[ "MIT" ]
null
null
null
poj/2/2591.cc
eagletmt/procon
adbe503eb3c1bbcc1538b2ee8988aa353937e8d4
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; int main(void) { static const int N = 10000000; vector<int> v(N); int a = 0, b = 0; v[0] = 1; for (int i = 1; i < N; i++) { int x = min(2*v[a]+1, 3*v[b]+1); if (x == 2*v[a]+1) { a++; } if (x == 3*v[b]+1) { b++; } v[i] = x; } int n; while (cin >> n) { cout << v[n-1] << endl; } return 0; }
14.642857
36
0.429268
eagletmt
ae81c922341310210d05bf5ccbe9a368b12e9ce0
1,086
hpp
C++
function/codeFunction.hpp
TaylorP/TML
e4c0c7ce69645a1cf30df005af786a15f85b54a2
[ "MIT" ]
4
2015-12-17T21:58:27.000Z
2019-10-31T16:50:41.000Z
function/codeFunction.hpp
TaylorP/TML
e4c0c7ce69645a1cf30df005af786a15f85b54a2
[ "MIT" ]
null
null
null
function/codeFunction.hpp
TaylorP/TML
e4c0c7ce69645a1cf30df005af786a15f85b54a2
[ "MIT" ]
1
2019-05-07T18:51:00.000Z
2019-05-07T18:51:00.000Z
#ifndef CODE_FUNCTION_HPP #define CODE_FUNCTION_HPP #include "function/function.hpp" #include "exception/functionException.hpp" /// Function for full width code blocks class CodeFunction : public Function { public: /// Constructs a new code function CodeFunction(const bool pFilter) : Function(pFilter) { } /// Emits a full width code block to the stream virtual void emit(std::ostream& pStream, const std::vector<std::string>& pInput) const { // Validate parameter count if (pInput.size() != 2) { throw(FunctionException("@code", "Function expects exactly 2 parameters")); } // Print the pre tag, including the linenums and language class pStream << "<pre class='prettyprint linenums " << pInput[0] << "'>"; newline(pStream); // Print the code pStream << pInput[1]; newline(pStream); // Close the pre tag pStream << "</pre>"; newline(pStream); } }; #endif
25.255814
78
0.577348
TaylorP
ae857cf2e59e794dc8dcefaa309ac2c647a69b70
840
cpp
C++
Durna/Source/Runtime/Platform/OpenGL/OpenGLContext.cpp
MrWpGg/Durna
62c8ca2d69623e70e2dac49a5560cd3ac2c304ed
[ "Apache-2.0" ]
null
null
null
Durna/Source/Runtime/Platform/OpenGL/OpenGLContext.cpp
MrWpGg/Durna
62c8ca2d69623e70e2dac49a5560cd3ac2c304ed
[ "Apache-2.0" ]
null
null
null
Durna/Source/Runtime/Platform/OpenGL/OpenGLContext.cpp
MrWpGg/Durna
62c8ca2d69623e70e2dac49a5560cd3ac2c304ed
[ "Apache-2.0" ]
null
null
null
#include "DurnaPCH.h" #include "OpenGLContext.h" #include <glad/glad.h> #include <GLFW/glfw3.h> #include <gl/GL.h> namespace Durna { OpenGLContext::OpenGLContext(GLFWwindow* InWindowHandle) : WindowHandle(InWindowHandle) { DRN_ASSERT(WindowHandle, "WindowHandle is null!") } void OpenGLContext::Init() { DRN_PROFILE_FUNCTION(); glfwMakeContextCurrent(WindowHandle); int Status = gladLoadGLLoader((GLADloadproc)glfwGetProcAddress); DRN_ASSERT(Status, "Failed to init glad!"); LOG_TRACE(LOGCAT_GL, "initialized"); LOG_TRACE(LOGCAT_GL, "Vendor: {0}", glGetString(GL_VENDOR)); LOG_TRACE(LOGCAT_GL, "Renderer: {0}", glGetString(GL_RENDERER)); LOG_TRACE(LOGCAT_GL, "Version: {0}", glGetString(GL_VERSION)); } void OpenGLContext::SwapBuffers() { DRN_PROFILE_FUNCTION(); glfwSwapBuffers(WindowHandle); } }
21.538462
66
0.736905
MrWpGg
ae8a84f1881c8f25d27c1cb296519ae738c84b22
2,627
cpp
C++
src/network/vector_write.cpp
mpbarnwell/lightstep-tracer-cpp
4f8f110e7b69d1b8d24c9ea130cd560295e479b6
[ "MIT" ]
47
2016-05-23T10:39:50.000Z
2022-03-08T08:46:25.000Z
src/network/vector_write.cpp
mpbarnwell/lightstep-tracer-cpp
4f8f110e7b69d1b8d24c9ea130cd560295e479b6
[ "MIT" ]
63
2016-07-26T00:02:09.000Z
2022-03-11T07:20:44.000Z
src/network/vector_write.cpp
mpbarnwell/lightstep-tracer-cpp
4f8f110e7b69d1b8d24c9ea130cd560295e479b6
[ "MIT" ]
19
2016-09-21T17:59:03.000Z
2021-09-16T06:42:40.000Z
#include "network/vector_write.h" #include <algorithm> #include <cassert> #include <cerrno> #include <climits> #include <cstring> #include <iterator> #include <sstream> #include <stdexcept> #include "common/platform/error.h" #include "common/platform/memory.h" #include "common/platform/network.h" namespace lightstep { //-------------------------------------------------------------------------------------------------- // Write //-------------------------------------------------------------------------------------------------- bool Write(int socket, std::initializer_list<FragmentInputStream*> fragment_input_streams) { int num_fragments = 0; for (auto fragment_input_stream : fragment_input_streams) { num_fragments += fragment_input_stream->num_fragments(); } if (num_fragments == 0) { return true; } const auto max_batch_size = std::min(static_cast<int>(IoVecMax), num_fragments); auto fragments = static_cast<IoVec*>(alloca(sizeof(IoVec) * max_batch_size)); auto fragment_iter = fragments; const auto fragment_last = fragments + max_batch_size; int num_bytes_written = 0; int batch_num_bytes = 0; bool error = false; bool blocked = false; ErrorCode error_code; auto do_write = [&]() noexcept { auto rcode = WriteV(socket, fragments, static_cast<int>(std::distance(fragments, fragment_iter))); if (rcode < 0) { error_code = GetLastErrorCode(); if (IsBlockingErrorCode(error_code)) { blocked = true; } else { error = true; } return; } auto num_batch_bytes_written = static_cast<int>(rcode); assert(num_batch_bytes_written <= batch_num_bytes); num_bytes_written += num_batch_bytes_written; if (num_batch_bytes_written < batch_num_bytes) { blocked = true; } }; auto do_fragment = [&](void* data, int size) noexcept { *fragment_iter++ = MakeIoVec(data, static_cast<size_t>(size)); batch_num_bytes += size; if (fragment_iter != fragment_last) { return true; } do_write(); fragment_iter = fragments; batch_num_bytes = 0; return !(error || blocked); }; for (auto fragment_input_stream : fragment_input_streams) { if (!fragment_input_stream->ForEachFragment(do_fragment)) { break; } } if (batch_num_bytes > 0) { do_write(); } auto result = Consume(fragment_input_streams, num_bytes_written); if (error) { std::ostringstream oss; oss << "writev failed: " << GetErrorCodeMessage(error_code); throw std::runtime_error{oss.str()}; } return result; } } // namespace lightstep
29.852273
100
0.625809
mpbarnwell
ae8d05d82a6f88cc465c3192a18107f3ee98669a
1,326
cpp
C++
aws-cpp-sdk-cognito-idp/source/model/SetUserMFAPreferenceRequest.cpp
lintonv/aws-sdk-cpp
15e19c265ffce19d2046b18aa1b7307fc5377e58
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-cognito-idp/source/model/SetUserMFAPreferenceRequest.cpp
lintonv/aws-sdk-cpp
15e19c265ffce19d2046b18aa1b7307fc5377e58
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-cognito-idp/source/model/SetUserMFAPreferenceRequest.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2022-03-23T15:17:18.000Z
2022-03-23T15:17:18.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/cognito-idp/model/SetUserMFAPreferenceRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::CognitoIdentityProvider::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; SetUserMFAPreferenceRequest::SetUserMFAPreferenceRequest() : m_sMSMfaSettingsHasBeenSet(false), m_softwareTokenMfaSettingsHasBeenSet(false), m_accessTokenHasBeenSet(false) { } Aws::String SetUserMFAPreferenceRequest::SerializePayload() const { JsonValue payload; if(m_sMSMfaSettingsHasBeenSet) { payload.WithObject("SMSMfaSettings", m_sMSMfaSettings.Jsonize()); } if(m_softwareTokenMfaSettingsHasBeenSet) { payload.WithObject("SoftwareTokenMfaSettings", m_softwareTokenMfaSettings.Jsonize()); } if(m_accessTokenHasBeenSet) { payload.WithString("AccessToken", m_accessToken); } return payload.View().WriteReadable(); } Aws::Http::HeaderValueCollection SetUserMFAPreferenceRequest::GetRequestSpecificHeaders() const { Aws::Http::HeaderValueCollection headers; headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "AWSCognitoIdentityProviderService.SetUserMFAPreference")); return headers; }
22.862069
119
0.775264
lintonv
ae8d9be81b36679f7935111b3f8dac0d2e28a798
7,590
cpp
C++
source/AI/deeplearning/Normalization.cpp
TrojanVulgar/AI-framework
46779b44ebb542ff88b8b9e91fb9a0889191f928
[ "MIT", "Unlicense" ]
57
2018-02-21T13:28:23.000Z
2022-03-05T05:48:41.000Z
src/AI/deeplearning/Normalization.cpp
Flowx08/artificial_intelligence
ab4fec14e6af3e3fca271b76fdb67f05d7e588ed
[ "MIT" ]
null
null
null
src/AI/deeplearning/Normalization.cpp
Flowx08/artificial_intelligence
ab4fec14e6af3e3fca271b76fdb67f05d7e588ed
[ "MIT" ]
25
2018-08-27T01:54:03.000Z
2022-03-04T02:58:18.000Z
//////////////////////////////////////////////////////////// /// INCLUDES //////////////////////////////////////////////////////////// #include "Normalization.hpp" #include <cmath> #include "../util/ensure.hpp" #ifdef CUDA_BACKEND #include "CUDA_backend.hpp" #endif //////////////////////////////////////////////////////////// /// NAMESPACE AI //////////////////////////////////////////////////////////// namespace ai { //////////////////////////////////////////////////////////// std::shared_ptr<Operation> Normalization::make(float momentum) { return std::shared_ptr<Operation>(new Normalization(momentum)); } //////////////////////////////////////////////////////////// Normalization::Normalization(float momentum) { ensure(momentum >= 0 && momentum < 1); _gamma = 1.f; _beta = 0.f; _epsilon = 1e-4; _momentum = momentum; _d_beta = 0; _d_gamma = 0; } //////////////////////////////////////////////////////////// Normalization::Normalization(ai::IOData& data) { ai::IOData* size = data.findNode("size"); ensure(size != NULL); ai::IOData* width = data.findNode("width"); ensure(width != NULL); ai::IOData* height = data.findNode("height"); ensure(height != NULL); ai::IOData* depth = data.findNode("depth"); ensure(depth != NULL); ai::IOData* gamma = data.findNode("gamma"); ensure(gamma != NULL); ai::IOData* beta = data.findNode("beta"); ensure(beta != NULL); ai::IOData* epsilon = data.findNode("epsilon"); ensure(epsilon != NULL); ai::IOData* momentum = data.findNode("momentum"); ensure(momentum != NULL); size->get(_size); width->get(_width); height->get(_height); depth->get(_depth); gamma->get(_gamma); beta->get(_beta); epsilon->get(_epsilon); momentum->get(_momentum); _outputs.setshape(_width, _height, _depth); _outputs.fill(0); _errors.setshape(_size); _errors.fill(0); _deviation.setshape(_size); _deviation.fill(0); _normalized.setshape(_size); _normalized.fill(0); _d_beta = 0; _d_gamma = 0; #ifdef CUDA_BACKEND float* tmp = new float[5]; tmp[0] = 0; //variance tmp[1] = _gamma; //gamma tmp[2] = _beta; //beta tmp[3] = 0; //gamma delta tmp[4] = 0; //beta delta _params.setshape(5); _params.copyToDevice(tmp, 5); delete[] tmp; #endif } //////////////////////////////////////////////////////////// void Normalization::initialize(std::vector<Operation*> &inputs) { //Check for errors ensure(inputs.size() == 1); //Calculate size _size = inputs[0]->_outputs.size(); _width = inputs[0]->_outputs.width(); _height = inputs[0]->_outputs.height(); _depth = inputs[0]->_outputs.depth(); //Initialize vectors _outputs.setshape(_width, _height, _depth); _outputs.fill(0); _errors.setshape(_size); _errors.fill(0); _deviation.setshape(_size); _deviation.fill(0); _normalized.setshape(_size); _normalized.fill(0); _d_beta = 0; _d_gamma = 0; #ifdef CUDA_BACKEND float* tmp = new float[5]; tmp[0] = 0; //variance tmp[1] = _gamma; //gamma tmp[2] = _beta; //beta tmp[3] = 0; //gamma delta tmp[4] = 0; //beta delta _params.setshape(5); _params.copyToDevice(tmp, 5); delete[] tmp; #endif } //////////////////////////////////////////////////////////// void Normalization::save(ai::IOData& data) { data.pushNode("size", _size); data.pushNode("width", _width); data.pushNode("height", _height); data.pushNode("depth", _depth); data.pushNode("gamma", _gamma); data.pushNode("beta", _beta); data.pushNode("epsilon", _epsilon); data.pushNode("momentum", _momentum); } //////////////////////////////////////////////////////////// void Normalization::run(std::vector<Operation*> &inputs, const bool training) { //Check for correct input size ensure(inputs.size() == 1); ensure(inputs[0]->_outputs.size() == _outputs.size()); #ifdef CUDA_BACKEND ai::cuda::normalization_foreward(inputs[0]->_outputs.pointer(), _deviation.pointer(), _normalized.pointer(), _outputs.pointer(), &_params.pointer()[0], &_params.pointer()[1], &_params.pointer()[2], _epsilon, _size); //===== TESTING NORMALIZATION ====== /* Tensor_float t_out(_outputs.size()); _outputs.copyToHost(t_out.pointer(), t_out.size()); printf("%s\n", t_out.tostring().c_str()); */ #else //Shortcuts Tensor_float& in = inputs[0]->_outputs; //Calculate mean _mean = 0; for (int i = 0; i < in.size(); i++) _mean += in[i]; _mean /= (double)in.size(); //Subtract mean vector to all inputs and calculate variance _variance = 0; for (int i = 0; i < in.size(); i++) { _deviation[i] = in[i] - _mean; _variance += _deviation[i] * _deviation[i]; } _variance /= (double)in.size(); //Calculate normalized vector for (int i = 0; i < in.size(); i++) { _normalized[i] = _deviation[i] / std::sqrt(_variance + _epsilon); _outputs[i] = _normalized[i] * _gamma + _beta; } //===== TESTING NORMALIZATION ====== //printf("%s\n", _outputs.tostring().c_str()); #endif } //////////////////////////////////////////////////////////// void Normalization::backprop(std::vector<Operation*> &inputs) { //Check for correct input size ensure(inputs.size() == 1); #ifdef CUDA_BACKEND ai::cuda::normalization_backward(_errors.pointer(), inputs[0]->_errors.pointer(), _deviation.pointer(), &_params.pointer()[0], &_params.pointer()[1], &_params.pointer()[2], _epsilon, _size); #else //Shortcuts Tensor_float &out_errors = inputs[0]->_errors; //Pre compute some expressions float sum_errors = 0.f; float sum_errors_dev = 0.f; for (int i = 0; i < _errors.size(); i++) { sum_errors += _errors[i]; sum_errors_dev += _errors[i] * _deviation[i]; } //Calculate output errors for (int i = 0; i < out_errors.size(); i++) { out_errors[i] = 1.0 / (float)_size * _gamma / sqrt(_variance + _epsilon) * ((float)_size * _errors[i] - sum_errors - _deviation[i] / (_variance + _epsilon) * sum_errors_dev); } /* dh = (1. / N) * gamma * (var + eps)**(-1. / 2.) * (N * dy - np.sum(dy, axis=0) - (h - mu) * (var + eps)**(-1.0) * np.sum(dy * (h - mu), axis=0)) */ #endif } //////////////////////////////////////////////////////////// void Normalization::accumulate_deltas(std::vector<Operation*> &inputs) { #ifdef CUDA_BACKEND ai::cuda::normalization_accumulate_deltas(_errors.pointer(), _deviation.pointer(), &_params.pointer()[0], &_params.pointer()[3], &_params.pointer()[4], _epsilon, _size); #else //calculate beta delta for (int i = 0; i < _errors.size(); i++) _d_beta += _errors[i]; //calculate gamma delta for (int i = 0; i < _errors.size(); i++) _d_gamma += _deviation[i] * sqrt(_variance + _epsilon) * _errors[i]; #endif } //////////////////////////////////////////////////////////// void Normalization::update_parameters(const float learningrate) { #ifdef CUDA_BACKEND ai::cuda::normalization_update_parameters(&_params.pointer()[1], &_params.pointer()[2], &_params.pointer()[3], &_params.pointer()[4], _momentum, _size, learningrate); #else _beta += ((double)_d_beta / (double)_size) * learningrate; _gamma += ((double)_d_gamma / (double)_size) * learningrate; _d_beta *= _momentum; _d_gamma *= _momentum; #endif } //////////////////////////////////////////////////////////// const Operation::Type Normalization::get_type() const { return Operation::Normalization; } //////////////////////////////////////////////////////////// void Normalization::print() { printf("Type: Normalization, Size: %d, Momentum: %f", _size, _momentum); } } /* namespace ai */
28.00738
112
0.570224
TrojanVulgar
ae8e94744ca6aae111967b6d1661e80f23646a74
1,150
cpp
C++
codeforces/C - Cycle/Time limit exceeded on test 11 (3).cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/C - Cycle/Time limit exceeded on test 11 (3).cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/C - Cycle/Time limit exceeded on test 11 (3).cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: Oct/25/2019 15:28 * solution_verdict: Time limit exceeded on test 11 language: GNU C++14 * run_time: 2500 ms memory_used: 6200 KB * problem: https://codeforces.com/contest/117/problem/C ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; const int N=5e3; bitset<N+2>ot[N+2],in[N+2]; int main() { ios_base::sync_with_stdio(0);cin.tie(0); int n;cin>>n; for(int i=0;i<n;i++) { string s;cin>>s; for(int j=0;j<n;j++) if(s[j]=='1')ot[i][j]=1,in[j][i]=1; } for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(ot[i][j]&&(in[i]&ot[j]).count()) { cout<<i+1<<" "<<j+1<<" "; in[i]&=ot[j]; cout<<in[i]._Find_first()+1<<endl; exit(0); } } } cout<<-1<<endl; return 0; }
31.081081
111
0.376522
kzvd4729
ae92cacf2969dd5c33f9045e79d00e2a0f097cd7
6,807
cpp
C++
samples/tuple-builder/main.cpp
tim42/alphyn
af0c32df6813bbfded1df271283f9dd5378d0190
[ "MIT" ]
5
2016-03-05T00:39:13.000Z
2020-01-03T09:49:21.000Z
samples/tuple-builder/main.cpp
tim42/alphyn
af0c32df6813bbfded1df271283f9dd5378d0190
[ "MIT" ]
null
null
null
samples/tuple-builder/main.cpp
tim42/alphyn
af0c32df6813bbfded1df271283f9dd5378d0190
[ "MIT" ]
null
null
null
#include <tools/ct_string.hpp> #include <tools/demangle.hpp> #include <alphyn.hpp> #include <default_token.hpp> #include <iostream> #include <tuple> // #include <iomanip> template<const char *TypeName, typename Type> struct db_type_entry { using type = Type; // a small comparison function static constexpr bool strcmp(const char *s, size_t start, size_t end) { size_t i = start; size_t j = 0; for (; i < end && TypeName[j] != '\0' && TypeName[j] == s[i]; ++i, ++j); if (i != end || TypeName[j] != '\0') return false; return true; } }; template<typename... Entries> using type_db = neam::ct::type_list<Entries...>; /// \brief a very simple tuple builder /// \param TypeDB should be a type_db< db_type_entry< string, type >... > template<typename TypeDB, template<typename...> class TupleType = std::tuple> struct tuple_builder { // token relative things (type and invalid) using token_type = neam::ct::alphyn::token<size_t>; using type_t = typename token_type::type_t; /// \brief possible "types" for a token enum e_token_type : type_t { invalid = neam::ct::alphyn::invalid_token_type, // tokens (terminals) tok_end = 0, tok_id = 1, tok_comma = 2, tok_br_open = 3, tok_br_close = 4, // non-terminals start = 100, expr = 101, val = 104, }; // THE LEXER THINGS // // token builders template<typename... Entries> struct _id_token_builder { // search the type in the Type DB static constexpr token_type e_id(const char *s, size_t index, size_t end) { size_t type_index = TypeDB::size; // invalid size_t i = 0; NEAM_EXECUTE_PACK( (++i) && (type_index == TypeDB::size) && Entries::strcmp(s, index, end) && (type_index = i - 1) ); if (type_index < TypeDB::size) return token_type {e_token_type::tok_id, type_index, s, index, end}; else return token_type::generate_invalid_token(s, index); } }; template<typename List> using id_token_builder = typename neam::ct::extract_types<_id_token_builder, List>::type; // regular expressions constexpr static neam::string_t re_id = "[a-zA-Z0-9_-]+"; constexpr static neam::string_t re_end = "$"; /// \brief The lexical syntax that will be used to tokenize a string (tokens are easier to parse) using lexical_syntax = neam::ct::alphyn::lexical_syntax < neam::ct::alphyn::syntactic_unit<neam::ct::alphyn::letter<','>, token_type, token_type::generate_token_with_type<e_token_type::tok_comma>>, neam::ct::alphyn::syntactic_unit<neam::ct::alphyn::letter<'<'>, token_type, token_type::generate_token_with_type<e_token_type::tok_br_open >>, neam::ct::alphyn::syntactic_unit<neam::ct::alphyn::letter<'>'>, token_type, token_type::generate_token_with_type<e_token_type::tok_br_close >>, neam::ct::alphyn::syntactic_unit<neam::ct::alphyn::regexp<re_id>, token_type, id_token_builder<TypeDB>::e_id>, neam::ct::alphyn::syntactic_unit<neam::ct::alphyn::regexp<re_end>, token_type, token_type::generate_token_with_type<e_token_type::tok_end>> >; /// \brief We simply want to skip white spaces using skipper = neam::ct::alphyn::white_space_skipper; /// \brief Finally, the lexer using lexer = neam::ct::alphyn::lexer<tuple_builder>; // THE PARSER THINGS // // synthesizers: template<typename TokID> struct token_to_type // it transforms a token to a type { using type = typename TypeDB::template get_type<TokID::token.value>::type; }; template<typename Type> struct type_to_tuple // it transforms a single type to a tuple { using type = TupleType<Type>; }; template<typename Tuple, typename TokComma, typename Type> struct append_type_to_tuple {}; template<typename... TupleEntries, typename TokComma, typename Type> struct append_type_to_tuple<TupleType<TupleEntries...>, TokComma, Type> // it appends a type to a tuple { using type = TupleType<TupleEntries..., Type>; }; /// \brief Shortcuts for production_rule template<typename Attribute, type_t... TokensOrRules> using production_rule = neam::ct::alphyn::production_rule<tuple_builder, Attribute, TokensOrRules...>; /// \brief Shortcut for production_rule_set template<type_t Name, typename... Rules> using production_rule_set = neam::ct::alphyn::production_rule_set<tuple_builder, Name, Rules...>; /// \brief The parser grammar using grammar = neam::ct::alphyn::grammar<tuple_builder, start, production_rule_set<start, production_rule<neam::ct::alphyn::forward_attribute<1>, tok_br_open, expr, tok_br_close, tok_end> // start -> < expr > $ >, production_rule_set<expr, production_rule<neam::ct::alphyn::synthesizer_attribute<type_to_tuple>, val>, // expr -> val production_rule<neam::ct::alphyn::synthesizer_attribute<append_type_to_tuple>, expr, tok_comma, val> // expr -> expr, val >, production_rule_set<val, production_rule<neam::ct::alphyn::synthesizer_attribute<token_to_type>, tok_id>, // val -> id production_rule<neam::ct::alphyn::forward_attribute<1>, tok_br_open, expr, tok_br_close> // val -> < expr > > >; /// \brief The parser. It parses things. using parser = neam::ct::alphyn::parser<tuple_builder>; }; // create a simple type DB constexpr neam::string_t int_str = "int"; constexpr neam::string_t uint_str = "uint"; constexpr neam::string_t long_str = "long"; constexpr neam::string_t ulong_str = "ulong"; constexpr neam::string_t float_str = "float"; constexpr neam::string_t double_str = "double"; using simple_type_db = type_db < db_type_entry<int_str, int>, db_type_entry<uint_str, unsigned int>, db_type_entry<long_str, long>, db_type_entry<ulong_str, unsigned long>, db_type_entry<float_str, float>, db_type_entry<double_str, double> >; // a test string: constexpr neam::string_t tuple_str = "<int, float, uint, int, <long, <long>, double>>"; using res_tuple = tuple_builder<simple_type_db>::parser::ct_parse_string<tuple_str>; // create a std::tuple from the string using res_type_list = tuple_builder<simple_type_db, neam::ct::type_list>::parser::ct_parse_string<tuple_str>; // create a neam::ct::type_list from the same string // check that the tuple is correct: static_assert(std::is_same<res_tuple, std::tuple<int, float, unsigned int, int, std::tuple<long, std::tuple<long>, double>>>::value, "invalid tuple type (did you change the string ?)"); int main(int /*argc*/, char **/*argv*/) { std::cout << "result tuple: " << neam::demangle<res_tuple>() << std::endl; std::cout << "result type list: " << neam::demangle<res_type_list>() << std::endl; return 0; }
36.207447
185
0.680917
tim42
ae94e27df10cc6338e95e909a79090597b203348
12,220
cpp
C++
engine/private/abstracts/pool-protected.cpp
cppcooper/Cheryl-Engine
9a0b08da46539f756c6fe7d70212e9ca91c6fbe7
[ "MIT" ]
null
null
null
engine/private/abstracts/pool-protected.cpp
cppcooper/Cheryl-Engine
9a0b08da46539f756c6fe7d70212e9ca91c6fbe7
[ "MIT" ]
1
2019-01-22T22:07:27.000Z
2019-01-22T22:07:27.000Z
engine/private/abstracts/pool-protected.cpp
cppcooper/cheryl-engine
9a0b08da46539f756c6fe7d70212e9ca91c6fbe7
[ "MIT" ]
null
null
null
#include "abstracts/pool.h" inline bool inRange(const size_t ts, const ce_uintptr p, const ce_uintptr r, const size_t s){ return (r <= p && p < r+(ts*s)); } inline bool inRange(const size_t &ts, const ce_uintptr &p, const size_t &ps, const ce_uintptr &r, const size_t &rs){ return (r <= p && p+(ts*ps) <= r+(ts*rs)); } inline bool isAligned(const size_t &ts, const ce_uintptr &a, const ce_uintptr &b, const size_t &bs){ return a == b+(ts*bs); } inline bool update(std::multimap<size_t,openalloc_iter> &OpenList, openlist_iter &iter, const alloc &a){ if(iter != OpenList.end()){ iter->first = a.head_size; iter->second->first = a.head; iter->second->second = a; return true; } return false; } inline bool update(std::map<ce_uintptr,alloc> &ClosedList, closed_iter &iter, const alloc &a){ if(iter != ClosedList.end()){ iter->first = a.head; iter->second = a; return true; } return false; } bool AbstractPool::isClosed(const ce_uintptr &p){ return find_closed(p) != ClosedList.end(); } bool AbstractPool::isOpen(const ce_uintptr &p){ return find_open(p) != OpenAllocations.end(); } bool AbstractPool::merge(openlist_iter &iter, const alloc &a){ if(iter != OpenList.end()){ alloc &b = iter->second->second; if(isAligned(type_size, a.head, b.head, b.head_size)) { //merging in on the right b.head_size += a.head_size; return update(OpenList,iter,b); } if(isAligned(type_size, b.head, a.head, a.head_size)){ //merging in on the left b.head = a.head; b.head_size += a.head_size; return update(OpenList,iter,b); } return false; } throw invalid_args(__CEFUNCTION__, __LINE__, "Invalid iterator."); } int8_t AbstractPool::grow(closed_iter &p_iter, const size_t &N){ if(p_iter != ClosedList.end()){ alloc &a = p_iter->second; assert(N > a.head_size && "Allocation is not less than the grow parameter N"); auto neighbours = find_neighbours(p_alloc.head); size_t bytes_needed = bytes-a.head_size; alloc left,right; if(neighbours.second != OpenAllocations.end()){ right = neighbours.second->second; } if(neighbours.first != OpenAllocations.end()){ left = neighbours.first->second; } //Check available space (right, then left) if(right.head_size >= bytes_needed){ a.head_size = N; update(ClosedList,p_iter,a); alloc &b = neighbours.second->second; b.head_size -= bytes_needed; if(b.head_size==0){ erase_open(neighbours.second->second); } else { b.head = a.head+a.head_size; if(!update(OpenList,find_open(b),b)){ throw failed_operation(__CEFUNCTION__, __LINE__, "Failed to find OpenList iterator."); } } return 1; } if(left.head_size >= bytes_needed){ a.head -= bytes_needed; a.head_size = N; update(ClosedList,p_iter,a); alloc &b = neighbours.first->second; b.head_size -= bytes_needed; if(b.head_size==0){ erase_open(neighbours.second->second); } else { b_ol_iter->first = b.head_size; if(!update(OpenList,find_open(b),b)){ throw failed_operation(__CEFUNCTION__, __LINE__, "Failed to find OpenList iterator."); } } return -1; } } return 0; } bool AbstractPool::shrink(closed_iter &p_iter, const size_t &N){ if(p_iter != ClosedList.end()){ alloc &a = p_iter->second; assert(N < a.head_size && "Allocation is not greater than the shrink parameter N"); size_t remainder = a.head_size - N; a.head_size = N; if(remainder!=0){ alloc b{a.master, a.head+a.head_size, a.master_size, remainder}; auto right_al_iter = find_neighbours(b.head).second; if(right_al_iter != OpenAllocations.end()){ alloc &right = right_al_iter->second; if(isAligned(type_size, right.head, b.head, b.head_size)){ right.head = b.head; right.head_size += b.head_size; if(!update(OpenList,find_open(right),right)){ throw failed_operation(__CEFUNCTION__, __LINE__, "Failed to find OpenList iterator."); } } else { add_open(right); } } } return true; } return false; } /* */ void AbstractPool::add_open(const alloc &a){ auto result = OpenAllocations.emplace(a.head,a); if(!result.second){ throw bad_request(__CEFUNCTION__,__LINE__,"Allocation already exists in OpenAllocations"); } if(!OpenList.emplace(a.head_size,result.first).second){ throw bad_request(__CEFUNCTION__,__LINE__,"Allocation already exists in OpenList"); } } /* */ void AbstractPool::erase_open(openlist_iter &iter){ if(iter==OpenList.end()){ throw invalid_args(__CEFUNCTION__,__LINE__); } OpenAllocations.erase(iter->second); OpenList.erase(iter); } /* */ void AbstractPool::erase_open(openalloc_iter &iter){ if(iter==OpenList.end()){ throw invalid_args(__CEFUNCTION__,__LINE__); } alloc a = iter->second; auto iter2 = find_open(a); if(iter2==OpenList.end()){ throw bad_request(__CEFUNCTION__,__LINE__,"Cannot find the OpenList iterator"); } OpenAllocations.erase(iter); OpenList.erase(iter2); } /* protected method moves an allocation from the ClosedList to the OpenList */ void AbstractPool::moveto_open(closed_iter &iter){ //todo: perform merging if(iter==ClosedList.end()){ throw invalid_args(__CEFUNCTION__, __LINE__, "Iterator is invalid."); } alloc &p_alloc = iter->second; m_free += p_alloc.head_size; m_used -= p_alloc.head_size; auto neighbours = find_neighbours(p_alloc.head); alloc left,right; if(neighbours.second != OpenAllocations.end()){ right = neighbours.second->second; } if(neighbours.first != OpenAllocations.end()){ left = neighbours.first->second; } //todo: remember we might need to merge with both left and right bool merged = false; if(isAligned(type_size, right.head, p_alloc.head, p_alloc.head_size)){ auto iter = find_open(right); merged = merge(iter, p_alloc); p_alloc = iter->second->second; if(!merged){ throw failed_operation(__CEFUNCTION__, __LINE__, "Failed attempt of merging allocations."); } } if(isAligned(type_size, p_alloc.head, left.head, left.head_size)){ auto left_ol_iter = find_open(left); if(merged){ auto right_ol_iter = find_open(right); merged = merge(left_ol_iter, p_alloc); erase_open(right_ol_iter); } else { merged = merge(left_ol_iter, p_alloc); } if(!merged){ throw failed_operation(__CEFUNCTION__, __LINE__, "Failed attempt of merging allocations."); } } if(!merged){ add_open(p_alloc); } ClosedList.erase(iter); } /* protected method moves an allocation from the ClosedList to the OpenList */ void AbstractPool::moveto_open(closed_iter &iter, const ce_uintptr &p, const size_t &N){ //todo: perform merging if(iter==ClosedList.end()){ throw invalid_args(__CEFUNCTION__, __LINE__, "Iterator is invalid."); } alloc &a = iter->second; if(a.head == p && a.head_size == N){ moveto_open(iter); } else if(inRange(type_size, p, N, a.head, a.head_size)) { auto neighbours = find_neighbours(p_alloc.head); alloc left,right; if(neighbours.second != OpenAllocations.end()){ right = neighbours.second->second; } if(neighbours.first != OpenAllocations.end()){ left = neighbours.first->second; } alloc b{a.head, p, a.master_size, N}; m_free += b.head_size; m_used -= b.head_size; if(isAligned(type_size, right.head, b.head, b.head_size)){ if(!merge(find_open(right),b)){ throw failed_operation(__CEFUNCTION__, __LINE__, "Failed attempt of merging allocations."); } a.head_size -= N; } else if(isAligned(type_size, b.head, left.head, left.head_size)) { if(!merge(find_open(left),b)){ throw failed_operation(__CEFUNCTION__, __LINE__, "Failed attempt of merging allocations."); } a.head += N; a.head_size -= N; } else { //update front closed, add back closed, add middle to open size_t front = b.head - a.head; alloc c{b.master, b.head+b.head_size, b.master_size, a.head_size-(b.head_size+front)} a.head_size = front; add_open(b); ClosedList.emplace(c.head,c); } update(ClosedList,iter,a); } else { throw bad_request(__CEFUNCTION__, __LINE__, "Range [p,p+N] is not in the range of the iterator sub-allocation passed."); } } /* */ neighbours AbstractPool::find_neighbours(const ce_uintptr &p){ //assert(isClosed(p) && "p isn't managed, what did you do!"); //maybe an exception should be thrown :-/ auto end = OpenAllocations.end(); if(isOpen(p)){ // p would have been merged with its neighbours when joining the Open list return std::make_pair(end,end); //throwing an exception is probably preferable } openalloc_iter left,right; left = right = OpenAllocations.lower_bound(p); if(left != OpenAllocations.begin()){ --left; } else { left = end; } auto iter = find_closed(p); alloc &a = iter->second; if(left != end){ if(!isAligned(type_size, a.head, left.head, left.head_size)){ left = end; } } if(right != end){ if(!isAligned(type_size, right.head, a.head, a.head_size)){ right = end; } } return std::make_pair(left,right); } /* todo: revise? */ closed_iter AbstractPool::find_closed(const ce_uintptr &p){ auto iter = ClosedList.lower_bound(p); if(iter != ClosedList.end()){ if(iter->second.head != p){ if(iter != ClosedList.begin()){ --iter; if(!inRange(p, iter->second.head, iter->second.head_size)){ iter = ClosedList.end() } } else { iter = ClosedList.end(); } } } return iter; } /* */ openlist_iter AbstractPool::find_open(const alloc &a){ auto iter = OpenList.lower_bound(a.head_size); for(; iter != OpenList.end(); ++iter){ alloc &v = iter->second->second; if(v.head_size != a.head_size){ return OpenList.end(); } else if(v.head == a.head){ return iter; } } return OpenList.end(); } openalloc_iter AbstractPool::find_open(const ce_uintptr &p){ auto iter = OpenAllocations.lower_bound(p); if(iter != OpenAllocations.end()){ if(iter->second.head != p){ if(iter != OpenAllocations.begin()){ --iter; if(!inRange(p, iter->second.head, iter->second.head_size)){ iter = OpenAllocations.end() } } else { iter = OpenAllocations.end(); } } } return iter; }
33.850416
129
0.562193
cppcooper
ae9bf247d58776908d027655c5c3c795a38d297a
1,067
cpp
C++
examples/io/scoped_rdbuf.cpp
freundlich/fcppt
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
[ "BSL-1.0" ]
13
2015-02-21T18:35:14.000Z
2019-12-29T14:08:29.000Z
examples/io/scoped_rdbuf.cpp
cpreh/fcppt
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
[ "BSL-1.0" ]
5
2016-08-27T07:35:47.000Z
2019-04-21T10:55:34.000Z
examples/io/scoped_rdbuf.cpp
freundlich/fcppt
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
[ "BSL-1.0" ]
8
2015-01-10T09:22:37.000Z
2019-12-01T08:31:12.000Z
// Copyright Carl Philipp Reh 2009 - 2021. // 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 <fcppt/char_type.hpp> #include <fcppt/make_ref.hpp> #include <fcppt/reference_to_base.hpp> #include <fcppt/text.hpp> #include <fcppt/io/cout.hpp> #include <fcppt/io/ostringstream.hpp> #include <fcppt/io/scoped_rdbuf.hpp> #include <fcppt/config/external_begin.hpp> #include <ios> #include <streambuf> #include <fcppt/config/external_end.hpp> int main() { // NOLINTNEXTLINE(fuchsia-default-arguments-calls) fcppt::io::ostringstream ostream{}; { fcppt::io::scoped_rdbuf const scoped( fcppt::reference_to_base<std::basic_ios<fcppt::char_type>>( fcppt::make_ref(fcppt::io::cout())), fcppt::reference_to_base<std::basic_streambuf<fcppt::char_type>>( fcppt::make_ref(*ostream.rdbuf()))); fcppt::io::cout() << FCPPT_TEXT("This is a test!\n"); } fcppt::io::cout() << ostream.str(); }
30.485714
73
0.686036
freundlich
ae9d30de25c69e912ba510c43a532010ee55f8cc
1,419
cpp
C++
2019/8_space_image_format/B.cpp
GimmeDanger/advent-of-code
d2a6ece95801b22f972e918fa76be8466dc7afa3
[ "MIT" ]
null
null
null
2019/8_space_image_format/B.cpp
GimmeDanger/advent-of-code
d2a6ece95801b22f972e918fa76be8466dc7afa3
[ "MIT" ]
null
null
null
2019/8_space_image_format/B.cpp
GimmeDanger/advent-of-code
d2a6ece95801b22f972e918fa76be8466dc7afa3
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define FAST_IO() \ ios::sync_with_stdio(false); \ cout.tie(nullptr); \ cin.tie(nullptr) #define dbg 1 int main() { FAST_IO(); #if dbg cout << endl; ifstream cin("input.txt"); #endif const int rows = 6; const int cols = 25; vector<vector<int>> layers(1, vector<int>()); { for (char ch = '\0'; cin >> ch; ) { if (layers.back().size () == (rows * cols)) { layers.emplace_back(); } int d = ch - '0'; if (d >= 0 && d <= 2) layers.back().push_back(d); } } reverse(begin(layers), end(layers)); vector<int> answer (rows * cols, 2); for (const auto &l : layers) { assert(l.size() == cols * rows); for (size_t i = 0; i < l.size(); i++) { if (l[i] != 2) answer[i] = l[i]; } } for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { cout << (answer[r * cols + c] == 1 ? '*' : ' '); } cout << endl; } // My secret code: CYKBY // ** * ** * *** * * // * * * ** * * * * * // * * * ** *** * * // * * * * * * * // * * * * * * * * // ** * * * *** * #if dbg cin.close(); cout << endl; #endif return 0; }
22.171875
80
0.372798
GimmeDanger
ae9db79c5cbab6496f178a5eba9ee3de03974881
3,196
hpp
C++
include/AcmeExplorer.hpp
akaguha/acme_explorer
7c9aad2c7d9d4871b572e0a9e194ce484c77af87
[ "BSD-3-Clause" ]
null
null
null
include/AcmeExplorer.hpp
akaguha/acme_explorer
7c9aad2c7d9d4871b572e0a9e194ce484c77af87
[ "BSD-3-Clause" ]
null
null
null
include/AcmeExplorer.hpp
akaguha/acme_explorer
7c9aad2c7d9d4871b572e0a9e194ce484c77af87
[ "BSD-3-Clause" ]
null
null
null
/********************************************************************************** * BSD 3-Clause License * * Copyright (c) 2018, Akash Guha * 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. * *********************************************************************************** * * @file AcmeExplorer.hpp * @author Akash Guha(akaguha@terpmail.umd.edu) * @version 1.0 * * @brief ENPM808X, Final Project - Localization, mapping and navigation using turtlebot * * @section DESCRIPTION * * This program is the header implementation of the AcmeExplorer class * */ #ifndef INCLUDE_ACMEEXPLORER_HPP_ #define INCLUDE_ACMEEXPLORER_HPP_ #include <ros/ros.h> #include <std_msgs/String.h> #include <string> #include "Navigate.hpp" /** * @brief Class for AcmeExplorer */ class AcmeExplorer { private: bool botCheckFlag = false; // Flag to check the robot status ros::NodeHandle nH; // Create a node handle public: /** * @brief Constructor for AcmeExplorer class for testing purpose * * @param str as string * @return nothing */ explicit AcmeExplorer(std::string str); /** * @brief Default constructor for AcmeExplorer class * * @param nothing * @return nothing */ AcmeExplorer(); /** * @brief Default destructor for AcmeExplorer class * * @param nothing * @return nothing */ ~AcmeExplorer(); /** * @brief Function to get the robot's status * * @param nothing * @return true or flase based on the bot's status */ bool getbotCheckFlag(); /** * @brief Function to set the status flag * * @param nothing * @return nothing */ void setbotCheckFlag(); }; #endif // INCLUDE_ACMEEXPLORER_HPP_
31.96
88
0.68179
akaguha
ae9f855756b68ee3c0e86dfc7c980a8cfb6e60c7
2,732
cpp
C++
boneyard/v0.10/samples/tictactoe/main.cpp
zlatko-michailov/abc
51b607582fbcc79da76efe8370ed7a4ef8e5fc0f
[ "MIT" ]
2
2020-11-05T06:06:01.000Z
2021-01-18T15:23:11.000Z
boneyard/v0.10/samples/tictactoe/main.cpp
zlatko-michailov/abc
51b607582fbcc79da76efe8370ed7a4ef8e5fc0f
[ "MIT" ]
11
2020-11-03T11:35:57.000Z
2020-12-10T00:49:30.000Z
boneyard/v0.10/samples/tictactoe/main.cpp
zlatko-michailov/abc
51b607582fbcc79da76efe8370ed7a4ef8e5fc0f
[ "MIT" ]
1
2020-11-05T05:39:15.000Z
2020-11-05T05:39:15.000Z
/* MIT License Copyright (c) 2018-2020 Zlatko Michailov 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 <iostream> //// #include "../../src/socket.h" #include "../../src/http.h" #include "player.h" #include "board.h" int main() { { abc::tcp_server_socket<> listener; listener.bind("30303"); listener.listen(2); abc::tcp_client_socket<> client = std::move(listener.accept()); abc::socket_streambuf<abc::tcp_client_socket<>> sb(&client); abc::http_server_stream<> http(&sb); char buffer[abc::size::k1 + 1]; http.get_method(buffer, sizeof(buffer)); std::cout << "Method =" << buffer << std::endl; http.get_resource(buffer, sizeof(buffer)); std::cout << "Resource=" << buffer << std::endl; http.get_protocol(buffer, sizeof(buffer)); std::cout << "Protocol=" << buffer << std::endl; http.put_protocol("HTTP/1.1"); http.put_status_code("200"); http.put_reason_phrase("OK"); http.put_header_name("Content-Length"); http.put_header_value("10"); http.end_headers(); http.put_body("1234567890"); http.flush(); } abc::samples::tictactoe::board board; board.print(); abc::samples::tictactoe::player_t player = abc::samples::tictactoe::player::me; while (!board.is_game_over()) { bool made_move = false; while (!made_move) { std::cout << "Player " << abc::samples::tictactoe::player::symbol[player] << ": " << std::endl; abc::samples::tictactoe::rowcol_t row; std::cout << "Enter row: "; std::cin >> row; row -= '0'; abc::samples::tictactoe::rowcol_t col; std::cout << "Enter col: "; std::cin >> col; col -= '0'; made_move = board.make_move(row, col, player); } board.print(); player = abc::samples::tictactoe::player::other(player); } return 0; }
30.021978
98
0.702782
zlatko-michailov
aea40bc3c4a8c9636c15681045a396cdde4d2f1f
1,178
cpp
C++
src/Overlay/Widget/GameModeSelectWidget.cpp
GrimFlash/BBCF-Improvement-Mod-GGPO
9482ead2edd70714f427d3a5683d17b19ab8ac2e
[ "MIT" ]
48
2020-06-09T22:53:52.000Z
2022-01-02T12:44:33.000Z
src/Overlay/Widget/GameModeSelectWidget.cpp
GrimFlash/BBCF-Improvement-Mod-GGPO
9482ead2edd70714f427d3a5683d17b19ab8ac2e
[ "MIT" ]
2
2020-05-27T21:25:49.000Z
2020-05-27T23:56:56.000Z
src/Overlay/Widget/GameModeSelectWidget.cpp
GrimFlash/BBCF-Improvement-Mod-GGPO
9482ead2edd70714f427d3a5683d17b19ab8ac2e
[ "MIT" ]
12
2020-06-17T20:44:17.000Z
2022-01-04T18:15:27.000Z
#include "GameModeSelectWidget.h" #include "Core/interfaces.h" #include <imgui.h> void GameModeSelectWidget() { ImGui::BeginGroup(); ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 5.0f); ImGui::BeginChild("GameModeSelection", ImVec2(200, 210), true); ImGui::TextUnformatted("Select game mode:"); for (int i = 0; i < g_interfaces.pGameModeManager->GetGameModesCount(); i++) { std::string gameModeName = g_interfaces.pGameModeManager->GetGameModeName((CustomGameMode)i); std::string gameModeDesc = g_interfaces.pGameModeManager->GetGameModeDesc((CustomGameMode)i); if (ImGui::RadioButton(gameModeName.c_str(), (int*)&g_interfaces.pGameModeManager->GetActiveGameModeRef(), i)) { if (g_interfaces.pRoomManager->IsRoomFunctional()) { g_interfaces.pOnlineGameModeManager->SetThisPlayerGameMode(g_interfaces.pGameModeManager->GetActiveGameMode()); g_interfaces.pOnlineGameModeManager->SendGameModePacket(); } } if (ImGui::IsItemHovered() && !gameModeDesc.empty()) { ImGui::BeginTooltip(); ImGui::TextUnformatted(gameModeDesc.c_str()); ImGui::EndTooltip(); } } ImGui::EndChild(); ImGui::PopStyleVar(); ImGui::EndGroup(); }
28.047619
115
0.741087
GrimFlash
aea4259ff064193e7efb0d9ca8df92be5eb99481
4,086
cpp
C++
src/dialog/TableDialog/TableDialog.cpp
BlasterAlex/Uni-Correlation-Coefficient
709b6318d0c28a8704cfb3b1157a70fd95758e39
[ "Apache-2.0" ]
null
null
null
src/dialog/TableDialog/TableDialog.cpp
BlasterAlex/Uni-Correlation-Coefficient
709b6318d0c28a8704cfb3b1157a70fd95758e39
[ "Apache-2.0" ]
null
null
null
src/dialog/TableDialog/TableDialog.cpp
BlasterAlex/Uni-Correlation-Coefficient
709b6318d0c28a8704cfb3b1157a70fd95758e39
[ "Apache-2.0" ]
2
2019-09-04T14:34:08.000Z
2019-09-17T05:46:36.000Z
/*** * Copyright 2019 Alexander Pishchulev (https://github.com/BlasterAlex) * * 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 <QCloseEvent> #include <QDialog> #include <QHeaderView> #include <QIcon> #include <QLabel> #include <QString> #include <QTableWidget> #include <QTableWidgetItem> #include <QVBoxLayout> #include <QVariant> #include <QVector> #include <QWidget> #include "../../Table/Table.hpp" #include "FloatItem/FloatItem.hpp" #include "TableDialog.hpp" TableDialog::TableDialog(int n, Table t, QWidget *parent) : QDialog(parent) { num = n; setMinimumWidth(550); setMinimumHeight(450); setStyleSheet("QHeaderView::section {" " background-color: #bdbdbd;" " padding: 4px;" " font-size: 14pt;" " border-style: none;" " border-bottom: 1px solid #fffff8;" " border-right: 1px solid #fffff8;" "}" "" "QHeaderView::section:horizontal {" " border-top: 1px solid #fffff8;" "}" "QHeaderView::section:horizontal:hover {" " background-color: #a8a8a8;" " text-decoration: underline;" " font-weight: bold;" "}" "" "QHeaderView::down-arrow {" " image: url(data/images/sort-down-solid.svg);" " width: 12px;" " margin: 0 10px 0 0;" "}" "" "QHeaderView::up-arrow {" " image: url(data/images/sort-up-solid.svg);" " width: 12px;" " margin: 0 10px 0 0;" "}" "" "QHeaderView::up-arrow," "QHeaderView::down-arrow:hover {" " width: 13px;" "}" "" "QLabel {" " margin: 0 0 5px 0;" "}"); QVBoxLayout *mainLayout = new QVBoxLayout(this); mainLayout->setMargin(0); mainLayout->setContentsMargins(0, 0, 0, 0); mainLayout->setSpacing(0); // Название setWindowTitle(t.name.split(".")[0]); // Заголовок QLabel *textLabel = new QLabel(this); textLabel->setText(t.name.split(".")[0]); QFont font = textLabel->font(); font.setPointSize(14); font.setBold(true); textLabel->setFont(font); textLabel->setAlignment(Qt::AlignTop | Qt::AlignCenter); mainLayout->addWidget(textLabel); // Таблица table = new QTableWidget(this); // Запрет редактирования таблицы table->setEditTriggers(QAbstractItemView::NoEditTriggers); // Отключение фокуса на таблице table->setFocusPolicy(Qt::NoFocus); table->setSelectionMode(QAbstractItemView::NoSelection); // Включение сортировки столбцов table->setSortingEnabled(true); table->horizontalHeader()->setSortIndicatorShown(true); // Размеры table->horizontalHeader()->setStretchLastSection(true); table->verticalHeader()->hide(); // Шапка таблицы table->setRowCount(t.getSize()); table->setColumnCount(2); table->setHorizontalHeaderLabels(QStringList() << "rank" << "name"); // Данные int count = 0; foreach (QVector<QString> rows, t.data) { table->setItem(count, 0, new FloatItem(rows[0])); table->setItem(count++, 1, new QTableWidgetItem(rows[1])); } mainLayout->addWidget(table); } // Событие закрытия окна void TableDialog::closeEvent(QCloseEvent *event) { emit shutdown(); event->accept(); }
30.721805
77
0.589574
BlasterAlex
aea4ab3795001276666987946d5919524daafc4c
1,084
hxx
C++
src/identicals.hxx
puzzlef/pagerank-nvgraph
bbc0ddb2c898c75ad93a4087ab7a57222666d1f4
[ "MIT" ]
null
null
null
src/identicals.hxx
puzzlef/pagerank-nvgraph
bbc0ddb2c898c75ad93a4087ab7a57222666d1f4
[ "MIT" ]
null
null
null
src/identicals.hxx
puzzlef/pagerank-nvgraph
bbc0ddb2c898c75ad93a4087ab7a57222666d1f4
[ "MIT" ]
null
null
null
#pragma once #include <map> #include <vector> #include <utility> #include <algorithm> #include "_main.hxx" #include "vertices.hxx" using std::map; using std::vector; using std::move; using std::sort; template <class G, class J> auto edgeIdenticalsFromSize(const G& x, const J& ks, size_t n) { using K = typename G::key_type; using vec = vector<K>; map<vec, vec> m; vec es; // Find groups of identicals. for (auto u : ks) { copyWrite(x.edgeKeys(u), es); sortValues(es); m[es].push_back(u); } // Copy identicals from given size in sorted order. vector2d<K> a; for (auto& p : m) { auto& is = p.second; if (is.size()<n) continue; sortValues(is); a.push_back(move(is)); } return a; } template <class G> auto edgeIdenticalsFromSize(const G& x, size_t n) { return edgeIdenticalsFromSize(x, x.vertexKeys(), n); } template <class G, class J> auto edgeIdenticals(const G& x, const J& ks) { return edgeIdenticalsFromSize(x, ks, 2); } template <class G> auto edgeIdenticals(const G& x) { return edgeIdenticals(x, x.vertexKeys()); }
20.45283
64
0.663284
puzzlef
aea4b12af672195e2cb87e4e44f68d99a15ba8fd
3,478
cpp
C++
tr3_embedded/Actuator_v3/src/Controller.setup.cpp
SlateRobotics/tr3_essentials
c8608f04a83a5ca53f25ce0e5f6bce217e378c6f
[ "MIT" ]
2
2021-01-22T05:52:10.000Z
2021-02-09T18:11:20.000Z
tr3_embedded/Actuator_v3/src/Controller.setup.cpp
SlateRobotics/tr3_essentials
c8608f04a83a5ca53f25ce0e5f6bce217e378c6f
[ "MIT" ]
1
2020-08-07T08:47:52.000Z
2020-08-07T08:47:52.000Z
tr3_embedded/Actuator_v3/src/Controller.setup.cpp
SlateRobotics/tr3_essentials
c8608f04a83a5ca53f25ce0e5f6bce217e378c6f
[ "MIT" ]
3
2020-08-03T17:42:18.000Z
2021-04-06T14:23:35.000Z
#include "Controller.h" void Controller::setUp () { led.setUp(); motor.setUp(); led.white(); pinMode(PIN_ACS712, INPUT); pinMode(PIN_FAN, OUTPUT); fanOff(); encoderTorque.setUp(); encoderTorque.storage = &storage; encoderTorque.EEADDR_ENC_OFFSET = EEADDR_ENC_TRQ_OFFSET; encoderTorque.EEADDR_ENC_UP = EEADDR_ENC_TRQ_UP; encoderTorque.EEADDR_ENC_LAP = EEADDR_ENC_TRQ_LAP; encoderOutput.setUp(); encoderOutput.storage = &storage; encoderOutput.EEADDR_ENC_OFFSET = EEADDR_ENC_OUT_OFFSET; encoderOutput.EEADDR_ENC_UP = EEADDR_ENC_OUT_UP; encoderOutput.EEADDR_ENC_LAP = EEADDR_ENC_OUT_LAP; setUpConfig(); pidPos.SetOutputLimits(MIN_TORQUE, MAX_TORQUE); pidVel.SetOutputLimits(DEFAULT_MOTOR_MIN, DEFAULT_MOTOR_MAX); pidTrq.SetOutputLimits(DEFAULT_MOTOR_MIN, DEFAULT_MOTOR_MAX); //setUpImu(); //step_imu(); cmd_resetTorque(); } void Controller::setUpImu() { int imuStatus = imu.begin(19, 18); if (imuStatus < 0) { Serial.println("IMU initialization unsuccessful"); Serial.println("Check IMU wiring or try cycling power"); Serial.println("Restarting in 3000 ms... "); if (requireImu == true) { long start = millis(); while(millis() - start < 3000) { led.blink(255, 165, 0); delay(50); } ESP.restart(); } } } void Controller::setUpConfig () { storage.begin(&led); if (storage.isConfigured()) { SEA_SPRING_RATE = storage.readFloat(EEADDR_SEA_SPRING_RATE); SEA_COEFF_M = storage.readFloat(EEADDR_SEA_M); SEA_COEFF_B = storage.readFloat(EEADDR_SEA_B); #if (NODE_ID == NODE_G0) state.position = storage.readFloat(EEADDR_ENC_OUT_POS); #endif encoderTorque.configure(); encoderOutput.configure(); if (storage.readBool(EEADDR_MTR_FLIP)) { motor.flipDrivePins(); } MIN_POSITION = storage.readFloat(EEADDR_POSITION_MIN); MAX_POSITION = storage.readFloat(EEADDR_POSITION_MAX); MIN_VELOCITY = storage.readFloat(EEADDR_VELOCITY_MIN); MAX_VELOCITY = storage.readFloat(EEADDR_VELOCITY_MAX); MIN_TORQUE = storage.readFloat(EEADDR_TORQUE_MIN); MAX_TORQUE = storage.readFloat(EEADDR_TORQUE_MAX); expected_torque_min = MIN_TORQUE; expected_torque_max = MAX_TORQUE; pidPos.SetTunings(0, storage.readFloat(EEADDR_PID_POS_P)); pidPos.SetTunings(1, storage.readFloat(EEADDR_PID_POS_I)); pidPos.SetTunings(2, storage.readFloat(EEADDR_PID_POS_D)); pidPos.SetTunings(3, storage.readFloat(EEADDR_PID_POS_IC)); pidPos.SetTunings(4, storage.readFloat(EEADDR_PID_POS_FF)); pidVel.SetTunings(0, storage.readFloat(EEADDR_PID_VEL_P)); pidVel.SetTunings(1, storage.readFloat(EEADDR_PID_VEL_I)); pidVel.SetTunings(2, storage.readFloat(EEADDR_PID_VEL_D)); pidVel.SetTunings(3, storage.readFloat(EEADDR_PID_VEL_IC)); pidVel.SetTunings(4, storage.readFloat(EEADDR_PID_VEL_FF)); pidTrq.SetTunings(0, storage.readFloat(EEADDR_PID_TRQ_P)); pidTrq.SetTunings(1, storage.readFloat(EEADDR_PID_TRQ_I)); pidTrq.SetTunings(2, storage.readFloat(EEADDR_PID_TRQ_D)); pidTrq.SetTunings(3, storage.readFloat(EEADDR_PID_TRQ_IC)); pidTrq.SetTunings(4, storage.readFloat(EEADDR_PID_TRQ_FF)); } else { storage.reset(); } }
35.131313
81
0.682289
SlateRobotics