hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
sequencelengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
sequencelengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
sequencelengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
4f1d9e36be378fb394dc7da2e912f46bf7c71a18
3,639
cpp
C++
button_events_game.cpp
darkoppressor/cosmic-runner
feeb1154ffb1af9de2a34e1b418a6432500176c3
[ "MIT" ]
null
null
null
button_events_game.cpp
darkoppressor/cosmic-runner
feeb1154ffb1af9de2a34e1b418a6432500176c3
[ "MIT" ]
null
null
null
button_events_game.cpp
darkoppressor/cosmic-runner
feeb1154ffb1af9de2a34e1b418a6432500176c3
[ "MIT" ]
null
null
null
/* Copyright (c) 2012 Cheese and Bacon Games, LLC */ /* This file is licensed under the MIT License. */ /* See the file docs/LICENSE.txt for the full license text. */ #include "game.h" #include "android_leaderboard.h" #include <button_events.h> #include <window_manager.h> #include <game_manager.h> #include <android.h> #include <gui_manager.h> #include <boost/algorithm/string.hpp> using namespace std; bool Button_Events::handle_button_event_game (string button_event, Window* parent_window, bool& window_opened_on_top) { if (button_event == "game_over") { Window_Manager::close_all_windows(); if (Game::is_score_high()) { Window_Manager::get_window("input_name")->toggle_on(); GUI_Manager::confirm_gui_object(); } else { Android_Leaderboard::submit_highscore(Android_Leaderboard::HIGH_SCORES, Game::get_score()); Android_Leaderboard::submit_highscore(Android_Leaderboard::BEST_KILL_COUNT, Game::get_kills()); Android_Leaderboard::submit_highscore(Android_Leaderboard::DEBRIS_DODGED, Game::get_dodges()); Game_Manager::stop(); Window_Manager::get_window("main_menu")->toggle_on(); Window_Manager::get_window("high_scores")->toggle_on(); } window_opened_on_top = true; return true; } else if (button_event == "gpg_toggle_sign_in") { if (Android::gpg_is_silent_sign_in_attempt_complete()) { if (!Android::gpg_is_signed_in()) { Android::gpg_sign_in(); Game::android_gpg_signing_in(); } else { Android::gpg_sign_out(); } } return true; } else if (boost::algorithm::starts_with(button_event, "gpg_show_leaderboard_")) { boost::algorithm::erase_first(button_event, "gpg_show_leaderboard_"); if (Android::gpg_is_signed_in()) { Android::gpg_show_leaderboard(button_event); } return true; } else if (button_event == "gpg_show_all_leaderboards") { if (Android::gpg_is_signed_in()) { Android::gpg_show_all_leaderboards(); } return true; } else if (button_event == "gpg_show_achievements") { if (Android::gpg_is_signed_in()) { Android::gpg_show_achievements(); } return true; } else if (button_event == "name") { Window_Manager::close_all_windows(); if (parent_window != 0) { Game::add_high_score(parent_window->get_info_text(0)); Android_Leaderboard::submit_highscore(Android_Leaderboard::HIGH_SCORES, Game::get_score()); Android_Leaderboard::submit_highscore(Android_Leaderboard::BEST_KILL_COUNT, Game::get_kills()); Android_Leaderboard::submit_highscore(Android_Leaderboard::DEBRIS_DODGED, Game::get_dodges()); } Game_Manager::stop(); Window_Manager::get_window("main_menu")->toggle_on(); Window_Manager::get_window("high_scores")->toggle_on(); window_opened_on_top = true; return true; } else if (boost::algorithm::starts_with(button_event, "select_upgrade_")) { boost::algorithm::erase_first(button_event, "select_upgrade_"); Window_Manager::close_all_windows(); Game::player_add_upgrade(button_event); Game::complete_contract(); return true; } else if (button_event == "skip_upgrade") { Window_Manager::close_all_windows(); Game::restore_hull_from_contract(); Game::complete_contract(); return true; } return false; }
31.643478
119
0.646057
darkoppressor
4f1ee99281ef141d42a038f41cd1ddb9cc86f312
26,803
cpp
C++
src/core/Variant.cpp
WilliamTambellini/godopy
7b4142ddf7acafa66e1b2b201afa5fa37a4c7f4e
[ "MIT" ]
null
null
null
src/core/Variant.cpp
WilliamTambellini/godopy
7b4142ddf7acafa66e1b2b201afa5fa37a4c7f4e
[ "MIT" ]
null
null
null
src/core/Variant.cpp
WilliamTambellini/godopy
7b4142ddf7acafa66e1b2b201afa5fa37a4c7f4e
[ "MIT" ]
null
null
null
#include "Variant.hpp" #include <gdnative/variant.h> #include "CoreTypes.hpp" #include "Defs.hpp" #include "GodotGlobal.hpp" #include "Object.hpp" #include <iostream> #include <stdexcept> #ifndef NO_IMPORT_ARRAY #define NO_IMPORT_ARRAY #endif #include "PythonGlobal.hpp" #include <_lib/godot/core/types.hpp> namespace godot { Variant::Variant() { godot::api->godot_variant_new_nil(&_godot_variant); } Variant::Variant(const Variant &v) { godot::api->godot_variant_new_copy(&_godot_variant, &v._godot_variant); } Variant::Variant(bool p_bool) { godot::api->godot_variant_new_bool(&_godot_variant, p_bool); } Variant::Variant(signed int p_int) // real one { godot::api->godot_variant_new_int(&_godot_variant, p_int); } Variant::Variant(unsigned int p_int) { godot::api->godot_variant_new_uint(&_godot_variant, p_int); } Variant::Variant(signed short p_short) // real one { godot::api->godot_variant_new_int(&_godot_variant, (int)p_short); } Variant::Variant(int64_t p_char) // real one { godot::api->godot_variant_new_int(&_godot_variant, p_char); } Variant::Variant(uint64_t p_char) { godot::api->godot_variant_new_uint(&_godot_variant, p_char); } Variant::Variant(float p_float) { godot::api->godot_variant_new_real(&_godot_variant, p_float); } Variant::Variant(double p_double) { godot::api->godot_variant_new_real(&_godot_variant, p_double); } Variant::Variant(const String &p_string) { godot::api->godot_variant_new_string(&_godot_variant, (godot_string *)&p_string); } Variant::Variant(const char *const p_cstring) { String s = String(p_cstring); godot::api->godot_variant_new_string(&_godot_variant, (godot_string *)&s); } Variant::Variant(const wchar_t *p_wstring) { String s = p_wstring; godot::api->godot_variant_new_string(&_godot_variant, (godot_string *)&s); } Variant::Variant(const Vector2 &p_vector2) { godot::api->godot_variant_new_vector2(&_godot_variant, (godot_vector2 *)&p_vector2); } Variant::Variant(const Rect2 &p_rect2) { godot::api->godot_variant_new_rect2(&_godot_variant, (godot_rect2 *)&p_rect2); } Variant::Variant(const Vector3 &p_vector3) { godot::api->godot_variant_new_vector3(&_godot_variant, (godot_vector3 *)&p_vector3); } Variant::Variant(const Plane &p_plane) { godot::api->godot_variant_new_plane(&_godot_variant, (godot_plane *)&p_plane); } Variant::Variant(const AABB &p_aabb) { godot::api->godot_variant_new_aabb(&_godot_variant, (godot_aabb *)&p_aabb); } Variant::Variant(const Quat &p_quat) { godot::api->godot_variant_new_quat(&_godot_variant, (godot_quat *)&p_quat); } Variant::Variant(const Basis &p_transform) { godot::api->godot_variant_new_basis(&_godot_variant, (godot_basis *)&p_transform); } Variant::Variant(const Transform2D &p_transform) { godot::api->godot_variant_new_transform2d(&_godot_variant, (godot_transform2d *)&p_transform); } Variant::Variant(const Transform &p_transform) { godot::api->godot_variant_new_transform(&_godot_variant, (godot_transform *)&p_transform); } Variant::Variant(const Color &p_color) { godot::api->godot_variant_new_color(&_godot_variant, (godot_color *)&p_color); } Variant::Variant(const NodePath &p_path) { godot::api->godot_variant_new_node_path(&_godot_variant, (godot_node_path *)&p_path); } Variant::Variant(const RID &p_rid) { godot::api->godot_variant_new_rid(&_godot_variant, (godot_rid *)&p_rid); } Variant::Variant(const Object *p_object) { if (p_object) godot::api->godot_variant_new_object(&_godot_variant, p_object->_owner); else godot::api->godot_variant_new_nil(&_godot_variant); } Variant::Variant(const Dictionary &p_dictionary) { godot::api->godot_variant_new_dictionary(&_godot_variant, (godot_dictionary *)&p_dictionary); } Variant::Variant(const Array &p_array) { godot::api->godot_variant_new_array(&_godot_variant, (godot_array *)&p_array); } Variant::Variant(const PoolByteArray &p_raw_array) { godot::api->godot_variant_new_pool_byte_array(&_godot_variant, (godot_pool_byte_array *)&p_raw_array); } Variant::Variant(const PoolIntArray &p_int_array) { godot::api->godot_variant_new_pool_int_array(&_godot_variant, (godot_pool_int_array *)&p_int_array); } Variant::Variant(const PoolRealArray &p_real_array) { godot::api->godot_variant_new_pool_real_array(&_godot_variant, (godot_pool_real_array *)&p_real_array); } Variant::Variant(const PoolStringArray &p_string_array) { godot::api->godot_variant_new_pool_string_array(&_godot_variant, (godot_pool_string_array *)&p_string_array); } Variant::Variant(const PoolVector2Array &p_vector2_array) { godot::api->godot_variant_new_pool_vector2_array(&_godot_variant, (godot_pool_vector2_array *)&p_vector2_array); } Variant::Variant(const PoolVector3Array &p_vector3_array) { godot::api->godot_variant_new_pool_vector3_array(&_godot_variant, (godot_pool_vector3_array *)&p_vector3_array); } Variant::Variant(const PoolColorArray &p_color_array) { godot::api->godot_variant_new_pool_color_array(&_godot_variant, (godot_pool_color_array *)&p_color_array); } Variant::Variant(const PyObject *p_python_object) { if (p_python_object == Py_None) { // Py_XDECREF(p_python_object); // XXX godot::api->godot_variant_new_nil(&_godot_variant); } else if (PyBool_Check(p_python_object)) { godot::api->godot_variant_new_bool(&_godot_variant, PyLong_AsLong((PyObject *)p_python_object)); } else if (PyLong_Check(p_python_object)) { godot::api->godot_variant_new_int(&_godot_variant, PyLong_AsLong((PyObject *)p_python_object)); } else if (PyFloat_Check(p_python_object)) { const double p_double = PyFloat_AsDouble((PyObject *)p_python_object); godot::api->godot_variant_new_real(&_godot_variant, p_double); } else if (PyUnicode_Check(p_python_object) || PyBytes_Check(p_python_object)) { String s = String(p_python_object); godot::api->godot_variant_new_string(&_godot_variant, (godot_string *)&s); } else if (PyByteArray_Check(p_python_object)) { godot_pool_byte_array *p; godot::api->godot_pool_byte_array_new(p); godot::api->godot_pool_byte_array_resize(p, PyByteArray_GET_SIZE(p_python_object)); godot_pool_byte_array_write_access *_write_access = godot::api->godot_pool_byte_array_write(p); const uint8_t *ptr = godot::api->godot_pool_byte_array_write_access_ptr(_write_access); memcpy((void *)ptr, (void *)PyByteArray_AS_STRING(p_python_object), PyByteArray_GET_SIZE(p_python_object)); godot::api->godot_variant_new_pool_byte_array(&_godot_variant, p); godot::api->godot_pool_byte_array_write_access_destroy(_write_access); godot::api->godot_pool_byte_array_destroy(p); } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_AABB) { godot_aabb *p = _python_wrapper_to_aabb((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_aabb(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Array) { godot_array *p = _python_wrapper_to_godot_array((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_array(&_godot_variant, p); } else { godot::api->godot_variant_new_nil(&_godot_variant); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Basis) { godot_basis *p = _python_wrapper_to_basis((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_basis(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Color) { godot_color *p = _python_wrapper_to_color((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_color(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Dictionary) { godot_dictionary *p = _python_wrapper_to_godot_dictionary((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_dictionary(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_NodePath) { godot_node_path *p = _python_wrapper_to_nodepath((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_node_path(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Plane) { godot_plane *p = _python_wrapper_to_plane((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_plane(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_PoolByteArray) { godot_pool_byte_array *p = _python_wrapper_to_poolbytearray((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_pool_byte_array(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_PoolIntArray) { godot_pool_int_array *p = _python_wrapper_to_poolintarray((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_pool_int_array(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_PoolRealArray) { godot_pool_real_array *p = _python_wrapper_to_poolrealarray((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_pool_real_array(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_PoolStringArray) { godot_pool_string_array *p = _python_wrapper_to_poolstringarray((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_pool_string_array(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_PoolVector2Array) { godot_pool_vector2_array *p = _python_wrapper_to_poolvector2array((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_pool_vector2_array(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_PoolVector3Array) { godot_pool_vector3_array *p = _python_wrapper_to_poolvector3array((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_pool_vector3_array(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_PoolColorArray) { godot_pool_color_array *p = _python_wrapper_to_poolcolorarray((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_pool_color_array(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Quat) { godot_quat *p = _python_wrapper_to_quat((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_quat(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Rect2) { godot_rect2 *p = _python_wrapper_to_rect2((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_rect2(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_RID) { godot_rid *p = _python_wrapper_to_rid((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_rid(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_String) { godot_string *p = _python_wrapper_to_godot_string((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_string(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Transform) { godot_transform *p = _python_wrapper_to_transform((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_transform(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Transform2D) { godot_transform2d *p = _python_wrapper_to_transform2d((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_transform2d(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Vector2) { godot_vector2 *p = _python_wrapper_to_vector2((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_vector2(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Vector3) { godot_vector3 *p = _python_wrapper_to_vector3((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_vector3(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (PyObject_IsInstance((PyObject *)p_python_object, (PyObject *)PyGodotType__Wrapped)) { godot_object *p = _cython_binding_to_godot_object((PyObject *)p_python_object); godot::api->godot_variant_new_object(&_godot_variant, p); // TODO: dict -> Dictionary, other iterables -> Array, array.Array -> PoolArray*, numpy.array -> PoolArray* } else if (PyArray_Check((PyObject *)p_python_object)) { PyArrayObject *arr = (PyArrayObject *)p_python_object; if (PyArray_NDIM(arr) == 1 && PyArray_TYPE(arr) == NPY_UINT8) { PoolByteArray _arr = PoolByteArray(arr); godot::api->godot_variant_new_pool_byte_array(&_godot_variant, (godot_pool_byte_array *)&_arr); } else if (PyArray_NDIM(arr) == 1 && PyArray_ISINTEGER(arr)) { PoolIntArray _arr(arr); godot::api->godot_variant_new_pool_int_array(&_godot_variant, (godot_pool_int_array *)&_arr); } else if (PyArray_NDIM(arr) == 1 && PyArray_ISFLOAT(arr)) { PoolRealArray _arr(arr); godot::api->godot_variant_new_pool_real_array(&_godot_variant, (godot_pool_real_array *)&_arr); } else if (PyArray_NDIM(arr) == 1 && PyArray_ISSTRING(arr)) { PoolStringArray _arr(arr); godot::api->godot_variant_new_pool_string_array(&_godot_variant, (godot_pool_string_array *)&_arr); } else if (PyArray_NDIM(arr) == 1) { Array _arr; for (int idx = 0; idx < PyArray_SIZE(arr); idx++) { PyObject *item = PyArray_GETITEM(arr, (const char *)PyArray_GETPTR1(arr, idx)); // TODO: Check NULL pointer _arr.append(Variant(item)); } godot::api->godot_variant_new_array(&_godot_variant, (godot_array *)&_arr); } else if (PyArray_NDIM(arr) == 2 && PyArray_ISNUMBER(arr) && PyArray_DIM(arr, 1) == 2) { PoolVector2Array _arr = PoolVector2Array(arr); godot::api->godot_variant_new_pool_vector2_array(&_godot_variant, (godot_pool_vector2_array *)&_arr); } else if (PyArray_NDIM(arr) == 2 && PyArray_ISNUMBER(arr) && PyArray_DIM(arr, 1) == 3) { PoolVector3Array _arr = PoolVector3Array(arr); godot::api->godot_variant_new_pool_vector3_array(&_godot_variant, (godot_pool_vector3_array *)&_arr); } else if (PyArray_NDIM(arr) == 2 && PyArray_ISNUMBER(arr) && PyArray_DIM(arr, 1) == 4) { PoolColorArray _arr = PoolColorArray(arr); godot::api->godot_variant_new_pool_color_array(&_godot_variant, (godot_pool_color_array *)&_arr); } else { throw std::invalid_argument("could not convert NumPy array"); } } else if (PySequence_Check((PyObject *)p_python_object)) { Array arr = Array(p_python_object); godot::api->godot_variant_new_array(&_godot_variant, (godot_array *)&arr); } else if (PyMapping_Check((PyObject *)p_python_object)) { Dictionary dict = Dictionary(p_python_object); godot::api->godot_variant_new_dictionary(&_godot_variant, (godot_dictionary *)&dict); } else if (PyIndex_Check((PyObject *)p_python_object)) { const Py_ssize_t p_num = PyNumber_AsSsize_t((PyObject *)p_python_object, NULL); godot::api->godot_variant_new_int(&_godot_variant, p_num); } else if (PyNumber_Check((PyObject *)p_python_object)) { PyObject *p_num = PyNumber_Float((PyObject *)p_python_object); const double p_double = PyFloat_AsDouble((PyObject *)p_num); godot::api->godot_variant_new_real(&_godot_variant, p_double); } else if (PyObject_CheckBuffer((PyObject *)p_python_object)) { throw std::invalid_argument("generic Python buffer support is not implemented yet"); } else { // raises ValueError in Cython/Python context throw std::invalid_argument("could not cast Python object to Godot Variant"); } } Variant &Variant::operator=(const Variant &v) { godot::api->godot_variant_new_copy(&_godot_variant, &v._godot_variant); return *this; } Variant::operator bool() const { return booleanize(); } Variant::operator signed int() const { return godot::api->godot_variant_as_int(&_godot_variant); } Variant::operator unsigned int() const // this is the real one { return godot::api->godot_variant_as_uint(&_godot_variant); } Variant::operator signed short() const { return godot::api->godot_variant_as_int(&_godot_variant); } Variant::operator unsigned short() const { return godot::api->godot_variant_as_uint(&_godot_variant); } Variant::operator signed char() const { return godot::api->godot_variant_as_int(&_godot_variant); } Variant::operator unsigned char() const { return godot::api->godot_variant_as_uint(&_godot_variant); } Variant::operator int64_t() const { return godot::api->godot_variant_as_int(&_godot_variant); } Variant::operator uint64_t() const { return godot::api->godot_variant_as_uint(&_godot_variant); } Variant::operator wchar_t() const { return godot::api->godot_variant_as_int(&_godot_variant); } Variant::operator float() const { return godot::api->godot_variant_as_real(&_godot_variant); } Variant::operator double() const { return godot::api->godot_variant_as_real(&_godot_variant); } Variant::operator String() const { String ret; *(godot_string *)&ret = godot::api->godot_variant_as_string(&_godot_variant); return ret; } Variant::operator Vector2() const { godot_vector2 s = godot::api->godot_variant_as_vector2(&_godot_variant); return *(Vector2 *)&s; } Variant::operator Rect2() const { godot_rect2 s = godot::api->godot_variant_as_rect2(&_godot_variant); return *(Rect2 *)&s; } Variant::operator Vector3() const { godot_vector3 s = godot::api->godot_variant_as_vector3(&_godot_variant); return *(Vector3 *)&s; } Variant::operator Plane() const { godot_plane s = godot::api->godot_variant_as_plane(&_godot_variant); return *(Plane *)&s; } Variant::operator AABB() const { godot_aabb s = godot::api->godot_variant_as_aabb(&_godot_variant); return *(AABB *)&s; } Variant::operator Quat() const { godot_quat s = godot::api->godot_variant_as_quat(&_godot_variant); return *(Quat *)&s; } Variant::operator Basis() const { godot_basis s = godot::api->godot_variant_as_basis(&_godot_variant); return *(Basis *)&s; } Variant::operator Transform() const { godot_transform s = godot::api->godot_variant_as_transform(&_godot_variant); return *(Transform *)&s; } Variant::operator Transform2D() const { godot_transform2d s = godot::api->godot_variant_as_transform2d(&_godot_variant); return *(Transform2D *)&s; } Variant::operator Color() const { godot_color s = godot::api->godot_variant_as_color(&_godot_variant); return *(Color *)&s; } Variant::operator NodePath() const { NodePath ret; *(godot_node_path *)&ret = godot::api->godot_variant_as_node_path(&_godot_variant); return ret; } Variant::operator RID() const { godot_rid s = godot::api->godot_variant_as_rid(&_godot_variant); return *(RID *)&s; } Variant::operator Dictionary() const { Dictionary ret; *(godot_dictionary *)&ret = godot::api->godot_variant_as_dictionary(&_godot_variant); return ret; } Variant::operator Array() const { Array ret; *(godot_array *)&ret = godot::api->godot_variant_as_array(&_godot_variant); return ret; } Variant::operator PoolByteArray() const { PoolByteArray ret; *(godot_pool_byte_array *)&ret = godot::api->godot_variant_as_pool_byte_array(&_godot_variant); return ret; } Variant::operator PoolIntArray() const { PoolIntArray ret; *(godot_pool_int_array *)&ret = godot::api->godot_variant_as_pool_int_array(&_godot_variant); return ret; } Variant::operator PoolRealArray() const { PoolRealArray ret; *(godot_pool_real_array *)&ret = godot::api->godot_variant_as_pool_real_array(&_godot_variant); return ret; } Variant::operator PoolStringArray() const { PoolStringArray ret; *(godot_pool_string_array *)&ret = godot::api->godot_variant_as_pool_string_array(&_godot_variant); return ret; } Variant::operator PoolVector2Array() const { PoolVector2Array ret; *(godot_pool_vector2_array *)&ret = godot::api->godot_variant_as_pool_vector2_array(&_godot_variant); return ret; } Variant::operator PoolVector3Array() const { PoolVector3Array ret; *(godot_pool_vector3_array *)&ret = godot::api->godot_variant_as_pool_vector3_array(&_godot_variant); return ret; } Variant::operator PoolColorArray() const { PoolColorArray ret; *(godot_pool_color_array *)&ret = godot::api->godot_variant_as_pool_color_array(&_godot_variant); return ret; } Variant::operator godot_object *() const { return godot::api->godot_variant_as_object(&_godot_variant); } Variant::operator PyObject *() const { PyObject *obj; switch (get_type()) { case NIL: obj = Py_None; break; case BOOL: obj = booleanize() ? Py_True : Py_False; break; case INT: obj = PyLong_FromSsize_t(godot::api->godot_variant_as_int(&_godot_variant)); break; case REAL: obj = PyFloat_FromDouble(godot::api->godot_variant_as_real(&_godot_variant)); break; case STRING: { String s = *this; obj = PyUnicode_FromWideChar(s.unicode_str(), s.length()); break; } case VECTOR2: { Vector2 cpp_obj = *this; return _vector2_to_python_wrapper(cpp_obj); } case RECT2: { Rect2 cpp_obj = *this; return _rect2_to_python_wrapper(cpp_obj); } case VECTOR3: { Vector3 cpp_obj = *this; return _vector3_to_python_wrapper(cpp_obj); } case TRANSFORM2D: { Transform2D cpp_obj = *this; return _transform2d_to_python_wrapper(cpp_obj); } case PLANE: { Plane cpp_obj = *this; return _plane_to_python_wrapper(cpp_obj); } case QUAT: { Quat cpp_obj = *this; return _quat_to_python_wrapper(cpp_obj); } case RECT3: { AABB cpp_obj = *this; return _aabb_to_python_wrapper(cpp_obj); } case BASIS: { Basis cpp_obj = *this; return _basis_to_python_wrapper(cpp_obj); } case TRANSFORM: { Transform cpp_obj = *this; return _transform_to_python_wrapper(cpp_obj); } case COLOR: { Color cpp_obj = *this; return _color_to_python_wrapper(cpp_obj); } case NODE_PATH: { NodePath cpp_obj = *this; return _nodepath_to_python_wrapper(cpp_obj); } case _RID: { RID cpp_obj = *this; return _rid_to_python_wrapper(cpp_obj); } case OBJECT: { godot_object *c_obj = godot::api->godot_variant_as_object(&_godot_variant); return _godot_object_to_python_binding(c_obj); } case DICTIONARY: { const Dictionary dict = *this; const Array keys = dict.keys(); obj = PyDict_New(); for (int i = 0; i < keys.size(); i++) { Variant _key = keys[i]; PyObject *key = _key; PyObject *val = dict[_key]; // TODO: Check unlikely NULL pointers PyDict_SetItem(obj, key, val); } break; } case ARRAY: { const Array arr = *this; obj = PyTuple_New(arr.size()); for (int i = 0; i < arr.size(); i++) { PyObject *item = arr[i]; // TODO: Check unlikely NULL pointers PyTuple_SET_ITEM(obj, i, item); } break; } case POOL_BYTE_ARRAY: { PoolByteArray cpp_obj = *this; return _poolbytearray_to_python_wrapper(cpp_obj); } case POOL_INT_ARRAY: { PoolIntArray cpp_obj = *this; return _poolintarray_to_python_wrapper(cpp_obj); } case POOL_REAL_ARRAY: { PoolRealArray cpp_obj = *this; return _poolrealarray_to_python_wrapper(cpp_obj); } case POOL_STRING_ARRAY: { PoolStringArray cpp_obj = *this; return _poolstringarray_to_numpy(cpp_obj); } case POOL_VECTOR2_ARRAY: { PoolVector2Array cpp_obj = *this; return _poolvector2array_to_python_wrapper(cpp_obj); } case POOL_VECTOR3_ARRAY: { PoolVector3Array cpp_obj = *this; return _poolvector3array_to_python_wrapper(cpp_obj); } case POOL_COLOR_ARRAY: { PoolColorArray cpp_obj = *this; return _poolcolorarray_to_python_wrapper(cpp_obj); } default: // raises ValueError in Cython/Python context throw std::invalid_argument("could not cast Python object to Godot Variant"); } Py_XINCREF(obj); return obj; } Variant::Type Variant::get_type() const { return (Type)godot::api->godot_variant_get_type(&_godot_variant); } Variant Variant::call(const String &method, const Variant **args, const int arg_count) { Variant v; *(godot_variant *)&v = godot::api->godot_variant_call(&_godot_variant, (godot_string *)&method, (const godot_variant **)args, arg_count, nullptr); return v; } bool Variant::has_method(const String &method) { return godot::api->godot_variant_has_method(&_godot_variant, (godot_string *)&method); } bool Variant::operator==(const Variant &b) const { return godot::api->godot_variant_operator_equal(&_godot_variant, &b._godot_variant); } bool Variant::operator!=(const Variant &b) const { return !(*this == b); } bool Variant::operator<(const Variant &b) const { return godot::api->godot_variant_operator_less(&_godot_variant, &b._godot_variant); } bool Variant::operator<=(const Variant &b) const { return (*this < b) || (*this == b); } bool Variant::operator>(const Variant &b) const { return !(*this <= b); } bool Variant::operator>=(const Variant &b) const { return !(*this < b); } bool Variant::hash_compare(const Variant &b) const { return godot::api->godot_variant_hash_compare(&_godot_variant, &b._godot_variant); } bool Variant::booleanize() const { return godot::api->godot_variant_booleanize(&_godot_variant); } Variant::~Variant() { godot::api->godot_variant_destroy(&_godot_variant); } } // namespace godot
32.607056
147
0.745066
WilliamTambellini
4f203c48428c692de98f2b0fdd812268d388a572
2,114
cc
C++
src/logging/log_stream.cc
xiw2-0/minids
46510205af0e0a6c14e9d360fc83e13cd45bcf9d
[ "MIT" ]
3
2020-06-09T02:31:43.000Z
2021-03-30T09:14:33.000Z
src/logging/log_stream.cc
xiw2-0/minids
46510205af0e0a6c14e9d360fc83e13cd45bcf9d
[ "MIT" ]
null
null
null
src/logging/log_stream.cc
xiw2-0/minids
46510205af0e0a6c14e9d360fc83e13cd45bcf9d
[ "MIT" ]
null
null
null
/// Copyright (c) 2020 xiw /// /// MIT License /// \author Wang Xi #include "logging/log_stream.h" #include <thread> #include <sstream> namespace logging { void LogStream::buf(char** p_buf, size_t* size) { *p_buf = buf_; *size = buf_pointer_; } LogStream &LogStream::operator<<(bool arg) { if(arg) append("true"); else append("false"); return *this; } LogStream &LogStream::operator<<(char arg) { char str[2] = {arg,'\0'}; append(str); return *this; } LogStream &LogStream::operator<<(int16_t arg) { auto str = std::to_string(arg); append(str.c_str()); return *this; } LogStream &LogStream::operator<<(uint16_t arg) { auto str = std::to_string(arg); append(str.c_str()); return *this; } LogStream &LogStream::operator<<(int32_t arg) { auto str = std::to_string(arg); append(str.c_str()); return *this; } LogStream &LogStream::operator<<(uint32_t arg) { auto str = std::to_string(arg); append(str.c_str()); return *this; } LogStream &LogStream::operator<<(int64_t arg) { auto str = std::to_string(arg); append(str.c_str()); return *this; } LogStream &LogStream::operator<<(uint64_t arg) { auto str = std::to_string(arg); append(str.c_str()); return *this; } LogStream &LogStream::operator<<(float arg) { auto str = std::to_string(arg); append(str.c_str()); return *this; } LogStream &LogStream::operator<<(double arg) { auto str = std::to_string(arg); append(str.c_str()); return *this; } LogStream &LogStream::operator<<(const char *arg) { append(arg); return *this; } LogStream &LogStream::operator<<(const string &arg) { append(arg.c_str()); return *this; } void LogStream::append(const char *s) { auto buf_left = buf_size_ - buf_pointer_ > 0 ? buf_size_ - buf_pointer_ : 0; buf_pointer_ += ::snprintf(buf_ + buf_pointer_, buf_left, "%s", s); } /// global output std::function<void(const char*, size_t)> g_out = [](const char* buf, size_t size){ ::fwrite(buf, 1, size, ::stdout); }; /// global flush std::function<void()> g_flush = [](){ ::fflush(::stdout); }; } // namespace logging
17.048387
82
0.644276
xiw2-0
4f2070c48921f7111b5e881d6412c44aa0dddea4
8,179
cpp
C++
LFFD_ncnn.cpp
Qengineering/LFFD-ncnn-Raspberry-Pi-4
edcb609603325ca97c6f02dcfefb32f937383279
[ "BSD-3-Clause" ]
2
2021-04-18T06:47:05.000Z
2021-06-16T09:52:44.000Z
LFFD_ncnn.cpp
Qengineering/LFFD-ncnn-Raspberry-Pi-4
edcb609603325ca97c6f02dcfefb32f937383279
[ "BSD-3-Clause" ]
null
null
null
LFFD_ncnn.cpp
Qengineering/LFFD-ncnn-Raspberry-Pi-4
edcb609603325ca97c6f02dcfefb32f937383279
[ "BSD-3-Clause" ]
null
null
null
#include "LFFD_ncnn.h" LFFD::LFFD(int scale_num, int num_thread_) { num_output_scales = scale_num; num_thread = num_thread_; if (num_output_scales == 5) { param_file_name = "symbol_10_320_20L_5scales_v2_deploy.param"; bin_file_name = "train_10_320_20L_5scales_v2_iter_1000000.bin"; receptive_field_list = { 20, 40, 80, 160, 320 }; receptive_field_stride = { 4, 8, 16, 32, 64 }; bbox_small_list = { 10, 20, 40, 80, 160 }; bbox_large_list = { 20, 40, 80, 160, 320 }; receptive_field_center_start = { 3, 7, 15, 31, 63 }; for (size_t i = 0; i < receptive_field_list.size(); i++) { constant.push_back(receptive_field_list[i] / 2); } output_blob_names = { "softmax0","conv8_3_bbox", "softmax1","conv11_3_bbox", "softmax2","conv14_3_bbox", "softmax3","conv17_3_bbox", "softmax4","conv20_3_bbox" }; } else if (num_output_scales == 8) { param_file_name = "symbol_10_560_25L_8scales_v1_deploy.param"; bin_file_name = "train_10_560_25L_8scales_v1_iter_1400000.bin"; receptive_field_list = { 15, 20, 40, 70, 110, 250, 400, 560 }; receptive_field_stride = { 4, 4, 8, 8, 16, 32, 32, 32 }; bbox_small_list = { 10, 15, 20, 40, 70, 110, 250, 400 }; bbox_large_list = { 15, 20, 40, 70, 110, 250, 400, 560 }; receptive_field_center_start = { 3, 3, 7, 7, 15, 31, 31, 31 }; for (size_t i = 0; i < receptive_field_list.size(); i++) { constant.push_back(receptive_field_list[i] / 2); } output_blob_names={ "softmax0","conv8_3_bbox", "softmax1","conv10_3_bbox", "softmax2","conv13_3_bbox", "softmax3","conv15_3_bbox", "softmax4","conv18_3_bbox", "softmax5","conv21_3_bbox", "softmax6","conv23_3_bbox", "softmax7","conv25_3_bbox" }; } lffd.load_param(param_file_name.data()); lffd.load_model(bin_file_name.data()); } LFFD::~LFFD() { lffd.clear(); } int LFFD::detect(ncnn::Mat& img, std::vector<FaceInfo>& face_list, int resize_h, int resize_w, float score_threshold, float nms_threshold, int top_k, std::vector<int> skip_scale_branch_list) { if (img.empty()) { std::cout << "image is empty ,please check!" << std::endl; return -1; } image_h = img.h; image_w = img.w; ncnn::Mat in; ncnn::resize_bilinear(img,in,resize_w,resize_h); float ratio_w=(float)image_w/in.w; float ratio_h=(float)image_h/in.h; ncnn::Mat ncnn_img = in; ncnn_img.substract_mean_normalize(mean_vals, norm_vals); std::vector<FaceInfo> bbox_collection; ncnn::Extractor ex = lffd.create_extractor(); ex.set_num_threads(num_thread); ex.input("data", ncnn_img); for (int i = 0; i <num_output_scales; i++) { ncnn::Mat conf; ncnn::Mat reg; ex.extract(output_blob_names[2*i].c_str(), conf); ex.extract(output_blob_names[2 * i+1].c_str(), reg); generateBBox(bbox_collection, conf, reg, score_threshold, conf.w, conf.h, in.w, in.h, i); } std::vector<FaceInfo> valid_input; get_topk_bbox(bbox_collection, valid_input, top_k); nms(valid_input, face_list, nms_threshold); for(size_t i=0;i<face_list.size();i++){ face_list[i].x1*=ratio_w; face_list[i].y1*=ratio_h; face_list[i].x2*=ratio_w; face_list[i].y2*=ratio_h; float w,h,maxSize; float cenx,ceny; w=face_list[i].x2-face_list[i].x1; h=face_list[i].y2-face_list[i].y1; maxSize = w > h ? w : h; cenx=face_list[i].x1+w/2; ceny=face_list[i].y1+h/2; face_list[i].x1=cenx-maxSize/2>0? cenx - maxSize / 2:0; face_list[i].y1=ceny-maxSize/2>0? ceny - maxSize / 2:0; face_list[i].x2=cenx+maxSize/2>image_w? image_w-1: cenx + maxSize / 2; face_list[i].y2=ceny+maxSize/2> image_h? image_h-1: ceny + maxSize / 2; } return 0; } void LFFD::generateBBox(std::vector<FaceInfo>& bbox_collection, ncnn::Mat score_map, ncnn::Mat box_map, float score_threshold, int fea_w, int fea_h, int cols, int rows, int scale_id) { float* RF_center_Xs = new float[fea_w]; float* RF_center_Xs_mat = new float[fea_w * fea_h]; float* RF_center_Ys = new float[fea_h]; float* RF_center_Ys_mat = new float[fea_h * fea_w]; for (int x = 0; x < fea_w; x++) { RF_center_Xs[x] = receptive_field_center_start[scale_id] + receptive_field_stride[scale_id] * x; } for (int x = 0; x < fea_h; x++) { for (int y = 0; y < fea_w; y++) { RF_center_Xs_mat[x * fea_w + y] = RF_center_Xs[y]; } } for (int x = 0; x < fea_h; x++) { RF_center_Ys[x] = receptive_field_center_start[scale_id] + receptive_field_stride[scale_id] * x; for (int y = 0; y < fea_w; y++) { RF_center_Ys_mat[x * fea_w + y] = RF_center_Ys[x]; } } float* x_lt_mat = new float[fea_h * fea_w]; float* y_lt_mat = new float[fea_h * fea_w]; float* x_rb_mat = new float[fea_h * fea_w]; float* y_rb_mat = new float[fea_h * fea_w]; //x-left-top float mid_value = 0; for (int j = 0; j < fea_h * fea_w; j++) { mid_value = RF_center_Xs_mat[j] - box_map.channel(0)[j] * constant[scale_id]; x_lt_mat[j] = mid_value < 0 ? 0 : mid_value; } //y-left-top for (int j = 0; j < fea_h * fea_w; j++) { mid_value = RF_center_Ys_mat[j] - box_map.channel(1)[j] * constant[scale_id]; y_lt_mat[j] = mid_value < 0 ? 0 : mid_value; } //x-right-bottom for (int j = 0; j < fea_h * fea_w; j++) { mid_value = RF_center_Xs_mat[j] - box_map.channel(2)[j] * constant[scale_id]; x_rb_mat[j] = mid_value > cols - 1 ? cols - 1 : mid_value; } //y-right-bottom for (int j = 0; j < fea_h * fea_w; j++) { mid_value = RF_center_Ys_mat[j] - box_map.channel(3)[j] * constant[scale_id]; y_rb_mat[j] = mid_value > rows - 1 ? rows - 1 : mid_value; } for (int k = 0; k < fea_h * fea_w; k++) { if (score_map.channel(0)[k] > score_threshold) { FaceInfo faceinfo; faceinfo.x1 = x_lt_mat[k]; faceinfo.y1 = y_lt_mat[k]; faceinfo.x2 = x_rb_mat[k]; faceinfo.y2 = y_rb_mat[k]; faceinfo.score = score_map[k]; faceinfo.area = (faceinfo.x2 - faceinfo.x1) * (faceinfo.y2 - faceinfo.y1); bbox_collection.push_back(faceinfo); } } delete[] RF_center_Xs; RF_center_Xs = NULL; delete[] RF_center_Ys; RF_center_Ys = NULL; delete[] RF_center_Xs_mat; RF_center_Xs_mat = NULL; delete[] RF_center_Ys_mat; RF_center_Ys_mat = NULL; delete[] x_lt_mat; x_lt_mat = NULL; delete[] y_lt_mat; y_lt_mat = NULL; delete[] x_rb_mat; x_rb_mat = NULL; delete[] y_rb_mat; y_rb_mat = NULL; } void LFFD::get_topk_bbox(std::vector<FaceInfo>& input, std::vector<FaceInfo>& output, int top_k) { std::sort(input.begin(), input.end(), [](const FaceInfo& a, const FaceInfo& b) { return a.score > b.score; }); if (input.size() > size_t(top_k)) { for (int k = 0; k < top_k; k++) { output.push_back(input[k]); } } else { output = input; } } void LFFD::nms(std::vector<FaceInfo>& input, std::vector<FaceInfo>& output, float threshold, int type) { if(input.empty()) return; std::sort(input.begin(), input.end(), [](const FaceInfo& a, const FaceInfo& b) { return a.score > b.score; }); int box_num = input.size(); std::vector<int> merged(box_num, 0); for (int i = 0; i < box_num; i++) { if (merged[i]) continue; output.push_back(input[i]); for (int j = i + 1; j < box_num; j++) { if (merged[j]) continue; float inner_x0 = input[i].x1 > input[j].x1 ? input[i].x1 : input[j].x1;//std::max(input[i].x1, input[j].x1); float inner_y0 = input[i].y1 > input[j].y1 ? input[i].y1 : input[j].y1; float inner_x1 = input[i].x2 < input[j].x2 ? input[i].x2 : input[j].x2; //bug fixed ,sorry float inner_y1 = input[i].y2 < input[j].y2 ? input[i].y2 : input[j].y2; float inner_h = inner_y1 - inner_y0 + 1; float inner_w = inner_x1 - inner_x0 + 1; if (inner_h <= 0 || inner_w <= 0) continue; float inner_area = inner_h * inner_w; float h1 = input[j].y2 - input[j].y1 + 1; float w1 = input[j].x2 - input[j].x1 + 1; float area1 = h1 * w1; float score= inner_area/area1; if (score > threshold) merged[j] = 1; } } }
30.981061
182
0.627461
Qengineering
4f21000a633dbc7b4704b27b1a2782af1fbd7e35
3,686
cpp
C++
streambox/test/test-join-2.cpp
chenzongxiong/streambox
76f95780d1bf6c02731e39d8ac73937cea352b95
[ "Unlicense" ]
3
2019-07-03T14:03:31.000Z
2021-12-19T10:18:49.000Z
streambox/test/test-join-2.cpp
chenzongxiong/streambox
76f95780d1bf6c02731e39d8ac73937cea352b95
[ "Unlicense" ]
6
2020-02-17T12:01:30.000Z
2021-12-09T22:02:33.000Z
streambox/test/test-join-2.cpp
chenzongxiong/streambox
76f95780d1bf6c02731e39d8ac73937cea352b95
[ "Unlicense" ]
2
2020-12-03T04:41:18.000Z
2021-01-11T21:44:42.000Z
/* #include<stdio.h> #include<assert.h> #include<iostream> #include<typeinfo> #include "Create.h" #include "Read.h" */ #include "core/Pipeline.h" //#include "TransformEvaluator.h" //#include "TransformEvaluate.h" #include "Source/UnboundedInMemEvaluator_Join.h" //#include "SimpleMapperEvaluator.h" #include "Join/JoinEvaluator1.h" #include "Sink/RecordBitmapBundleSinkEvaluator.h" #include <tuple> #include "test-common.h" /* * +--- SimpleMapper -- (KVPair)--\ * Unbound -(long)-> + Join --> (KVPai * +--- SimpleMapper -- (KVPair)--/ * */ /* template<class T> auto operator<<(std::ostream& os, const T& t) -> decltype(t.print(os), os) { t.print(os); return os; } */ template<class T> using BundleT = RecordBitmapBundle<T>; #ifdef DEBUG pipeline_config config = { .records_per_interval = 1000 * 1000, .target_tput = (1000 * 500), .record_size = sizeof(long), //.input_file = "/ssd/1g.txt", .input_file = "/tmp/test-digit.txt", }; #else pipeline_config config = { .records_per_interval = 1000 * 1000, //.target_tput = (10 * 1000 * 1000), .target_tput = 2000 * 1000, //k2: 2000 should be fine .record_size = sizeof(long), //.input_file = "/ssd/1g.txt", .input_file = "/tmp/test-digit.txt", }; #endif int main(int ac, char *av[]) { parse_options(ac, av, &config); print_config(); // create a new Bounded transform //UnboundedInMem<long, BundleT> unbound ("[unbounded]", 50, 0); //UnboundedInMem_Join<long, BundleT> unbound ("[unbounded]", UnboundedInMem_Join unbound ("[unbounded]", config.input_file.c_str(), config.records_per_interval , /* records per wm interval */ config.target_tput, /* target tput (rec/sec) */ config.record_size, 0 //XXX session_gap_ms = ???? ); // create a new pipeline Pipeline* p = Pipeline::create(NULL); /* vector<PCollection*> o2 = p->apply2(&unbound); o2[0]->_name = "src_out0"; o2[1]->_name = "src_out1"; SimpleMapper<long, pair<long, long>> mapper0 ("[mapper0]"); SimpleMapper<long, pair<long, long>> mapper1 ("[mapper1]"); connect_transform(unbound, mapper0); connect_transform(unbound, mapper1); */ /* old design vector<PCollection*> o2 = p->apply2(&unbound); o2[0]->_name = "src_out0"; o2[1]->_name = "src_out1"; SimpleMapper<long, pair<long, long>> mapper0 ("[mapper0]"); auto c11 = dynamic_cast<PCollection *>(o2[0]->apply1(&mapper0)); c11->_name = "mapper0_out"; mapper0.set_side_info(1); //left side SimpleMapper<long, pair<long, long>> mapper1 ("[mapper1]"); auto c12 = dynamic_cast<PCollection *>(o2[1]->apply1(&mapper1)); c12->_name = "mapper1_out"; mapper1.set_side_info(2); //right side */ PCollection *unbound_output = dynamic_cast<PCollection *>(p->apply1(&unbound)); unbound_output->_name = "unbound_output"; Join<pair<long,long>> join("[join]", seconds(1)); auto c2 = dynamic_cast<PCollection *>(unbound_output->apply1(&join)); //auto c3 = dynamic_cast<PCollection *>(c12->apply1(&join)); ///c2 = c2; //assert(c2 == c3); // same output. join.set_side_info(3); RecordBitmapBundleSink<pair<long, vector<long>>> sink("[sink]"); auto c4 = dynamic_cast<PCollection *>(c2->apply1(&sink)); c4 = c4; assert(c4); //just for fixing warning sink.set_side_info(4); RecordBitmapBundleSink<pair<long, vector<long>>> sink1("[sink1]"); auto c5 = dynamic_cast<PCollection *>(c4->apply1(&sink1)); c5 = c5; assert(c5); //just for fixing warning //assert(false && "set RecordBitmapBundleSink side_info to 4!!"); sink1.set_side_info(5); EvaluationBundleContext eval(1, config.cores); //XXX target_wm_delta_secs?? eval.runSimple(p); return 0; }
29.253968
80
0.663049
chenzongxiong
4f23b6cc5bc4a79d61a90b2c317d723d6fb33dfb
444
cpp
C++
lib/poprand/codelets/SetSeedSupervisor.cpp
giantchen2012/poplibs
2bc6b6f3d40863c928b935b5da88f40ddd77078e
[ "MIT" ]
1
2021-02-23T05:58:24.000Z
2021-02-23T05:58:24.000Z
lib/poprand/codelets/SetSeedSupervisor.cpp
giantchen2012/poplibs
2bc6b6f3d40863c928b935b5da88f40ddd77078e
[ "MIT" ]
null
null
null
lib/poprand/codelets/SetSeedSupervisor.cpp
giantchen2012/poplibs
2bc6b6f3d40863c928b935b5da88f40ddd77078e
[ "MIT" ]
null
null
null
// Copyright (c) 2019 Graphcore Ltd. All rights reserved. #include "RandomUtils.hpp" using namespace poplar; namespace poprand { class SetSeedSupervisor : public SupervisorVertexIf<ASM_CODELETS_ENABLED> { public: SetSeedSupervisor(); Input<Vector<unsigned, ONE_PTR, 8>> seed; const uint32_t seedModifierUser; const uint32_t seedModifierHw; IS_EXTERNAL_CODELET(true); bool compute() { return true; } }; } // namespace poprand
20.181818
75
0.756757
giantchen2012
4f23d25e3dd58ad9ec5517f35b4fd0e826371bd6
24,265
cpp
C++
Src/FileDialog.cpp
bluescan/tacit-texview
084e2ee2f8e516b6d4449caf9b6712181db162f5
[ "ISC" ]
76
2019-07-03T06:43:37.000Z
2020-05-08T20:23:08.000Z
Src/FileDialog.cpp
bluescan/tacit-texview
084e2ee2f8e516b6d4449caf9b6712181db162f5
[ "ISC" ]
15
2020-01-12T23:37:09.000Z
2020-05-01T04:44:14.000Z
Src/FileDialog.cpp
bluescan/tacit-texview
084e2ee2f8e516b6d4449caf9b6712181db162f5
[ "ISC" ]
2
2020-01-18T14:13:14.000Z
2020-04-05T14:17:07.000Z
// FileDialog.cpp // // Dialog that allows selection of a file or directory. May be used for opening a file/directory or saving to a file. // // Copyright (c) 2021, 2022 Tristan Grimmer. // Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby // granted, provided that the above copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN // AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR // PERFORMANCE OF THIS SOFTWARE. #include <Math/tVector2.h> #include <System/tTime.h> #include "imgui.h" #include "FileDialog.h" #include "TacentView.h" #include "Image.h" using namespace tStd; using namespace tMath; using namespace tSystem; using namespace tImage; using namespace tInterface; namespace tInterface { // Content items are containers used to store information about a piece of information in a file dialog. It stores // the stuff you see in the right-hand panel. Namely the information displayed in a table row about a file or // directory, as well as if it is selected or not. struct ContentItem : tLink<ContentItem> { ContentItem(const tString& dirName); ContentItem(const tSystem::tFileInfo& fileInfo); bool Selected; // Each field (column) gets its own ID. This is needed so when sorting, we know what information to use in the // sorting function. We tell ImGui about the ID, and it passes that along when it tells us to sort. enum class FieldID { Invalid = -1, Name, ModTime, FileType, FileSize }; struct CompareFunctionObject { CompareFunctionObject(ImGuiTableSortSpecs* specs) : SortSpecs(specs) { } ImGuiTableSortSpecs* SortSpecs; bool operator() (const ContentItem& a, const ContentItem& b) const; }; // Name field. tString Name; bool IsDir; // These are not valid for directories. Note that we store field data redundantly in some cases since we need to be // able to sort based on a key decoupled from the display string. For example, sorting by date should be done with // an integer, not the string representation. Same with filesizes, we may want them displayed in KB or MB is they // get large, but want to sort on num-bytes. We store the string reps because it's more efficient to cache them // rather than regenerate them every time. // Modification time (last) field. int64 ModTime; // In posix epoch. tString ModTimeString; // Displayed. // File type field. tSystem::tFileType FileType; tString FileTypeString; // Displayed. // File size field. int64 FileSize; tString FileSizeString; // Displayed. }; // Tree nodes are displayed directly in the left panel and their contained Contents list in the right. TreeNodes // represent directories and other containers like favourites and network shares. A TreeNode has children TreeNodes. class TreeNode { public: TreeNode() : Name(), Parent(nullptr) { } TreeNode(const tString& name, FileDialog* dialog, TreeNode* parent = nullptr) : Name(name), Dialog(dialog), Parent(parent) { } void AppendChild(TreeNode* treeNode) { Children.Append(treeNode); } // For windows these do a case-insensitive compare. For case sensitive filesystems like Linux uses // these to a case-sensitive compare. TreeNode* Find(const tString& name) const; bool Contains(const tString& name) const { return Find(name) ? true : false; } int Depth() const; bool IsNetworkLocation() const; ContentItem* FindSelectedItem() const; tString Name; FileDialog* Dialog; bool ChildrenPopulated = false; TreeNode* Parent; tItList<TreeNode> Children; bool NextOpen = false; // Is the Contents list below populated and valid. It is slightly different than having an empty Contents list // because a leaf empty directory may have no contents, but it HAS read the filesystem so is populated. bool ContentsPopulated = false; tList<ContentItem> Contents; }; } ContentItem::ContentItem(const tString& dirName) : Selected(false), IsDir(true) { Name = dirName; ModTime = 0; ModTimeString.Clear(); FileType = tSystem::tFileType::Invalid; FileSize = 0; FileSizeString.Clear(); } ContentItem::ContentItem(const tSystem::tFileInfo& fileInfo) : Selected(false) { // Name field. Name = tSystem::tGetFileName(fileInfo.FileName); IsDir = fileInfo.Directory; // Modification time field. Choose greater of mod and creation time. ModTime = tMath::tMax(fileInfo.ModificationTime, fileInfo.CreationTime); tsPrintf(ModTimeString, "%s", tSystem::tConvertTimeToString(tSystem::tConvertTimeToLocal(ModTime)).Chars()); // File type field. FileType = tSystem::tGetFileType(Name); FileTypeString.Set(tSystem::tGetFileTypeName(FileType)); // File size field. FileSize = fileInfo.FileSize; if (FileSize < 10000) tsPrintf(FileSizeString, "%'d B", FileSize); else if (FileSize < 10000000) tsPrintf(FileSizeString, "%'d KB", FileSize/1024); else if (FileSize < 10000000000) tsPrintf(FileSizeString, "%'d MB", FileSize/(1024*1024)); else tsPrintf(FileSizeString, "%'d GB", FileSize/(1024*1024*1024)); } bool ContentItem::CompareFunctionObject::operator() (const ContentItem& a, const ContentItem& b) const { tAssert(SortSpecs); // We always put directories at the top regardless of field contents and sorting order. if (a.IsDir && !b.IsDir) return true; // This makes both the directories (that come first) as well as the files (that come after) sort correctly. // That is, do the sorting if we're comparing file-to-file or dir-to-dir. if (a.IsDir == b.IsDir) { // NumSpecs will be > 1 if more than one column is selected for sorting. The order is important. int numSpecs = SortSpecs->SpecsCount; for (int s = 0; s < numSpecs; s++) { const ImGuiTableColumnSortSpecs& colSortSpec = SortSpecs->Specs[s]; FieldID field = FieldID(colSortSpec.ColumnUserID); int64 delta = 0; switch (field) { case FieldID::Name: delta = tStd::tStricmp(a.Name.Chars(), b.Name.Chars()); break; case FieldID::ModTime: delta = a.ModTime - b.ModTime; break; case FieldID::FileType: delta = tStd::tStricmp(a.FileTypeString.Chars(), b.FileTypeString.Chars()); break; case FieldID::FileSize: delta = a.FileSize - b.FileSize; break; } if ((delta < 0) && (colSortSpec.SortDirection == ImGuiSortDirection_Ascending)) return true; else if ((delta > 0) && (colSortSpec.SortDirection == ImGuiSortDirection_Descending)) return true; } } return false; } TreeNode* TreeNode::Find(const tString& name) const { for (tItList<TreeNode>::Iter child = Children.First(); child; child++) { #ifdef PLATFORM_WINDOWS if (child->Name.IsEqualCI(name)) #else if (child->Name == name) #endif return child; } return nullptr; } int TreeNode::Depth() const { int depth = 0; TreeNode* parent = Parent; while (parent) { depth++; parent = parent->Parent; } return depth; } ContentItem* TreeNode::FindSelectedItem() const { for (ContentItem* item = Contents.First(); item; item = item->Next()) if (item->Selected) return item; return nullptr; } bool TreeNode::IsNetworkLocation() const { bool isNet = false; const TreeNode* curr = this; while (curr) { if ((curr->Depth() == 0) && (curr->Name == "Network")) isNet = true; curr = curr->Parent; } return isNet; } FileDialog::FileDialog(DialogMode mode, const tSystem::tFileTypes& fileTypes) : Mode(mode), FileTypes(fileTypes) { BookmarkTreeNode = new TreeNode("Bookmarks", this); LocalTreeNode = new TreeNode("Local", this); #ifdef PLATFORM_WINDOWS NetworkTreeNode = new TreeNode("Network", this); #endif // @wip Bookmarks is disabled until I implement it fully. PopulateBookmarks(); PopulateLocal(); #ifdef PLATFORM_WINDOWS PopulateNetwork(); #endif } void FileDialog::OpenPopup() { //ImGui::SetNextWindowSize(tVector2(640.0f, 400.0f), ImGuiCond_FirstUseEver); switch (Mode) { case DialogMode::OpenDir: ImGui::OpenPopup("Open Directory"); break; case DialogMode::OpenFile: ImGui::OpenPopup("Open File"); break; case DialogMode::SaveFile: ImGui::OpenPopup("Save File"); break; } } void FileDialog::PopulateBookmarks() { #if defined(PLATFORM_LINUX) // All linux platforms get a 'home' bookmark. #endif #if defined(PLATFORM_WINDOWS) // All windows platforms get a 'user' bookmark. TreeNode* user = new TreeNode("User", this, BookmarkTreeNode); BookmarkTreeNode->AppendChild(user); #endif } void FileDialog::PopulateLocal() { #if defined(PLATFORM_WINDOWS) tList<tStringItem> drives; tSystem::tGetDrives(drives); for (tStringItem* drive = drives.First(); drive; drive = drive->Next()) { TreeNode* driveNode = new TreeNode(*drive, this, LocalTreeNode); LocalTreeNode->AppendChild(driveNode); } #elif defined(PLATFORM_LINUX) TreeNode* rootNode = new TreeNode("/", this, LocalTreeNode); LocalTreeNode->AppendChild(rootNode); #endif } #ifdef PLATFORM_WINDOWS void FileDialog::RequestNetworkSharesThread() { tSystem::tGetNetworkShares(NetworkShareResults); } void FileDialog::PopulateNetwork() { // Start the request on a different thread. std::thread threadGetShares(&FileDialog::RequestNetworkSharesThread, this); threadGetShares.detach(); } void FileDialog::ProcessShareResults() { // Most of time this will be empty since we remove the items when they are available, just like a message queue. tStringItem* share = NetworkShareResults.ShareNames.Remove(); if (share) { tList<tStringItem> exploded; tExplodeShareName(exploded, *share); tString machName = *exploded.First(); if (!NetworkTreeNode->Contains(machName)) { TreeNode* machine = new TreeNode(machName.Text(), this, NetworkTreeNode); NetworkTreeNode->AppendChild(machine); } TreeNode* machNode = NetworkTreeNode->Find(machName); tAssert(machNode); tStringItem* shareName = (exploded.GetNumItems() == 2) ? exploded.Last() : nullptr; if (shareName && !machNode->Contains(*shareName)) { TreeNode* shareNode = new TreeNode(shareName->Text(), this, machNode); machNode->AppendChild(shareNode); } delete share; } } #endif void FileDialog::TreeNodeRecursive(TreeNode* node) { int flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_DefaultOpen | ((node->Children.GetNumItems() == 0) ? ImGuiTreeNodeFlags_Leaf : 0) | ((SelectedNode == node) ? ImGuiTreeNodeFlags_Selected : 0); bool populate = false; // This is the magic that's needed if you select from the right-hand panel. if (node->NextOpen) { ImGui::SetNextTreeNodeOpen(true); node->NextOpen = false; populate = true; } bool isOpen = ImGui::TreeNodeEx(node->Name, flags); bool isClicked = ImGui::IsItemClicked(); if (isClicked) { SelectedNode = node; populate = true; } // We only bother populating children if we need to. if (populate && !node->ChildrenPopulated) { #ifdef PLATFORM_WINDOWS if (!ProcessingNetworkPath || (node->Depth() >= 2)) #endif { // Need to be careful here. tFindDirs would (reasonably?) use the current working dir if we passed in an empty string. tString currDir = GetSelectedDir(); tList<tStringItem> foundDirs; if (!currDir.IsEmpty()) tSystem::tFindDirs(foundDirs, currDir); for (tStringItem* dir = foundDirs.First(); dir; dir = dir->Next()) { tString relDir = tSystem::tGetRelativePath(currDir, *dir); relDir.ExtractLeft("./"); relDir.ExtractRight("/"); TreeNode* child = new TreeNode(relDir, this, node); node->AppendChild(child); } node->ChildrenPopulated = true; } } if (isOpen) { // Recurse children. for (tItList<TreeNode>::Iter child = node->Children.First(); child; child++) TreeNodeRecursive(child.GetObject()); ImGui::TreePop(); } } void FileDialog::InvalidateAllNodeContent() { #ifdef PLATFORM_WINDOWS InvalidateAllNodeContentRecursive(NetworkTreeNode); #endif InvalidateAllNodeContentRecursive(LocalTreeNode); } void FileDialog::InvalidateAllNodeContentRecursive(TreeNode* node) { node->Contents.Empty(); node->ContentsPopulated = false; for (tItList<TreeNode>::Iter child = node->Children.First(); child; child++) InvalidateAllNodeContentRecursive(child.GetObject()); } void FileDialog::DoSelectable(ContentItem* item) { tString label = item->Name; if (ImGui::Selectable(label, &item->Selected, ImGuiSelectableFlags_SpanAllColumns)) { // This block enforces single selection. if (Mode != DialogMode::OpenFiles) { if (item->Selected) { // Only allowed one selected max. Clear the others. for (ContentItem* i = SelectedNode->Contents.First(); i; i = i->Next()) { if (i == item) continue; i->Selected = false; } } // Do not allow deselection of the single item. item->Selected = true; } // If a directory is selected in the right panel, we support updating the current selected TreeNode. if (item->IsDir) { SelectedNode->NextOpen = true; TreeNode* node = SelectedNode->Find(item->Name); if (!node) { // Need to create a new one and connect it up. node = new TreeNode(item->Name, this, SelectedNode); SelectedNode->AppendChild(node); tAssert(node->ChildrenPopulated == false); } SelectedNode = node; } } } void FileDialog::TreeNodeFlat(TreeNode* node) { int flags = (node->Children.GetNumItems() == 0) ? ImGuiTreeNodeFlags_Leaf : 0; if (SelectedNode == node) flags |= ImGuiTreeNodeFlags_Selected; flags |= ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick; bool isOpen = ImGui::TreeNodeEx(node->Name, flags); bool isClicked = ImGui::IsItemClicked(); if (isOpen) { // Recurse children. // for (tItList<TreeNode>::Iter child = node->Children.First(); child; child++) // FavouritesTreeNodeFlat(child.GetObject()); ImGui::TreePop(); } } FileDialog::DialogResult FileDialog::DoPopup() { // The unused isOpen bool is just so we get a close button in ImGui. bool isOpen = true; const char* label = nullptr; switch (Mode) { case DialogMode::OpenFile: label = "Open File"; break; case DialogMode::OpenFiles: label = "Open Files"; break; case DialogMode::OpenDir: label = "Open Directory"; break; case DialogMode::SaveFile: label = "Save File"; break; } ImGui::SetNextWindowSize(tVector2(660.0f, 400.0f), ImGuiCond_Appearing); if (!ImGui::BeginPopupModal(label, &isOpen, 0)) return DialogResult::Closed; DialogResult result = DialogResult::Open; Result.Clear(); // The left and right panels are cells in a 1 row, 2 column table. float bottomBarHeight = 20.0f + 28.0f; ImGui::PushStyleColor(ImGuiCol_TableBorderLight, tVector4(0.50f, 0.50f, 0.54f, 1.00f)); if (ImGui::BeginTable("FileDialogTable", 2, ImGuiTableFlags_Resizable, tVector2(0.0f, -bottomBarHeight))) { ImGui::TableSetupColumn("LeftTreeColumn", ImGuiTableColumnFlags_WidthFixed, 160.0f); ImGui::TableSetupColumn("RightContentColumn", ImGuiTableColumnFlags_WidthStretch); ImGui::TableNextRow(); // Left tree panel. ImGui::TableSetColumnIndex(0); ImGui::BeginChild("LeftTreePanel", tVector2(0.0f, -bottomBarHeight), false, ImGuiWindowFlags_HorizontalScrollbar); ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, tVector2(0.0f, 3.0f)); // This block is the workhorse of the dialog. // @wip Bookmarks are disabled until implemented fully. TreeNodeFlat(BookmarkTreeNode); TreeNodeRecursive(LocalTreeNode); #ifdef PLATFORM_WINDOWS ProcessShareResults(); ProcessingNetworkPath = true; TreeNodeRecursive(NetworkTreeNode); ProcessingNetworkPath = false; #endif ImGui::PopStyleVar(); ImGui::EndChild(); // Right content panel. ImGui::TableSetColumnIndex(1); ImGui::BeginChild("RightContentPanel", tVector2(0.0f, -bottomBarHeight)); if (SelectedNode) { if (!SelectedNode->ContentsPopulated) { tString selDir = GetSelectedDir(); // Directories. tList<tStringItem> foundDirs; if (!selDir.IsEmpty()) tSystem::tFindDirs(foundDirs, selDir); for (tStringItem* dir = foundDirs.First(); dir; dir = dir->Next()) { (*dir)[dir->Length()-1] = '\0'; // Remove slash. ContentItem* contentItem = new ContentItem(tSystem::tGetFileName(*dir)); SelectedNode->Contents.Append(contentItem); } // Files. tList<tFileInfo> foundFiles; if (!selDir.IsEmpty()) { tSystem::tFileTypes selectedTypes; selectedTypes.AddSelected(FileTypes, true); tSystem::tExtensions extensions(selectedTypes); tSystem::tFindFilesFast(foundFiles, selDir, extensions); } for (tFileInfo* fileInfo = foundFiles.First(); fileInfo; fileInfo = fileInfo->Next()) { ContentItem* contentItem = new ContentItem(*fileInfo); SelectedNode->Contents.Append(contentItem); } SelectedNode->ContentsPopulated = true; } int tableFlags = ImGuiTableFlags_Resizable | ImGuiTableFlags_NoSavedSettings | ImGuiTableFlags_Reorderable | // Drag columns to an order you like. ImGuiTableFlags_Hideable | // Hide individual columns. ImGuiTableFlags_Sortable | // Sort by column. // ImGuiTableFlags_SortTristate // Ascending, Descending, None. May get 0 sort specs. ImGuiTableFlags_SortMulti | // Allow sorting multiple columns by shift-selecting them. May get > 1 sort specs. //ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_ScrollY; // This is needed so the table itself has a scroll bar that respects the top-row freeze. ImGui::PushStyleColor(ImGuiCol_TableBorderLight, tVector4(0.25f, 0.25f, 0.28f, 1.00f)); if (ImGui::BeginTable("ContentItems", 5, tableFlags)) { // The columns. Each one gets its own unique ID. int iconFlags = ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_NoSort; int nameFlags = ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_PreferSortAscending | ImGuiTableColumnFlags_DefaultSort | ImGuiTableColumnFlags_PreferSortAscending | ImGuiTableColumnFlags_NoHide | ImGuiTableColumnFlags_NoReorder; int propFlags = ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_PreferSortAscending; ImGui::TableSetupColumn("Icon", iconFlags, 24.0f, uint32(ContentItem::FieldID::Invalid) ); ImGui::TableSetupColumn("Name", nameFlags, 190.0f, uint32(ContentItem::FieldID::Name) ); ImGui::TableSetupColumn("Modified", propFlags, 120.0f, uint32(ContentItem::FieldID::ModTime) ); ImGui::TableSetupColumn("Type", propFlags, 36.0f, uint32(ContentItem::FieldID::FileType) ); ImGui::TableSetupColumn("Size", propFlags, 0.0f, uint32(ContentItem::FieldID::FileSize) ); ImGui::TableSetupScrollFreeze(0, 1); // Make this row always visible. ImGui::TableHeadersRow(); // Sort the rows. ImGuiTableSortSpecs* sortSpecs = ImGui::TableGetSortSpecs(); if (sortSpecs && (sortSpecs->SpecsDirty) && (sortSpecs->SpecsCount > 0)) { ContentItem::CompareFunctionObject compare(sortSpecs); SelectedNode->Contents.Sort(compare); sortSpecs->SpecsDirty = false; } // Do the content rows. We could use ImGuiListClipper here but so far, even with thousands of files in // the Contents list, it is very responsive. Also, since it's a list rather than an array, we'd still // need a 'Next' loop to get to the right clipper starting point (clipper.DisplayStart). for (ContentItem* item = SelectedNode->Contents.First(); item; item = item->Next()) { ImGui::TableNextRow(); ImGui::TableNextColumn(); uint64 imgID = item->IsDir ? Viewer::FolderImage.Bind() : Viewer::FileImage.Bind(); ImGui::SetCursorPosX(ImGui::GetCursorPosX()+4.0f); ImGui::Image(ImTextureID(imgID), tVector2(16, 16), tVector2(0, 1), tVector2(1, 0), Viewer::ColourEnabledTint); // The name column selectable spans all columns. ImGui::TableNextColumn(); DoSelectable(item); ImGui::TableNextColumn(); if (!item->IsDir) ImGui::Text("%s", item->ModTimeString.Text()); ImGui::TableNextColumn(); if (!item->IsDir) ImGui::Text("%s", item->FileTypeString.Text()); ImGui::TableNextColumn(); if (!item->IsDir) ImGui::Text("%s", item->FileSizeString.Text()); } ImGui::EndTable(); } ImGui::PopStyleColor(); } ImGui::EndChild(); ImGui::EndTable(); } ImGui::PopStyleColor(); ContentItem* selItem = SelectedNode ? SelectedNode->FindSelectedItem() : nullptr; bool resultAvail = false; if (selItem) { resultAvail = ( ((Mode == DialogMode::OpenFile) && !selItem->IsDir) || ((Mode == DialogMode::SaveFile) && !selItem->IsDir) || ((Mode == DialogMode::OpenDir) && selItem->IsDir) // @todo multiple files. ); } if (!resultAvail && (Mode == DialogMode::OpenDir) && SelectedNode) { // OK to select dir in left-hand pane. int depth = SelectedNode->Depth(); resultAvail = ( (depth > 1) || (!SelectedNode->IsNetworkLocation() && (depth > 0)) ); } // For file modes, display the filename and types combo. if (Mode != DialogMode::OpenDir) { int flags = ImGuiInputTextFlags_ReadOnly; ImGui::SetNextItemWidth( ImGui::GetWindowContentRegionMax().x / 2.0f ); if (!resultAvail) ImGui::PushStyleColor(ImGuiCol_Text, tVector4(0.5f, 0.5f, 0.52f, 1.0f) ); tString fname = resultAvail ? selItem->Name : "File Name"; ImGui::InputText("##File Name", fname.Text(), fname.Length()+1, flags); if (!resultAvail) ImGui::PopStyleColor(); ImGui::SameLine(); ImGui::SetNextItemWidth(140); ImGui::SetCursorPosX(ImGui::GetWindowContentRegionMax().x - 140.0f); // Nothing selected means all types used. bool allTypes = !FileTypes.AnySelected(); tString currChosen = allTypes ? "All Image Types" : FileTypes.GetSelectedString(tSystem::tFileTypes::Separator::CommaSpace, 4); if (ImGui::BeginCombo("##TypeFilter", currChosen.Chars())) //, ImGuiComboFlags_NoArrowButton)) { if (ImGui::Selectable("All Image Types", allTypes)) { FileTypes.ClearSelected(); InvalidateAllNodeContent(); } for (tFileTypes::tFileTypeItem* typeItem = FileTypes.First(); typeItem; typeItem = typeItem->Next()) { tFileType fileType = typeItem->FileType; const char* fileTypeName = tSystem::tGetFileTypeName(fileType); if (!fileTypeName) continue; if (ImGui::Selectable(fileTypeName, typeItem->Selected)) { typeItem->Selected = !typeItem->Selected; InvalidateAllNodeContent(); } if (typeItem->Selected) ImGui::SetItemDefaultFocus(); } // Update the filters. ImGui::EndCombo(); } } // Cancel and OK buttons. ImGui::SetCursorPosY(ImGui::GetWindowContentRegionMax().y - 20.0f); if (resultAvail) { ImGui::SetCursorPosX(ImGui::GetWindowContentRegionMax().x - 140.0f); if (ImGui::Button("Open", tVector2(70.0f, 0.0f))) { Result = GetSelectedDir(); if ((Mode == DialogMode::OpenFile) && selItem) Result += selItem->Name; result = DialogResult::OK; } ImGui::SameLine(); } ImGui::SetCursorPosX(ImGui::GetWindowContentRegionMax().x - 70.0f); if (ImGui::Button("Cancel", tVector2(70.0f, 0.0f))) result = DialogResult::Cancel; if (result != DialogResult::Open) ImGui::CloseCurrentPopup(); ImGui::EndPopup(); return result; } tString FileDialog::GetResult() { return Result; } tString FileDialog::GetSelectedDir() { if (!SelectedNode) return tString(); bool isNetworkLoc = SelectedNode->IsNetworkLocation(); tString dir; TreeNode* curr = SelectedNode; while (curr) { if (!curr->Name.IsEmpty() && (curr->Depth() > 0)) { if (isNetworkLoc && (curr->Depth() == 1)) dir = curr->Name + "\\" + dir; else dir = curr->Name + "/" + dir; } curr = curr->Parent; } if (isNetworkLoc) dir = tString("\\\\") + dir; return dir; }
30.068154
242
0.705131
bluescan
4f2605188c3c8162aa30dfb72b435008f808b798
24,573
cpp
C++
Mac_Libraries/FreeImage_3_18/Source/FreeImage/MultiPage.cpp
aws4y/OpenNebulosity
406162ea39de7e8fb90147ee43f6ee95dd56dfde
[ "BSD-3-Clause" ]
111
2015-01-13T18:14:31.000Z
2022-02-20T14:26:55.000Z
Mac_Libraries/FreeImage_3_18/Source/FreeImage/MultiPage.cpp
aws4y/OpenNebulosity
406162ea39de7e8fb90147ee43f6ee95dd56dfde
[ "BSD-3-Clause" ]
54
2015-02-23T16:57:41.000Z
2021-02-19T08:16:27.000Z
Mac_Libraries/FreeImage_3_18/Source/FreeImage/MultiPage.cpp
aws4y/OpenNebulosity
406162ea39de7e8fb90147ee43f6ee95dd56dfde
[ "BSD-3-Clause" ]
26
2015-01-17T13:07:56.000Z
2021-12-02T07:43:29.000Z
// ========================================================== // Multi-Page functions // // Design and implementation by // - Floris van den Berg (flvdberg@wxs.nl) // - Laurent Rocher (rocherl@club-internet.fr) // - Steve Johnson (steve@parisgroup.net) // - Petr Pytelka (pyta@lightcomp.com) // - Hervé Drolon (drolon@infonie.fr) // - Vadim Alexandrov (vadimalexandrov@users.sourceforge.net // - Martin Dyring-Andersen (mda@spamfighter.com) // - Volodymyr Goncharov (volodymyr.goncharov@gmail.com) // - Mihail Naydenov (mnaydenov@users.sourceforge.net) // // This file is part of FreeImage 3 // // COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES // THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE // OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED // CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT // THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY // SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL // PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER // THIS DISCLAIMER. // // Use at your own risk! // ========================================================== #ifdef _MSC_VER #pragma warning (disable : 4786) // identifier was truncated to 'number' characters #endif #include "CacheFile.h" #include "FreeImageIO.h" #include "Plugin.h" #include "Utilities.h" #include "FreeImage.h" namespace { // ---------------------------------------------------------- enum BlockType { BLOCK_CONTINUEUS, BLOCK_REFERENCE }; // ---------------------------------------------------------- class PageBlock { union { struct { int m_start; int m_end; }; struct { int m_reference; int m_size; }; }; public: BlockType m_type; PageBlock(BlockType type = BLOCK_CONTINUEUS, int val1 = -1, int val2 = -1) : m_type(type) { if(m_type == BLOCK_CONTINUEUS) { m_start = val1; m_end = val2; } else { m_reference = val1; m_size = val2; } } bool isValid() const { return !(m_type == BLOCK_CONTINUEUS && m_start == -1 && m_end == -1); } /*explicit*/ operator bool() const { return isValid(); } int getStart() const { assert(isValid() && m_type == BLOCK_CONTINUEUS); return m_start; } int getEnd() const { assert(isValid() && m_type == BLOCK_CONTINUEUS); return m_end; } bool isSinglePage() const { assert(isValid()); return m_type == BLOCK_CONTINUEUS ? (m_start == m_end) : true; } int getPageCount() const { assert(isValid()); return m_type == BLOCK_CONTINUEUS ? (m_end - m_start + 1) : 1;} int getReference() const { assert(isValid() && m_type == BLOCK_REFERENCE); return m_reference; } int getSize() const { assert(isValid() && m_type == BLOCK_REFERENCE); return m_size; } }; // ---------------------------------------------------------- typedef std::list<PageBlock> BlockList; typedef BlockList::iterator BlockListIterator; // ---------------------------------------------------------- struct MULTIBITMAPHEADER { MULTIBITMAPHEADER() : node(NULL) , fif(FIF_UNKNOWN) , handle(NULL) , changed(FALSE) , page_count(0) , read_only(TRUE) , cache_fif(fif) , load_flags(0) { SetDefaultIO(&io); } PluginNode *node; FREE_IMAGE_FORMAT fif; FreeImageIO io; fi_handle handle; CacheFile m_cachefile; std::map<FIBITMAP *, int> locked_pages; BOOL changed; int page_count; BlockList m_blocks; std::string m_filename; BOOL read_only; FREE_IMAGE_FORMAT cache_fif; int load_flags; }; // ===================================================================== // Helper functions // ===================================================================== inline void ReplaceExtension(std::string& dst_filename, const std::string& src_filename, const std::string& dst_extension) { size_t lastDot = src_filename.find_last_of('.'); if (lastDot == std::string::npos) { dst_filename = src_filename; dst_filename += "."; dst_filename += dst_extension; } else { dst_filename = src_filename.substr(0, lastDot + 1); dst_filename += dst_extension; } } } //< ns // ===================================================================== // Internal Multipage functions // ===================================================================== inline MULTIBITMAPHEADER * FreeImage_GetMultiBitmapHeader(FIMULTIBITMAP *bitmap) { return (MULTIBITMAPHEADER *)bitmap->data; } static BlockListIterator DLL_CALLCONV FreeImage_FindBlock(FIMULTIBITMAP *bitmap, int position) { assert(NULL != bitmap); MULTIBITMAPHEADER *header = FreeImage_GetMultiBitmapHeader(bitmap); // step 1: find the block that matches the given position int prev_count = 0; int count = 0; BlockListIterator i; for (i = header->m_blocks.begin(); i != header->m_blocks.end(); ++i) { prev_count = count; count += i->getPageCount(); if (count > position) { break; } } // step 2: make sure we found the node. from here it gets a little complicated: // * if the block is single page, just return it // * if the block is a span of pages, split it in 3 new blocks // and return the middle block, which is now a single page if ((i != header->m_blocks.end()) && (count > position)) { if (i->isSinglePage()) { return i; } const int item = i->getStart() + (position - prev_count); // left part if (item != i->getStart()) { header->m_blocks.insert(i, PageBlock(BLOCK_CONTINUEUS, i->getStart(), item - 1)); } // middle part BlockListIterator block_target = header->m_blocks.insert(i, PageBlock(BLOCK_CONTINUEUS, item, item)); // right part if (item != i->getEnd()) { header->m_blocks.insert(i, PageBlock(BLOCK_CONTINUEUS, item + 1, i->getEnd())); } // remove the old block that was just splitted header->m_blocks.erase(i); // return the splitted block return block_target; } // we should never go here ... assert(false); return header->m_blocks.end(); } int DLL_CALLCONV FreeImage_InternalGetPageCount(FIMULTIBITMAP *bitmap) { if (bitmap) { if (((MULTIBITMAPHEADER *)bitmap->data)->handle) { MULTIBITMAPHEADER *header = FreeImage_GetMultiBitmapHeader(bitmap); header->io.seek_proc(header->handle, 0, SEEK_SET); void *data = FreeImage_Open(header->node, &header->io, header->handle, TRUE); int page_count = (header->node->m_plugin->pagecount_proc != NULL) ? header->node->m_plugin->pagecount_proc(&header->io, header->handle, data) : 1; FreeImage_Close(header->node, &header->io, header->handle, data); return page_count; } } return 0; } // ===================================================================== // Multipage functions // ===================================================================== FIMULTIBITMAP * DLL_CALLCONV FreeImage_OpenMultiBitmap(FREE_IMAGE_FORMAT fif, const char *filename, BOOL create_new, BOOL read_only, BOOL keep_cache_in_memory, int flags) { FILE *handle = NULL; try { // sanity check on the parameters if (create_new) { read_only = FALSE; } // retrieve the plugin list to find the node belonging to this plugin PluginList *list = FreeImage_GetPluginList(); if (list) { PluginNode *node = list->FindNodeFromFIF(fif); if (node) { if (!create_new) { handle = fopen(filename, "rb"); if (handle == NULL) { return NULL; } } std::auto_ptr<FIMULTIBITMAP> bitmap (new FIMULTIBITMAP); std::auto_ptr<MULTIBITMAPHEADER> header (new MULTIBITMAPHEADER); header->m_filename = filename; // io is default header->node = node; header->fif = fif; header->handle = handle; header->read_only = read_only; header->cache_fif = fif; header->load_flags = flags; // store the MULTIBITMAPHEADER in the surrounding FIMULTIBITMAP structure bitmap->data = header.get(); // cache the page count header->page_count = FreeImage_InternalGetPageCount(bitmap.get()); // allocate a continueus block to describe the bitmap if (!create_new) { header->m_blocks.push_back(PageBlock(BLOCK_CONTINUEUS, 0, header->page_count - 1)); } // set up the cache if (!read_only) { std::string cache_name; ReplaceExtension(cache_name, filename, "ficache"); if (!header->m_cachefile.open(cache_name, keep_cache_in_memory)) { // an error occured ... fclose(handle); return NULL; } } // return the multibitmap // std::bad_alloc won't be thrown from here on header.release(); // now owned by bitmap return bitmap.release(); // now owned by caller } } } catch (std::bad_alloc &) { /** @todo report error */ } if (handle) { fclose(handle); } return NULL; } FIMULTIBITMAP * DLL_CALLCONV FreeImage_OpenMultiBitmapFromHandle(FREE_IMAGE_FORMAT fif, FreeImageIO *io, fi_handle handle, int flags) { try { BOOL read_only = FALSE; // modifications (if any) will be stored into the memory cache if (io && handle) { // retrieve the plugin list to find the node belonging to this plugin PluginList *list = FreeImage_GetPluginList(); if (list) { PluginNode *node = list->FindNodeFromFIF(fif); if (node) { std::auto_ptr<FIMULTIBITMAP> bitmap (new FIMULTIBITMAP); std::auto_ptr<MULTIBITMAPHEADER> header (new MULTIBITMAPHEADER); header->io = *io; header->node = node; header->fif = fif; header->handle = handle; header->read_only = read_only; header->cache_fif = fif; header->load_flags = flags; // store the MULTIBITMAPHEADER in the surrounding FIMULTIBITMAP structure bitmap->data = header.get(); // cache the page count header->page_count = FreeImage_InternalGetPageCount(bitmap.get()); // allocate a continueus block to describe the bitmap header->m_blocks.push_back(PageBlock(BLOCK_CONTINUEUS, 0, header->page_count - 1)); // no need to open cache - it is in-memory by default header.release(); return bitmap.release(); } } } } catch (std::bad_alloc &) { /** @todo report error */ } return NULL; } BOOL DLL_CALLCONV FreeImage_SaveMultiBitmapToHandle(FREE_IMAGE_FORMAT fif, FIMULTIBITMAP *bitmap, FreeImageIO *io, fi_handle handle, int flags) { if(!bitmap || !bitmap->data || !io || !handle) { return FALSE; } BOOL success = TRUE; // retrieve the plugin list to find the node belonging to this plugin PluginList *list = FreeImage_GetPluginList(); if (list) { PluginNode *node = list->FindNodeFromFIF(fif); if(node) { MULTIBITMAPHEADER *header = FreeImage_GetMultiBitmapHeader(bitmap); // dst data void *data = FreeImage_Open(node, io, handle, FALSE); // src data void *data_read = NULL; if(header->handle) { // open src header->io.seek_proc(header->handle, 0, SEEK_SET); data_read = FreeImage_Open(header->node, &header->io, header->handle, TRUE); } // write all the pages to the file using handle and io int count = 0; for (BlockListIterator i = header->m_blocks.begin(); i != header->m_blocks.end(); i++) { if (success) { switch(i->m_type) { case BLOCK_CONTINUEUS: { for (int j = i->getStart(); j <= i->getEnd(); j++) { // load the original source data FIBITMAP *dib = header->node->m_plugin->load_proc(&header->io, header->handle, j, header->load_flags, data_read); // save the data success = node->m_plugin->save_proc(io, dib, handle, count, flags, data); count++; FreeImage_Unload(dib); } break; } case BLOCK_REFERENCE: { // read the compressed data BYTE *compressed_data = (BYTE*)malloc(i->getSize() * sizeof(BYTE)); header->m_cachefile.readFile((BYTE *)compressed_data, i->getReference(), i->getSize()); // uncompress the data FIMEMORY *hmem = FreeImage_OpenMemory(compressed_data, i->getSize()); FIBITMAP *dib = FreeImage_LoadFromMemory(header->cache_fif, hmem, 0); FreeImage_CloseMemory(hmem); // get rid of the buffer free(compressed_data); // save the data success = node->m_plugin->save_proc(io, dib, handle, count, flags, data); count++; // unload the dib FreeImage_Unload(dib); break; } } } else { break; } } // close the files FreeImage_Close(header->node, &header->io, header->handle, data_read); FreeImage_Close(node, io, handle, data); return success; } } return FALSE; } BOOL DLL_CALLCONV FreeImage_CloseMultiBitmap(FIMULTIBITMAP *bitmap, int flags) { if (bitmap) { BOOL success = TRUE; if (bitmap->data) { MULTIBITMAPHEADER *header = FreeImage_GetMultiBitmapHeader(bitmap); // saves changes only of images loaded directly from a file if (header->changed && !header->m_filename.empty()) { try { // open a temp file std::string spool_name; ReplaceExtension(spool_name, header->m_filename, "fispool"); // open the spool file and the source file FILE *f = fopen(spool_name.c_str(), "w+b"); // saves changes if (f == NULL) { FreeImage_OutputMessageProc(header->fif, "Failed to open %s, %s", spool_name.c_str(), strerror(errno)); success = FALSE; } else { success = FreeImage_SaveMultiBitmapToHandle(header->fif, bitmap, &header->io, (fi_handle)f, flags); // close the files if (fclose(f) != 0) { success = FALSE; FreeImage_OutputMessageProc(header->fif, "Failed to close %s, %s", spool_name.c_str(), strerror(errno)); } } if (header->handle) { fclose((FILE *)header->handle); } // applies changes to the destination file if (success) { remove(header->m_filename.c_str()); success = (rename(spool_name.c_str(), header->m_filename.c_str()) == 0) ? TRUE:FALSE; if(!success) { FreeImage_OutputMessageProc(header->fif, "Failed to rename %s to %s", spool_name.c_str(), header->m_filename.c_str()); } } else { remove(spool_name.c_str()); } } catch (std::bad_alloc &) { success = FALSE; } } else { if (header->handle && !header->m_filename.empty()) { fclose((FILE *)header->handle); } } // delete the last open bitmaps while (!header->locked_pages.empty()) { FreeImage_Unload(header->locked_pages.begin()->first); header->locked_pages.erase(header->locked_pages.begin()->first); } // delete the FIMULTIBITMAPHEADER delete header; } delete bitmap; return success; } return FALSE; } int DLL_CALLCONV FreeImage_GetPageCount(FIMULTIBITMAP *bitmap) { if (bitmap) { MULTIBITMAPHEADER *header = FreeImage_GetMultiBitmapHeader(bitmap); if (header->page_count == -1) { header->page_count = 0; for (BlockListIterator i = header->m_blocks.begin(); i != header->m_blocks.end(); ++i) { header->page_count += i->getPageCount(); } } return header->page_count; } return 0; } static PageBlock FreeImage_SavePageToBlock(MULTIBITMAPHEADER *header, FIBITMAP *data) { PageBlock res; if (header->read_only || !header->locked_pages.empty()) { return res; } DWORD compressed_size = 0; BYTE *compressed_data = NULL; // compress the bitmap data // open a memory handle FIMEMORY *hmem = FreeImage_OpenMemory(); if(hmem==NULL) { return res; } // save the file to memory if(!FreeImage_SaveToMemory(header->cache_fif, data, hmem, 0)) { FreeImage_CloseMemory(hmem); return res; } // get the buffer from the memory stream if(!FreeImage_AcquireMemory(hmem, &compressed_data, &compressed_size)) { FreeImage_CloseMemory(hmem); return res; } // write the compressed data to the cache int ref = header->m_cachefile.writeFile(compressed_data, compressed_size); // get rid of the compressed data FreeImage_CloseMemory(hmem); res = PageBlock(BLOCK_REFERENCE, ref, compressed_size); return res; } void DLL_CALLCONV FreeImage_AppendPage(FIMULTIBITMAP *bitmap, FIBITMAP *data) { if (!bitmap || !data) { return; } MULTIBITMAPHEADER *header = FreeImage_GetMultiBitmapHeader(bitmap); if(const PageBlock block = FreeImage_SavePageToBlock(header, data)) { // add the block header->m_blocks.push_back(block); header->changed = TRUE; header->page_count = -1; } } void DLL_CALLCONV FreeImage_InsertPage(FIMULTIBITMAP *bitmap, int page, FIBITMAP *data) { if (!bitmap || !data) { return; } if (page >= FreeImage_GetPageCount(bitmap)) { return; } MULTIBITMAPHEADER *header = FreeImage_GetMultiBitmapHeader(bitmap); if(const PageBlock block = FreeImage_SavePageToBlock(header, data)) { // add a block if (page > 0) { BlockListIterator block_source = FreeImage_FindBlock(bitmap, page); header->m_blocks.insert(block_source, block); } else { header->m_blocks.push_front(block); } header->changed = TRUE; header->page_count = -1; } } void DLL_CALLCONV FreeImage_DeletePage(FIMULTIBITMAP *bitmap, int page) { if (bitmap) { MULTIBITMAPHEADER *header = FreeImage_GetMultiBitmapHeader(bitmap); if ((!header->read_only) && (header->locked_pages.empty())) { if (FreeImage_GetPageCount(bitmap) > 1) { BlockListIterator i = FreeImage_FindBlock(bitmap, page); if (i != header->m_blocks.end()) { switch(i->m_type) { case BLOCK_CONTINUEUS : header->m_blocks.erase(i); break; case BLOCK_REFERENCE : header->m_cachefile.deleteFile(i->getReference()); header->m_blocks.erase(i); break; } header->changed = TRUE; header->page_count = -1; } } } } } FIBITMAP * DLL_CALLCONV FreeImage_LockPage(FIMULTIBITMAP *bitmap, int page) { if (bitmap) { MULTIBITMAPHEADER *header = FreeImage_GetMultiBitmapHeader(bitmap); // only lock if the page wasn't locked before... for (std::map<FIBITMAP *, int>::iterator i = header->locked_pages.begin(); i != header->locked_pages.end(); ++i) { if (i->second == page) { return NULL; } } // open the bitmap header->io.seek_proc(header->handle, 0, SEEK_SET); void *data = FreeImage_Open(header->node, &header->io, header->handle, TRUE); // load the bitmap data if (data != NULL) { FIBITMAP *dib = (header->node->m_plugin->load_proc != NULL) ? header->node->m_plugin->load_proc(&header->io, header->handle, page, header->load_flags, data) : NULL; // close the file FreeImage_Close(header->node, &header->io, header->handle, data); // if there was still another bitmap open, get rid of it if (dib) { header->locked_pages[dib] = page; return dib; } return NULL; } } return NULL; } void DLL_CALLCONV FreeImage_UnlockPage(FIMULTIBITMAP *bitmap, FIBITMAP *page, BOOL changed) { if ((bitmap) && (page)) { MULTIBITMAPHEADER *header = FreeImage_GetMultiBitmapHeader(bitmap); // find out if the page we try to unlock is actually locked... if (header->locked_pages.find(page) != header->locked_pages.end()) { // store the bitmap compressed in the cache for later writing if (changed && !header->read_only) { header->changed = TRUE; // cut loose the block from the rest BlockListIterator i = FreeImage_FindBlock(bitmap, header->locked_pages[page]); // compress the data DWORD compressed_size = 0; BYTE *compressed_data = NULL; // open a memory handle FIMEMORY *hmem = FreeImage_OpenMemory(); // save the page to memory FreeImage_SaveToMemory(header->cache_fif, page, hmem, 0); // get the buffer from the memory stream FreeImage_AcquireMemory(hmem, &compressed_data, &compressed_size); // write the data to the cache if (i->m_type == BLOCK_REFERENCE) { header->m_cachefile.deleteFile(i->getReference()); } int iPage = header->m_cachefile.writeFile(compressed_data, compressed_size); *i = PageBlock(BLOCK_REFERENCE, iPage, compressed_size); // get rid of the compressed data FreeImage_CloseMemory(hmem); } // reset the locked page so that another page can be locked FreeImage_Unload(page); header->locked_pages.erase(page); } } } BOOL DLL_CALLCONV FreeImage_MovePage(FIMULTIBITMAP *bitmap, int target, int source) { if (bitmap) { MULTIBITMAPHEADER *header = FreeImage_GetMultiBitmapHeader(bitmap); if ((!header->read_only) && (header->locked_pages.empty())) { if ((target != source) && ((target >= 0) && (target < FreeImage_GetPageCount(bitmap))) && ((source >= 0) && (source < FreeImage_GetPageCount(bitmap)))) { BlockListIterator block_source = FreeImage_FindBlock(bitmap, target); BlockListIterator block_target = FreeImage_FindBlock(bitmap, source); header->m_blocks.insert(block_target, *block_source); header->m_blocks.erase(block_source); header->changed = TRUE; return TRUE; } } } return FALSE; } BOOL DLL_CALLCONV FreeImage_GetLockedPageNumbers(FIMULTIBITMAP *bitmap, int *pages, int *count) { if ((bitmap) && (count)) { MULTIBITMAPHEADER *header = FreeImage_GetMultiBitmapHeader(bitmap); if ((pages == NULL) || (*count == 0)) { *count = (int)header->locked_pages.size(); } else { int c = 0; for (std::map<FIBITMAP *, int>::iterator i = header->locked_pages.begin(); i != header->locked_pages.end(); ++i) { pages[c] = i->second; c++; if (c == *count) { break; } } } return TRUE; } return FALSE; } // ===================================================================== // Memory IO Multipage functions // ===================================================================== FIMULTIBITMAP * DLL_CALLCONV FreeImage_LoadMultiBitmapFromMemory(FREE_IMAGE_FORMAT fif, FIMEMORY *stream, int flags) { BOOL read_only = FALSE; // modifications (if any) will be stored into the memory cache // retrieve the plugin list to find the node belonging to this plugin PluginList *list = FreeImage_GetPluginList(); if (list) { PluginNode *node = list->FindNodeFromFIF(fif); if (node) { FIMULTIBITMAP *bitmap = new(std::nothrow) FIMULTIBITMAP; if (bitmap) { MULTIBITMAPHEADER *header = new(std::nothrow) MULTIBITMAPHEADER; if (header) { header->node = node; header->fif = fif; SetMemoryIO(&header->io); header->handle = (fi_handle)stream; header->read_only = read_only; header->cache_fif = fif; header->load_flags = flags; // store the MULTIBITMAPHEADER in the surrounding FIMULTIBITMAP structure bitmap->data = header; // cache the page count header->page_count = FreeImage_InternalGetPageCount(bitmap); // allocate a continueus block to describe the bitmap header->m_blocks.push_back(PageBlock(BLOCK_CONTINUEUS, 0, header->page_count - 1)); // no need to open cache - it is in-memory by default return bitmap; } delete bitmap; } } } return NULL; } BOOL DLL_CALLCONV FreeImage_SaveMultiBitmapToMemory(FREE_IMAGE_FORMAT fif, FIMULTIBITMAP *bitmap, FIMEMORY *stream, int flags) { if (stream && stream->data) { FreeImageIO io; SetMemoryIO(&io); return FreeImage_SaveMultiBitmapToHandle(fif, bitmap, &io, (fi_handle)stream, flags); } return FALSE; }
27.364143
168
0.613722
aws4y
4f261cdeb0b5320194a0a3c3fa545dbdb6fcccbb
1,582
hpp
C++
cli_args.hpp
iszczesniak/ddpp
bc27ad2b7f699d8ef2e11dcb3b56d538d92e4b4e
[ "BSL-1.0" ]
null
null
null
cli_args.hpp
iszczesniak/ddpp
bc27ad2b7f699d8ef2e11dcb3b56d538d92e4b4e
[ "BSL-1.0" ]
null
null
null
cli_args.hpp
iszczesniak/ddpp
bc27ad2b7f699d8ef2e11dcb3b56d538d92e4b4e
[ "BSL-1.0" ]
null
null
null
#ifndef CLI_ARGS_HPP #define CLI_ARGS_HPP #include "connection.hpp" #include "routing.hpp" #include <optional> #include <string> /** * These are the program arguments. In this single class we store all * information passed at the command line. */ struct cli_args { /// ----------------------------------------------------------------- /// The network and routing options /// ----------------------------------------------------------------- /// The network file name. std::string net; /// The number of units. int units; // Use the generic Dijkstra search. bool gd = false; // Use the brute force search. bool bf = false; // Use the edge exclusion search. bool ee = false; /// ----------------------------------------------------------------- /// The traffic options /// ----------------------------------------------------------------- /// The mean client arrival time. double mcat; /// The offered load. double ol; /// The mean holding time. double mht; /// The mean number of units. double mnu; /// ----------------------------------------------------------------- /// The simulation options /// ----------------------------------------------------------------- /// The seed int seed; /// The population name. std::string population; /// The kickoff time for stats. double kickoff; /// The limit on the simulation time. double sim_time; }; /** * This function parses the command-line arguments. */ cli_args process_cli_args(int argc, const char* argv[]); #endif /* CLI_ARGS_HPP */
21.093333
71
0.484829
iszczesniak
4f26672294b4cc622c3bd4f079929719d6af4fc7
7,896
cpp
C++
src/dgetrs_nopiv_batched.cpp
shengren/magma-1.6.1
1adfee30b763e9491a869403e0f320b3888923b6
[ "BSD-3-Clause" ]
21
2017-10-06T05:05:05.000Z
2022-03-13T15:39:20.000Z
src/dgetrs_nopiv_batched.cpp
shengren/magma-1.6.1
1adfee30b763e9491a869403e0f320b3888923b6
[ "BSD-3-Clause" ]
1
2017-03-23T00:27:24.000Z
2017-03-23T00:27:24.000Z
src/dgetrs_nopiv_batched.cpp
shengren/magma-1.6.1
1adfee30b763e9491a869403e0f320b3888923b6
[ "BSD-3-Clause" ]
4
2018-01-09T15:49:58.000Z
2022-03-13T15:39:27.000Z
/* -- MAGMA (version 1.6.1) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver November 2013 @author Azzam Haidar @generated from zgetrs_nopiv_batched.cpp normal z -> d, Fri Jan 30 19:00:19 2015 */ #include "common_magma.h" #include "batched_kernel_param.h" /** Purpose ------- Solves a system of linear equations A * X = B, A**T * X = B, or A**H * X = B with a general N-by-N matrix A using the LU factorization computed by DGETRF_GPU. Arguments --------- @param[in] trans magma_trans_t Specifies the form of the system of equations: - = MagmaNoTrans: A * X = B (No transpose) - = MagmaTrans: A**T * X = B (Transpose) - = MagmaConjTrans: A**H * X = B (Conjugate transpose) @param[in] n INTEGER The order of the matrix A. N >= 0. @param[in] nrhs INTEGER The number of right hand sides, i.e., the number of columns of the matrix B. NRHS >= 0. @param[in] dA DOUBLE_PRECISION array on the GPU, dimension (LDA,N) The factors L and U from the factorization A = P*L*U as computed by DGETRF_GPU. @param[in] ldda INTEGER The leading dimension of the array A. LDA >= max(1,N). @param[in] ipiv INTEGER array, dimension (N) The pivot indices from DGETRF; for 1 <= i <= N, row i of the matrix was interchanged with row IPIV(i). @param[in,out] dB DOUBLE_PRECISION array on the GPU, dimension (LDB,NRHS) On entry, the right hand side matrix B. On exit, the solution matrix X. @param[in] lddb INTEGER The leading dimension of the array B. LDB >= max(1,N). @param[out] info INTEGER - = 0: successful exit - < 0: if INFO = -i, the i-th argument had an illegal value @ingroup magma_dgesv_comp ********************************************************************/ extern "C" magma_int_t magma_dgetrs_nopiv_batched( magma_trans_t trans, magma_int_t n, magma_int_t nrhs, double **dA_array, magma_int_t ldda, double **dB_array, magma_int_t lddb, magma_int_t *info_array, magma_int_t batchCount, magma_queue_t queue) { /* Local variables */ magma_int_t notran = (trans == MagmaNoTrans); magma_int_t info = 0; if ( (! notran) && (trans != MagmaTrans) && (trans != MagmaConjTrans) ) { info = -1; } else if (n < 0) { info = -2; } else if (nrhs < 0) { info = -3; } else if (ldda < max(1,n)) { info = -5; } else if (lddb < max(1,n)) { info = -8; } if (info != 0) { magma_xerbla( __func__, -(info) ); return info; } /* Quick return if possible */ if (n == 0 || nrhs == 0) { return info; } double **dA_displ = NULL; double **dB_displ = NULL; double **dW1_displ = NULL; double **dW2_displ = NULL; double **dW3_displ = NULL; double **dW4_displ = NULL; double **dinvA_array = NULL; double **dwork_array = NULL; magma_malloc((void**)&dA_displ, batchCount * sizeof(*dA_displ)); magma_malloc((void**)&dB_displ, batchCount * sizeof(*dB_displ)); magma_malloc((void**)&dW1_displ, batchCount * sizeof(*dW1_displ)); magma_malloc((void**)&dW2_displ, batchCount * sizeof(*dW2_displ)); magma_malloc((void**)&dW3_displ, batchCount * sizeof(*dW3_displ)); magma_malloc((void**)&dW4_displ, batchCount * sizeof(*dW4_displ)); magma_malloc((void**)&dinvA_array, batchCount * sizeof(*dinvA_array)); magma_malloc((void**)&dwork_array, batchCount * sizeof(*dwork_array)); magma_int_t invA_msize = ((n+TRI_NB-1)/TRI_NB)*TRI_NB*TRI_NB; magma_int_t dwork_msize = n*nrhs; double* dinvA = NULL; double* dwork = NULL;// dinvA and dwork are workspace in dtrsm magma_dmalloc( &dinvA, invA_msize * batchCount); magma_dmalloc( &dwork, dwork_msize * batchCount ); /* check allocation */ if ( dW1_displ == NULL || dW2_displ == NULL || dW3_displ == NULL || dW4_displ == NULL || dinvA_array == NULL || dwork_array == NULL || dinvA == NULL || dwork == NULL || dA_displ == NULL || dB_displ == NULL ) { magma_free(dA_displ); magma_free(dB_displ); magma_free(dW1_displ); magma_free(dW2_displ); magma_free(dW3_displ); magma_free(dW4_displ); magma_free(dinvA_array); magma_free(dwork_array); magma_free( dinvA ); magma_free( dwork ); info = MAGMA_ERR_DEVICE_ALLOC; magma_xerbla( __func__, -(info) ); return info; } magmablas_dlaset_q(MagmaFull, invA_msize, batchCount, MAGMA_D_ZERO, MAGMA_D_ZERO, dinvA, invA_msize, queue); magmablas_dlaset_q(MagmaFull, dwork_msize, batchCount, MAGMA_D_ZERO, MAGMA_D_ZERO, dwork, dwork_msize, queue); dset_pointer(dwork_array, dwork, n, 0, 0, dwork_msize, batchCount, queue); dset_pointer(dinvA_array, dinvA, TRI_NB, 0, 0, invA_msize, batchCount, queue); magma_ddisplace_pointers(dA_displ, dA_array, ldda, 0, 0, batchCount, queue); magma_ddisplace_pointers(dB_displ, dB_array, lddb, 0, 0, batchCount, queue); magma_queue_t cstream; magmablasGetKernelStream(&cstream); //printf(" I am after malloc getri\n"); if (notran) { // solve dwork = L^-1 * NRHS magmablas_dtrsm_outofplace_batched(MagmaLeft, MagmaLower, MagmaNoTrans, MagmaUnit, 1, n, nrhs, MAGMA_D_ONE, dA_displ, ldda, // dA dB_displ, lddb, // dB dwork_array, n, // dX //output dinvA_array, invA_msize, dW1_displ, dW2_displ, dW3_displ, dW4_displ, 1, batchCount, queue); // solve X = U^-1 * dwork magmablas_dtrsm_outofplace_batched(MagmaLeft, MagmaUpper, MagmaNoTrans, MagmaNonUnit, 1, n, nrhs, MAGMA_D_ONE, dA_displ, ldda, // dA dwork_array, n, // dB dB_displ, lddb, // dX //output dinvA_array, invA_msize, dW1_displ, dW2_displ, dW3_displ, dW4_displ, 1, batchCount, queue); } else{ /* Solve A**T * X = B or A**H * X = B. */ // solve magmablas_dtrsm_outofplace_batched(MagmaLeft, MagmaUpper, trans, MagmaUnit, 1, n, nrhs, MAGMA_D_ONE, dA_displ, ldda, // dA dB_displ, lddb, // dB dwork_array, n, // dX //output dinvA_array, invA_msize, dW1_displ, dW2_displ, dW3_displ, dW4_displ, 1, batchCount, queue); // solve magmablas_dtrsm_outofplace_batched(MagmaLeft, MagmaLower, trans, MagmaNonUnit, 1, n, nrhs, MAGMA_D_ONE, dA_displ, ldda, // dA dwork_array, n, // dB dB_displ, lddb, // dX //output dinvA_array, invA_msize, dW1_displ, dW2_displ, dW3_displ, dW4_displ, 1, batchCount, queue); } magma_queue_sync(cstream); magma_free(dA_displ); magma_free(dB_displ); magma_free(dW1_displ); magma_free(dW2_displ); magma_free(dW3_displ); magma_free(dW4_displ); magma_free(dinvA_array); magma_free(dwork_array); magma_free( dinvA ); magma_free( dwork ); return info; }
33.457627
114
0.556864
shengren
4f272caf25db73404a223d05b9618e45e9ad4f6c
983
cpp
C++
src/point.cpp
ASjet/GreedySnake
c07a22ede63a8c4f42bc6af2d8c8c95cd46b0311
[ "MIT" ]
1
2020-05-30T07:15:18.000Z
2020-05-30T07:15:18.000Z
src/point.cpp
ITFS777/GreedySnake
c07a22ede63a8c4f42bc6af2d8c8c95cd46b0311
[ "MIT" ]
null
null
null
src/point.cpp
ITFS777/GreedySnake
c07a22ede63a8c4f42bc6af2d8c8c95cd46b0311
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include "point.h" #include "cursor.h" //////////////////////////////////////////////////////////////////////////////// Point Point::setPos(int px, int py) { x = px; y = py; return *this; } //////////////////////////////////////////////////////////////////////////////// Point Point::print(string str) const { SetCursorPosition(x, y); std::cout << str; return *this; } //////////////////////////////////////////////////////////////////////////////// Point Point::clear(void) const { SetCursorPosition(x, y); std::cout << " "; return *this; } //////////////////////////////////////////////////////////////////////////////// Point Point::setCursorHere(void) const { SetCursorPosition(x, y); return *this; } //////////////////////////////////////////////////////////////////////////////// Point Point::move(int movement_x, int movement_y) { x += movement_x; y += movement_y; return *this; }
25.868421
80
0.364191
ASjet
4f27ecd1cb71c6a135ca2cb4186af73b73d21aaf
6,378
cpp
C++
clang/test/CodeGenCXX/reference-cast.cpp
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
2,338
2018-06-19T17:34:51.000Z
2022-03-31T11:00:37.000Z
clang/test/CodeGenCXX/reference-cast.cpp
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
3,740
2019-01-23T15:36:48.000Z
2022-03-31T22:01:13.000Z
clang/test/CodeGenCXX/reference-cast.cpp
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
500
2019-01-23T07:49:22.000Z
2022-03-30T02:59:37.000Z
// RUN: %clang_cc1 -emit-llvm -triple x86_64-apple-darwin10 -o - %s | FileCheck %s // PR6024 extern int i; // CHECK: define{{.*}} nonnull align {{[0-9]+}} dereferenceable({{[0-9]+}}) i32* @_Z16lvalue_noop_castv() [[NUW:#[0-9]+]] const int &lvalue_noop_cast() { if (i == 0) // CHECK: store i32 17, i32* return (const int&)17; else if (i == 1) // CHECK: store i32 17, i32* return static_cast<const int&>(17); // CHECK: store i32 17, i32* return 17; } // CHECK-LABEL: define{{.*}} nonnull align {{[0-9]+}} dereferenceable({{[0-9]+}}) i16* @_Z20lvalue_integral_castv() const short &lvalue_integral_cast() { if (i == 0) // CHECK: store i16 17, i16* return (const short&)17; else if (i == 1) // CHECK: store i16 17, i16* return static_cast<const short&>(17); // CHECK: store i16 17, i16* return 17; } // CHECK-LABEL: define{{.*}} nonnull align {{[0-9]+}} dereferenceable({{[0-9]+}}) i16* @_Z29lvalue_floating_integral_castv() const short &lvalue_floating_integral_cast() { if (i == 0) // CHECK: store i16 17, i16* return (const short&)17.5; else if (i == 1) // CHECK: store i16 17, i16* return static_cast<const short&>(17.5); // CHECK: store i16 17, i16* return 17.5; } // CHECK-LABEL: define{{.*}} nonnull align {{[0-9]+}} dereferenceable({{[0-9]+}}) float* @_Z29lvalue_integral_floating_castv() const float &lvalue_integral_floating_cast() { if (i == 0) // CHECK: store float 1.700000e+{{0*}}1, float* return (const float&)17; else if (i == 1) // CHECK: store float 1.700000e+{{0*}}1, float* return static_cast<const float&>(17); // CHECK: store float 1.700000e+{{0*}}1, float* return 17; } // CHECK-LABEL: define{{.*}} nonnull align {{[0-9]+}} dereferenceable({{[0-9]+}}) float* @_Z20lvalue_floating_castv() const float &lvalue_floating_cast() { if (i == 0) // CHECK: store float 1.700000e+{{0*}}1, float* return (const float&)17.0; else if (i == 1) // CHECK: store float 1.700000e+{{0*}}1, float* return static_cast<const float&>(17.0); // CHECK: store float 1.700000e+{{0*}}1, float* return 17.0; } int get_int(); // CHECK-LABEL: define{{.*}} nonnull align {{[0-9]+}} dereferenceable({{[0-9]+}}) i8* @_Z24lvalue_integer_bool_castv() const bool &lvalue_integer_bool_cast() { if (i == 0) // CHECK: call i32 @_Z7get_intv() // CHECK: store i8 return (const bool&)get_int(); else if (i == 1) // CHECK: call i32 @_Z7get_intv() // CHECK: store i8 return static_cast<const bool&>(get_int()); // CHECK: call i32 @_Z7get_intv() // CHECK: store i8 return get_int(); } float get_float(); // CHECK-LABEL: define{{.*}} nonnull align {{[0-9]+}} dereferenceable({{[0-9]+}}) i8* @_Z25lvalue_floating_bool_castv() const bool &lvalue_floating_bool_cast() { if (i == 0) // CHECK: call float @_Z9get_floatv() // CHECK: fcmp une float // CHECK: store i8 return (const bool&)get_float(); else if (i == 1) // CHECK: call float @_Z9get_floatv() // CHECK: fcmp une float // CHECK: store i8 return static_cast<const bool&>(get_float()); // CHECK: call float @_Z9get_floatv() // CHECK: fcmp une float // CHECK: store i8 return get_float(); } struct X { }; typedef int X::*pm; typedef int (X::*pmf)(int); pm get_pointer_to_member_data(); pmf get_pointer_to_member_function(); // CHECK-LABEL: define{{.*}} nonnull align {{[0-9]+}} dereferenceable({{[0-9]+}}) i8* @_Z26lvalue_ptrmem_to_bool_castv() const bool &lvalue_ptrmem_to_bool_cast() { if (i == 0) // CHECK: call i64 @_Z26get_pointer_to_member_datav() // CHECK: store i8 // CHECK: store i8* return (const bool&)get_pointer_to_member_data(); else if (i == 1) // CHECK: call i64 @_Z26get_pointer_to_member_datav() // CHECK: store i8 // CHECK: store i8* return static_cast<const bool&>(get_pointer_to_member_data()); // CHECK: call i64 @_Z26get_pointer_to_member_datav() // CHECK: store i8 // CHECK: store i8* return get_pointer_to_member_data(); } // CHECK-LABEL: define{{.*}} nonnull align {{[0-9]+}} dereferenceable({{[0-9]+}}) i8* @_Z27lvalue_ptrmem_to_bool_cast2v const bool &lvalue_ptrmem_to_bool_cast2() { if (i == 0) // CHECK: {{call.*_Z30get_pointer_to_member_functionv}} // CHECK: store i8 // CHECK: store i8* return (const bool&)get_pointer_to_member_function(); else if (i == 1) // CHECK: {{call.*_Z30get_pointer_to_member_functionv}} // CHECK: store i8 // CHECK: store i8* return static_cast<const bool&>(get_pointer_to_member_function()); // CHECK: {{call.*_Z30get_pointer_to_member_functionv}} // CHECK: store i8 // CHECK: store i8* return get_pointer_to_member_function(); } _Complex double get_complex_double(); // CHECK: {{define.*_Z2f1v}} const _Complex float &f1() { if (i == 0) // CHECK: {{call.*_Z18get_complex_doublev}} // CHECK: fptrunc // CHECK: fptrunc // CHECK: store float // CHECK: store float return (const _Complex float&)get_complex_double(); else if (i == 1) // CHECK: {{call.*_Z18get_complex_doublev}} // CHECK: fptrunc // CHECK: fptrunc // CHECK: store float // CHECK: store float return static_cast<const _Complex float&>(get_complex_double()); // CHECK: {{call.*_Z18get_complex_doublev}} // CHECK: fptrunc // CHECK: fptrunc // CHECK: store float // CHECK: store float return get_complex_double(); } // CHECK-LABEL: define{{.*}} i32 @_Z7pr10592RKi(i32* unsigned pr10592(const int &v) { // CHECK: [[VADDR:%[a-zA-Z0-9.]+]] = alloca i32* // CHECK-NEXT: [[REFTMP:%[a-zA-Z0-9.]+]] = alloca i32 // CHECK-NEXT: store i32* [[V:%[a-zA-Z0-9.]+]], i32** [[VADDR]] // CHECK-NEXT: [[VADDR_1:%[a-zA-Z0-9.]+]] = load i32*, i32** [[VADDR]] // CHECK-NEXT: [[VVAL:%[a-zA-Z0-9.]+]] = load i32, i32* [[VADDR_1]] // CHECK-NEXT: store i32 [[VVAL]], i32* [[REFTMP]] // CHECK-NEXT: [[VVAL_I:%[a-zA-Z0-9.]+]] = load i32, i32* [[REFTMP]] // CHECK-NEXT: ret i32 [[VVAL_I]] return static_cast<const unsigned &>(v); } namespace PR10650 { struct Helper { unsigned long long id(); }; unsigned long long test(Helper *obj) { return static_cast<const unsigned long long&>(obj->id()); } // CHECK-LABEL: define{{.*}} i64 @_ZN7PR106504testEPNS_6HelperE // CHECK: store i64 } // CHECK: attributes [[NUW]] = { mustprogress noinline nounwind{{.*}} }
32.375635
126
0.6328
mkinsner
4f28ed79035c5618b5d7b8c757caa1390ed920f6
13,010
cc
C++
src/yb/util/decimal.cc
pritamdamania87/yugabyte-db
70355f6c9248356e84cf21588013ea477fd04a5d
[ "Apache-2.0", "CC0-1.0" ]
1
2021-01-15T00:24:31.000Z
2021-01-15T00:24:31.000Z
src/yb/util/decimal.cc
pritamdamania87/yugabyte-db
70355f6c9248356e84cf21588013ea477fd04a5d
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
src/yb/util/decimal.cc
pritamdamania87/yugabyte-db
70355f6c9248356e84cf21588013ea477fd04a5d
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
// Copyright (c) YugaByte, 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. // #include <vector> #include <limits> #include <iomanip> #include <glog/logging.h> #include "yb/gutil/strings/substitute.h" #include "yb/util/decimal.h" using std::string; using std::vector; namespace yb { namespace util { void Decimal::clear() { digits_ = {}; exponent_ = VarInt(0); is_positive_ = true; } string Decimal::ToDebugString() const { string output = "[ "; output += is_positive_ ? "+" : "-"; output += " 10^"; output += exponent_.is_positive_ ? "+" : ""; output += exponent_.ToString() + " * 0."; for (int digit : digits_) { output += '0' + digit; } output += " ]"; return output; } Status Decimal::ToPointString(string* string_val, const int max_length) const { if (digits_.empty()) { *string_val = "0"; return Status::OK(); } int64_t exponent = 0; RETURN_NOT_OK(exponent_.ToInt64(&exponent)); if (exponent > max_length || exponent < -max_length) { return STATUS_SUBSTITUTE(InvalidArgument, "Max length $0 too small to encode decimal with exponent $1", max_length, exponent); } string output; if (!is_positive_) { output = "-"; } if (exponent <= 0) { output += "0."; for (int i = 0; i < -exponent; i++) { output.push_back('0'); } for (size_t i = 0; i < digits_.size(); i++) { output.push_back('0' + digits_[i]); if (output.size() > max_length) { return STATUS_SUBSTITUTE(InvalidArgument, "Max length $0 too small to encode Decimal", max_length); } } } else { for (size_t i = 0; i < digits_.size(); i++) { if (exponent == i) { output.push_back('.'); } output.push_back('0' + digits_[i]); if (output.size() > max_length) { return STATUS_SUBSTITUTE(InvalidArgument, "Max length $0 too small to encode Decimal", max_length); } } for (size_t i = digits_.size(); i < exponent; i++) { output.push_back('0'); if (output.size() > max_length) { return STATUS_SUBSTITUTE(InvalidArgument, "Max length $0 too small to encode Decimal", max_length); } } } *string_val = std::move(output); return Status::OK(); } string Decimal::ToScientificString() const { if (digits_.empty()) { return "0"; } string output; if (!is_positive_) { output = "-"; } output.push_back('0' + digits_[0]); output.push_back('.'); for (size_t i = 1; i < digits_.size(); i++) { output.push_back('0' + digits_[i]); } output.push_back('e'); VarInt exponent = exponent_ + VarInt(-1); if (exponent.is_positive_) { output += "+"; } output += exponent.ToString(); return output; } string Decimal::ToString() const { string output; if (Decimal::ToPointString(&output).ok()) { return output; } else { return ToScientificString(); } } Status Decimal::ToDouble(double* double_val) const { try { *double_val = std::stod(ToString()); } catch (std::exception& e) { // Possible exception types: std::invalid_argument, std::out_of_range. return STATUS(InvalidArgument, e.what()); } return Status::OK(); } Status Decimal::ToVarInt(VarInt *varint_value, const int max_length) const { int64_t exponent = 0; RETURN_NOT_OK(exponent_.ToInt64(&exponent)); if (exponent <= 0) { *varint_value = VarInt(0); return Status::OK(); } if (exponent > max_length) { return STATUS_SUBSTITUTE(InvalidArgument, "Max length $0 too small to convert Decimal to VarInt, need $1", max_length, exponent); } vector<uint8_t> digits(digits_.begin(), digits_.size() > exponent ? digits_.begin() + exponent : digits_.end()); while (digits.size() < exponent) { digits.push_back(0); } std::reverse(digits.begin(), digits.end()); *varint_value = VarInt(digits, 10, is_positive_); return Status::OK(); } Status Decimal::FromString(const Slice &slice) { if (slice.empty()) { return STATUS(InvalidArgument, "Cannot decode empty slice to Decimal"); } is_positive_ = slice[0] != '-'; size_t i = 0; if (slice[0] == '+' || slice[0] == '-') { i++; } bool point_found = false; size_t point_position = 0; digits_.clear(); for (; i < slice.size() && slice[i] != 'e' && slice[i] != 'E'; i++) { if (slice[i] == '.' && !point_found) { point_found = true; point_position = digits_.size(); continue; } if (PREDICT_TRUE(slice[i] >= '0' && slice[i] <= '9')) { digits_.push_back(slice[i]-'0'); } else { return STATUS_SUBSTITUTE( InvalidArgument, "Invalid character $0 found at position $1 when parsing Decimal $2", slice[i], i, slice.ToString()); } } if (PREDICT_FALSE(digits_.empty())) { return STATUS_SUBSTITUTE( InvalidArgument, "There are no digits in the decimal $0 before the e / E", slice.ToString()); } if (!point_found) { point_position = digits_.size(); } if (i < slice.size()) { Slice exponent_slice(slice); exponent_slice.remove_prefix(i+1); RETURN_NOT_OK(exponent_.FromString(exponent_slice)); } else { exponent_ = VarInt(0); } exponent_ = exponent_ + VarInt(static_cast<int64_t> (point_position)); make_canonical(); return Status::OK(); } constexpr size_t kPrecisionLimit = 20; namespace { string StringFromDouble(double double_val, int precision_limit = kPrecisionLimit) { std::stringstream ss; ss << std::setprecision(precision_limit); ss << double_val; return ss.str(); } } // namespace Status Decimal::FromDouble(double double_val) { string str = StringFromDouble(double_val); if (str == "nan") { return STATUS(Corruption, "Cannot convert nan to Decimal"); } else if (str == "inf") { return STATUS(Corruption, "Cannot convert inf to Decimal"); } else if (str == "-inf") { return STATUS(Corruption, "Cannot convert -inf to Decimal"); } return FromString(str); } Status Decimal::FromVarInt(const VarInt &varint_val) { return FromString(varint_val.ToString()); } bool Decimal::is_integer() const { return digits_.empty() || exponent_ >= VarInt(static_cast<int64_t>(digits_.size())); } int Decimal::CompareTo(const Decimal &other) const { if (is_positive_ != other.is_positive_) { return static_cast<int>(is_positive_) - static_cast<int>(other.is_positive_); } int comp; // We must compare zeros in a special way because the exponent logic doesn't work with special // canonicalization for zero. if (digits_.empty() || other.digits_.empty()) { comp = static_cast<int>(digits_.empty()) - static_cast<int>(other.digits_.empty()); return is_positive_ ? -comp : comp; } comp = exponent_.CompareTo(other.exponent_); if (comp != 0) { return is_positive_ ? comp : -comp; } for (size_t i = 0; i < digits_.size() && i < other.digits_.size(); i++) { comp = static_cast<int>(digits_[i]) - static_cast<int>(other.digits_[i]); if (comp != 0) { return is_positive_ ? comp : -comp; } } comp = static_cast<int>(this->digits_.size()) - static_cast<int>(other.digits_.size()); return is_positive_ ? comp : -comp; } string Decimal::EncodeToComparable() const { // Zero is encoded to the special value 128. if (digits_.empty()) { return string(1, 128); } // We reserve two bits for sign: -, zero, and +. Their sign portions are resp. '00', '10', '11'. string exponent = exponent_.EncodeToComparable(/* is_signed */ true, /* num_reserved_bits */ 2); const string mantissa = VarInt(digits_, 10).EncodeToDigitPairs(); string output = exponent + mantissa; // The first two (reserved) bits are set to 1 here. output[0] += 192; // For negatives, everything is complemented (including the sign bits) which were set to 1 above. if (!is_positive_) { for (int i = 0; i < output.size(); i++) { output[i] = ~output[i]; // Bitwise not. } } return output; } Status Decimal::DecodeFromComparable(const Slice& slice, size_t *num_decoded_bytes) { if (slice.empty()) { return STATUS(Corruption, "Cannot decode Decimal from empty slice."); } // Zero is specially decoded from the value 128. if (slice[0] == 128) { clear(); *num_decoded_bytes = 1; return Status::OK(); } // The first bit is enough to decode the sign. is_positive_ = slice[0] >= 128; // We have to complement everything if negative, so we are making a copy. string encoded = slice.ToString(); if (!is_positive_) { for (size_t i = 0; i < encoded.size(); i++) { encoded[i] = ~encoded[i]; } } size_t num_exponent_bytes = 0; RETURN_NOT_OK(exponent_.DecodeFromComparable( encoded, &num_exponent_bytes, /* is signed */ true, /* num_reserved_bits */ 2)); Slice remaining_slice(encoded); remaining_slice.remove_prefix(num_exponent_bytes); VarInt mantissa; size_t num_mantissa_bytes = 0; RETURN_NOT_OK(mantissa.DecodeFromDigitPairs(remaining_slice, &num_mantissa_bytes)); digits_ = vector<uint8_t>(mantissa.digits_.begin(), mantissa.digits_.end()); *num_decoded_bytes = num_exponent_bytes + num_mantissa_bytes; return Status::OK(); } Status Decimal::DecodeFromComparable(const Slice& slice) { size_t num_decoded_bytes; return DecodeFromComparable(slice, &num_decoded_bytes); } Status Decimal::DecodeFromComparable(const string& str) { return DecodeFromComparable(Slice(str)); } string Decimal::EncodeToSerializedBigDecimal(bool* is_out_of_range) const { // Note that BigDecimal's scale is not the same as our exponent, but related by the following: VarInt varint_scale = VarInt(static_cast<int64_t> (digits_.size())) - exponent_; // Must use 4 bytes for the two's complement encoding of the scale. bool is_overflow = false; string scale = varint_scale.EncodeToTwosComplement(&is_overflow, 4); *is_out_of_range = is_overflow; vector<uint8_t> digits(digits_); // VarInt representation needs reversed digits. std::reverse(digits.begin(), digits.end()); // Note that the mantissa varint needs to have the same sign as the current decimal. // Get the digit array in int from int8_t in this class. string mantissa = VarInt(digits, 10, is_positive_).EncodeToTwosComplement(&is_overflow); return scale + mantissa; } Status Decimal::DecodeFromSerializedBigDecimal(const Slice &slice) { if (slice.size() < 5) { return STATUS_SUBSTITUTE( Corruption, "Serialized BigDecimal must have at least 5 bytes. Found $0", slice.size()); } // Decode the scale from the first 4 bytes. VarInt scale; RETURN_NOT_OK(scale.DecodeFromTwosComplement(Slice(slice.data(), 4))); VarInt mantissa; RETURN_NOT_OK(mantissa.DecodeFromTwosComplement(Slice(slice.data() + 4, slice.size() - 4))); // Must convert to base 10 before we can interpret as digits in our Decimal representation mantissa = mantissa.ConvertToBase(10); // The sign of the BigDecimal is the sign of the mantissa is_positive_ = mantissa.is_positive_; digits_ = vector <uint8_t> (mantissa.digits_.begin(), mantissa.digits_.end()); // The varint has the digits in reverse order std::reverse(digits_.begin(), digits_.end()); exponent_ = VarInt(static_cast<int64_t> (digits_.size())) - scale; make_canonical(); return Status::OK(); } bool Decimal::IsIdenticalTo(const Decimal &other) const { return is_positive_ == other.is_positive_ && exponent_ == other.exponent_ && digits_ == other.digits_; } bool Decimal::is_canonical() const { if (digits_.empty()) { return is_positive_ && exponent_ == VarInt(0); } return digits_.front() != 0 && digits_.back() != 0; } void Decimal::make_canonical() { if (is_canonical()) { return; } size_t num_zeros = 0; while (num_zeros < digits_.size() && digits_[num_zeros] == 0) { num_zeros++; } exponent_ = exponent_ - VarInt(num_zeros); for (size_t i = num_zeros; i < digits_.size() + num_zeros; i++) { digits_[i-num_zeros] = i < digits_.size() ? digits_[i] : 0; } while (!digits_.empty() && digits_.back() == 0) { digits_.pop_back(); } if (digits_.empty()) { clear(); } } Decimal DecimalFromComparable(const Slice& slice) { Decimal decimal; CHECK_OK(decimal.DecodeFromComparable(slice)); return decimal; } Decimal DecimalFromComparable(const std::string& str) { return DecimalFromComparable(Slice(str)); } std::ostream& operator<<(ostream& os, const Decimal& d) { os << d.ToString(); return os; } } // namespace util } // namespace yb
31.274038
100
0.661337
pritamdamania87
4f29447f962c137f6be33b5b63db77efaf3c0b91
1,479
cpp
C++
HackerRank/ProblemSolving/cppSolutions/Data Structures/Trees/treePreorderTraversal.cpp
pakosel/competitive-coding-problems
187a2f13725e06ab3301ae2be37f16fbec0c0588
[ "MIT" ]
17
2017-08-12T14:42:46.000Z
2022-02-26T16:35:44.000Z
HackerRank/ProblemSolving/cppSolutions/Data Structures/Trees/treePreorderTraversal.cpp
pakosel/competitive-coding-problems
187a2f13725e06ab3301ae2be37f16fbec0c0588
[ "MIT" ]
21
2019-09-20T07:06:27.000Z
2021-11-02T10:30:50.000Z
HackerRank/ProblemSolving/cppSolutions/Data Structures/Trees/treePreorderTraversal.cpp
pakosel/competitive-coding-problems
187a2f13725e06ab3301ae2be37f16fbec0c0588
[ "MIT" ]
21
2017-05-28T10:15:07.000Z
2021-07-20T07:19:58.000Z
#include <bits/stdc++.h> using namespace std; class Node { public: int data; Node *left; Node *right; Node(int d) { data = d; left = NULL; right = NULL; } }; class Solution { public: Node* insert(Node* root, int data) { if(root == NULL) { return new Node(data); } else { Node* cur; if(data <= root->data) { cur = insert(root->left, data); root->left = cur; } else { cur = insert(root->right, data); root->right = cur; } return root; } } /* you only have to complete the function given below. Node is defined as class Node { public: int data; Node *left; Node *right; Node(int d) { data = d; left = NULL; right = NULL; } }; */ void preOrder(Node *root) { if(root==NULL){ return; } cout<<root->data<<" "; preOrder(root->left); preOrder(root->right); } }; //End of Solution int main() { Solution myTree; Node* root = NULL; int t; int data; std::cin >> t; while(t-- > 0) { std::cin >> data; root = myTree.insert(root, data); } myTree.preOrder(root); return 0; }
18.036585
56
0.415822
pakosel
4f2acf2ee7baf76ba9ec40965975179cc65cc4c0
14,878
cpp
C++
src/InstructionWalker.cpp
Mookel/VC4C
d72978253820e4175fa591206dedda6c586068b3
[ "MIT" ]
null
null
null
src/InstructionWalker.cpp
Mookel/VC4C
d72978253820e4175fa591206dedda6c586068b3
[ "MIT" ]
null
null
null
src/InstructionWalker.cpp
Mookel/VC4C
d72978253820e4175fa591206dedda6c586068b3
[ "MIT" ]
null
null
null
/* * Author: doe300 * * See the file "LICENSE" for the full license governing this code. */ #include "InstructionWalker.h" #include "BasicBlock.h" #include "CompilationError.h" #include "Method.h" #include "analysis/ControlFlowGraph.h" using namespace vc4c; const InstructionWalker tombstone_traits<InstructionWalker>::tombstone; bool InstructionVisitor::visit(const InstructionWalker& start) const { InstructionWalker it(start); while(true) { auto res = op(it); switch(res) { case InstructionVisitResult::CONTINUE: { if(followJumps && it.get<intermediate::Branch>()) { intermediate::Branch* jump = it.get<intermediate::Branch>(); auto jumpIt = it; for(auto target : jump->getTargetLabels()) { if(auto nextBlock = it.getBasicBlock()->method.findBasicBlock(target)) { bool cont = visit(nextBlock->walk()); if(!cont) return false; } } if(jump->isUnconditional()) // the control-flow always jumps, destination is already processed return true; // handle either-or-jumps, check previous instruction intermediate::Branch* prevJump = it.copy().previousInBlock().get<intermediate::Branch>(); auto prevJumpIt = it; if(prevJump != nullptr && jump->branchCondition.isInversionOf(prevJump->branchCondition)) { auto lastBranchCond = it.getBasicBlock()->findLastSettingOfFlags(jumpIt); auto secondLastBranchCond = it.getBasicBlock()->findLastSettingOfFlags(prevJumpIt); if(lastBranchCond == secondLastBranchCond) // the branches are only guaranteed to cover all cases if they refer to the same branch // condition return true; } } if(stopAtBlock) { it.nextInBlock(); if(it.isEndOfBlock()) return true; continue; } else { it.nextInMethod(); if(it.isEndOfMethod()) return true; continue; } } case InstructionVisitResult::STOP_BRANCH: // stop this branch, but continue with other branches return true; case InstructionVisitResult::STOP_ALL: // stop all return false; } throw CompilationError(CompilationStep::GENERAL, "Unhandled case of instruction visiting"); } } bool InstructionVisitor::visitReverse(const InstructionWalker& start, analysis::ControlFlowGraph* blockGraph) const { // FIXME has problems with instructionwalkers freed in Method::cleanEmptyInstructions() (e.g. TestEmulator) InstructionWalker it(start); while(true) { auto res = op(it); switch(res) { case InstructionVisitResult::CONTINUE: { if(!it.isStartOfBlock()) { it.previousInBlock(); continue; } else if(stopAtBlock) { return true; } else if(!followJumps) { it.previousInMethod(); continue; } else // start of block and follow jumps -> follow jumps backwards { bool continueBranches = true; if(blockGraph != nullptr) { // use pre-calculated graph of basic blocks blockGraph->assertNode(it.getBasicBlock()) .forAllIncomingEdges([&continueBranches, this, blockGraph]( const analysis::CFGNode& node, const analysis::CFGEdge& edge) -> bool { // this makes sure, a STOP_ALL skips other predecessors if(continueBranches) continueBranches = visitReverse(edge.data.getPredecessor(node.key), blockGraph); return true; }); } else { // re-calculate predecessor blocks it.getBasicBlock()->forPredecessors([&continueBranches, this](InstructionWalker it) -> void { // this makes sure, a STOP_ALL skips other predecessors if(continueBranches) continueBranches = visitReverse(it); }); } return continueBranches; } } case InstructionVisitResult::STOP_BRANCH: // stop this branch, but continue with other branches return true; case InstructionVisitResult::STOP_ALL: // stop all return false; } throw CompilationError(CompilationStep::GENERAL, "Unhandled case of instruction visiting"); } } InstructionWalker::InstructionWalker() : basicBlock(nullptr), pos(nullptr) {} InstructionWalker::InstructionWalker(BasicBlock* basicBlock, intermediate::InstructionsIterator pos) : basicBlock(basicBlock), pos(pos) { } BasicBlock* InstructionWalker::getBasicBlock() { return basicBlock; } const BasicBlock* InstructionWalker::getBasicBlock() const { return basicBlock; } InstructionWalker& InstructionWalker::nextInBlock() { ++pos; return *this; } InstructionWalker& InstructionWalker::previousInBlock() { --pos; return *this; } InstructionWalker& InstructionWalker::nextInMethod() { if(!isEndOfBlock()) // we need this check since for a linked list it seems that last->next == first, which would jump back to the // label of the block nextInBlock(); if(isEndOfBlock()) { if(auto tmp = basicBlock->method.getNextBlockAfter(basicBlock)) { basicBlock = tmp; pos = basicBlock->instructions.begin(); } } return *this; } InstructionWalker& InstructionWalker::previousInMethod() { previousInBlock(); if(isStartOfBlock()) { if(auto tmp = basicBlock->method.getPreviousBlock(basicBlock)) { basicBlock = tmp; pos = basicBlock->instructions.end(); --pos; } } return *this; } InstructionWalker InstructionWalker::copy() const { return InstructionWalker(basicBlock, pos); } bool InstructionWalker::operator==(const InstructionWalker& other) const { return basicBlock == other.basicBlock && pos == other.pos; } bool InstructionWalker::isEndOfMethod() const { if(basicBlock == nullptr) return true; if(!isEndOfBlock()) return false; const auto& lastBlock = *(--basicBlock->method.end()); return &lastBlock == basicBlock; } bool InstructionWalker::isStartOfMethod() const { return isStartOfBlock() && basicBlock->isStartOfMethod(); } bool InstructionWalker::isEndOfBlock() const { if(basicBlock == nullptr) return true; return pos == basicBlock->instructions.end(); } bool InstructionWalker::isStartOfBlock() const { if(basicBlock == nullptr) return false; return pos == basicBlock->instructions.begin(); } static inline void throwOnEnd(bool isEnd) { if(isEnd) throw CompilationError(CompilationStep::GENERAL, "End of method or block reached!"); } intermediate::IntermediateInstruction* InstructionWalker::get() { throwOnEnd(isEndOfBlock()); return (*pos).get(); } const intermediate::IntermediateInstruction* InstructionWalker::get() const { throwOnEnd(isEndOfBlock()); return (*pos).get(); } intermediate::IntermediateInstruction* InstructionWalker::release() { throwOnEnd(isEndOfBlock()); if(get<intermediate::BranchLabel>()) basicBlock->method.updateCFGOnBlockRemoval(basicBlock); if(get<intermediate::Branch>()) { // need to remove the branch from the block before triggering the CFG update std::unique_ptr<intermediate::IntermediateInstruction> tmp(pos->release()); basicBlock->method.updateCFGOnBranchRemoval( *basicBlock, dynamic_cast<intermediate::Branch*>(tmp.get())->getTargetLabels()); return tmp.release(); } return (*pos).release(); } InstructionWalker& InstructionWalker::reset(intermediate::IntermediateInstruction* instr) { throwOnEnd(isEndOfBlock()); if(dynamic_cast<intermediate::BranchLabel*>(instr) != dynamic_cast<intermediate::BranchLabel*>((*pos).get())) throw CompilationError(CompilationStep::GENERAL, "Can't add labels into a basic block", instr->to_string()); // if we reset the label with another label, the CFG dos not change if(get<intermediate::Branch>()) { // need to remove the branch from the block before triggering the CFG update std::unique_ptr<intermediate::IntermediateInstruction> tmp(pos->release()); basicBlock->method.updateCFGOnBranchRemoval( *basicBlock, dynamic_cast<intermediate::Branch*>(tmp.get())->getTargetLabels()); } (*pos).reset(instr); if(dynamic_cast<intermediate::Branch*>(instr)) basicBlock->method.updateCFGOnBranchInsertion(*this); return *this; } InstructionWalker& InstructionWalker::erase() { throwOnEnd(isEndOfBlock()); if(get<intermediate::BranchLabel>()) basicBlock->method.updateCFGOnBlockRemoval(basicBlock); if(get<intermediate::Branch>()) { // need to remove the branch from the block before triggering the CFG update std::unique_ptr<intermediate::IntermediateInstruction> tmp(pos->release()); basicBlock->method.updateCFGOnBranchRemoval( *basicBlock, dynamic_cast<intermediate::Branch*>(tmp.get())->getTargetLabels()); } pos = basicBlock->instructions.erase(pos); return *this; } InstructionWalker& InstructionWalker::safeErase() { if(!isEndOfBlock() && get() && get()->hasDecoration(intermediate::InstructionDecorations::MANDATORY_DELAY)) { reset((new intermediate::Nop(intermediate::DelayType::WAIT_REGISTER)) ->addDecorations(intermediate::InstructionDecorations::MANDATORY_DELAY)); return nextInBlock(); } return erase(); } InstructionWalker& InstructionWalker::emplace(intermediate::IntermediateInstruction* instr) { if(isStartOfBlock()) throw CompilationError( CompilationStep::GENERAL, "Can't emplace at the start of a basic block", instr->to_string()); if(basicBlock == nullptr) throw CompilationError( CompilationStep::GENERAL, "Can't emplace into an iterator which is not associated with a basic block"); if(dynamic_cast<intermediate::BranchLabel*>(instr) != nullptr) throw CompilationError(CompilationStep::GENERAL, "Can't add labels into a basic block", instr->to_string()); pos = basicBlock->instructions.emplace(pos, instr); if(dynamic_cast<intermediate::Branch*>(instr)) basicBlock->method.updateCFGOnBranchInsertion(*this); return *this; } ConstInstructionWalker::ConstInstructionWalker() : basicBlock(nullptr), pos(nullptr) {} ConstInstructionWalker::ConstInstructionWalker(InstructionWalker it) : basicBlock(it.basicBlock), pos(it.pos) {} ConstInstructionWalker::ConstInstructionWalker( const BasicBlock* basicBlock, intermediate::ConstInstructionsIterator pos) : basicBlock(basicBlock), pos(pos) { } const BasicBlock* ConstInstructionWalker::getBasicBlock() const { return basicBlock; } ConstInstructionWalker& ConstInstructionWalker::nextInBlock() { ++pos; return *this; } ConstInstructionWalker& ConstInstructionWalker::previousInBlock() { --pos; return *this; } ConstInstructionWalker& ConstInstructionWalker::nextInMethod() { if(!isEndOfBlock()) // we need this check since for a linked list it seems that last->next == first, which would jump back to the // label of the block nextInBlock(); if(isEndOfBlock()) { if(auto tmp = basicBlock->method.getNextBlockAfter(basicBlock)) { basicBlock = tmp; pos = basicBlock->instructions.begin(); } } return *this; } bool InstructionWalker::replaceValueInBlock( const Value& oldValue, const Value& newValue, LocalUse::Type type, bool forward, bool stopWhenWritten) { bool replaced = false; auto it = copy(); if(forward) { it.nextInBlock(); while(!it.isEndOfBlock()) { replaced = it->replaceValue(oldValue, newValue, type); if(it->getOutput().has_value() && it->getOutput().value() == oldValue && stopWhenWritten) break; it.nextInBlock(); } } else { it.previousInBlock(); while(!it.isStartOfBlock()) { replaced = it->replaceValue(oldValue, newValue, type); if(it->getOutput().has_value() && it->getOutput().value() == oldValue && stopWhenWritten) break; it.previousInBlock(); } } return replaced; } ConstInstructionWalker& ConstInstructionWalker::previousInMethod() { previousInBlock(); if(isStartOfBlock()) { if(auto tmp = basicBlock->method.getPreviousBlock(basicBlock)) { basicBlock = tmp; pos = basicBlock->instructions.end(); --pos; } } return *this; } ConstInstructionWalker ConstInstructionWalker::copy() const { return ConstInstructionWalker(basicBlock, pos); } bool ConstInstructionWalker::operator==(const ConstInstructionWalker& other) const { return basicBlock == other.basicBlock && pos == other.pos; } bool ConstInstructionWalker::isEndOfMethod() const { if(basicBlock == nullptr) return true; const auto& lastBlock = *(--basicBlock->method.end()); return isEndOfBlock() && &lastBlock == basicBlock; } bool ConstInstructionWalker::isStartOfMethod() const { return isStartOfBlock() && basicBlock->isStartOfMethod(); } bool ConstInstructionWalker::isEndOfBlock() const { if(basicBlock == nullptr) return true; return pos == basicBlock->instructions.end(); } bool ConstInstructionWalker::isStartOfBlock() const { if(basicBlock == nullptr) return false; return pos == basicBlock->instructions.begin(); } const intermediate::IntermediateInstruction* ConstInstructionWalker::get() const { throwOnEnd(isEndOfBlock()); return (*pos).get(); }
31.190776
120
0.617556
Mookel
4f2c7c45a4c6a2a344655c2da31ef6e080d04499
2,810
hpp
C++
libraries/blockchain/include/bts/blockchain/snapshot_state.hpp
jasonqin/bitshares1-core
b575445f31d9d5955414a178b9128fd1a423c3fa
[ "Unlicense" ]
82
2015-01-04T21:11:35.000Z
2015-06-08T17:53:49.000Z
libraries/blockchain/include/bts/blockchain/snapshot_state.hpp
jasonqin/bitshares1-core
b575445f31d9d5955414a178b9128fd1a423c3fa
[ "Unlicense" ]
428
2015-01-01T18:42:04.000Z
2015-06-08T16:08:08.000Z
libraries/blockchain/include/bts/blockchain/snapshot_state.hpp
jasonqin/bitshares1-core
b575445f31d9d5955414a178b9128fd1a423c3fa
[ "Unlicense" ]
53
2015-01-05T02:31:30.000Z
2015-06-05T18:50:57.000Z
#pragma once #include <bts/blockchain/graphene.hpp> #include <bts/blockchain/types.hpp> #include <fc/time.hpp> namespace bts { namespace blockchain { struct snapshot_summary { uint64_t num_balance_owners = 0; uint64_t num_asset_balances = 0; uint64_t num_vesting_balances = 0; uint64_t num_canceled_asks = 0; uint64_t num_canceled_bids = 0; uint64_t num_canceled_shorts = 0; uint64_t num_account_names = 0; uint64_t num_witnesses = 0; uint64_t num_workers = 0; uint64_t num_mias = 0; uint64_t num_collateral_positions = 0; uint64_t num_uias = 0; }; struct snapshot_vesting_balance { time_point_sec start_time; uint32_t duration_seconds = 0; share_type original_balance = 0; share_type current_balance = 0; }; struct snapshot_balance { map<string, share_type> assets; optional<snapshot_vesting_balance> vesting; }; struct snapshot_account { uint32_t id; time_point_sec timestamp; public_key_type owner_key; public_key_type active_key; optional<public_key_type> signing_key; optional<share_type> daily_pay; }; struct snapshot_debt { share_type collateral = 0; share_type debt = 0; }; struct snapshot_asset { uint32_t id; string owner; string description; uint64_t precision = 1; share_type max_supply = 0; share_type collected_fees = 0; map<address, snapshot_debt> debts; }; struct snapshot_state { signed_block_header head_block; share_type max_core_supply = 0; snapshot_summary summary; map<address, snapshot_balance> balances; map<string, snapshot_account> accounts; map<string, snapshot_asset> assets; }; } } // bts::blockchain FC_REFLECT( bts::blockchain::snapshot_summary, (num_balance_owners)(num_asset_balances)(num_vesting_balances) (num_canceled_asks)(num_canceled_bids)(num_canceled_shorts) (num_account_names)(num_witnesses)(num_workers) (num_mias)(num_collateral_positions)(num_uias)) FC_REFLECT( bts::blockchain::snapshot_vesting_balance, (start_time)(duration_seconds)(original_balance)(current_balance) ) FC_REFLECT( bts::blockchain::snapshot_balance, (assets)(vesting) ) FC_REFLECT( bts::blockchain::snapshot_account, (id)(timestamp)(owner_key)(active_key)(signing_key)(daily_pay) ) FC_REFLECT( bts::blockchain::snapshot_debt, (collateral)(debt) ) FC_REFLECT( bts::blockchain::snapshot_asset, (id)(owner)(description)(precision)(max_supply)(collected_fees)(debts) ) FC_REFLECT( bts::blockchain::snapshot_state, (head_block)(max_core_supply)(summary)(balances)(accounts)(assets) )
29.893617
122
0.690036
jasonqin
4f2d49c583b36f4b94fc624a8c5079ed09d03b47
1,030
cpp
C++
unit2/2_2.cpp
Helio452b/essential_Cpp_coding
57ac4b28874da099581054ef6db809fade032c37
[ "MIT" ]
2
2020-05-06T16:27:10.000Z
2020-05-06T16:27:14.000Z
unit2/2_2.cpp
Helio452b/essential_Cpp_coding
57ac4b28874da099581054ef6db809fade032c37
[ "MIT" ]
null
null
null
unit2/2_2.cpp
Helio452b/essential_Cpp_coding
57ac4b28874da099581054ef6db809fade032c37
[ "MIT" ]
2
2020-05-06T16:12:41.000Z
2021-01-20T15:52:52.000Z
#include <iostream> #include <windows.h> #include <vector> #include <string> using namespace std; bool pentagonal_get(int num,vector<int> &vect) { int fx_i; if (num<=0 || num>1024) { return false; } else { for (int i = 1; i <= num; i++) { fx_i = i*(i*3-1)/2; vect.push_back(fx_i); } } return true; } bool vect_printf(vector<int> &vects,string type_str) { cout<<"The type "<<type_str<<" and the pentagonal is:"<<endl; for (int i = 0; i < vects.size(); i++) { cout<<vects[i]<<" "; } cout<<endl<<endl; return true; } int main(void) { vector<int> vect; bool res; int num; cout<<"please enter num"<<endl<<endl; while (cin>>num) { res = pentagonal_get(num,vect); if (res == false) { cout<<"overflow"<<endl; } else { vect_printf(vect,"int"); } vector<int>().swap(vect); } return 0; }
16.349206
65
0.484466
Helio452b
4f2ec7e8b4afeda72473ecf93ed7a7594185e807
15,934
cpp
C++
apiwzem/PnlWzemUsgAAccess.cpp
mpsitech/wzem-WhizniumSBE-Engine-Monitor
0d9a204660bfad57f25dbd641fd86713986f32f1
[ "MIT" ]
null
null
null
apiwzem/PnlWzemUsgAAccess.cpp
mpsitech/wzem-WhizniumSBE-Engine-Monitor
0d9a204660bfad57f25dbd641fd86713986f32f1
[ "MIT" ]
null
null
null
apiwzem/PnlWzemUsgAAccess.cpp
mpsitech/wzem-WhizniumSBE-Engine-Monitor
0d9a204660bfad57f25dbd641fd86713986f32f1
[ "MIT" ]
null
null
null
/** * \file PnlWzemUsgAAccess.cpp * API code for job PnlWzemUsgAAccess (implementation) * \copyright (C) 2016-2020 MPSI Technologies GmbH * \author Alexander Wirthmueller (auto-generation) * \date created: 6 Dec 2020 */ // IP header --- ABOVE #include "PnlWzemUsgAAccess.h" using namespace std; using namespace Sbecore; using namespace Xmlio; /****************************************************************************** class PnlWzemUsgAAccess::VecVDo ******************************************************************************/ uint PnlWzemUsgAAccess::VecVDo::getIx( const string& sref ) { string s = StrMod::lc(sref); if (s == "butnewclick") return BUTNEWCLICK; if (s == "butduplicateclick") return BUTDUPLICATECLICK; if (s == "butdeleteclick") return BUTDELETECLICK; if (s == "butrefreshclick") return BUTREFRESHCLICK; return(0); }; string PnlWzemUsgAAccess::VecVDo::getSref( const uint ix ) { if (ix == BUTNEWCLICK) return("ButNewClick"); if (ix == BUTDUPLICATECLICK) return("ButDuplicateClick"); if (ix == BUTDELETECLICK) return("ButDeleteClick"); if (ix == BUTREFRESHCLICK) return("ButRefreshClick"); return(""); }; /****************************************************************************** class PnlWzemUsgAAccess::ContInf ******************************************************************************/ PnlWzemUsgAAccess::ContInf::ContInf( const uint numFCsiQst ) : Block() { this->numFCsiQst = numFCsiQst; mask = {NUMFCSIQST}; }; bool PnlWzemUsgAAccess::ContInf::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "ContInfWzemUsgAAccess"); else basefound = checkXPath(docctx, basexpath); string itemtag = "ContitemInfWzemUsgAAccess"; if (basefound) { if (extractUintAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "numFCsiQst", numFCsiQst)) add(NUMFCSIQST); }; return basefound; }; set<uint> PnlWzemUsgAAccess::ContInf::comm( const ContInf* comp ) { set<uint> items; if (numFCsiQst == comp->numFCsiQst) insert(items, NUMFCSIQST); return(items); }; set<uint> PnlWzemUsgAAccess::ContInf::diff( const ContInf* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {NUMFCSIQST}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class PnlWzemUsgAAccess::StatApp ******************************************************************************/ PnlWzemUsgAAccess::StatApp::StatApp( const uint ixWzemVExpstate ) : Block() { this->ixWzemVExpstate = ixWzemVExpstate; mask = {IXWZEMVEXPSTATE}; }; bool PnlWzemUsgAAccess::StatApp::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); string srefIxWzemVExpstate; bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "StatAppWzemUsgAAccess"); else basefound = checkXPath(docctx, basexpath); string itemtag = "StatitemAppWzemUsgAAccess"; if (basefound) { if (extractStringAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "srefIxWzemVExpstate", srefIxWzemVExpstate)) { ixWzemVExpstate = VecWzemVExpstate::getIx(srefIxWzemVExpstate); add(IXWZEMVEXPSTATE); }; }; return basefound; }; set<uint> PnlWzemUsgAAccess::StatApp::comm( const StatApp* comp ) { set<uint> items; if (ixWzemVExpstate == comp->ixWzemVExpstate) insert(items, IXWZEMVEXPSTATE); return(items); }; set<uint> PnlWzemUsgAAccess::StatApp::diff( const StatApp* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {IXWZEMVEXPSTATE}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class PnlWzemUsgAAccess::StatShr ******************************************************************************/ PnlWzemUsgAAccess::StatShr::StatShr( const bool ButNewAvail , const bool ButDuplicateAvail , const bool ButDuplicateActive , const bool ButDeleteAvail , const bool ButDeleteActive ) : Block() { this->ButNewAvail = ButNewAvail; this->ButDuplicateAvail = ButDuplicateAvail; this->ButDuplicateActive = ButDuplicateActive; this->ButDeleteAvail = ButDeleteAvail; this->ButDeleteActive = ButDeleteActive; mask = {BUTNEWAVAIL, BUTDUPLICATEAVAIL, BUTDUPLICATEACTIVE, BUTDELETEAVAIL, BUTDELETEACTIVE}; }; bool PnlWzemUsgAAccess::StatShr::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "StatShrWzemUsgAAccess"); else basefound = checkXPath(docctx, basexpath); string itemtag = "StatitemShrWzemUsgAAccess"; if (basefound) { if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButNewAvail", ButNewAvail)) add(BUTNEWAVAIL); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButDuplicateAvail", ButDuplicateAvail)) add(BUTDUPLICATEAVAIL); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButDuplicateActive", ButDuplicateActive)) add(BUTDUPLICATEACTIVE); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButDeleteAvail", ButDeleteAvail)) add(BUTDELETEAVAIL); if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "ButDeleteActive", ButDeleteActive)) add(BUTDELETEACTIVE); }; return basefound; }; set<uint> PnlWzemUsgAAccess::StatShr::comm( const StatShr* comp ) { set<uint> items; if (ButNewAvail == comp->ButNewAvail) insert(items, BUTNEWAVAIL); if (ButDuplicateAvail == comp->ButDuplicateAvail) insert(items, BUTDUPLICATEAVAIL); if (ButDuplicateActive == comp->ButDuplicateActive) insert(items, BUTDUPLICATEACTIVE); if (ButDeleteAvail == comp->ButDeleteAvail) insert(items, BUTDELETEAVAIL); if (ButDeleteActive == comp->ButDeleteActive) insert(items, BUTDELETEACTIVE); return(items); }; set<uint> PnlWzemUsgAAccess::StatShr::diff( const StatShr* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {BUTNEWAVAIL, BUTDUPLICATEAVAIL, BUTDUPLICATEACTIVE, BUTDELETEAVAIL, BUTDELETEACTIVE}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class PnlWzemUsgAAccess::StgIac ******************************************************************************/ PnlWzemUsgAAccess::StgIac::StgIac( const uint TcoFegWidth , const uint TcoFeaWidth , const uint TcoAccWidth ) : Block() { this->TcoFegWidth = TcoFegWidth; this->TcoFeaWidth = TcoFeaWidth; this->TcoAccWidth = TcoAccWidth; mask = {TCOFEGWIDTH, TCOFEAWIDTH, TCOACCWIDTH}; }; bool PnlWzemUsgAAccess::StgIac::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "StgIacWzemUsgAAccess"); else basefound = checkXPath(docctx, basexpath); string itemtag = "StgitemIacWzemUsgAAccess"; if (basefound) { if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TcoFegWidth", TcoFegWidth)) add(TCOFEGWIDTH); if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TcoFeaWidth", TcoFeaWidth)) add(TCOFEAWIDTH); if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "TcoAccWidth", TcoAccWidth)) add(TCOACCWIDTH); }; return basefound; }; void PnlWzemUsgAAccess::StgIac::writeXML( xmlTextWriter* wr , string difftag , bool shorttags ) { if (difftag.length() == 0) difftag = "StgIacWzemUsgAAccess"; string itemtag; if (shorttags) itemtag = "Si"; else itemtag = "StgitemIacWzemUsgAAccess"; xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str()); writeUintAttr(wr, itemtag, "sref", "TcoFegWidth", TcoFegWidth); writeUintAttr(wr, itemtag, "sref", "TcoFeaWidth", TcoFeaWidth); writeUintAttr(wr, itemtag, "sref", "TcoAccWidth", TcoAccWidth); xmlTextWriterEndElement(wr); }; set<uint> PnlWzemUsgAAccess::StgIac::comm( const StgIac* comp ) { set<uint> items; if (TcoFegWidth == comp->TcoFegWidth) insert(items, TCOFEGWIDTH); if (TcoFeaWidth == comp->TcoFeaWidth) insert(items, TCOFEAWIDTH); if (TcoAccWidth == comp->TcoAccWidth) insert(items, TCOACCWIDTH); return(items); }; set<uint> PnlWzemUsgAAccess::StgIac::diff( const StgIac* comp ) { set<uint> commitems; set<uint> diffitems; commitems = comm(comp); diffitems = {TCOFEGWIDTH, TCOFEAWIDTH, TCOACCWIDTH}; for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it); return(diffitems); }; /****************************************************************************** class PnlWzemUsgAAccess::Tag ******************************************************************************/ PnlWzemUsgAAccess::Tag::Tag( const string& Cpt , const string& TxtRecord1 , const string& TxtRecord2 , const string& Trs , const string& TxtShowing1 , const string& TxtShowing2 , const string& TcoFeg , const string& TcoFea , const string& TcoAcc ) : Block() { this->Cpt = Cpt; this->TxtRecord1 = TxtRecord1; this->TxtRecord2 = TxtRecord2; this->Trs = Trs; this->TxtShowing1 = TxtShowing1; this->TxtShowing2 = TxtShowing2; this->TcoFeg = TcoFeg; this->TcoFea = TcoFea; this->TcoAcc = TcoAcc; mask = {CPT, TXTRECORD1, TXTRECORD2, TRS, TXTSHOWING1, TXTSHOWING2, TCOFEG, TCOFEA, TCOACC}; }; bool PnlWzemUsgAAccess::Tag::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "TagWzemUsgAAccess"); else basefound = checkXPath(docctx, basexpath); string itemtag = "TagitemWzemUsgAAccess"; if (basefound) { if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "Cpt", Cpt)) add(CPT); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "TxtRecord1", TxtRecord1)) add(TXTRECORD1); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "TxtRecord2", TxtRecord2)) add(TXTRECORD2); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "Trs", Trs)) add(TRS); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "TxtShowing1", TxtShowing1)) add(TXTSHOWING1); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "TxtShowing2", TxtShowing2)) add(TXTSHOWING2); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "TcoFeg", TcoFeg)) add(TCOFEG); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "TcoFea", TcoFea)) add(TCOFEA); if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "TcoAcc", TcoAcc)) add(TCOACC); }; return basefound; }; /****************************************************************************** class PnlWzemUsgAAccess::DpchAppData ******************************************************************************/ PnlWzemUsgAAccess::DpchAppData::DpchAppData( const string& scrJref , StgIac* stgiac , QryWzemUsgAAccess::StgIac* stgiacqry , const set<uint>& mask ) : DpchAppWzem(VecWzemVDpch::DPCHAPPWZEMUSGAACCESSDATA, scrJref) { if (find(mask, ALL)) this->mask = {SCRJREF, STGIAC, STGIACQRY}; else this->mask = mask; if (find(this->mask, STGIAC) && stgiac) this->stgiac = *stgiac; if (find(this->mask, STGIACQRY) && stgiacqry) this->stgiacqry = *stgiacqry; }; string PnlWzemUsgAAccess::DpchAppData::getSrefsMask() { vector<string> ss; string srefs; if (has(SCRJREF)) ss.push_back("scrJref"); if (has(STGIAC)) ss.push_back("stgiac"); if (has(STGIACQRY)) ss.push_back("stgiacqry"); StrMod::vectorToString(ss, srefs); return(srefs); }; void PnlWzemUsgAAccess::DpchAppData::writeXML( xmlTextWriter* wr ) { xmlTextWriterStartElement(wr, BAD_CAST "DpchAppWzemUsgAAccessData"); xmlTextWriterWriteAttribute(wr, BAD_CAST "xmlns", BAD_CAST "http://www.mpsitech.com/wzem"); if (has(SCRJREF)) writeString(wr, "scrJref", scrJref); if (has(STGIAC)) stgiac.writeXML(wr); if (has(STGIACQRY)) stgiacqry.writeXML(wr); xmlTextWriterEndElement(wr); }; /****************************************************************************** class PnlWzemUsgAAccess::DpchAppDo ******************************************************************************/ PnlWzemUsgAAccess::DpchAppDo::DpchAppDo( const string& scrJref , const uint ixVDo , const set<uint>& mask ) : DpchAppWzem(VecWzemVDpch::DPCHAPPWZEMUSGAACCESSDO, scrJref) { if (find(mask, ALL)) this->mask = {SCRJREF, IXVDO}; else this->mask = mask; this->ixVDo = ixVDo; }; string PnlWzemUsgAAccess::DpchAppDo::getSrefsMask() { vector<string> ss; string srefs; if (has(SCRJREF)) ss.push_back("scrJref"); if (has(IXVDO)) ss.push_back("ixVDo"); StrMod::vectorToString(ss, srefs); return(srefs); }; void PnlWzemUsgAAccess::DpchAppDo::writeXML( xmlTextWriter* wr ) { xmlTextWriterStartElement(wr, BAD_CAST "DpchAppWzemUsgAAccessDo"); xmlTextWriterWriteAttribute(wr, BAD_CAST "xmlns", BAD_CAST "http://www.mpsitech.com/wzem"); if (has(SCRJREF)) writeString(wr, "scrJref", scrJref); if (has(IXVDO)) writeString(wr, "srefIxVDo", VecVDo::getSref(ixVDo)); xmlTextWriterEndElement(wr); }; /****************************************************************************** class PnlWzemUsgAAccess::DpchEngData ******************************************************************************/ PnlWzemUsgAAccess::DpchEngData::DpchEngData() : DpchEngWzem(VecWzemVDpch::DPCHENGWZEMUSGAACCESSDATA) { feedFCsiQst.tag = "FeedFCsiQst"; }; string PnlWzemUsgAAccess::DpchEngData::getSrefsMask() { vector<string> ss; string srefs; if (has(SCRJREF)) ss.push_back("scrJref"); if (has(CONTINF)) ss.push_back("continf"); if (has(FEEDFCSIQST)) ss.push_back("feedFCsiQst"); if (has(STATAPP)) ss.push_back("statapp"); if (has(STATSHR)) ss.push_back("statshr"); if (has(STGIAC)) ss.push_back("stgiac"); if (has(TAG)) ss.push_back("tag"); if (has(RST)) ss.push_back("rst"); if (has(STATAPPQRY)) ss.push_back("statappqry"); if (has(STATSHRQRY)) ss.push_back("statshrqry"); if (has(STGIACQRY)) ss.push_back("stgiacqry"); StrMod::vectorToString(ss, srefs); return(srefs); }; void PnlWzemUsgAAccess::DpchEngData::readXML( xmlXPathContext* docctx , string basexpath , bool addbasetag ) { clear(); bool basefound; if (addbasetag) basefound = checkUclcXPaths(docctx, basexpath, basexpath, "DpchEngWzemUsgAAccessData"); else basefound = checkXPath(docctx, basexpath); if (basefound) { if (extractStringUclc(docctx, basexpath, "scrJref", "", scrJref)) add(SCRJREF); if (continf.readXML(docctx, basexpath, true)) add(CONTINF); if (feedFCsiQst.readXML(docctx, basexpath, true)) add(FEEDFCSIQST); if (statapp.readXML(docctx, basexpath, true)) add(STATAPP); if (statshr.readXML(docctx, basexpath, true)) add(STATSHR); if (stgiac.readXML(docctx, basexpath, true)) add(STGIAC); if (tag.readXML(docctx, basexpath, true)) add(TAG); if (rst.readXML(docctx, basexpath, true)) add(RST); if (statappqry.readXML(docctx, basexpath, true)) add(STATAPPQRY); if (statshrqry.readXML(docctx, basexpath, true)) add(STATSHRQRY); if (stgiacqry.readXML(docctx, basexpath, true)) add(STGIACQRY); } else { continf = ContInf(); feedFCsiQst.clear(); statapp = StatApp(); statshr = StatShr(); stgiac = StgIac(); tag = Tag(); rst.clear(); statappqry = QryWzemUsgAAccess::StatApp(); statshrqry = QryWzemUsgAAccess::StatShr(); stgiacqry = QryWzemUsgAAccess::StgIac(); }; };
29.076642
135
0.654324
mpsitech
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
324
Edit dataset card