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
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
ed7b0576bda202465cadb697b22a494c2857d554
735
cpp
C++
aoj/aoj_1147.cpp
Doarakko/competitive-programming
5ae78c501664af08a3f16c81dbd54c68310adec8
[ "MIT" ]
1
2017-07-11T16:47:29.000Z
2017-07-11T16:47:29.000Z
icpc/icpc_2007_d_a.cpp
Doarakko/Competitive-Programming
10642a4bd7266c828dd2fc6e311284e86bdf2968
[ "MIT" ]
1
2021-02-07T09:10:26.000Z
2021-02-07T09:10:26.000Z
icpc/icpc_2007_d_a.cpp
Doarakko/Competitive-Programming
10642a4bd7266c828dd2fc6e311284e86bdf2968
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main(int argc, const char * argv[]) { int n, p; int max, min, sum, avg; while (cin >> n, n) { //初期化 sum = 0; for (int i = 0; i < n; i++) { //入力 cin >> p; sum += p; //1つ目の入力 if(i == 0){ min = p; max = p; } //最大値・最小値更新 if(max < p){ max = p; }else if(min > p){ min = p; } } //平均の計算 avg = (sum-(min + max)) / (n - 2); //出力 cout << avg << endl; } return 0; }
18.375
42
0.280272
Doarakko
ed7c46d25402b96e26ac7d1eff52663acb8ce51a
784
hh
C++
Mu2eUtilities/inc/particleEnteringG4Volume.hh
AndrewEdmonds11/Offline
99d525aa55a477fb3f21826ac817224c25cda040
[ "Apache-2.0" ]
1
2021-06-25T00:00:12.000Z
2021-06-25T00:00:12.000Z
Mu2eUtilities/inc/particleEnteringG4Volume.hh
AndrewEdmonds11/Offline
99d525aa55a477fb3f21826ac817224c25cda040
[ "Apache-2.0" ]
null
null
null
Mu2eUtilities/inc/particleEnteringG4Volume.hh
AndrewEdmonds11/Offline
99d525aa55a477fb3f21826ac817224c25cda040
[ "Apache-2.0" ]
1
2020-05-27T22:33:52.000Z
2020-05-27T22:33:52.000Z
// A function to find the SimParticle that entered the volume // (e.g. the gas in the straw) and is "responsible" for making a // StepPointMC. This aggregates showers inside a volume back to the // particle that caused it. // // Andrei Gaponenko, 2014 #ifndef Mu2eUtilities_inc_particleEnteringG4Volume_hh #define Mu2eUtilities_inc_particleEnteringG4Volume_hh #include "canvas/Persistency/Common/Ptr.h" #include "MCDataProducts/inc/SimParticle.hh" #include "MCDataProducts/inc/StepPointMC.hh" #include "MCDataProducts/inc/StrawGasStep.hh" namespace mu2e{ art::Ptr<mu2e::SimParticle> particleEnteringG4Volume(const StepPointMC& step); art::Ptr<mu2e::SimParticle> particleEnteringG4Volume(const StrawGasStep& step); } #endif /* Mu2eUtilities_inc_particleEnteringG4Volume_hh */
35.636364
81
0.80102
AndrewEdmonds11
142e5c13f24aa664a9fe0e76c1db039b80f80f62
690
hpp
C++
include/RED4ext/Types/generated/cp/TestPlatformController.hpp
Sombra0xCC/RED4ext.SDK
218b411991ed0b7cb7acd5efdddd784f31c66f20
[ "MIT" ]
1
2021-02-01T23:07:50.000Z
2021-02-01T23:07:50.000Z
include/RED4ext/Types/generated/cp/TestPlatformController.hpp
Sombra0xCC/RED4ext.SDK
218b411991ed0b7cb7acd5efdddd784f31c66f20
[ "MIT" ]
null
null
null
include/RED4ext/Types/generated/cp/TestPlatformController.hpp
Sombra0xCC/RED4ext.SDK
218b411991ed0b7cb7acd5efdddd784f31c66f20
[ "MIT" ]
null
null
null
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/REDhash.hpp> #include <RED4ext/Types/SimpleTypes.hpp> #include <RED4ext/Types/generated/game/Object.hpp> namespace RED4ext { namespace cp { struct TestPlatformController : game::Object { static constexpr const char* NAME = "cpTestPlatformController"; static constexpr const char* ALIAS = NAME; NodeRef platform; // 228 NodeRef pointA; // 230 NodeRef pointB; // 238 float speed; // 240 uint8_t unk244[0x248 - 0x244]; // 244 }; RED4EXT_ASSERT_SIZE(TestPlatformController, 0x248); } // namespace cp } // namespace RED4ext
24.642857
67
0.727536
Sombra0xCC
1430c63236d13f48e1932ed4c536f565db1eb44a
1,261
cpp
C++
Source/Cross/Feature/MoFeatureResource/FLoaderMonitor.cpp
favedit/MoCross
2a550b3d41b0c33c44c66dd595e84b0e4ee95b08
[ "Apache-2.0" ]
3
2016-10-26T11:48:58.000Z
2017-10-24T18:35:17.000Z
Source/Cross/Feature/MoFeatureResource/FLoaderMonitor.cpp
favedit/MoCross
2a550b3d41b0c33c44c66dd595e84b0e4ee95b08
[ "Apache-2.0" ]
null
null
null
Source/Cross/Feature/MoFeatureResource/FLoaderMonitor.cpp
favedit/MoCross
2a550b3d41b0c33c44c66dd595e84b0e4ee95b08
[ "Apache-2.0" ]
6
2015-03-24T06:40:20.000Z
2019-03-18T13:56:13.000Z
#include "MoFrLoader.h" MO_NAMESPACE_BEGIN MO_CLASS_IMPLEMENT_INHERITS(FLoaderMonitor, FMonitor); //============================================================ // <T>构造加载器工作器。</T> //============================================================ FLoaderMonitor::FLoaderMonitor(){ } //============================================================ // <T>析构加载器工作器。</T> //============================================================ FLoaderMonitor::~FLoaderMonitor(){ } //============================================================ // <T>数据处理。</T> // // @return 处理结果 //============================================================ TResult FLoaderMonitor::Process(){ TResult result = ESuccess; //............................................................ // 获取处理对象 FLoader* pLoader = RLoaderManager::Instance().PopWaitLoader(); if(pLoader != NULL){ // 处理资源 if(pLoader->Process()){ MO_DEBUG(TC("Process loader success. (loader=0x%08X)"), pLoader); }else{ MO_ERROR(TC("Process loader failure. (loader=0x%08X)"), pLoader); result = EFailure; } // 释放资源 pLoader->ReferDecrease(); } //............................................................ return result; } MO_NAMESPACE_END
28.022222
74
0.38065
favedit
1433101dfa119a0fd1c5153c2160e76782e16cc2
811
hpp
C++
v3/include/AsyncSetAction.hpp
iwillusethenameaslongasican/etcd-cpp-apiv3-lua
f425578d59d66c124f8b946f49e0d17e7a79e287
[ "BSD-3-Clause" ]
null
null
null
v3/include/AsyncSetAction.hpp
iwillusethenameaslongasican/etcd-cpp-apiv3-lua
f425578d59d66c124f8b946f49e0d17e7a79e287
[ "BSD-3-Clause" ]
null
null
null
v3/include/AsyncSetAction.hpp
iwillusethenameaslongasican/etcd-cpp-apiv3-lua
f425578d59d66c124f8b946f49e0d17e7a79e287
[ "BSD-3-Clause" ]
null
null
null
#ifndef __ASYNC_SET_HPP__ #define __ASYNC_SET_HPP__ #include <grpc++/grpc++.h> #include "proto/rpc.grpc.pb.h" #include "v3/include/Action.hpp" #include "v3/include/AsyncTxnResponse.hpp" #include "etcd/Response.hpp" #include <unordered_map> #include <vector> using grpc::ClientAsyncResponseReader; using etcdserverpb::TxnResponse; using etcdserverpb::KV; using string_map = std::unordered_map<std::string, std::string>; namespace etcdv3 { class AsyncSetAction : public etcdv3::Action { public: AsyncSetAction(etcdv3::ActionParameters param, CompletionQueue* cq, unsigned long token, bool create=false); etcd::Response ParseResponse(); private: TxnResponse reply; std::unique_ptr<ClientAsyncResponseReader<TxnResponse>> response_reader; bool isCreate; }; } #endif
24.575758
114
0.747226
iwillusethenameaslongasican
14377e76afafbd2398bb7eedfd56b12927d1b436
13,656
cpp
C++
src/glhelper/glhelper_glfw.cpp
louishobson/GLHelper
2a914dd90eeb96797e3963f94d39b25625d47054
[ "Apache-2.0" ]
null
null
null
src/glhelper/glhelper_glfw.cpp
louishobson/GLHelper
2a914dd90eeb96797e3963f94d39b25625d47054
[ "Apache-2.0" ]
null
null
null
src/glhelper/glhelper_glfw.cpp
louishobson/GLHelper
2a914dd90eeb96797e3963f94d39b25625d47054
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2020 Louis Hobson <louis-hobson@hotmail.co.uk>. All Rights Reserved. * * Distributed under MIT licence as a part of the GLHelper C++ library. * For details, see: https://github.com/louishobson/GLHelper/blob/master/LICENSE * * src/glhelper/glhelper_glfw.cpp * * implementation of src/glhelper_glfw.hpp * */ /* INCLUDES */ /* include glhelper_glfw.hpp */ #include <glhelper/glhelper_glfw.hpp> /* WINDOW IMPLEMENTATION */ /* CONSTRUCTORS AND DESTRUCTORS */ /* constructor * * creates a working glfw window * glad will be implicity loaded to the window's context */ glh::glfw::window::window ( const std::string& title, const unsigned width, const unsigned height, const unsigned msaa_samples ) : managed { true } { /* register object */ register_object (); /* hint at number of samples */ glfwWindowHint ( GLFW_SAMPLES, msaa_samples ); /* create window */ winptr = glfwCreateWindow ( width, height, title.c_str (), NULL, NULL ); /* check success */ if ( !winptr ) { /* failed to create window, so produce error */ throw exception::glfw_exception { "GLH ERROR: failed to create GLFW window" }; } /* make window current */ make_current (); /* set current viewport size */ glfwSetWindowSize ( winptr, width, height ); /* poll events to generate previous dimensions/mouseinfo/etc storage */ poll_events (); /* finally swap the buffer */ swap_buffers (); } /* from pointer constructor * * constructs from pointer to already configured GLFWwindow * * _winptr: pointer to GLFWwindow * _managed: whether the window should be deleted on destruction of the object (defaults to true) */ glh::glfw::window::window ( GLFWwindow * _winptr, const bool _managed ) : winptr { _winptr } , managed { _managed } { /* register object */ register_object (); /* check window */ if ( !winptr ) { /* window is invalid, so produce exception */ throw exception::glfw_exception { "GLH ERROR: failed to copy valid GLFW window" }; } } /* destructor */ glh::glfw::window::~window () { /* if managed, destroy window */ if ( managed ) glfwDestroyWindow ( winptr ); /* unregister object */ unregister_object (); } /* EVENT CONTROL */ /* poll_events * * run any callbacks set for events which have occured since the last poll * immediately return even if no events have occured */ void glh::glfw::window::poll_events () { /* make window current, poll events and return */ make_current (); glfwPollEvents (); } /* wait_events * * wait for at least one event to have occured since the last poll, and run associated callbacks * if an event has already occured, this function returns immediately * * timeout: seconds to wait for events before returning (or 0 for infinite timeout) */ void glh::glfw::window::wait_events ( const double timeout ) { /* make window current */ make_current (); /* if timeout == 0, wait forever */ if ( timeout == 0. ) glfwWaitEvents (); /* else, wait on timeout */ else glfwWaitEventsTimeout ( timeout ); } /* post_empty_event * * post an empty event to cause wait event function to return */ void glh::glfw::window::post_empty_event () { /* make window current */ make_current (); /* post empty event and return */ glfwPostEmptyEvent (); } /* should_close * * return: boolean as to whether the window should close or not */ bool glh::glfw::window::should_close () const { /* return if window should close */ return glfwWindowShouldClose ( winptr ); } /* set_should close * * set close flag on window */ void glh::glfw::window::set_should_close () { /* set should close */ glfwSetWindowShouldClose ( winptr, true ); } /* get_dimensions * * get the dimensions of the window * * get_window_pos: set to true if position information is required * * return: dimensions_t containing dimensions info */ glh::glfw::window::dimensions_t glh::glfw::window::get_dimensions ( const bool get_window_pos ) const { /* generate dimension info */ dimensions_t dimensions; glfwGetWindowSize ( winptr, &dimensions.width, &dimensions.height ); dimensions.deltawidth = dimensions.width - prev_dimensions.width; dimensions.deltaheight = dimensions.height - prev_dimensions.height; if ( get_window_pos ) { glfwGetWindowPos ( winptr, &dimensions.xpos, &dimensions.ypos ); dimensions.deltaxpos = dimensions.xpos - prev_dimensions.xpos; dimensions.deltaypos = dimensions.ypos - prev_dimensions.ypos; } /* set prev_dimensions */ prev_dimensions = dimensions; /* return dimensions */ return dimensions; } /* get_key * * test to see if a key was pressed * * key: the GLFW code for the key * * return: GLFW_TRUE/FALSE for if the key has been pressed since last poll */ glh::glfw::window::keyinfo_t glh::glfw::window::get_key ( const int key, const bool get_scancode ) const { /* generate the keyinfo */ keyinfo_t keyinfo; keyinfo.key = key; if ( get_scancode ) keyinfo.scancode = glfwGetKeyScancode ( key ); keyinfo.action = glfwGetKey ( winptr, key ); keyinfo.mods = 0; /* return the keyinfo */ return keyinfo; } /* get_mouseinfo * * get info about the mouse position and its change * * get_fractions: set to true if fraction movement relative to window size is required * * return: mouseinfo_t containing mouse info */ glh::glfw::window::mouseinfo_t glh::glfw::window::get_mouseinfo ( const bool get_frations ) const { /* generate raw mouseinfo */ mouseinfo_t mouseinfo; glfwGetCursorPos ( winptr, &mouseinfo.xpos, &mouseinfo.ypos ); mouseinfo.deltaxpos = mouseinfo.xpos - prev_mouseinfo.xpos; mouseinfo.deltaypos = mouseinfo.ypos - prev_mouseinfo.ypos; /* set fractions in mouse info */ if ( get_frations ) { mouseinfo.xfrac = mouseinfo.xpos / prev_dimensions.width; mouseinfo.yfrac = mouseinfo.ypos / prev_dimensions.height; mouseinfo.deltaxfrac = mouseinfo.deltaxpos / prev_dimensions.width; mouseinfo.deltayfrac = mouseinfo.deltaypos / prev_dimensions.height; } /* set previous mouseinfo */ prev_mouseinfo = mouseinfo; /* return the mouse info */ return mouseinfo; } /* get_timeinfo * * get info about the timings of polls * * return: timeinfo_t containing info about poll times */ glh::glfw::window::timeinfo_t glh::glfw::window::get_timeinfo () const { /* generate timeinfo */ timeinfo_t timeinfo; timeinfo.now = glfwGetTime (); timeinfo.last = prev_timeinfo.now; timeinfo.delta = timeinfo.now - timeinfo.last; /* set prev_timeinfo */ prev_timeinfo = timeinfo; /* return timeinfo */ return timeinfo; } /* get_gamepadinfo * * get info about a gamepad * * joystick: the joystick to get info on * * return gamepadinfo_t containing info about the gamepad */ glh::glfw::window::gamepadinfo_t glh::glfw::window::get_gamepadinfo ( const int joystick ) const { /* create empty struct */ gamepadinfo_t gamepadinfo; std::memset ( &gamepadinfo, 0, sizeof ( gamepadinfo ) ); /* return if gamepad not present */ if ( !glfwJoystickPresent ( joystick ) ) return gamepadinfo; /* if can be mapped to a gamepad, use that */ if ( glfwJoystickIsGamepad ( joystick ) ) { /* generate gamepadinfo */ GLFWgamepadstate glfw_gamepadinfo; glfwGetGamepadState ( joystick, &glfw_gamepadinfo ); /* generate gamepadinfo */ gamepadinfo.button_a = glfw_gamepadinfo.buttons [ GLFW_GAMEPAD_BUTTON_A ]; gamepadinfo.button_b = glfw_gamepadinfo.buttons [ GLFW_GAMEPAD_BUTTON_B ]; gamepadinfo.button_x = glfw_gamepadinfo.buttons [ GLFW_GAMEPAD_BUTTON_X ]; gamepadinfo.button_y = glfw_gamepadinfo.buttons [ GLFW_GAMEPAD_BUTTON_Y ]; gamepadinfo.button_lh_bumper = glfw_gamepadinfo.buttons [ GLFW_GAMEPAD_BUTTON_LEFT_BUMPER ]; gamepadinfo.button_rh_bumper = glfw_gamepadinfo.buttons [ GLFW_GAMEPAD_BUTTON_RIGHT_BUMPER ]; gamepadinfo.button_back = glfw_gamepadinfo.buttons [ GLFW_GAMEPAD_BUTTON_BACK ]; gamepadinfo.button_start = glfw_gamepadinfo.buttons [ GLFW_GAMEPAD_BUTTON_START ]; gamepadinfo.button_lh_thumb = glfw_gamepadinfo.buttons [ GLFW_GAMEPAD_BUTTON_LEFT_THUMB ]; gamepadinfo.button_rh_thumb = glfw_gamepadinfo.buttons [ GLFW_GAMEPAD_BUTTON_RIGHT_THUMB ]; gamepadinfo.button_dpad_up = glfw_gamepadinfo.buttons [ GLFW_GAMEPAD_BUTTON_DPAD_UP ]; gamepadinfo.button_dpad_right = glfw_gamepadinfo.buttons [ GLFW_GAMEPAD_BUTTON_DPAD_RIGHT ]; gamepadinfo.button_dpad_down = glfw_gamepadinfo.buttons [ GLFW_GAMEPAD_BUTTON_DPAD_DOWN ]; gamepadinfo.button_dpad_left = glfw_gamepadinfo.buttons [ GLFW_GAMEPAD_BUTTON_DPAD_LEFT ]; gamepadinfo.axis_lh_x = glfw_gamepadinfo.axes [ GLFW_GAMEPAD_AXIS_LEFT_X ]; gamepadinfo.axis_lh_y = glfw_gamepadinfo.axes [ GLFW_GAMEPAD_AXIS_LEFT_Y ]; gamepadinfo.axis_rh_x = glfw_gamepadinfo.axes [ GLFW_GAMEPAD_AXIS_RIGHT_X ]; gamepadinfo.axis_rh_y = glfw_gamepadinfo.axes [ GLFW_GAMEPAD_AXIS_RIGHT_Y ]; gamepadinfo.axis_lh_trigger = glfw_gamepadinfo.axes [ GLFW_GAMEPAD_AXIS_LEFT_TRIGGER ]; gamepadinfo.axis_rh_trigger = glfw_gamepadinfo.axes [ GLFW_GAMEPAD_AXIS_RIGHT_TRIGGER ]; } else /* otherwise take a guess as to which axis and buttons map to which */ { /* get buttons and set them */ int button_count; const unsigned char * buttons = glfwGetJoystickButtons ( joystick, &button_count ); if ( button_count >= 4 ) { gamepadinfo.button_a = buttons [ 0 ]; gamepadinfo.button_b = buttons [ 1 ]; gamepadinfo.button_x = buttons [ 2 ]; gamepadinfo.button_y = buttons [ 3 ]; } if ( button_count >= 6 ) { gamepadinfo.button_lh_bumper = buttons [ 4 ]; gamepadinfo.button_rh_bumper = buttons [ 5 ]; } if ( button_count >= 8 ) { gamepadinfo.button_back = buttons [ 6 ]; gamepadinfo.button_start = buttons [ 7 ]; } /* get axis and set them */ int axis_count; const float * axis = glfwGetJoystickAxes ( joystick, &axis_count ); if ( axis_count >= 2 ) { gamepadinfo.axis_lh_x = axis [ 0 ]; gamepadinfo.axis_lh_y = axis [ 1 ]; } if ( axis_count >= 4 ) { gamepadinfo.axis_rh_x = axis [ 2 ]; gamepadinfo.axis_rh_y = axis [ 3 ]; } if ( axis_count >= 6 ) { gamepadinfo.axis_lh_trigger = axis [ 4 ]; gamepadinfo.axis_rh_trigger = axis [ 5 ]; } /* get hats and set them */ int hat_count; const unsigned char * hats = glfwGetJoystickHats ( joystick, &hat_count ); if ( hat_count >= 1 ) { gamepadinfo.button_dpad_up = hats [ 0 ] & GLFW_HAT_UP; gamepadinfo.button_dpad_right = hats [ 0 ] & GLFW_HAT_RIGHT; gamepadinfo.button_dpad_down = hats [ 0 ] & GLFW_HAT_DOWN; gamepadinfo.button_dpad_left = hats [ 0 ] & GLFW_HAT_LEFT; } } /* return info */ return gamepadinfo; } /* OTHER INPUT METHODS */ /* set_input_mode * * set the settings of an input mode * * mode: the mode to change * value: the value to change it to */ void glh::glfw::window::set_input_mode ( const int mode, const int value ) { /* set the input mode */ glfwSetInputMode ( winptr, mode, value ); } /* OPENGL WINDOW MANAGEMENT */ /* make_current * * makes the window current */ void glh::glfw::window::make_current () const { /* if window not already current */ if ( !is_current () ) { /* make the context current */ glfwMakeContextCurrent ( winptr ); /* tell the glad loader to load to the current context */ core::glad_loader::load (); } } /* is_current * * checks if the window is current */ bool glh::glfw::window::is_current () const { /* return true of context is current */ return ( glfwGetCurrentContext () == winptr ); } /* swap_buffers * * swap the GLFW buffers */ void glh::glfw::window::swap_buffers () { /* swap the buffers */ glfwSwapBuffers ( winptr ); } /* WINDOW OBJECT LIFETIME MANAGEMENT */ /* static int object_count * * static integer, keeping track of how many objects are currently in existance * is used to know when to initialise or terminate glfw * automatically initialised to 0 */ int glh::glfw::window::object_count = 0; /* register_object * * increment object_count and initialise glfw if necessary */ void glh::glfw::window::register_object () { /* increment object count and initialise glfw if was zero */ if ( object_count++ == 0 ) { /* init glfw */ glfwInit (); /* set version to 3, and only use core OpenGL functionality */ glfwWindowHint ( GLFW_CONTEXT_VERSION_MAJOR, 4 ); glfwWindowHint ( GLFW_CONTEXT_VERSION_MINOR, 4 ); glfwWindowHint ( GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE ); } } /* unregister_object * * decrement object_count and terminate glfw if necessary */ void glh::glfw::window::unregister_object () { /* decrement object count and terminate glfw if is now zero */ if ( --object_count == 0 ) { /* terminate glfw */ glfwTerminate (); } }
28.810127
128
0.661614
louishobson
143b590253685c14ba29c01f828c560643885f3b
7,076
cpp
C++
kortex_driver/src/generated/robot/deviceconfig_proto_converter.cpp
OLdGuann/ros_kortex
a334ce2a9fcbec12b27012f77183a81a75ec6e6e
[ "BSD-3-Clause" ]
89
2018-12-07T20:39:29.000Z
2022-03-18T18:13:31.000Z
kortex_driver/src/generated/robot/deviceconfig_proto_converter.cpp
OLdGuann/ros_kortex
a334ce2a9fcbec12b27012f77183a81a75ec6e6e
[ "BSD-3-Clause" ]
164
2019-01-25T21:43:16.000Z
2022-03-31T03:56:54.000Z
kortex_driver/src/generated/robot/deviceconfig_proto_converter.cpp
OLdGuann/ros_kortex
a334ce2a9fcbec12b27012f77183a81a75ec6e6e
[ "BSD-3-Clause" ]
102
2019-01-25T21:49:05.000Z
2022-03-28T17:20:16.000Z
/* * KINOVA (R) KORTEX (TM) * * Copyright (c) 2019 Kinova inc. All rights reserved. * * This software may be modified and distributed under the * terms of the BSD 3-Clause license. * * Refer to the LICENSE file for details. * */ /* * This file has been auto-generated and should not be modified. */ #include "kortex_driver/generated/robot/deviceconfig_proto_converter.h" int ToProtoData(kortex_driver::DeviceType input, Kinova::Api::DeviceConfig::DeviceType *output) { output->set_device_type((Kinova::Api::Common::DeviceTypes)input.device_type); return 0; } int ToProtoData(kortex_driver::RunMode input, Kinova::Api::DeviceConfig::RunMode *output) { output->set_run_mode((Kinova::Api::DeviceConfig::RunModes)input.run_mode); return 0; } int ToProtoData(kortex_driver::FirmwareVersion input, Kinova::Api::DeviceConfig::FirmwareVersion *output) { output->set_firmware_version(input.firmware_version); return 0; } int ToProtoData(kortex_driver::BootloaderVersion input, Kinova::Api::DeviceConfig::BootloaderVersion *output) { output->set_bootloader_version(input.bootloader_version); return 0; } int ToProtoData(kortex_driver::ModelNumber input, Kinova::Api::DeviceConfig::ModelNumber *output) { output->set_model_number(input.model_number); return 0; } int ToProtoData(kortex_driver::PartNumber input, Kinova::Api::DeviceConfig::PartNumber *output) { output->set_part_number(input.part_number); return 0; } int ToProtoData(kortex_driver::SerialNumber input, Kinova::Api::DeviceConfig::SerialNumber *output) { output->set_serial_number(input.serial_number); return 0; } int ToProtoData(kortex_driver::MACAddress input, Kinova::Api::DeviceConfig::MACAddress *output) { output->set_mac_address(std::string(input.mac_address.begin(), input.mac_address.end())); return 0; } int ToProtoData(kortex_driver::IPv4Settings input, Kinova::Api::DeviceConfig::IPv4Settings *output) { output->set_ipv4_address(input.ipv4_address); output->set_ipv4_subnet_mask(input.ipv4_subnet_mask); output->set_ipv4_default_gateway(input.ipv4_default_gateway); return 0; } int ToProtoData(kortex_driver::PartNumberRevision input, Kinova::Api::DeviceConfig::PartNumberRevision *output) { output->set_part_number_revision(input.part_number_revision); return 0; } int ToProtoData(kortex_driver::PowerOnSelfTestResult input, Kinova::Api::DeviceConfig::PowerOnSelfTestResult *output) { output->set_power_on_self_test_result(input.power_on_self_test_result); return 0; } int ToProtoData(kortex_driver::RebootRqst input, Kinova::Api::DeviceConfig::RebootRqst *output) { output->set_delay(input.delay); return 0; } int ToProtoData(kortex_driver::SafetyInformation input, Kinova::Api::DeviceConfig::SafetyInformation *output) { ToProtoData(input.handle, output->mutable_handle()); output->set_can_change_safety_state(input.can_change_safety_state); output->set_has_warning_threshold(input.has_warning_threshold); output->set_has_error_threshold(input.has_error_threshold); output->set_limit_type((Kinova::Api::DeviceConfig::SafetyLimitType)input.limit_type); output->set_default_warning_threshold(input.default_warning_threshold); output->set_default_error_threshold(input.default_error_threshold); output->set_upper_hard_limit(input.upper_hard_limit); output->set_lower_hard_limit(input.lower_hard_limit); output->set_status((Kinova::Api::Common::SafetyStatusValue)input.status); output->set_unit((Kinova::Api::Common::Unit)input.unit); return 0; } int ToProtoData(kortex_driver::SafetyInformationList input, Kinova::Api::DeviceConfig::SafetyInformationList *output) { output->clear_information(); for(int i = 0; i < input.information.size(); i++) { ToProtoData(input.information[i], output->add_information()); } return 0; } int ToProtoData(kortex_driver::SafetyEnable input, Kinova::Api::DeviceConfig::SafetyEnable *output) { ToProtoData(input.handle, output->mutable_handle()); output->set_enable(input.enable); return 0; } int ToProtoData(kortex_driver::SafetyThreshold input, Kinova::Api::DeviceConfig::SafetyThreshold *output) { ToProtoData(input.handle, output->mutable_handle()); output->set_value(input.value); return 0; } int ToProtoData(kortex_driver::SafetyConfiguration input, Kinova::Api::DeviceConfig::SafetyConfiguration *output) { ToProtoData(input.handle, output->mutable_handle()); output->set_error_threshold(input.error_threshold); output->set_warning_threshold(input.warning_threshold); ToProtoData(input.enable, output->mutable_enable()); return 0; } int ToProtoData(kortex_driver::SafetyConfigurationList input, Kinova::Api::DeviceConfig::SafetyConfigurationList *output) { output->clear_configuration(); for(int i = 0; i < input.configuration.size(); i++) { ToProtoData(input.configuration[i], output->add_configuration()); } return 0; } int ToProtoData(kortex_driver::SafetyStatus input, Kinova::Api::DeviceConfig::SafetyStatus *output) { output->set_value((Kinova::Api::Common::SafetyStatusValue)input.value); return 0; } int ToProtoData(kortex_driver::CalibrationParameter input, Kinova::Api::DeviceConfig::CalibrationParameter *output) { output->set_calibration_parameter_identifier(input.calibration_parameter_identifier); if(input.oneof_value.signedIntValue.size() > 0) { output->set_signedintvalue(input.oneof_value.signedIntValue[0]); } if(input.oneof_value.unsignedIntValue.size() > 0) { output->set_unsignedintvalue(input.oneof_value.unsignedIntValue[0]); } if(input.oneof_value.floatValue.size() > 0) { output->set_floatvalue(input.oneof_value.floatValue[0]); } return 0; } int ToProtoData(kortex_driver::Calibration input, Kinova::Api::DeviceConfig::Calibration *output) { output->set_calibration_item((Kinova::Api::DeviceConfig::CalibrationItem)input.calibration_item); output->clear_calibration_parameter(); for(int i = 0; i < input.calibration_parameter.size(); i++) { ToProtoData(input.calibration_parameter[i], output->add_calibration_parameter()); } return 0; } int ToProtoData(kortex_driver::CalibrationElement input, Kinova::Api::DeviceConfig::CalibrationElement *output) { output->set_calibration_item((Kinova::Api::DeviceConfig::CalibrationItem)input.calibration_item); return 0; } int ToProtoData(kortex_driver::CalibrationResult input, Kinova::Api::DeviceConfig::CalibrationResult *output) { output->set_calibration_status((Kinova::Api::DeviceConfig::CalibrationStatus)input.calibration_status); output->set_calibration_details(input.calibration_details); return 0; } int ToProtoData(kortex_driver::DeviceConfig_CapSenseConfig input, Kinova::Api::DeviceConfig::CapSenseConfig *output) { output->set_mode((Kinova::Api::DeviceConfig::CapSenseMode)input.mode); output->set_threshold_a(input.threshold_a); output->set_threshold_b(input.threshold_b); return 0; } int ToProtoData(kortex_driver::CapSenseRegister input, Kinova::Api::DeviceConfig::CapSenseRegister *output) { output->set_address(input.address); output->set_value(input.value); return 0; }
29.483333
121
0.782504
OLdGuann
143cc1932328fbca0b1487b2660ecd3f651c10d8
2,122
cpp
C++
src/movemanager.cpp
RCP1/evidence-navigation
e2a0e71537bf5b81bbd89855c71ea767bde4ca00
[ "MIT" ]
null
null
null
src/movemanager.cpp
RCP1/evidence-navigation
e2a0e71537bf5b81bbd89855c71ea767bde4ca00
[ "MIT" ]
null
null
null
src/movemanager.cpp
RCP1/evidence-navigation
e2a0e71537bf5b81bbd89855c71ea767bde4ca00
[ "MIT" ]
null
null
null
#include "movemanager.h" using namespace std; MoveManager::MoveManager() { // port "/dev/ttyUSB0", 38400 (standard of RP6), timeout in milliseconds serialhandler_ = new serial::Serial("/dev/ttyUSB0", 38400, serial::Timeout::simpleTimeout(1000)); // Set RTS pin on low for not resetting RP6 serialhandler_->setRTS(false); } MoveManager::~MoveManager() { //dtor } bool MoveManager::initConn() { bool b_opened = !serialhandler_->isOpen(); cout << "Press start now!" << endl; sleep(4); cout << "Done!" << endl; return b_opened; } void MoveManager::closeConn() { serialhandler_->close(); } int MoveManager::rotate(int int_degree) { //TODO return 0; } int MoveManager::move(int int_distance_mm) { //TODO return 0; } int MoveManager::rotateAndMove(int int_degree, int int_distance_mm) { string str_resp; size_t bytes_txrx = 0; char buffer[4]; int int_error_cnt = -1; if(abs(int_degree) > 360 || abs(int_distance_mm) >= 1000) // Not possible return 1; /** * Move command: * ui16_rotation as angle: char[3] * rot_dir: char //2:LEFT, 3:RIGHT * ui16_distance in mm: char[3] * dist_dir: char //0:FWD, 1:BWD * < As End of Command! * > Is sent, if cmd was successful */ sprintf(buffer, "%03d", abs(int_degree)); str_cmd_ = string(buffer); if(int_degree >= 0) str_cmd_ += "2"; else str_cmd_ += "3"; sprintf(buffer, "%03d", abs(int_distance_mm)); str_cmd_ += string(buffer); if(int_distance_mm >= 0) str_cmd_ += "0"; else str_cmd_ += "1"; str_cmd_ += "<"; serialhandler_->flushInput(); // Send do { bytes_txrx = serialhandler_->write(str_cmd_); int_error_cnt++; // Wait for received bytes and read those into string do { bytes_txrx = serialhandler_->read(str_resp, 1); }while(bytes_txrx < 1); // Answer is error? Return error 2 if(int_error_cnt >= 100 || str_resp == "<") break; }while(str_resp != ">"); if(str_resp == ">") return 0; else { cout << "Unable to send command, either wrong format or RP6 did not synchronized" << endl; return 2; } }
19.831776
99
0.636192
RCP1
14409125b86dc0c0bd66197efd1baa8cb7903b7b
1,214
cpp
C++
msg_oob/msg_oob_send.cpp
Shannon1/LinuxBasicSkillPractice
f7fe3bcc1bb7c7207ec5d93f1cb73353c4a36a30
[ "MIT" ]
null
null
null
msg_oob/msg_oob_send.cpp
Shannon1/LinuxBasicSkillPractice
f7fe3bcc1bb7c7207ec5d93f1cb73353c4a36a30
[ "MIT" ]
null
null
null
msg_oob/msg_oob_send.cpp
Shannon1/LinuxBasicSkillPractice
f7fe3bcc1bb7c7207ec5d93f1cb73353c4a36a30
[ "MIT" ]
null
null
null
// // Created by lee on 17-7-22. // #include <iostream> #include <sys/socket.h> #include <csignal> #include <cassert> #include <cstring> #include <unistd.h> #include <netinet/in.h> #include <arpa/inet.h> int main(int argc, char* argv[]) { if (argc <= 2) { std::cout << "Usage:\n" << std::string(argv[0]) << " ip port" << std::endl; return 1; } std::string ip(argv[1]); uint16_t port = (uint16_t)atoi(argv[2]); struct sockaddr_in address; bzero(&address, sizeof(address)); address.sin_family = AF_INET; inet_pton(AF_INET, ip.c_str(), &address.sin_addr); address.sin_port = htons((uint16_t)port); int sock = socket(AF_INET, SOCK_STREAM, 0); assert(sock >= 0); int ec = connect(sock, (struct sockaddr*)&address, sizeof(address)); if (ec < 0) { std::cout << "connect failed!\n"; } else { std::string oob_data = "abc"; std::string normal_data = "123"; send(sock, normal_data.c_str(), normal_data.size(), 0); send(sock, oob_data.c_str(), oob_data.size(), MSG_OOB); send(sock, normal_data.c_str(), normal_data.size(), 0); } close(sock); return 0; }
23.803922
72
0.581549
Shannon1
14413b5bee8dbe9255694dfc9eacd0b5d58cb569
772
cpp
C++
lib/cache/src/Request/Delete.cpp
astateful/dyplat
37c37c7ee9f55cc2a3abaa0f8ebbde34588d2f44
[ "BSD-3-Clause" ]
null
null
null
lib/cache/src/Request/Delete.cpp
astateful/dyplat
37c37c7ee9f55cc2a3abaa0f8ebbde34588d2f44
[ "BSD-3-Clause" ]
null
null
null
lib/cache/src/Request/Delete.cpp
astateful/dyplat
37c37c7ee9f55cc2a3abaa0f8ebbde34588d2f44
[ "BSD-3-Clause" ]
null
null
null
#include "Request/Delete.hpp" namespace astateful { namespace cache { RequestDelete::RequestDelete( const std::string& key, bool reply ) { m_buffer.push_back('d'); m_buffer.push_back('e'); m_buffer.push_back('l'); m_buffer.push_back('e'); m_buffer.push_back('t'); m_buffer.push_back('e'); m_buffer.push_back(' '); m_buffer.insert( m_buffer.end(), key.begin(), key.end() ); if ( !reply ) { m_buffer.push_back( ' ' ); m_buffer.push_back( 'n' ); m_buffer.push_back( 'o' ); m_buffer.push_back( 'r' ); m_buffer.push_back( 'e' ); m_buffer.push_back( 'p' ); m_buffer.push_back( 'l' ); m_buffer.push_back( 'y' ); } m_buffer.push_back( '\r' ); m_buffer.push_back( '\n' ); } } }
24.903226
70
0.591969
astateful
14452f672a7eb5827d7b3d7c6834afdc20aaca0e
2,309
cpp
C++
source/screens/Screen_TimerRechargeMenu.cpp
rbultman/tv-timer
29b0fc9f9d96fc8b1c294d21a51505a1fd2ed9ff
[ "MIT" ]
null
null
null
source/screens/Screen_TimerRechargeMenu.cpp
rbultman/tv-timer
29b0fc9f9d96fc8b1c294d21a51505a1fd2ed9ff
[ "MIT" ]
null
null
null
source/screens/Screen_TimerRechargeMenu.cpp
rbultman/tv-timer
29b0fc9f9d96fc8b1c294d21a51505a1fd2ed9ff
[ "MIT" ]
null
null
null
/* Screen_TimerRechargeMenu.h Author: Rob Bultman License: MIT */ #include <stdio.h> #include "Screen_TimerRechargeMenu.h" #define VSPACING 1 void Screen_TimerRechargeMenu::ButtonEventHandler(lv_obj_t *obj, lv_event_t event) { Screen_TimerRechargeMenu *pScreen = (Screen_TimerRechargeMenu *)lv_obj_get_user_data(obj); lv_obj_t *label = pScreen->startTimerButtonLabel; switch (event) { case LV_EVENT_FOCUSED: puts("Start timer button received focus."); lv_obj_set_style_local_text_color(label, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, LV_COLOR_WHITE); break; case LV_EVENT_DEFOCUSED: puts("Start timer button lost focus."); lv_obj_set_style_local_text_color(label, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, LV_COLOR_BLACK); break; case LV_EVENT_SHORT_CLICKED: puts("Start timer button clicked."); if (pScreen->buttonPressedCallback) { pScreen->buttonPressedCallback(Screen_Menu1Pressed); } break; } } lv_obj_t *Screen_TimerRechargeMenu::CreateScreen(lv_indev_t *pInputDevice, bool hasNextButton, bool hasPreviousButton) { this->ScreenClass::CreateScreen(pInputDevice, hasNextButton, hasPreviousButton); startTimerButton = lv_btn_create(scr, NULL); lv_obj_set_pos(startTimerButton, 0, 0); lv_obj_add_style(startTimerButton, LV_BTN_PART_MAIN, &menuButtonStyle); lv_obj_set_width(startTimerButton, LV_HOR_RES); lv_obj_set_event_cb(startTimerButton, ButtonEventHandler); lv_obj_set_user_data(startTimerButton, this); startTimerButtonLabel = lv_label_create(startTimerButton, NULL); lv_label_set_text(startTimerButtonLabel, "Start Timer"); group = lv_group_create(); lv_group_add_obj(group, startTimerButton); if (hasNextButton) lv_group_add_obj(group, nextButton); if (hasPreviousButton) lv_group_add_obj(group, previousButton); return scr; } void Screen_TimerRechargeMenu::UpdateScreen(time_t currentEpoch, ds3231_alrm_t &alarmTime) { char timeString[128]; GetTimeRemainingString(timeString, currentEpoch, alarmTime); if (strcmp(timeString, "0") == 0) { if (buttonPressedCallback) { buttonPressedCallback(Screen_TimeoutComplete); } } }
30.786667
118
0.727155
rbultman
1449c4966a69734fe17abe949386362511bb5c78
4,951
cpp
C++
src/allCellsDistOrder.cpp
guitargeek/leetcode
7d587774d3f922020b5ba3ca2d533b2686891fed
[ "MIT" ]
null
null
null
src/allCellsDistOrder.cpp
guitargeek/leetcode
7d587774d3f922020b5ba3ca2d533b2686891fed
[ "MIT" ]
null
null
null
src/allCellsDistOrder.cpp
guitargeek/leetcode
7d587774d3f922020b5ba3ca2d533b2686891fed
[ "MIT" ]
null
null
null
/** 1030. Matrix Cells in Distance Order We are given a matrix with R rows and C columns has cells with integer coordinates (r, c), where 0 <= r < R and 0 <= c < C. Additionally, we are given a cell in that matrix with coordinates (r0, c0). Return the coordinates of all cells in the matrix, sorted by their distance from (r0, c0) from smallest distance to largest distance. Here, the distance between two cells (r1, c1) and (r2, c2) is the Manhattan distance, |r1 - r2| + |c1 - c2|. (You may return the answer in any order that satisfies this condition.) Example 1: ``` Input: R = 1, C = 2, r0 = 0, c0 = 0 Output: [[0,0],[0,1]] Explanation: The distances from (r0, c0) to other cells are: [0,1] ``` Example 2: ``` Input: R = 2, C = 2, r0 = 0, c0 = 1 Output: [[0,1],[0,0],[1,1],[1,0]] Explanation: The distances from (r0, c0) to other cells are: [0,1,1,2] The answer [[0,1],[1,1],[0,0],[1,0]] would also be accepted as correct. ``` Example 3: ``` Input: R = 2, C = 3, r0 = 1, c0 = 2 Output: [[1,2],[0,2],[1,1],[0,1],[1,0],[0,0]] Explanation: The distances from (r0, c0) to other cells are: [0,1,1,2,2,3] There are other answers that would also be accepted as correct, such as [[1,2],[1,1],[0,2],[1,0],[0,1],[0,0]]. ``` Note: 1 <= R <= 100 1 <= C <= 100 0 <= r0 < R 0 <= c0 < C */ #include "leet.h" #include <algorithm> #include <numeric> namespace leet { using namespace std; namespace { template <class I1, class I2> void sort_by_key(I1 keys_begin, I1 keys_end, I2 data_begin, I2 data_end) { size_t size = keys_end - keys_begin; std::vector<size_t> p(size, 0); std::vector<size_t> rp(size); std::vector<bool> sorted(size, false); size_t i = 0; // Sort std::iota(p.begin(), p.end(), 0); std::sort(p.begin(), p.end(), [&](size_t i, size_t j) { return *(keys_begin + i) < *(keys_begin + j); }); // ----------- Apply permutation in-place ---------- // // Get reverse permutation item>position for (i = 0; i < size; ++i) { rp[p[i]] = i; } i = 0; typename I1::value_type savedKey; typename I2::value_type savedData; while (i < size) { size_t pos = i; // Save This element; if (!sorted[pos]) { savedKey = *(keys_begin + p[pos]); savedData = *(data_begin + p[pos]); } while (!sorted[pos]) { // Hold item to be replaced typename I1::value_type heldKey = *(keys_begin + pos); typename I2::value_type heldData = *(data_begin + pos); // Save where it should go size_t heldPos = rp[pos]; // Replace *(keys_begin + pos) = savedKey; *(data_begin + pos) = savedData; // Get last item to be the pivot savedKey = heldKey; savedData = heldData; // Mark this item as sorted sorted[pos] = true; // Go to the held item proper location pos = heldPos; } ++i; } } template <class RandomAccessIterator, class Extractor, class Compare> void precomputed_value_sort(RandomAccessIterator begin, RandomAccessIterator end, const Extractor& extr, const Compare& comp) { using Value = typename std::iterator_traits<RandomAccessIterator>::value_type; using Scalar = decltype(extr(*begin)); std::vector<Scalar> keys; keys.reserve(end - begin); for (auto i = begin; i != end; i++) keys.emplace_back(extr(*i)); sort_by_key(keys.begin(), keys.end(), begin, end); } template <class RandomAccessIterator, class Extractor> void precomputed_value_sort(RandomAccessIterator begin, RandomAccessIterator end, const Extractor& extr) { using Scalar = decltype(extr(*begin)); precomputed_value_sort(begin, end, extr, std::less<Scalar>()); } } // namespace vector<vector<int>> allCellsDistOrder(int R, int C, int r0, int c0) { vector<vector<int>> p; for (int r = 0; r < R; ++r) { for (int c = 0; c < C; ++c) { p.push_back({r, c}); } } precomputed_value_sort( p.begin(), p.end(), [&](auto const& p1) { return abs(p1[0] - r0) + abs(p1[1] - c0); }, [](auto const& d1, auto const& d2) { return d1 < d2; }); return p; } } // namespace leet
32.359477
120
0.508584
guitargeek
144e37fe70d8c71812eb63c6491fb5b45e27cc56
4,813
hpp
C++
include/seqan3/range/views/get.hpp
marehr/nomchop
a88bfb6f5d4a291a71b6b3192eeac81fdc450d43
[ "CC-BY-4.0", "CC0-1.0" ]
1
2021-03-01T11:12:56.000Z
2021-03-01T11:12:56.000Z
include/seqan3/range/views/get.hpp
simonsasse/seqan3
0ff2e117952743f081735df9956be4c512f4ccba
[ "CC0-1.0", "CC-BY-4.0" ]
2
2017-05-17T07:16:19.000Z
2020-02-13T16:10:10.000Z
include/seqan3/range/views/get.hpp
simonsasse/seqan3
0ff2e117952743f081735df9956be4c512f4ccba
[ "CC0-1.0", "CC-BY-4.0" ]
null
null
null
// ----------------------------------------------------------------------------------------------------- // Copyright (c) 2006-2020, Knut Reinert & Freie Universität Berlin // Copyright (c) 2016-2020, Knut Reinert & MPI für molekulare Genetik // This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License // shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE.md // ----------------------------------------------------------------------------------------------------- /*!\file * \author Joshua Kim <joshua.kim AT fu-berlin.de> * \brief Provides seqan3::views::get. */ #pragma once #include <seqan3/core/type_traits/basic.hpp> #include <seqan3/core/concept/tuple.hpp> #include <seqan3/std/ranges> namespace seqan3::views { /*!\name General purpose views * \{ */ /*!\brief A view calling std::get on each element in a range. * \tparam size_t The type of the range being processed. See below for requirements. [template parameter is * omitted in pipe notation] * \tparam index The index to get. * \param[in] urange The range being processed. [parameter is omitted in pipe notation] * \returns A range of elements where every element is the result of calling std::get<index> on the underlying element. See below for the properties of the returned range. * \ingroup views * * \details * * \header_file{seqan3/range/views/get.hpp} * * ### View properties * * | Concepts and traits | `urng_t` (underlying range type) | `rrng_t` (returned range type) | * |----------------------------------|:-------------------------------------:|:-------------------------------------------------------:| * | std::ranges::input_range | *required* | *preserved* | * | std::ranges::forward_range | | *preserved* | * | std::ranges::bidirectional_range | | *preserved* | * | std::ranges::random_access_range | | *preserved* | * | std::ranges::contiguous_range | | *lost* | * | | | | * | std::ranges::viewable_range | *required* | *preserved* | * | std::ranges::view | | *preserved* | * | std::ranges::sized_range | | *preserved* | * | std::ranges::common_range | | *preserved* | * | std::ranges::output_range | | *preserved* | * | seqan3::const_iterable_range | | *preserved* | * | | | | * | std::ranges::range_reference_t | seqan3::tuple_like | std::tuple_element_t<index, seqan3::reference_t<urng_t>>| * * See the \link views views submodule documentation \endlink for detailed descriptions of the view properties. * * ### Example * * \include test/snippet/range/views/get.cpp * \hideinitializer */ template <auto index> inline auto const get = std::views::transform([] (auto && in) -> decltype(auto) { using std::get; using seqan3::get; static_assert(tuple_like<decltype(in)>, "You may only pass ranges to views::get whose reference_t models the tuple_like."); // we need to explicitly remove && around temporaries to return values as values (and not as rvalue references) // we cannot simply cast to std::tuple_element_t (or set that as return value), because some tuples, like // our alphabet_tuple_base alphabets do not return that type when get is called on them (they return a proxy) using ret_type = remove_rvalue_reference_t<decltype(get<index>(std::forward<decltype(in)>(in)))>; return static_cast<ret_type>(get<index>(std::forward<decltype(in)>(in))); }); //!\} } // namespace seqan3::views
58.695122
137
0.450862
marehr
144e447ff6f96c1a3e922d742abb38b929e5b31b
6,099
cpp
C++
Userland/Applications/Calculator/KeypadValue.cpp
densogiaichned/serenity
99c0b895fed02949b528437d6b450d85befde7a5
[ "BSD-2-Clause" ]
2
2022-02-16T02:12:38.000Z
2022-02-20T18:40:41.000Z
Userland/Applications/Calculator/KeypadValue.cpp
densogiaichned/serenity
99c0b895fed02949b528437d6b450d85befde7a5
[ "BSD-2-Clause" ]
null
null
null
Userland/Applications/Calculator/KeypadValue.cpp
densogiaichned/serenity
99c0b895fed02949b528437d6b450d85befde7a5
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2021, the SerenityOS developers. * * SPDX-License-Identifier: BSD-2-Clause */ #include "KeypadValue.h" #include <AK/IntegralMath.h> #include <AK/Math.h> #include <AK/String.h> KeypadValue::KeypadValue(i64 value, u8 decimal_places) : m_value(value) , m_decimal_places(value == 0 ? 0 : decimal_places) { } KeypadValue::KeypadValue(i64 value) : m_value(value) { } KeypadValue::KeypadValue(StringView sv) { String str = sv.to_string(); // TODO: Once we have a StringView equivalent for this C API, we won't need to create a copy for this anymore. size_t first_index = 0; char* dot_ptr; i64 int_part = strtoll(&str[first_index], &dot_ptr, 10); size_t dot_index = dot_ptr - str.characters(); if ((dot_index < str.length()) && (str[dot_index] == '.')) { size_t second_index = dot_index + 1; char* end_ptr; i64 frac_part = strtoll(&str[second_index], &end_ptr, 10); size_t end_index = end_ptr - str.characters(); u8 frac_length = end_index - second_index; *this = KeypadValue { int_part } + KeypadValue { frac_part, frac_length }; } else { *this = KeypadValue { int_part }; } }; KeypadValue KeypadValue::operator+(KeypadValue const& rhs) { return operator_helper<KeypadValue>(*this, rhs, [](KeypadValue const&, KeypadValue const& more_decimal_places, i64 less_decimal_places_equalized, i64 more_decimal_places_equalized, bool) -> KeypadValue { return { more_decimal_places_equalized + less_decimal_places_equalized, more_decimal_places.m_decimal_places }; }); } KeypadValue KeypadValue::operator-(KeypadValue const& rhs) { return *this + (-rhs); } KeypadValue KeypadValue::operator*(KeypadValue const& rhs) { return operator_helper<KeypadValue>(*this, rhs, [](KeypadValue const& less_decimal_places, KeypadValue const& more_decimal_places, i64, i64, bool) -> KeypadValue { return { less_decimal_places.m_value * more_decimal_places.m_value, (u8)(less_decimal_places.m_decimal_places + more_decimal_places.m_decimal_places) }; }); } KeypadValue KeypadValue::operator-(void) const { return { -m_value, m_decimal_places }; } KeypadValue KeypadValue::sqrt(void) const { return KeypadValue { AK::sqrt((double)(*this)) }; } KeypadValue KeypadValue::invert(void) const { return KeypadValue { 1.0 / (double)(*this) }; } KeypadValue KeypadValue::operator/(KeypadValue const& rhs) { return KeypadValue { (double)(*this) / (double)rhs }; } bool KeypadValue::operator<(KeypadValue const& rhs) { return operator_helper<bool>(*this, rhs, [](KeypadValue const&, KeypadValue const&, i64 less_decimal_places_equalized, i64 more_decimal_places_equalized, bool lhs_is_less) { if (lhs_is_less) return (less_decimal_places_equalized < more_decimal_places_equalized); else return (more_decimal_places_equalized < less_decimal_places_equalized); }); } bool KeypadValue::operator==(KeypadValue const& rhs) { return operator_helper<bool>(*this, rhs, [](KeypadValue const&, KeypadValue const&, i64 less_decimal_places_equalized, i64 more_decimal_places_equalized, bool) { return less_decimal_places_equalized == more_decimal_places_equalized; }); } // This is a helper function for the operators. A lot of them need to do very similar calculations, so this function // does the calculations for them and calls them on the result. In case they don't need the result of a particular // calculation, they simply ignore that argument. // The arguments to this function are the operands on the left- and right-hand sides and the callback to call on the // values computed by this function. // The first two KeypadValues it passes to the callback are the two original operands, but sorted by the amount of // decimal places. // The next two i64s it passes to the callback are these sorted KeypadValues, but normalized, which means that if // you have for example 12.1 (represented as {121, 1}) and 54.23 (represented as {5423, 2}), you will get 1210 and // 5423, so that you can compare these two i64s directly in order to compare the original KeypadValues. // Unfortunately, not all operators are symmetric, so the last boolean tells the callback whether the left-hand side // was the KeypadValue with less decimal places (true), or the one with more decimal places (false). template<typename T, typename F> ALWAYS_INLINE T KeypadValue::operator_helper(KeypadValue const& lhs, KeypadValue const& rhs, F callback) { KeypadValue const& less_decimal_places = (lhs.m_decimal_places < rhs.m_decimal_places) ? lhs : rhs; KeypadValue const& more_decimal_places = (lhs.m_decimal_places < rhs.m_decimal_places) ? rhs : lhs; i64 more_decimal_places_equalized = more_decimal_places.m_value; i64 less_decimal_places_equalized = AK::pow<i64>(10, more_decimal_places.m_decimal_places - less_decimal_places.m_decimal_places) * less_decimal_places.m_value; bool lhs_is_less = (lhs.m_decimal_places < rhs.m_decimal_places); return callback(less_decimal_places, more_decimal_places, less_decimal_places_equalized, more_decimal_places_equalized, lhs_is_less); } KeypadValue::KeypadValue(double d) { bool negative = false; if (d < 0) { negative = true; d = -d; } i8 current_pow = 0; while (AK::pow(10.0, (double)current_pow) <= d) current_pow += 1; current_pow -= 1; double epsilon = 1e-6; while (d >= epsilon || current_pow >= 0) { m_value *= 10; i8 digit = (u64)(d * AK::pow(0.1, (double)current_pow)) % 10; m_value += digit; d -= digit * AK::pow(10.0, (double)current_pow); if (current_pow < 0) m_decimal_places += 1; current_pow -= 1; if (m_decimal_places > 6) break; } m_value = negative ? (-m_value) : m_value; } KeypadValue::operator double() const { double res = (double)m_value / AK::pow(10.0, (double)m_decimal_places); return res; }
37.417178
207
0.70159
densogiaichned
1450443059c8695c0bb0ec98e504c1a1f77a5cc0
23,039
cpp
C++
Plugins/DisguiseUERenderStream/Source/RenderStream/Private/RenderStream.cpp
realtimeninja/RenderStreamNinja
7c78a04b9f090445c4daa2f0238e979c73a7f6a2
[ "BSD-3-Clause" ]
4
2020-10-07T00:25:40.000Z
2022-02-04T19:12:30.000Z
Plugins/DisguiseUERenderStream/Source/RenderStream/Private/RenderStream.cpp
realtimeninja/RenderStreamNinja
7c78a04b9f090445c4daa2f0238e979c73a7f6a2
[ "BSD-3-Clause" ]
null
null
null
Plugins/DisguiseUERenderStream/Source/RenderStream/Private/RenderStream.cpp
realtimeninja/RenderStreamNinja
7c78a04b9f090445c4daa2f0238e979c73a7f6a2
[ "BSD-3-Clause" ]
1
2020-10-07T18:15:09.000Z
2020-10-07T18:15:09.000Z
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. #include "RenderStream.h" #include "RenderStreamSettings.h" #include "RenderStreamMediaCapture.h" #include "Core/Public/Modules/ModuleManager.h" #include "CoreUObject/Public/Misc/PackageName.h" #include "Misc/CoreDelegates.h" #include "Json/Public/Serialization/JsonSerializer.h" #include "Misc/FileHelper.h" #include "Kismet/GameplayStatics.h" #include "Engine/LevelStreaming.h" #include "Engine/LevelScriptActor.h" #include "Engine/World.h" #include "Camera/CameraActor.h" #include "ShaderCore.h" #include "Interfaces/IPluginManager.h" #include "fnv.hpp" #include <map> DEFINE_LOG_CATEGORY(LogRenderStream); #define LOCTEXT_NAMESPACE "FRenderStreamModule" namespace { void log_default(const char* text) { UE_LOG(LogRenderStream, Log, TEXT("%s"), ANSI_TO_TCHAR(text)); } void log_verbose(const char* text) { UE_LOG(LogRenderStream, Verbose, TEXT("%s"), ANSI_TO_TCHAR(text)); } void log_error(const char* text) { UE_LOG(LogRenderStream, Error, TEXT("%s"), ANSI_TO_TCHAR(text)); } } void RenderStreamStatus::setInputAndOutputStatuses(const FString& topText, const FString& bottomText, const FSlateColor& color) { outputText = topText; inputText = bottomText; outputColor = color; inputColor = color; changed = true; } void RenderStreamStatus::setOutputStatus(const FString& text, const FSlateColor& color) { outputText = text; outputColor = color; changed = true; } void RenderStreamStatus::setInputStatus(const FString& text, const FSlateColor& color) { inputText = text; inputColor = color; changed = true; } void FRenderStreamModule::StartupModule() { FString ShaderDirectory = FPaths::Combine(IPluginManager::Get().FindPlugin(TEXT("DisguiseUERenderStream"))->GetBaseDir(), TEXT("Shaders")); AddShaderSourceDirectoryMapping("/DisguiseUERenderStream", ShaderDirectory); // This code will execute after your module is loaded into memory; the exact timing is specified in the .uplugin file per-module m_status.setInputAndOutputStatuses("Initialising stream", "Waiting for data from d3", RSSTATUS_ORANGE); if (!RenderStreamLink::instance ().loadExplicit ()) { UE_LOG(LogRenderStream, Error, TEXT ("Failed to load RenderStream DLL - d3 not installed?")); m_status.setInputAndOutputStatuses("Error", "Failed to load RenderStream DLL - d3 not installed?", RSSTATUS_RED); } else { int major, minor; RenderStreamLink::instance().rs_getVersion(&major, &minor); UE_LOG(LogRenderStream, Log, TEXT("Loaded d3renderstream.dll version %i.%i."), major, minor); if (major != RENDER_STREAM_VERSION_MAJOR || minor != RENDER_STREAM_VERSION_MINOR) { UE_LOG(LogRenderStream, Error, TEXT("Unsupported RenderStream library, expected version %i.%i"), RENDER_STREAM_VERSION_MAJOR, RENDER_STREAM_VERSION_MINOR); m_status.setInputAndOutputStatuses("Error", "Unsupported RenderStream library", RSSTATUS_RED); RenderStreamLink::instance().unloadExplicit(); return; } int errCode = RenderStreamLink::instance().rs_init(); if (errCode != 0) { UE_LOG(LogRenderStream, Error, TEXT("Unable to initialise RenderStream library error code %d"), errCode); m_status.setInputAndOutputStatuses("Error", "Unable to initialise RenderStream library", RSSTATUS_RED); RenderStreamLink::instance().unloadExplicit(); return; } FString assetName = FApp::GetProjectName(); if (RenderStreamLink::instance().rs_createAsset(TCHAR_TO_ANSI(*assetName), &m_assetHandle) != 0) { UE_LOG(LogRenderStream, Error, TEXT("Unable to create asset - failure to initialise.")); m_status.setInputAndOutputStatuses("Error", "Unable to create asset - failure to initialise", RSSTATUS_RED); RenderStreamLink::instance().unloadExplicit(); return; } UE_LOG(LogRenderStream, Log, TEXT("Created Asset '%s'"), *assetName); } OnBeginFrameHandle = FCoreDelegates::OnBeginFrame.AddRaw(this, &FRenderStreamModule::OnBeginFrame); } void FRenderStreamModule::ShutdownModule() { if (!RenderStreamLink::instance().isAvailable()) return; UE_LOG(LogRenderStream, Log, TEXT("Shutting down RenderStream")); FCoreDelegates::OnBeginFrame.Remove(OnBeginFrameHandle); if (m_assetHandle != 0) RenderStreamLink::instance().rs_destroyAsset(&m_assetHandle); // This function may be called during shutdown to clean up your module. For modules that support dynamic reloading, // we call this function before unloading the module. if (!RenderStreamLink::instance ().unloadExplicit ()) { UE_LOG (LogRenderStream, Warning, TEXT ("Failed to free render stream module.")); } } bool FRenderStreamModule::SupportsAutomaticShutdown () { return true; } bool FRenderStreamModule::SupportsDynamicReloading () { return true; } void validateField(StreamFNV& fnv, FString key_, FString undecoratedSuffix, const TSharedPtr< FJsonValue >& JsonValue) { if (!JsonValue) throw std::runtime_error("Null parameter"); const TSharedPtr<FJsonObject>& JsonParameter = JsonValue->AsObject(); if (!JsonParameter) throw std::runtime_error("Non-object parameter"); FString key = key_ + (undecoratedSuffix.IsEmpty() ? "" : "_" + undecoratedSuffix); if (key != JsonParameter->GetStringField(TEXT("key"))) throw std::runtime_error("Parameter mismatch"); const std::string stdKey = TCHAR_TO_ANSI(*key); fnv.addData(reinterpret_cast<const unsigned char*>(stdKey.data()), stdKey.size()); } void FRenderStreamModule::ValidateSchema(const TSharedPtr<FJsonObject>& JsonSchema, const AActor* Root, const AActor* PersistentRoot, SchemaSpec& spec) { StreamFNV fnv; const FString Scene = JsonSchema->GetStringField(TEXT("name")); TArray< TSharedPtr<FJsonValue> > JsonParameters = JsonSchema->GetArrayField(TEXT("parameters")); const FString nPersistentParametersFieldName = TEXT("nPersistentParameters"); const FString nLevelParametersFieldName = TEXT("nLevelParameters"); if (!JsonSchema->HasField(nPersistentParametersFieldName) || !JsonSchema->HasField(nLevelParametersFieldName)) { throw std::runtime_error("Missing supplementary fields in schema.json. Rebuild schema by opening project in Editor."); } const int nPersistentParameters = int(JsonSchema->GetNumberField(nPersistentParametersFieldName)); const int nLevelParameters = int(JsonSchema->GetNumberField(nLevelParametersFieldName)); UE_LOG(LogRenderStream, Log, TEXT("Validating schema for %s"), *Scene); if (ValidateRoot(PersistentRoot, JsonParameters, spec, fnv) != nPersistentParameters) throw std::runtime_error("Excess persistent parameters in schema"); if (Root) { JsonParameters.RemoveAt(0, nPersistentParameters); if (ValidateRoot(Root, JsonParameters, spec, fnv) != nLevelParameters) throw std::runtime_error("Excess level parameters in schema"); } spec.schemaRoot = Root; spec.schemaPersistentRoot = PersistentRoot; UE_LOG(LogRenderStream, Log, TEXT("Validated schema")); spec.schemaHash = fnv.getHash(); } size_t FRenderStreamModule::ValidateRoot(const AActor* Root, const TArray< TSharedPtr<FJsonValue> >& JsonParameters, SchemaSpec& spec, StreamFNV& fnv) const { size_t nParameters = 0; for (TFieldIterator<FProperty> PropIt(Root->GetClass(), EFieldIteratorFlags::ExcludeSuper); PropIt; ++PropIt) { const FProperty* Property = *PropIt; const FString Name = Property->GetName(); if (!Property->HasAllPropertyFlags(CPF_Edit | CPF_BlueprintVisible) || Property->HasAllPropertyFlags(CPF_DisableEditOnInstance)) { UE_LOG(LogRenderStream, Verbose, TEXT("Unexposed property: %s"), *Name); } else if (const FBoolProperty* BoolProperty = CastField<const FBoolProperty>(Property)) { UE_LOG(LogRenderStream, Log, TEXT("Exposed bool property: %s"), *Name); if (JsonParameters.Num() < nParameters + 1) throw std::runtime_error("Property not exposed in schema"); validateField(fnv, Name, "", JsonParameters[nParameters]); ++nParameters; } else if (const FByteProperty* ByteProperty = CastField<const FByteProperty>(Property)) { UE_LOG(LogRenderStream, Log, TEXT("Exposed int property: %s"), *Name); if (JsonParameters.Num() < nParameters + 1) throw std::runtime_error("Property not exposed in schema"); validateField(fnv, Name, "", JsonParameters[nParameters]); ++nParameters; } else if (const FIntProperty* IntProperty = CastField<const FIntProperty>(Property)) { UE_LOG(LogRenderStream, Log, TEXT("Exposed int property: %s"), *Name); if (JsonParameters.Num() < nParameters + 1) throw std::runtime_error("Property not exposed in schema"); validateField(fnv, Name, "", JsonParameters[nParameters]); ++nParameters; } else if (const FFloatProperty* FloatProperty = CastField<const FFloatProperty>(Property)) { UE_LOG(LogRenderStream, Log, TEXT("Exposed float property: %s"), *Name); if (JsonParameters.Num() < nParameters + 1) throw std::runtime_error("Property not exposed in schema"); validateField(fnv, Name, "", JsonParameters[nParameters]); ++nParameters; } else if (const FStructProperty* StructProperty = CastField<const FStructProperty>(Property)) { const void* StructAddress = StructProperty->ContainerPtrToValuePtr<void>(Root); if (StructProperty->Struct == TBaseStructure<FVector>::Get()) { UE_LOG(LogRenderStream, Log, TEXT("Exposed vector property: %s"), *Name); if (JsonParameters.Num() < nParameters + 3) throw std::runtime_error("Properties not exposed in schema"); validateField(fnv, Name, "x", JsonParameters[nParameters + 0]); validateField(fnv, Name, "y", JsonParameters[nParameters + 1]); validateField(fnv, Name, "z", JsonParameters[nParameters + 2]); nParameters += 3; } else if (StructProperty->Struct == TBaseStructure<FColor>::Get()) { UE_LOG(LogRenderStream, Log, TEXT("Exposed colour property: %s"), *Name); if (JsonParameters.Num() < nParameters + 4) throw std::runtime_error("Properties not exposed in schema"); validateField(fnv, Name, "r", JsonParameters[nParameters + 0]); validateField(fnv, Name, "g", JsonParameters[nParameters + 1]); validateField(fnv, Name, "b", JsonParameters[nParameters + 2]); validateField(fnv, Name, "a", JsonParameters[nParameters + 3]); nParameters += 4; } else if (StructProperty->Struct == TBaseStructure<FLinearColor>::Get()) { UE_LOG(LogRenderStream, Log, TEXT("Exposed linear colour property: %s"), *Name); if (JsonParameters.Num() < nParameters + 4) throw std::runtime_error("Properties not exposed in schema"); validateField(fnv, Name, "r", JsonParameters[nParameters + 0]); validateField(fnv, Name, "g", JsonParameters[nParameters + 1]); validateField(fnv, Name, "b", JsonParameters[nParameters + 2]); validateField(fnv, Name, "a", JsonParameters[nParameters + 3]); nParameters += 4; } else { UE_LOG(LogRenderStream, Log, TEXT("Exposed struct property: %s"), *Name); } } else { UE_LOG(LogRenderStream, Log, TEXT("Unsupported exposed property: %s"), *Name); } } spec.nParameters += nParameters; return nParameters; } size_t FRenderStreamModule::ApplyParameters(AActor* Root, const std::vector<float>& parameters, const size_t offset) { if (!Root) return offset; size_t i = offset; for (TFieldIterator<FProperty> PropIt(Root->GetClass(), EFieldIteratorFlags::ExcludeSuper); PropIt; ++PropIt) { FProperty* Property = *PropIt; if (!Property->HasAllPropertyFlags(CPF_Edit | CPF_BlueprintVisible) || Property->HasAllPropertyFlags(CPF_DisableEditOnInstance)) { continue; } else if (const FBoolProperty* BoolProperty = CastField<const FBoolProperty>(Property)) { const bool v = bool(parameters.at(i)); BoolProperty->SetPropertyValue_InContainer(Root, v); ++i; } else if (FByteProperty* ByteProperty = CastField<FByteProperty>(Property)) { const uint8 v = uint8(parameters.at(i)); ByteProperty->SetPropertyValue_InContainer(Root, v); ++i; } else if (FIntProperty* IntProperty = CastField<FIntProperty>(Property)) { const int32 v = int(parameters.at(i)); IntProperty->SetPropertyValue_InContainer(Root, v); ++i; } else if (FFloatProperty* FloatProperty = CastField<FFloatProperty>(Property)) { const float v = parameters.at(i); FloatProperty->SetPropertyValue_InContainer(Root, v); ++i; } else if (FStructProperty* StructProperty = CastField<FStructProperty>(Property)) { void* StructAddress = StructProperty->ContainerPtrToValuePtr<void>(Root); if (StructProperty->Struct == TBaseStructure<FVector>::Get()) { FVector v(parameters.at(i), parameters.at(i + 1), parameters.at(i + 2)); StructProperty->CopyCompleteValue(StructAddress, &v); i += 3; } else if (StructProperty->Struct == TBaseStructure<FColor>::Get()) { FColor v(parameters.at(i) * 255, parameters.at(i + 1) * 255, parameters.at(i + 2) * 255, parameters.at(i + 3) * 255); StructProperty->CopyCompleteValue(StructAddress, &v); i += 4; } else if (StructProperty->Struct == TBaseStructure<FLinearColor>::Get()) { FLinearColor v(parameters.at(i), parameters.at(i + 1), parameters.at(i + 2), parameters.at(i + 3)); StructProperty->CopyCompleteValue(StructAddress, &v); i += 4; } } } return i; } void FRenderStreamModule::LoadSchemas(const UWorld& World) { m_specs.clear(); FString Schema; FString SchemaPath = FPaths::Combine(*FPaths::ProjectContentDir(), *FString("DisguiseRenderStream"), *FString("schema.json")); FFileHelper::LoadFileToString(Schema, *SchemaPath); TArray< TSharedPtr<FJsonValue> > JsonSchemas; TSharedRef< TJsonReader<> > Reader = TJsonReaderFactory<>::Create(Schema); if (FJsonSerializer::Deserialize(Reader, JsonSchemas)) { #if WITH_EDITOR try { #endif const TArray<ULevelStreaming*>& streamingLevels = World.GetStreamingLevels(); std::map<FString, ULevelStreaming*> LevelLookup; for (ULevelStreaming* streamingLevel : streamingLevels) { FString Scene = FPackageName::GetLongPackageAssetName(streamingLevel->GetWorldAssetPackageName()); if (streamingLevel->GetWorld()) Scene.RemoveFromStart(streamingLevel->GetWorld()->StreamingLevelsPrefix); LevelLookup[Scene] = streamingLevel; } m_specs.resize(JsonSchemas.Num()); for (size_t i = 0; i < m_specs.size(); ++i) { if (!JsonSchemas[i]) throw std::runtime_error("Null schema"); const TSharedPtr<FJsonObject>& JsonSchema = JsonSchemas[i]->AsObject(); if (!JsonSchema) throw std::runtime_error("Non-object schema"); const FString Scene = JsonSchema->GetStringField(TEXT("name")); ULevelStreaming* streamingLevel = LevelLookup[Scene]; SchemaSpec& spec = m_specs[i]; spec.streamingLevel = streamingLevel; const AActor* persistentRoot = World.PersistentLevel->GetLevelScriptActor(); const AActor* levelRoot = streamingLevel ? streamingLevel->GetLevelScriptActor() : nullptr; ValidateSchema(JsonSchema, levelRoot, persistentRoot, spec); UE_LOG(LogRenderStream, Log, TEXT("Loaded schema for %s (%s): %d parameters"), *Scene, streamingLevel ? *streamingLevel->GetWorldAssetPackageName() : TEXT("null"), spec.nParameters); } #if WITH_EDITOR } catch (const std::exception& e) { UE_LOG(LogRenderStream, Error, TEXT("Failed to parse schema %s: %s"), *SchemaPath, *FString(e.what())); Schema = TEXT("[]"); } #endif } else { UE_LOG(LogRenderStream, Error, TEXT("Failed to parse schema %s"), *SchemaPath); Schema = TEXT("[]"); } if (m_specs.empty()) { m_specs.resize(1); SchemaSpec& spec = m_specs.front(); spec.streamingLevel = nullptr; StreamFNV fnv; spec.schemaHash = fnv.getHash(); } if (RenderStreamLink::instance().rs_setSchema(m_assetHandle, TCHAR_TO_ANSI(*Schema)) != 0) { UE_LOG(LogRenderStream, Error, TEXT("Unable to set remote parameter schema")); } } void FRenderStreamModule::OnBeginFrame() { if (!RenderStreamLink::instance().isAvailable()) return; // If no captures are active, maintain asset sync, but do not delay processing. int timeout = 0; if (m_activeCaptures.Num() > 0) timeout = 500; RenderStreamLink::AssetHandle updateAsset = 0; uint32_t ret = RenderStreamLink::instance().rs_awaitFrameData(&updateAsset, timeout, &m_frameData); if (ret != 0 || m_assetHandle != updateAsset || m_frameData.scene >= m_specs.size()) { if (m_frameDataValid) m_status.setInputStatus("Stopped receiving data from d3", RSSTATUS_ORANGE); m_frameDataValid = false; // TODO: Mark timecode as invalid only after some multiple of the expected incoming framerate. return; } if (!m_frameDataValid) m_status.setInputStatus("Receiving data from d3", RSSTATUS_GREEN); m_frameDataValid = true; // If no captures are active, skip schema validation (and error logging). if (m_activeCaptures.Num() == 0) return; const SchemaSpec& spec = m_specs.at(m_frameData.scene); URenderStreamMediaCapture* SchemaCallbackTarget = m_activeCaptures[0].Get(); const UWorld* World = SchemaCallbackTarget ? SchemaCallbackTarget->SchemaWorld() : nullptr; if (World) { AActor* persistentRoot = World->PersistentLevel->GetLevelScriptActor(); if (spec.streamingLevel == nullptr && spec.schemaPersistentRoot == persistentRoot) // base level { std::vector<float> parameters; parameters.resize(spec.nParameters); if (RenderStreamLink::instance().rs_getFrameParameters(m_assetHandle, spec.schemaHash, parameters.data(), parameters.size() * sizeof(float)) == RenderStreamLink::RS_ERROR_SUCCESS) { ApplyParameters(persistentRoot, parameters, 0); } for (ULevelStreaming* streamingLevel : World->GetStreamingLevels()) { streamingLevel->SetShouldBeVisible(false); } } else { for (ULevelStreaming* streamingLevel : World->GetStreamingLevels()) { if (spec.streamingLevel == streamingLevel) { if (!streamingLevel->IsLevelLoaded()) { UE_LOG(LogRenderStream, Log, TEXT("Loading level %s"), *streamingLevel->GetWorldAssetPackageFName().ToString()); FLatentActionInfo LatentInfo; LatentInfo.CallbackTarget = SchemaCallbackTarget; LatentInfo.ExecutionFunction = "UpdateSchema"; LatentInfo.UUID = int32(uintptr_t(this)); LatentInfo.Linkage = 0; UGameplayStatics::LoadStreamLevel(World, streamingLevel->GetWorldAssetPackageFName(), true, true, LatentInfo); } else if (spec.schemaRoot == streamingLevel->GetLevelScriptActor()) { AActor* levelRoot = streamingLevel->GetLevelScriptActor(); streamingLevel->SetShouldBeVisible(true); std::vector<float> parameters; parameters.resize(spec.nParameters); if (!parameters.empty() && RenderStreamLink::instance().rs_getFrameParameters(m_assetHandle, spec.schemaHash, parameters.data(), parameters.size() * sizeof(float)) == RenderStreamLink::RS_ERROR_SUCCESS) { size_t offset = 0; offset = ApplyParameters(persistentRoot, parameters, offset); ApplyParameters(levelRoot, parameters, offset); } } } else if (spec.streamingLevel != nullptr) { streamingLevel->SetShouldBeVisible(false); // hide all levels not associated with this schema } } } } for (const TWeakObjectPtr<URenderStreamMediaCapture>& ptr : m_activeCaptures) { if (URenderStreamMediaCapture* capture = ptr.Get()) { RenderStreamLink::CameraData cameraData; if (RenderStreamLink::instance().rs_getFrameCamera(m_assetHandle, capture->streamHandle(), &cameraData) == RenderStreamLink::RS_ERROR_SUCCESS) { capture->ApplyCameraData(m_frameData, cameraData); } } } } void FRenderStreamModule::AddActiveCapture(URenderStreamMediaCapture* InCapture) { m_activeCaptures.Add(InCapture); } void FRenderStreamModule::RemoveActiveCapture(URenderStreamMediaCapture* InCapture) { m_activeCaptures.Remove(InCapture); } /*static*/ FRenderStreamModule* FRenderStreamModule::Get() { return &FModuleManager::GetModuleChecked<FRenderStreamModule>("RenderStream"); } #undef LOCTEXT_NAMESPACE IMPLEMENT_MODULE(FRenderStreamModule, RenderStream)
41.586643
226
0.635097
realtimeninja
1454787751afabaf3ef73838b47916f1bb4e1dc3
2,564
hpp
C++
ports/linux/WebServer.linux.hpp
Draegerwerk/SDCesp
ea3da666b18a3a3b273add398fd49cc78d6fa94c
[ "BSD-3-Clause" ]
3
2020-04-10T05:41:42.000Z
2022-03-21T11:51:53.000Z
ports/linux/WebServer.linux.hpp
Draegerwerk/SDCesp
ea3da666b18a3a3b273add398fd49cc78d6fa94c
[ "BSD-3-Clause" ]
3
2020-03-31T08:57:56.000Z
2021-03-17T09:06:36.000Z
ports/linux/WebServer.linux.hpp
Draegerwerk/SDCesp
ea3da666b18a3a3b273add398fd49cc78d6fa94c
[ "BSD-3-Clause" ]
3
2020-03-30T07:40:36.000Z
2021-05-21T10:11:59.000Z
#pragma once #include "Log.hpp" #include "Request.linux.hpp" #include "WebServer/WebServer.hpp" #include "rapidxml.hpp" #include "server_https.hpp" #include "services/ServiceInterface.hpp" #include <future> class ServiceInterface; template <class SocketType> class WebServerSimple : public WebServerInterface { public: explicit WebServerSimple(); WebServerSimple(const WebServerSimple& other) = delete; WebServerSimple& operator=(const WebServerSimple& other) = delete; WebServerSimple(WebServerSimple&& other) = delete; WebServerSimple& operator=(WebServerSimple&& other) = delete; ~WebServerSimple() override; void start() override; void stop() override; void add_service(std::shared_ptr<ServiceInterface> service) override; private: std::unique_ptr<SimpleWeb::Server<SocketType>> server_; std::thread server_thread_{}; }; template <class SocketType> void WebServerSimple<SocketType>::start() { // Start server and receive assigned port when server is listening for requests std::promise<std::uint16_t> server_port; server_thread_ = std::thread([this, &server_port]() { // Start server server_->start([&server_port](unsigned short port) { server_port.set_value(port); }); }); LOG(LogLevel::INFO, "Server listening on port " << server_port.get_future().get()); } template <class SocketType> void WebServerSimple<SocketType>::stop() { server_->stop(); LOG(LogLevel::INFO, "Server stopping..."); server_thread_.join(); } template <class SocketType> WebServerSimple<SocketType>::~WebServerSimple<SocketType>() { stop(); } template <class SocketType> void WebServerSimple<SocketType>::add_service(std::shared_ptr<ServiceInterface> service) { const auto handler = [service](std::shared_ptr<typename SimpleWeb::Server<SocketType>::Response> response, std::shared_ptr<typename SimpleWeb::Server<SocketType>::Request> request) { try { service->handle_request(std::make_unique<RequestSimple<SocketType>>(response, request)); } catch (rapidxml::parse_error& e) { LOG(LogLevel::ERROR, "Rapidxml Parse error: " << e.what()); } catch (std::exception& e) { LOG(LogLevel::ERROR, "Error handling Request: std::exception: " << e.what()); } catch (...) { LOG(LogLevel::ERROR, "Error while handling request!"); } }; server_->resource["^" + service->get_uri() + "$"]["GET"] = handler; server_->resource["^" + service->get_uri() + "$"]["POST"] = handler; }
30.164706
98
0.684477
Draegerwerk
14550fdd9a0de037ff1fe6d2b46aaaf75d988977
1,423
hpp
C++
gui/include/interfaces/GuiCaptureInterface.hpp
JMassing/Pokerbot
40b2e4756fc8ef1be4af4d649deb6035a9774bdc
[ "MIT" ]
1
2021-12-10T06:27:47.000Z
2021-12-10T06:27:47.000Z
gui/include/interfaces/GuiCaptureInterface.hpp
JMassing/Pokerbot
40b2e4756fc8ef1be4af4d649deb6035a9774bdc
[ "MIT" ]
null
null
null
gui/include/interfaces/GuiCaptureInterface.hpp
JMassing/Pokerbot
40b2e4756fc8ef1be4af4d649deb6035a9774bdc
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include "ICaptureGui.hpp" namespace gui { /** \ingroup gui * @class GuiCaptureInterface * @author Julian Massing (julimassing@gmail.com) * @brief Implements communication interface between capture and GUI module. * * @version 1.0 * @date 2020-11-21 * * @copyright Copyright (c) 2020 * */ class GuiCaptureInterface: public capture::ICaptureGui { public: //Camera Controls capture::CameraSettings& camera_settings_; Image live_image_; bool& user_input_; capture::CameraSettings getSettings() const override { return this->camera_settings_; } bool checkUserInput() const override { return this->user_input_; } void setImage(const Image& image) { this->live_image_ = image; } explicit GuiCaptureInterface( capture::CameraSettings& camera_settings, bool& input ): camera_settings_(camera_settings), user_input_(input), live_image_{} {}; virtual ~GuiCaptureInterface() {}; // Using default copy and move constructors. GuiCaptureInterface(const GuiCaptureInterface& other) = default; GuiCaptureInterface& operator=(const GuiCaptureInterface& other) = default; GuiCaptureInterface(GuiCaptureInterface&& other) noexcept = default; GuiCaptureInterface& operator=(GuiCaptureInterface&& other) noexcept = default; }; } // namespace gui
22.587302
82
0.692902
JMassing
14552e71661c65d0879270ceff1f32e7ca60d0b5
2,477
cpp
C++
src/clotho/classifiers/classifier_toolkit.cpp
putnampp/clotho
6dbfd82ef37b4265381cd78888cd6da8c61c68c2
[ "ECL-2.0", "Apache-2.0" ]
3
2015-06-16T21:27:57.000Z
2022-01-25T23:26:54.000Z
src/clotho/classifiers/classifier_toolkit.cpp
putnampp/clotho
6dbfd82ef37b4265381cd78888cd6da8c61c68c2
[ "ECL-2.0", "Apache-2.0" ]
3
2015-06-16T21:12:42.000Z
2015-06-23T12:41:00.000Z
src/clotho/classifiers/classifier_toolkit.cpp
putnampp/clotho
6dbfd82ef37b4265381cd78888cd6da8c61c68c2
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
// Copyright 2015 Patrick Putnam // // 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 "clotho/classifiers/classifier_toolkit.hpp" const std::string CLASSIFIER_BLOCK_K = "classifier"; const std::string TOOLKIT_BLOCK_K = "toolkit"; const std::string TYPE_K = "type"; classifier_toolkit::classifier_toolkit() {} void classifier_toolkit::tool_configurations( boost::property_tree::ptree & config ) { boost::property_tree::ptree t; for( generator_citerator it = m_tools.begin(); it != m_tools.end(); ++it ) { boost::property_tree::ptree c; std::shared_ptr< iclassifier_generator > tmp( it->second->create(c) ); t.put_child( it->first, c ); } config.put_child( CLASSIFIER_BLOCK_K + "." + TOOLKIT_BLOCK_K, t ); } std::shared_ptr< iclassifier_generator > classifier_toolkit::get_classifier( boost::property_tree::ptree & config ) { if( configs.get_child_optional( CLASSIFIER_BLOCK_K + "." + TYPE_K ) == boost::none ) { config.put( CLASSIFIER_BLOCK_K + "." + TYPE_K, "" ); return std::shared_ptr< iclassifier_generator >(); } std::string tname = config.get< std::string >( CLASSIFIER_BLOCK_K + "." + TYPE_K, "" ); generator_iterator it = m_tools.find(tname); if( it != m_tools.end() ) { std::string fname = CLASSIFIER_BLOCK_K + "." + TOOLKIT_BLOCK_K + "." + tname; boost::property_tree::ptree c; if( config.get_child_optional( fname ) != boost::none ) { c = config.get_child(fname); } return it->second->create( c ); } return std::shared_ptr< iclassifier_generator >(); } void classifier_toolkit::register_classifier( iclassifier_generator * gen ) { if( gen == NULL ) return; generator_iterator it = m_classifiers.find( gen->name() ); if( it == m_classifiers.end() ) { m_classifiers.insert( std::make_pair( gen->name(), gen ) ); } } classifier_toolkit::~classifier_toolkit() {}
36.970149
117
0.672184
putnampp
145751f593d445bcdb0296a63d669c65098d293a
1,932
cpp
C++
devtools/lit/tests/Inputs/shtest-timeout/litcfg.cpp
PHP-OPEN-HUB/polarphp
70ff4046e280fd99d718d4761686168fa8012aa5
[ "PHP-3.01" ]
null
null
null
devtools/lit/tests/Inputs/shtest-timeout/litcfg.cpp
PHP-OPEN-HUB/polarphp
70ff4046e280fd99d718d4761686168fa8012aa5
[ "PHP-3.01" ]
null
null
null
devtools/lit/tests/Inputs/shtest-timeout/litcfg.cpp
PHP-OPEN-HUB/polarphp
70ff4046e280fd99d718d4761686168fa8012aa5
[ "PHP-3.01" ]
null
null
null
// This source file is part of the polarphp.org open source project // // Copyright (c) 2017 - 2019 polarphp software foundation // Copyright (c) 2017 - 2019 zzu_softboy <zzu_softboy@163.com> // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://polarphp.org/LICENSE.txt for license information // See https://polarphp.org/CONTRIBUTORS.txt for the list of polarphp project authors // // Created by polarboy on 2018/11/16. #include "LitConfig.h" #include "TestingConfig.h" #include "formats/ShellTest.h" #include "polarphp/basic/adt/StringRef.h" #include <filesystem> using polar::lit::LitConfig; using polar::lit::TestingConfig; using polar::lit::ShTest; using polar::basic::StringRef; namespace fs = std::filesystem; extern "C" { void root_cfgsetter(TestingConfig *config, LitConfig *litConfig) { std::string shellType; if (litConfig->hasParam("external")) { shellType = litConfig->getParam("external", "1"); } bool externalShell; if (shellType == "0") { litConfig->note("Using internal shell"); externalShell = false; } else { litConfig->note("Using external shell"); externalShell = true; } std::string configSetTimeout = litConfig->getParam("set_timeout", "0"); if (configSetTimeout != "0") { // Try setting the max individual test time in the configuration litConfig->setMaxIndividualTestTime(std::stoi(configSetTimeout)); } litConfig->getParam("external"); config->setName("per_test_timeout"); config->setSuffixes({".littest"}); config->setTestFormat(std::make_shared<ShTest>(externalShell)); config->setTestSourceRoot(fs::path(__FILE__).parent_path()); config->setTestExecRoot(config->getTestSourceRoot()); config->setExtraConfig("target_triple", "(unused)"); config->addSubstitution("%{short}", SHORT_GTEST_BIN); config->addSubstitution("%{infinite_loop}", INFINITE_LOOP_GTEST_BIN); } }
33.894737
85
0.715839
PHP-OPEN-HUB
14589f985cdd71c0b688c752efcf239b9785a5be
167
cpp
C++
docs/mfc/codesnippet/CPP/activex-control-containers-handling-events-from-an-activex-control_4.cpp
bobbrow/cpp-docs
769b186399141c4ea93400863a7d8463987bf667
[ "CC-BY-4.0", "MIT" ]
965
2017-06-25T23:57:11.000Z
2022-03-31T14:17:32.000Z
docs/mfc/codesnippet/CPP/activex-control-containers-handling-events-from-an-activex-control_4.cpp
bobbrow/cpp-docs
769b186399141c4ea93400863a7d8463987bf667
[ "CC-BY-4.0", "MIT" ]
3,272
2017-06-24T00:26:34.000Z
2022-03-31T22:14:07.000Z
docs/mfc/codesnippet/CPP/activex-control-containers-handling-events-from-an-activex-control_4.cpp
bobbrow/cpp-docs
769b186399141c4ea93400863a7d8463987bf667
[ "CC-BY-4.0", "MIT" ]
951
2017-06-25T12:36:14.000Z
2022-03-26T22:49:06.000Z
BOOL CContainerDlg::OnClickInCircctrl1(OLE_XPOS_PIXELS nX, OLE_YPOS_PIXELS nY) { // use nX and nY here TRACE(_T("nX = %d, nY = %d\n"), nX, nY); return TRUE; }
27.833333
78
0.664671
bobbrow
1459d18912bb342a208380270566a881f96bfdb8
11,370
hpp
C++
include/clotho/data_spaces/offspring_generator/offspring_generator_population_space_row_alignment.hpp
putnampp/clotho
6dbfd82ef37b4265381cd78888cd6da8c61c68c2
[ "ECL-2.0", "Apache-2.0" ]
3
2015-06-16T21:27:57.000Z
2022-01-25T23:26:54.000Z
include/clotho/data_spaces/offspring_generator/offspring_generator_population_space_row_alignment.hpp
putnampp/clotho
6dbfd82ef37b4265381cd78888cd6da8c61c68c2
[ "ECL-2.0", "Apache-2.0" ]
3
2015-06-16T21:12:42.000Z
2015-06-23T12:41:00.000Z
include/clotho/data_spaces/offspring_generator/offspring_generator_population_space_row_alignment.hpp
putnampp/clotho
6dbfd82ef37b4265381cd78888cd6da8c61c68c2
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
// Copyright 2015 Patrick Putnam // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef OFFSPRING_GENERATOR_POPULATION_SPACE_ROW_BLOCK_ALIGNMENT_HPP_ #define OFFSPRING_GENERATOR_POPULATION_SPACE_ROW_BLOCK_ALIGNMENT_HPP_ #include "clotho/data_spaces/offspring_generator/offspring_generator_def.hpp" #include "clotho/data_spaces/population_space/population_spaces.hpp" #include "clotho/data_spaces/crossover/common_crossovers.hpp" #include "clotho/data_spaces/phenotype_evaluator/common_phenotype_accumulators.hpp" #include "clotho/data_spaces/selection/selection_generator_factory.hpp" namespace clotho { namespace genetics { //template < class RNG, class BlockType, class WeightType, class AlleleSpaceType, class SelectionType, class TraitSpaceType, class FreeBufferType > template < class RNG, class BlockType, class AlleleSpaceType, class FitnessType, class TraitSpaceType, class FreeBufferType > class offspring_generator<RNG, population_space< row_block_alignment< BlockType >, TraitSpaceType >, AlleleSpaceType, FitnessType, TraitSpaceType, FreeBufferType > { public: typedef offspring_generator< RNG, population_space< row_block_alignment< BlockType >, TraitSpaceType >, AlleleSpaceType, FitnessType, TraitSpaceType, FreeBufferType > self_type; typedef RNG random_engine_type; typedef population_space< row_block_alignment< BlockType >, TraitSpaceType > population_type; typedef TraitSpaceType trait_space_type; typedef AlleleSpaceType allele_type; typedef std::vector< unsigned int > mutation_pool_type; typedef std::vector< unsigned int > mutation_distribution_type; typedef typename population_type::block_type block_type; typedef typename population_type::genome_pointer genome_pointer; typedef FreeBufferType free_buffer_type; typedef FitnessType fitness_type; typedef clotho::genetics::common_crossover< RNG, population_type, allele_type > crossover_type; typedef clotho::genetics::common_phenotype_accumulator< population_type, trait_space_type > phenotype_method; typedef typename phenotype_method::weight_type weight_type; typedef std::vector< std::pair< unsigned long long, unsigned long long > > time_vector; offspring_generator( random_engine_type * rng, allele_type * alleles, mutation_pool_type * mut_pool, mutation_distribution_type * mut_dist, fitness_type * fit, trait_space_type * traits, double recomb_rate, double bias_rate ) : m_rng( rng ) , m_parents( NULL ) , m_offspring( NULL ) , m_alleles( alleles ) , m_mut_pool( mut_pool ) , m_mut_dist( mut_dist ) , m_fitness( fit ) , m_off_begin( 0 ) , m_off_end( 0 ) , m_all_neutral( false ) , m_crossover_method( rng, alleles, recomb_rate, bias_rate ) , m_pheno_method( traits ) {} void reset( population_type * parents, population_type * offspring, const free_buffer_type & buf, unsigned int off_idx, unsigned int off_end, bool allNeutral ) { m_parents = parents; m_offspring = offspring; m_free_space.reset( buf ); m_off_begin = off_idx; m_off_end = off_end; m_all_neutral = allNeutral; } void operator()() { // crossover parents of offspring population // timer_type xover_time; crossover(); xover_time.stop(); // mutate offspring population // timer_type mutate_time; mutate(); mutate_time.stop(); // // evaluate phenotype of offspring population // timer_type pheno_time; phenotype(); pheno_time.stop(); // evaluate fixed alleles with offspring population // timer_type fixed_time; fixed(); fixed_time.stop(); // persist time logs m_crossover_times.push_back( std::make_pair( xover_time.getStart(), xover_time.getStop())); m_mutate_times.push_back( std::make_pair( mutate_time.getStart(), mutate_time.getStop())); m_phenotype_times.push_back( std::make_pair( pheno_time.getStart(), pheno_time.getStop())); m_fixed_times.push_back( std::make_pair( fixed_time.getStart(), fixed_time.getStop())); } // void record( time_vector & xover, time_vector & mut, time_vector & pheno, time_vector & fixed ) { // xover.push_back( std::make_pair( m_crossover_timer.getStart(), m_crossover_timer.getStop() ) ); // mut.push_back( std::make_pair( m_mutate_timer.getStart(), m_mutate_timer.getStop() ) ); // pheno.push_back( std::make_pair( m_phenotype_timer.getStart(), m_phenotype_timer.getStop() ) ); // fixed.push_back( std::make_pair( m_fixed_timer.getStart(), m_fixed_timer.getStop() ) ); // } // // void recordCrossover( boost::property_tree::ptree & log ) { // recordTime( log, m_crossover_timer ); // } // // void recordMutate( boost::property_tree::ptree & log ) { // recordTime( log, m_mutate_timer ); // } // // void recordPhenotype( boost::property_tree::ptree & log ) { // recordTime( log, m_phenotype_timer ); // } // // void recordFixed( boost::property_tree::ptree & log ) { // recordTime( log, m_fixed_timer ); // } void record( boost::property_tree::ptree & xo, boost::property_tree::ptree & mt, boost::property_tree::ptree & ph, boost::property_tree::ptree & fx ) { boost::property_tree::ptree xo_begins, xo_ends; buildTimeLog( xo_begins, xo_ends, m_crossover_times ); xo.put_child( "start", xo_begins); xo.put_child( "stop", xo_ends); boost::property_tree::ptree mt_begins, mt_ends; buildTimeLog( mt_begins, mt_ends, m_mutate_times ); mt.put_child( "start", mt_begins); mt.put_child( "stop", mt_ends); boost::property_tree::ptree ph_begins, ph_ends; buildTimeLog( ph_begins, ph_ends, m_phenotype_times ); ph.put_child( "start", ph_begins); ph.put_child( "stop", ph_ends); boost::property_tree::ptree fx_begins, fx_ends; buildTimeLog( fx_begins, fx_ends, m_fixed_times ); fx.put_child( "start", fx_begins); fx.put_child( "stop", fx_ends); } virtual ~offspring_generator() {} protected: void buildTimeLog( boost::property_tree::ptree & begins, boost::property_tree::ptree & ends, time_vector & t ) { for( typename time_vector::iterator it = t.begin(); it != t.end(); it++ ) { clotho::utility::add_value_array( begins, it->first ); clotho::utility::add_value_array( ends, it->second ); } } // void recordTime( boost::property_tree::ptree & log, const timer_type & t ) { // boost::property_tree::ptree elapsed, start, stop; // // elapsed = log.get_child("elapsed", elapsed); // start = log.get_child( "start", start ); // stop = log.get_child( "stop", stop ); // // clotho::utility::add_value_array( elapsed, t ); // clotho::utility::add_value_array( start, t.getStart() ); // clotho::utility::add_value_array( stop, t.getStop() ); // // log.put_child( "elapsed", elapsed ); // log.put_child( "start", start ); // log.put_child( "stop", stop ); // } // void crossover() { // typename selection_type::iterator b = m_fitness->begin() + m_off_begin, e = m_fitness->begin() + m_off_end; // // unsigned int off_idx = 2 * m_off_begin; // while( b != e ) { // perform_crossover_method( 2 * b->first, off_idx++ ); // perform_crossover_method( 2 * b->second, off_idx++ ); // // ++b; // } // } void crossover() { std::shared_ptr< selection_details< random_engine_type, unsigned int > > sel = clotho::genetics::make_selection_generator( m_rng, m_fitness); for( unsigned int i = m_off_begin; i < m_off_end; ++i ) { typename selection_details< random_engine_type >::parent_pair res = (*sel)(); perform_crossover_method( 2 * res.first, 2 * i ); perform_crossover_method( 2 * res.second, 2 * i + 1 ); } } void perform_crossover_method( unsigned int p_idx, unsigned int o_idx ) { genome_pointer top = m_parents->begin_genome( p_idx ), top_end = m_parents->end_genome(p_idx); genome_pointer bottom = m_parents->begin_genome( p_idx + 1 ), bottom_end = m_parents->end_genome( p_idx + 1 ); genome_pointer off = m_offspring->begin_genome( o_idx ), off_end = m_offspring->end_genome(o_idx); m_crossover_method( top, top_end, bottom, bottom_end, off, off_end ); } void mutate() { for( unsigned int i = 2 * m_off_begin; i < 2 * m_off_end; ++i ) { unsigned int lo = m_mut_dist->at( i ), hi = m_mut_dist->at( i + 1 ); while( lo < hi ) { unsigned int all_idx = m_mut_pool->at( lo ); m_offspring->mutate( i, all_idx ); ++lo; } } } void phenotype() { if( !m_all_neutral ) { for( unsigned int i = 2 * m_off_begin; i < 2 * m_off_end; ++i ) { genome_pointer first = m_offspring->begin_genome( i ), last = m_offspring->end_genome( i ); m_pheno_method( first, last ); m_offspring->updateGenomeWeights(i, m_pheno_method.getResults()); } } else { // constant phenotype m_pheno_method.resetBuffer(); for( unsigned int i = 2 * m_off_begin; i < 2 * m_off_end; ++i ) m_offspring->updateGenomeWeights( i, m_pheno_method.getResults() ); } } void fixed() { unsigned int M = m_offspring->getMaxBlocks(); for( unsigned int i = 2 * m_off_begin; i < 2 * m_off_end; ++i ) { block_type * f = m_offspring->begin_genome( i ); m_free_space.update( f, M ); } } random_engine_type * m_rng; population_type * m_parents, * m_offspring; allele_type * m_alleles; mutation_pool_type * m_mut_pool; mutation_distribution_type * m_mut_dist; fitness_type * m_fitness; unsigned int m_off_begin, m_off_end; bool m_all_neutral; crossover_type m_crossover_method; phenotype_method m_pheno_method; free_buffer_type m_free_space; time_vector m_crossover_times, m_mutate_times, m_phenotype_times, m_fitness_times, m_fixed_times; }; } // namespace genetics } // namespace clotho #endif // OFFSPRING_GENERATOR_POPULATION_SPACE_ROW_BLOCK_ALIGNMENT_HPP_
39.206897
231
0.644151
putnampp
145a53bb5498d508a2ddec4438917c24531d6e0f
4,029
hpp
C++
src/Evolution/DgSubcell/Actions/TakeTimeStep.hpp
nilsvu/spectre
1455b9a8d7e92db8ad600c66f54795c29c3052ee
[ "MIT" ]
117
2017-04-08T22:52:48.000Z
2022-03-25T07:23:36.000Z
src/Evolution/DgSubcell/Actions/TakeTimeStep.hpp
GitHimanshuc/spectre
4de4033ba36547113293fe4dbdd77591485a4aee
[ "MIT" ]
3,177
2017-04-07T21:10:18.000Z
2022-03-31T23:55:59.000Z
src/Evolution/DgSubcell/Actions/TakeTimeStep.hpp
geoffrey4444/spectre
9350d61830b360e2d5b273fdd176dcc841dbefb0
[ "MIT" ]
85
2017-04-07T19:36:13.000Z
2022-03-01T10:21:00.000Z
// Distributed under the MIT License. // See LICENSE.txt for details. #pragma once #include <optional> #include <tuple> #include <utility> #include "DataStructures/DataBox/DataBox.hpp" #include "DataStructures/DataVector.hpp" #include "DataStructures/Tensor/EagerMath/Determinant.hpp" #include "DataStructures/Tensor/Tensor.hpp" #include "Domain/CoordinateMaps/CoordinateMap.hpp" #include "Domain/CoordinateMaps/Tags.hpp" #include "Domain/ElementMap.hpp" #include "Domain/Tags.hpp" #include "Evolution/DgSubcell/Tags/Coordinates.hpp" #include "Evolution/DgSubcell/Tags/Jacobians.hpp" #include "Evolution/DiscontinuousGalerkin/MortarData.hpp" #include "Evolution/DiscontinuousGalerkin/MortarTags.hpp" #include "Utilities/ErrorHandling/Assert.hpp" /// \cond namespace Parallel { template <typename Metavariables> class GlobalCache; } // namespace Parallel namespace tuples { template <typename...> class TaggedTuple; } // namespace tuples /// \endcond namespace evolution::dg::subcell::fd::Actions { /*! * \brief Take a finite-difference time step on the subcell grid. * * The template parameter `TimeDerivative` must have a `static apply` function * that takes the `DataBox` by `gsl::not_null` as the first argument, the * cell-centered inverse Jacobian from the logical to the grid frame as the * second argument, and its determinant as the third argument. * * GlobalCache: nothing * * DataBox: * - Uses: * - `subcell::fd::Tags::InverseJacobianLogicalToGrid<Dim>` * - `subcell::fd::Tags::DetInverseJacobianLogicalToGrid` * - `domain::Tags::ElementMap<Dim, Frame::Grid>` * - `domain::CoordinateMaps::Tags::CoordinateMap<Dim, Grid, Inertial>` * - `subcell::Tags::Coordinates<Dim, Frame::ElementLogical>` * - Anything that `Metavariables::SubcellOptions::TimeDerivative` uses * - Adds: nothing * - Removes: nothing * - Modifies: * - `subcell::fd::Tags::InverseJacobianLogicalToGrid<Dim>` * - `subcell::fd::Tags::DetInverseJacobianLogicalToGrid` * - Anything that `Metavariables::SubcellOptions::TimeDerivative` modifies */ template <typename TimeDerivative> struct TakeTimeStep { template <typename DbTags, typename... InboxTags, typename Metavariables, typename ArrayIndex, typename ActionList, typename ParallelComponent, size_t Dim = Metavariables::volume_dim> static std::tuple<db::DataBox<DbTags>&&> apply( db::DataBox<DbTags>& box, tuples::TaggedTuple<InboxTags...>& /*inboxes*/, const Parallel::GlobalCache<Metavariables>& /*cache*/, const ArrayIndex& /*array_index*/, const ActionList /*meta*/, const ParallelComponent* const /*meta*/) { ASSERT((db::get<::domain::CoordinateMaps::Tags::CoordinateMap< Dim, Frame::Grid, Frame::Inertial>>(box)) .is_identity(), "Do not yet support moving mesh with DG-subcell."); db::mutate<fd::Tags::InverseJacobianLogicalToGrid<Dim>, fd::Tags::DetInverseJacobianLogicalToGrid>( make_not_null(&box), [](const auto inv_jac_ptr, const auto det_inv_jac_ptr, const auto& logical_to_grid_map, const auto& logical_coords) { if (not inv_jac_ptr->has_value()) { *inv_jac_ptr = logical_to_grid_map.inv_jacobian(logical_coords); *det_inv_jac_ptr = determinant(**inv_jac_ptr); } }, db::get<::domain::Tags::ElementMap<Dim, Frame::Grid>>(box), db::get<subcell::Tags::Coordinates<Dim, Frame::ElementLogical>>(box)); TimeDerivative::apply( make_not_null(&box), *db::get<fd::Tags::InverseJacobianLogicalToGrid<Dim>>(box), *db::get<fd::Tags::DetInverseJacobianLogicalToGrid>(box)); db::mutate<evolution::dg::Tags::MortarData<Dim>>( make_not_null(&box), [](const auto mortar_data_ptr) { for (auto& data : *mortar_data_ptr) { data.second = evolution::dg::MortarData<Dim>{}; } }); return {std::move(box)}; } }; } // namespace evolution::dg::subcell::fd::Actions
39.116505
79
0.694217
nilsvu
146304c24dd602e421b4b10a425dd16233a5178b
7,576
cpp
C++
glfw/src/Simulation/Systems/WindowSystem.cpp
hhsaez/crimild
e3efee09489939338df55e8af9a1f9ddc01301f7
[ "BSD-3-Clause" ]
36
2015-03-12T10:42:36.000Z
2022-01-12T04:20:40.000Z
glfw/src/Simulation/Systems/WindowSystem.cpp
hhsaez/crimild
e3efee09489939338df55e8af9a1f9ddc01301f7
[ "BSD-3-Clause" ]
1
2015-12-17T00:25:43.000Z
2016-02-20T12:00:57.000Z
glfw/src/Simulation/Systems/WindowSystem.cpp
hhsaez/crimild
e3efee09489939338df55e8af9a1f9ddc01301f7
[ "BSD-3-Clause" ]
6
2017-06-17T07:57:53.000Z
2019-04-09T21:11:24.000Z
#include "WindowSystem.hpp" #include <Concurrency/Async.hpp> #include <Foundation/Profiler.hpp> #include <Simulation/Simulation.hpp> #include <Simulation/Systems/RenderSystem.hpp> #include <Rendering/FrameBufferObject.hpp> #ifdef CRIMILD_PLATFORM_EMSCRIPTEN #include <emscripten.h> #include <emscripten/html5.h> void simulation_step( void ) { crimild::Simulation::getInstance()->update(); } #endif using namespace crimild; WindowSystem::WindowSystem( void ) { } WindowSystem::~WindowSystem( void ) { } bool WindowSystem::start( void ) { if ( !System::start() ) { return false; } int versionMajor; int versionMinor; int versionRevision; glfwGetVersion( &versionMajor, &versionMinor, &versionRevision ); Log::info( CRIMILD_CURRENT_CLASS_NAME, "Initialized GLFW ", versionMajor, ".", versionMinor, " rev. ", versionRevision ); if ( !createWindow() ) { return false; } int framebufferWidth = Simulation::getInstance()->getSettings()->get( "video.width", 1024 ); int framebufferHeight = Simulation::getInstance()->getSettings()->get( "video.height", 768 ); #if !defined( CRIMILD_PLATFORM_EMSCRIPTEN ) framebufferWidth = 0; framebufferHeight = 0; glfwGetFramebufferSize( _window, &framebufferWidth, &framebufferHeight); #endif // this is not working // bool supersampling = Simulation::getInstance()->getSettings()->get( "video.supersampling", true ); //#ifdef CRIMILD_PLATFORM_WIN32 // supersampling = false; //#endif // if ( supersampling ) { // int windowWidth = Simulation::getInstance()->getSettings()->get( "video.width", 1024 ); // int windowHeight = Simulation::getInstance()->getSettings()->get( "video.height", 768 ); // // framebufferWidth = Numerici::max( framebufferWidth, 2 * windowWidth ); // framebufferHeight = Numerici::max( framebufferHeight, 2 * windowHeight ); // } // else { // framebufferWidth = Simulation::getInstance()->getSettings()->get( "video.width", 1024 ); // framebufferHeight = Simulation::getInstance()->getSettings()->get( "video.height", 768 ); // } Log::info( CRIMILD_CURRENT_CLASS_NAME, "Framebuffer size (", framebufferWidth, "x", framebufferHeight, ")" ); auto renderer = Simulation::getInstance()->getRenderer(); auto screenBuffer = renderer->getScreenBuffer(); screenBuffer->resize( framebufferWidth, framebufferHeight ); renderer->configure(); // compute new aspect ratio for main camera, if any if ( Simulation::getInstance()->getMainCamera() != nullptr ) { auto aspect = ( float ) screenBuffer->getWidth() / ( float ) screenBuffer->getHeight(); Simulation::getInstance()->getMainCamera()->setAspectRatio( aspect ); } /* #ifdef __EMSCRIPTEN__ int result = emscripten_webgl_enable_extension(emscripten_webgl_get_current_context(), "OES_texture_float"); if (result < 0) { std::cerr << "Could not load extension \"OES_texture_float\"\n"; emscripten_run_script("alert('Could not load extension \"OES_texture_float\". Game will not work.')"); } result = emscripten_webgl_enable_extension(emscripten_webgl_get_current_context(), "OES_texture_float_linear"); if (result < 0) { std::cerr << "Could not load extension \"OES_texture_float_linear\"\n"; emscripten_run_script("alert('Could not load extension \"OES_texture_float_linear\". Game will not work.')"); } #endif */ crimild::concurrency::sync_frame( std::bind( &WindowSystem::update, this ) ); #ifdef CRIMILD_PLATFORM_EMSCRIPTEN emscripten_set_main_loop( simulation_step, 60, false ); #endif return true; } void WindowSystem::update( void ) { CRIMILD_PROFILE( "Window System - Update" ) static double accumTime = 0.0; double currentTime = glfwGetTime(); double delta = currentTime - accumTime; accumTime = currentTime; glfwPollEvents(); if ( glfwWindowShouldClose( _window ) ) { crimild::concurrency::sync_frame( [] { Simulation::getInstance()->stop(); }); return; } broadcastMessage( crimild::messaging::RenderNextFrame {} ); broadcastMessage( crimild::messaging::PresentNextFrame {} ); glfwSwapBuffers( _window ); if ( delta < 0.002 ) { // this trick prevents the simulation to run at very high speeds // this usually happens when the window is sent to background // and there is nothing to render int sleepTime = ( int )( ( 1.0 / 60.0 - delta ) * 1000.0 ); std::this_thread::sleep_for( std::chrono::milliseconds( sleepTime ) ); } if ( Simulation::getInstance()->getSettings()->get( "video.show_frame_time", false ) ) { std::string name = Simulation::getInstance()->getName(); std::stringstream ss; ss << name << " (" << delta << "ms)"; glfwSetWindowTitle( _window, ss.str().c_str() ); } crimild::concurrency::sync_frame( std::bind( &WindowSystem::update, this ) ); } void WindowSystem::stop( void ) { System::stop(); } bool WindowSystem::createWindow( void ) { int width = 1024; int height = 768; bool fullscreen = false; #if defined( CRIMILD_PLATFORM_EMSCRIPTEN ) // override window size based on canvas if ( emscripten_get_canvas_element_size( "crimild_canvas", &width, &height ) != EMSCRIPTEN_RESULT_SUCCESS ) { Log::error( CRIMILD_CURRENT_CLASS_NAME, "Cannot obtain canvas size" ); } Log::info( CRIMILD_CURRENT_CLASS_NAME, "Canvas size = (", width, "x", height, ")" ); Simulation::getInstance()->getSettings()->set( "video.width", width ); Simulation::getInstance()->getSettings()->set( "video.height", height ); Simulation::getInstance()->getSettings()->set( "video.fullscreen", fullscreen ); #endif width = Simulation::getInstance()->getSettings()->get( "video.width", 1024 ); height = Simulation::getInstance()->getSettings()->get( "video.height", 768 ); fullscreen = Simulation::getInstance()->getSettings()->get< bool >( "video.fullscreen", false ); Log::info( CRIMILD_CURRENT_CLASS_NAME, "Creating window of size (", width, "x", height, ")" ); std::string name = Simulation::getInstance()->getName(); if ( name == "" ) { name = "Crimild"; } bool vsync = true; int glMajor = 3; int glMinor = 3; int depthBits = 32; int stencilBits = 8; #if !defined( CRIMILD_PLATFORM_EMSCRIPTEN ) glfwWindowHint( GLFW_CONTEXT_VERSION_MAJOR, glMajor ); glfwWindowHint( GLFW_CONTEXT_VERSION_MINOR, glMinor ); glfwWindowHint( GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE ); glfwWindowHint( GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE ); glfwWindowHint( GLFW_RESIZABLE, GL_FALSE ); glfwWindowHint( GLFW_DEPTH_BITS, depthBits ); glfwWindowHint( GLFW_STENCIL_BITS, stencilBits ); #else glfwWindowHint(GLFW_RESIZABLE, GL_TRUE); #endif _window = glfwCreateWindow( width, height, name.c_str(), fullscreen ? glfwGetPrimaryMonitor() : NULL, NULL ); if ( _window == nullptr ) { Log::error( CRIMILD_CURRENT_CLASS_NAME, "Failed to create window" ); return false; } glfwMakeContextCurrent( _window ); glfwSwapInterval( vsync ? 1 : 0 ); broadcastMessage( messages::WindowSystemDidCreateWindow { this } ); glfwSetWindowSizeCallback( _window, []( GLFWwindow *window, int width, int height ) { Log::debug( CRIMILD_CURRENT_CLASS_NAME, "Window resized to ", width, "x", height ); }); glfwSetFramebufferSizeCallback( _window, []( GLFWwindow *window, int width, int height ) { Log::debug( CRIMILD_CURRENT_CLASS_NAME, "Framebuffer resized to ", width, "x", height ); }); return true; } void WindowSystem::destroyWindow( void ) { broadcastMessage( messages::WindowSystemWillDestroyWindow { this } ); }
32.655172
125
0.699446
hhsaez
14653b4874e9d18b6a8db04bca66c6e9b21bb73c
4,817
cpp
C++
snippets/cpp/VS_Snippets_Winforms/ToolboxCreatorCallbackSample/CPP/textdatatextboxcomponent.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
834
2017-06-24T10:40:36.000Z
2022-03-31T19:48:51.000Z
snippets/cpp/VS_Snippets_Winforms/ToolboxCreatorCallbackSample/CPP/textdatatextboxcomponent.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
7,042
2017-06-23T22:34:47.000Z
2022-03-31T23:05:23.000Z
snippets/cpp/VS_Snippets_Winforms/ToolboxCreatorCallbackSample/CPP/textdatatextboxcomponent.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
1,640
2017-06-23T22:31:39.000Z
2022-03-31T02:45:37.000Z
//<Snippet1> #using <System.Windows.Forms.dll> #using <System.Drawing.dll> #using <System.dll> using namespace System; using namespace System::ComponentModel; using namespace System::ComponentModel::Design; using namespace System::Drawing; using namespace System::Drawing::Design; using namespace System::Windows::Forms; using namespace System::Security::Permissions; namespace TextDataTextBoxComponent { // Custom toolbox item creates a TextBox and sets its Text property // to the constructor-specified text. [PermissionSetAttribute(SecurityAction::Demand, Name="FullTrust")] public ref class TextToolboxItem: public ToolboxItem { private: String^ text; delegate void SetTextMethodHandler( Control^ c, String^ text ); public: TextToolboxItem( String^ text ) : ToolboxItem() { this->text = text; } protected: // ToolboxItem::CreateComponentsCore to create the TextBox // and link a method to set its Text property. virtual array<IComponent^>^ CreateComponentsCore( IDesignerHost^ host ) override { TextBox^ textbox = dynamic_cast<TextBox^>(host->CreateComponent( TextBox::typeid )); // Because the designer resets the text of the textbox, use // a SetTextMethodHandler to set the text to the value of // the text data. Control^ c = dynamic_cast<Control^>(host->RootComponent); array<Object^>^temp0 = {textbox,text}; c->BeginInvoke( gcnew SetTextMethodHandler( this, &TextToolboxItem::OnSetText ), temp0 ); array<IComponent^>^temp1 = {textbox}; return temp1; } private: // Method to set the text property of a TextBox after it is initialized. void OnSetText( Control^ c, String^ text ) { c->Text = text; } }; // Component that adds a "Text" data format ToolboxItemCreatorCallback // to the Toolbox. This component uses a custom ToolboxItem that // creates a TextBox containing the text data. public ref class TextDataTextBoxComponent: public Component { private: bool creatorAdded; IToolboxService^ ts; public: TextDataTextBoxComponent() { creatorAdded = false; } property System::ComponentModel::ISite^ Site { // ISite to register TextBox creator virtual System::ComponentModel::ISite^ get() override { return __super::Site; } virtual void set( System::ComponentModel::ISite^ value ) override { if ( value != nullptr ) { __super::Site = value; if ( !creatorAdded ) AddTextTextBoxCreator(); } else { if ( creatorAdded ) RemoveTextTextBoxCreator(); __super::Site = value; } } } private: // Adds a "Text" data format creator to the toolbox that creates // a textbox from a text fragment pasted to the toolbox. void AddTextTextBoxCreator() { ts = dynamic_cast<IToolboxService^>(GetService( IToolboxService::typeid )); if ( ts != nullptr ) { ToolboxItemCreatorCallback^ textCreator = gcnew ToolboxItemCreatorCallback( this, &TextDataTextBoxComponent::CreateTextBoxForText ); try { ts->AddCreator( textCreator, "Text", dynamic_cast<IDesignerHost^>(GetService( IDesignerHost::typeid )) ); creatorAdded = true; } catch ( Exception^ ex ) { MessageBox::Show( ex->ToString(), "Exception Information" ); } } } // Removes any "Text" data format creator from the toolbox. void RemoveTextTextBoxCreator() { if ( ts != nullptr ) { ts->RemoveCreator( "Text", dynamic_cast<IDesignerHost^>(GetService( IDesignerHost::typeid )) ); creatorAdded = false; } } // ToolboxItemCreatorCallback delegate format method to create // the toolbox item. ToolboxItem^ CreateTextBoxForText( Object^ serializedObject, String^ format ) { IDataObject^ o = gcnew DataObject(dynamic_cast<IDataObject^>(serializedObject)); if( o->GetDataPresent("System::String", true) ) { String^ toolboxText = dynamic_cast<String^>(o->GetData( "System::String", true )); return( gcnew TextToolboxItem( toolboxText )); } return nullptr; } public: ~TextDataTextBoxComponent() { if ( creatorAdded ) RemoveTextTextBoxCreator(); } }; } //</Snippet1>
28.502959
98
0.599543
BohdanMosiyuk
1469780fc0d5d5e0e0d1909b33ae4af3590af9f3
372
cpp
C++
CodeChef DSA Learning/Week 1/ZCO14003.cpp
mishrraG/100DaysOfCode
3358af290d4f05889917808d68b95f37bd76e698
[ "MIT" ]
13
2020-08-10T14:06:37.000Z
2020-09-24T14:21:33.000Z
CodeChef DSA Learning/Week 1/ZCO14003.cpp
mishrraG/DaysOfCP
3358af290d4f05889917808d68b95f37bd76e698
[ "MIT" ]
null
null
null
CodeChef DSA Learning/Week 1/ZCO14003.cpp
mishrraG/DaysOfCP
3358af290d4f05889917808d68b95f37bd76e698
[ "MIT" ]
1
2020-09-05T12:56:22.000Z
2020-09-05T12:56:22.000Z
#include<bits/stdc++.h> using namespace std; int main() { long long int N,x,maxx; cin>>N; int A[N]; for(long long int i=0;i<N;i++) { cin>>A[i]; } sort(A,A+N); maxx=A[0]*(N-0); for(long long int i=1;i<N;i++) { x=A[i]*(N-i); if(x>=maxx) { maxx=x; } } cout<<maxx; return 0; }
15.5
34
0.419355
mishrraG
146c7f41d74c1071c46f79c497b8b2b56487b703
11,752
cpp
C++
Samples/CameraResolution/cpp/Scenario3_AspectRatio.xaml.cpp
dujianxin/Windows-universal-samples
d4e95ff0ac408c5d4d980bb18d53fb2c6556a273
[ "MIT" ]
2,504
2019-05-07T06:56:42.000Z
2022-03-31T19:37:59.000Z
Samples/CameraResolution/cpp/Scenario3_AspectRatio.xaml.cpp
dujianxin/Windows-universal-samples
d4e95ff0ac408c5d4d980bb18d53fb2c6556a273
[ "MIT" ]
314
2019-05-08T16:56:30.000Z
2022-03-21T07:13:45.000Z
Samples/CameraResolution/cpp/Scenario3_AspectRatio.xaml.cpp
dujianxin/Windows-universal-samples
d4e95ff0ac408c5d4d980bb18d53fb2c6556a273
[ "MIT" ]
2,219
2019-05-07T00:47:26.000Z
2022-03-30T21:12:31.000Z
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the Microsoft Public License. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* #include "pch.h" #include "Scenario3_AspectRatio.xaml.h" #include "StreamResolutionHelper.h" #include <sstream> #include <math.h> using namespace Concurrency; using namespace Platform; using namespace SDKTemplate; using namespace Windows::Devices; using namespace Windows::Devices::Enumeration; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::Media::Capture; using namespace Windows::Media::MediaProperties; using namespace Windows::Storage; using namespace Windows::UI::Core; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Controls::Primitives; using namespace Windows::UI::Xaml::Data; using namespace Windows::UI::Xaml::Input; using namespace Windows::UI::Xaml::Media; using namespace Windows::UI::Xaml::Navigation; /// <summary> /// Initializes a new instance of the <see cref="Scenario3_AspectRatio"/> class. /// </summary> Scenario3_AspectRatio::Scenario3_AspectRatio() : _rootPage(MainPage::Current) , _mediaCapture(nullptr) , _isPreviewing(false) , _isRecording(false) , _captureFolder(nullptr) { InitializeComponent(); } Scenario3_AspectRatio::~Scenario3_AspectRatio() { CleanupCameraAsync(); } void Scenario3_AspectRatio::OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^) { CleanupCameraAsync(); } /// <summary> /// Initializes the camera /// </summary> task<void> Scenario3_AspectRatio::InitializeCameraAsync() { _mediaCapture = ref new MediaCapture(); _mediaCaptureFailedEventToken = _mediaCapture->Failed += ref new MediaCaptureFailedEventHandler(this, &Scenario3_AspectRatio::MediaCapture_Failed); return create_task(_mediaCapture->InitializeAsync()) .then([this]() { PreviewControl->Source = _mediaCapture.Get(); return create_task(_mediaCapture->StartPreviewAsync()); }).then([this]() { return create_task(StorageLibrary::GetLibraryAsync(KnownLibraryId::Pictures)); }).then([this](StorageLibrary^ picturesLibrary) { _captureFolder = picturesLibrary->SaveFolder; if (_captureFolder == nullptr) { // In this case fall back to the local app storage since the Pictures Library is not available _captureFolder = ApplicationData::Current->LocalFolder; } }).then([this](task<void> previousTask) { try { _isPreviewing = true; previousTask.get(); return previousTask; } catch (AccessDeniedException^) { _rootPage->Current->NotifyUser("The app was denied access to the camera", NotifyType::ErrorMessage); return CleanupCameraAsync(); } }); } /// <summary> /// Cleans up the camera and state variables /// </summary> task<void> Scenario3_AspectRatio::CleanupCameraAsync() { std::list<task<void>> taskList; if (_isRecording) { auto stopRecordTask = create_task(_mediaCapture->StopRecordAsync()); taskList.push_back(stopRecordTask); _isRecording = false; } if (_isPreviewing) { auto stopPreviewTask = create_task(_mediaCapture->StopPreviewAsync()); taskList.push_back(stopPreviewTask); _isPreviewing = false; } return when_all(taskList.begin(), taskList.end()).then([this]() { if (_mediaCapture != nullptr) { _mediaCapture->Failed -= _mediaCaptureFailedEventToken; _mediaCapture = nullptr; } }); } /// <summary> /// Initializes the camera and populates the UI /// </summary> /// <param name="sender"></param> void Scenario3_AspectRatio::InitializeCameraButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^) { Button^ button = static_cast<Button^>(sender); button->IsEnabled = false; create_task(InitializeCameraAsync()) .then([this, button]() { if (_isPreviewing) { button->Visibility = Windows::UI::Xaml::Visibility::Collapsed; PreviewControl->Visibility = Windows::UI::Xaml::Visibility::Visible; CheckIfStreamsAreIdentical(); PopulateComboBoxes(); VideoButton->IsEnabled = true; } }); } /// <summary> /// Records an MP4 video to a StorageFile /// </summary> void Scenario3_AspectRatio::VideoButton_Click(Platform::Object^, Windows::UI::Xaml::RoutedEventArgs^) { if (_isPreviewing) { if (!_isRecording) { // Create a storage file and begin recording create_task(_captureFolder->CreateFileAsync("SimpleVideo.mp4", CreationCollisionOption::GenerateUniqueName)) .then([this](StorageFile^ file) { return create_task(_mediaCapture->StartRecordToStorageFileAsync(MediaEncodingProfile::CreateMp4(VideoEncodingQuality::Auto), file)) .then([this, file]() { // Reflect changes in the UI VideoButton->Content = "Stop Video"; _isRecording = true; _rootPage->Current->NotifyUser("Recording file, saving to: " + file->Path, NotifyType::StatusMessage); }); }).then([this](task<void> previousTask) { try { previousTask.get(); } catch (Exception^ ex) { // File I/O errors are reported as exceptions _rootPage->Current->NotifyUser(L"Exception when starting video recording: " + ex->Message, NotifyType::ErrorMessage); } }); } else { // Reflect the changes in the UI and stop recording VideoButton->Content = "Record Video"; _isRecording = false; create_task(_mediaCapture->StopRecordAsync()) .then([this]() { _rootPage->Current->NotifyUser("Stopped recording", NotifyType::StatusMessage); }); } } } /// <summary> /// Event handler for Preview settings combo box. Updates stream resolution based on the selection. /// </summary> /// <param name="sender"></param> void Scenario3_AspectRatio::PreviewSettings_Changed(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^) { if (_isPreviewing) { auto selectedItem = static_cast<ComboBoxItem^>(static_cast<ComboBox^>(sender)->SelectedItem); auto encodingProperties = static_cast<IMediaEncodingProperties^>(selectedItem->Tag); create_task(_rootPage->SetMediaStreamPropertiesAsync(_mediaCapture.Get(), PreviewControl, MediaStreamType::VideoPreview, encodingProperties)); // The preview just changed, update the video combo box MatchPreviewAspectRatio(); } } /// <summary> /// Event handler for Record settings combo box. Updates stream resolution based on the selection. /// </summary> /// <param name="sender"></param> void Scenario3_AspectRatio::VideoSettings_Changed(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^) { if (_isPreviewing) { auto selectedItem = static_cast<ComboBoxItem^>(static_cast<ComboBox^>(sender)->SelectedItem); auto encodingProperties = static_cast<IMediaEncodingProperties^>(selectedItem->Tag); create_task(_rootPage->SetMediaStreamPropertiesAsync(_mediaCapture.Get(), PreviewControl, MediaStreamType::VideoRecord, encodingProperties)); } } /// <summary> /// Populates the combo boxes with preview settings and matching ratio settings for the video stream /// </summary> void Scenario3_AspectRatio::PopulateComboBoxes() { // Query all properties of the device auto allProperties = _mediaCapture->VideoDeviceController->GetAvailableMediaStreamProperties(MediaStreamType::VideoPreview); // Populate the preview combo box with the entries for (auto encodingProperties : allProperties) { ComboBoxItem^ comboBoxItem = ref new ComboBoxItem(); auto streamHelper = ref new StreamResolutionHelper(encodingProperties); comboBoxItem->Content = streamHelper->GetFriendlyName(); comboBoxItem->Tag = encodingProperties; PreviewSettings->Items->Append(comboBoxItem); } MatchPreviewAspectRatio(); } /// <summary> /// Finds all the available video resolutions that match the aspect ratio of the preview stream /// Note: This should also be done with photos as well. This same method can be modified for photos /// by changing the MediaStreamType from VideoPreview to Photo. /// </summary> void Scenario3_AspectRatio::MatchPreviewAspectRatio() { // Clear out old entries VideoSettings->Items->Clear(); // Query all video properties of the device auto allProperties = _mediaCapture->VideoDeviceController->GetAvailableMediaStreamProperties(MediaStreamType::VideoRecord); // Query the current preview settings auto previewProperties = ref new StreamResolutionHelper(_mediaCapture->VideoDeviceController->GetMediaStreamProperties(MediaStreamType::VideoPreview)); // Get all formats that have the same-ish aspect ratio as the preview and create new entries in the UI // Allow for some tolerance in the aspect ratio comparison const double ASPECT_RATIO_TOLERANCE = 0.015; for (auto properties : allProperties) { auto streamHelper = ref new StreamResolutionHelper(properties); if (abs(streamHelper->AspectRatio() - previewProperties->AspectRatio()) < ASPECT_RATIO_TOLERANCE) { ComboBoxItem^ comboBoxItem = ref new ComboBoxItem(); comboBoxItem->Content = streamHelper->GetFriendlyName(); comboBoxItem->Tag = properties; VideoSettings->Items->Append(comboBoxItem); } } } /// <summary> /// On some devices there may not be seperate streams for preview/photo/video. In this case, changing any of them /// will change all of them since they are the same stream /// </summary> void Scenario3_AspectRatio::CheckIfStreamsAreIdentical() { if (_mediaCapture->MediaCaptureSettings->VideoDeviceCharacteristic == VideoDeviceCharacteristic::AllStreamsIdentical || _mediaCapture->MediaCaptureSettings->VideoDeviceCharacteristic == VideoDeviceCharacteristic::PreviewRecordStreamsIdentical) { _rootPage->Current->NotifyUser(L"Warning: Preview and record streams for this device are identical, changing one will affect the other", NotifyType::ErrorMessage); } } void Scenario3_AspectRatio::MediaCapture_Failed(MediaCapture^, MediaCaptureFailedEventArgs^ e) { String^ message = e->Message; Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, message]() { _rootPage->Current->NotifyUser("Preview stopped: " + message, NotifyType::ErrorMessage); _isPreviewing = false; CleanupCameraAsync(); })); }
37.909677
172
0.656654
dujianxin
14715c0d230539b642a3bffb6554833885758722
2,883
cpp
C++
archives/code_snippet/lru_cache.cpp
NopSmile/Blog
4e7d9eb7ced038781179b6db1c0fada73c353071
[ "MIT" ]
1
2019-05-25T03:07:07.000Z
2019-05-25T03:07:07.000Z
archives/code_snippet/lru_cache.cpp
NopSmile/Blog
4e7d9eb7ced038781179b6db1c0fada73c353071
[ "MIT" ]
1
2018-03-29T01:55:21.000Z
2018-03-29T01:55:21.000Z
archives/code_snippet/lru_cache.cpp
NopSmile/blog
4e7d9eb7ced038781179b6db1c0fada73c353071
[ "MIT" ]
2
2019-04-24T08:21:49.000Z
2021-01-15T06:49:47.000Z
#include <iostream> #include <unordered_map> #include <vector> using namespace std; template <class K, class T> struct LRUCacheEntry { K key; T data; LRUCacheEntry *prev; LRUCacheEntry *next; }; template <class K, class T> class LRUCache { private: unordered_map<K, LRUCacheEntry<K, T> *> mapping; vector<LRUCacheEntry<K, T> *> freeEntries; LRUCacheEntry<K, T> *head; LRUCacheEntry<K, T> *tail; LRUCacheEntry<K, T> *entries; public: LRUCache(size_t size) { entries = new LRUCacheEntry<K, T>[size]; for (int i = 0; i < size; i++) { freeEntries.push_back(entries + i); } head = new LRUCacheEntry<K, T>; tail = new LRUCacheEntry<K, T>; head->prev = NULL; head->next = tail; tail->next = NULL; tail->prev = head; } ~LRUCache() { delete head; delete tail; delete[] entries; } void Debug() { cout << "All cached elements:" << endl; LRUCacheEntry<K, T> *ptr = head; while ((ptr = ptr->next) != tail) { cout << ptr->key << " ==> " << ptr->data << endl; } } void Put(K key, T data) { LRUCacheEntry<K, T> *node = mapping[key]; if (node) { // refresh the link list detach(node); node->data = data; attach(node); } else { // cache is full if (freeEntries.empty()) { node = tail->prev; detach(node); mapping.erase(node->key); node->data = data; node->key = key; attach(node); } else { node = freeEntries.back(); freeEntries.pop_back(); node->key = key; node->data = data; mapping[key] = node; attach(node); } } } T Get(K key) { LRUCacheEntry<K, T> *node = mapping[key]; if (node) { detach(node); attach(node); return node->data; } else { return T(); } } private: void detach(LRUCacheEntry<K, T> *node) { node->prev->next = node->next; node->next->prev = node->prev; } void attach(LRUCacheEntry<K, T> *node) { node->next = head->next; node->prev = head; head->next = node; node->next->prev = node; } }; int main() { LRUCache<int, string> lruCache(3); lruCache.Put(1, "one"); lruCache.Debug(); lruCache.Put(2, "two"); lruCache.Debug(); lruCache.Put(3, "three"); lruCache.Debug(); lruCache.Put(2, "two"); lruCache.Debug(); lruCache.Put(4, "four"); lruCache.Put(1, "one"); lruCache.Debug(); return 0; }
24.853448
61
0.479015
NopSmile
147640ac9e9acbe98a5f1c527b48731746ee0e73
2,223
cpp
C++
Fedoraware/TeamFortress2/TeamFortress2/Features/Aimbot/Aimbot.cpp
FilippoFerarri/Fedoraware
94f6c18de53e0e5cc15dd4aeadb9e68143c765df
[ "WTFPL" ]
1
2022-03-06T06:21:04.000Z
2022-03-06T06:21:04.000Z
Fedoraware/TeamFortress2/TeamFortress2/Features/Aimbot/Aimbot.cpp
raspimana/Fedoraware
910bbbe0fc3cb335468f9005846a408c599ef9aa
[ "WTFPL" ]
1
2021-12-29T12:44:59.000Z
2022-01-05T14:28:59.000Z
Fedoraware/TeamFortress2/TeamFortress2/Features/Aimbot/Aimbot.cpp
raspimana/Fedoraware
910bbbe0fc3cb335468f9005846a408c599ef9aa
[ "WTFPL" ]
2
2022-03-03T02:25:56.000Z
2022-03-03T17:12:42.000Z
#include "Aimbot.h" #include "../Vars.h" #include "AimbotHitscan/AimbotHitscan.h" #include "AimbotProjectile/AimbotProjectile.h" #include "AimbotMelee/AimbotMelee.h" bool CAimbot::ShouldRun(CBaseEntity* pLocal, CBaseCombatWeapon* pWeapon) { if (g_GlobalInfo.m_bFreecamActive) return false; if (!Vars::Aimbot::Global::Active.m_Var) return false; if (g_Interfaces.EngineVGui->IsGameUIVisible() || g_Interfaces.Surface->IsCursorVisible()) return false; if (!pLocal->IsAlive() || pLocal->IsTaunting() || pLocal->IsBonked() || pLocal->GetFeignDeathReady() || pLocal->IsCloaked() || pLocal->IsInBumperKart() || pLocal->IsAGhost()) return false; switch (g_GlobalInfo.m_nCurItemDefIndex) { case Soldier_m_RocketJumper: case Demoman_s_StickyJumper: return false; default: break; } switch (pWeapon->GetWeaponID()) { case TF_WEAPON_PDA: case TF_WEAPON_PDA_ENGINEER_BUILD: case TF_WEAPON_PDA_ENGINEER_DESTROY: case TF_WEAPON_PDA_SPY: case TF_WEAPON_PDA_SPY_BUILD: case TF_WEAPON_BUILDER: case TF_WEAPON_INVIS: case TF_WEAPON_BUFF_ITEM: case TF_WEAPON_GRAPPLINGHOOK: { return false; } default: break; } return true; } void CAimbot::Run(CUserCmd* pCmd) { g_GlobalInfo.m_nCurrentTargetIdx = 0; g_GlobalInfo.m_flCurAimFOV = 0.0f; g_GlobalInfo.m_vPredictedPos = Vec3(); g_GlobalInfo.m_bHitscanRunning = false; g_GlobalInfo.m_bHitscanSilentActive = false; g_GlobalInfo.m_bProjectileSilentActive = false; g_GlobalInfo.m_vAimPos = Vec3(); auto pLocal = g_Interfaces.EntityList->GetClientEntity(g_Interfaces.Engine->GetLocalPlayer()); if (pLocal) { auto pWeapon = pLocal->GetActiveWeapon(); if (!pWeapon) { return; } if (!ShouldRun(pLocal, pWeapon)) return; SandvichAimbot::IsSandvich(); if (SandvichAimbot::bIsSandvich) { g_GlobalInfo.m_WeaponType = EWeaponType::HITSCAN; } switch (g_GlobalInfo.m_WeaponType) { case EWeaponType::HITSCAN: { g_AimbotHitscan.Run(pLocal, pWeapon, pCmd); break; } case EWeaponType::PROJECTILE: { g_AimbotProjectile.Run(pLocal, pWeapon, pCmd); break; } case EWeaponType::MELEE: { g_AimbotMelee.Run(pLocal, pWeapon, pCmd); break; } default: break; } } }
20.394495
95
0.727845
FilippoFerarri
147cad9b079ea385ab91f530e3b0945e55e14dad
1,226
hpp
C++
hls/params/w0.hpp
ninfueng/mpwn
9931b98c9e1096214ce757ca1efdd1b1165a2057
[ "MIT" ]
2
2021-09-24T07:57:11.000Z
2021-09-24T13:25:58.000Z
hls/params/w0.hpp
ninfueng/mpwn
9931b98c9e1096214ce757ca1efdd1b1165a2057
[ "MIT" ]
null
null
null
hls/params/w0.hpp
ninfueng/mpwn
9931b98c9e1096214ce757ca1efdd1b1165a2057
[ "MIT" ]
null
null
null
half w0[6][1][25] {{{-0.001442,-0.328,0.4973,-0.2595,0.01351,-0.1135,0.1498,0.3096,-0.406,0.1106,0.09283,0.1658,-0.09814,-0.2242,0.2142,0.02885,0.0949,-0.2009,-0.1613,0.282,-0.004322,-0.07214,-0.03928,-0.02211,0.06995,},},{{0.02261,0.0647,-0.02469,-0.04752,-0.01765,0.03223,0.0477,0.04922,-0.1432,0.012245,-0.1173,0.1669,-0.0987,0.08954,-0.0396,-0.4639,0.4917,-0.1576,0.09515,0.03427,-0.5444,-0.005318,0.572,-0.02985,0.003162,},},{{0.4265,0.2893,-0.239,-0.354,-0.1749,-0.207,0.4092,0.0982,0.0883,-0.2986,0.04077,0.04688,-0.2744,-0.025,0.2146,0.2316,-0.3535,-0.006546,-0.01182,0.1307,-0.1498,-0.07684,0.0685,0.1578,-0.01307,},},{{-0.2118,0.0566,-0.12134,-0.4246,-1.451,-0.0939,0.2842,0.1382,-0.1948,-0.2788,0.1548,-0.0682,0.0194,0.07465,-0.0669,0.189,-0.1122,0.0496,0.12384,-0.1262,0.03262,-0.2251,0.02748,0.1666,-0.007996,},},{{-0.4832,-0.1642,-0.05872,0.374,-0.05566,-1.048,-0.531,0.0833,-0.2935,0.1755,0.1015,0.1707,-0.11383,-0.183,0.03433,-0.1799,-0.05237,0.1192,0.1714,-0.1345,-0.1559,0.1093,0.0347,0.07886,-0.02057,},},{{-0.04736,-0.02267,0.1619,0.04074,-0.1953,0.12354,0.07007,0.2236,-0.025,-0.04797,-0.03647,0.1533,0.02415,-0.1779,0.06915,0.1879,-0.2375,-0.321,-0.05603,0.2,-0.3997,-1.509,-0.445,0.08057,-0.0379,},},};
613
1,225
0.651713
ninfueng
1484e2176b5768001e8057687103ca5090cdd844
816
cpp
C++
dianliwangguomanyouji/cocos2d/tools/simulator/libsimulator/proj.win32/Runtime_win32.cpp
lrmssc/dlwghyj
107f77cde9f3ed3e0ccaf05649481c6eaf81939c
[ "MIT" ]
20
2015-01-23T09:03:56.000Z
2021-08-28T17:19:38.000Z
dianliwangguomanyouji/cocos2d/tools/simulator/libsimulator/proj.win32/Runtime_win32.cpp
lrmssc/dlwghyj
107f77cde9f3ed3e0ccaf05649481c6eaf81939c
[ "MIT" ]
3
2015-03-31T06:13:40.000Z
2017-10-04T12:30:29.000Z
dianliwangguomanyouji/cocos2d/tools/simulator/libsimulator/proj.win32/Runtime_win32.cpp
lrmssc/dlwghyj
107f77cde9f3ed3e0ccaf05649481c6eaf81939c
[ "MIT" ]
16
2015-06-08T04:10:12.000Z
2021-08-28T17:19:38.000Z
#include <io.h> #include <direct.h> #include <stdio.h> #include <vector> #include <string> #include "cocos2d.h" #include "runtime/ConfigParser.h" using namespace std; string getIPAddress() { WSADATA wsaData; char name[155]={0}; char *ip=nullptr; PHOSTENT hostinfo; // customized by user auto &bindAddress = ConfigParser::getInstance()->getBindAddress(); if (!bindAddress.empty()) { return bindAddress; } if ( WSAStartup( MAKEWORD(2,0), &wsaData ) == 0 ) { if( gethostname ( name, sizeof(name)) == 0) { if((hostinfo = gethostbyname(name)) != NULL) { ip = inet_ntoa (*(struct in_addr *)*hostinfo->h_addr_list); } } WSACleanup( ); } return ip; }
20.923077
75
0.54902
lrmssc
14860a9c838150c9c097a0b0cf09fe4cd12356e2
5,326
cpp
C++
Source/Data/TLS/Base/NptTlsTrustAnchor_Base_0033.cpp
Dschee/Neptune
016d132f8e4449e6b0f79fbc5ce25de365eab983
[ "BSD-3-Clause" ]
17
2015-09-17T06:53:47.000Z
2021-08-09T03:41:21.000Z
Source/Data/TLS/Base/NptTlsTrustAnchor_Base_0033.cpp
Dschee/Neptune
016d132f8e4449e6b0f79fbc5ce25de365eab983
[ "BSD-3-Clause" ]
17
2015-01-05T21:06:22.000Z
2015-12-07T20:45:44.000Z
Source/Data/TLS/Base/NptTlsTrustAnchor_Base_0033.cpp
Dschee/Neptune
016d132f8e4449e6b0f79fbc5ce25de365eab983
[ "BSD-3-Clause" ]
18
2015-12-09T21:27:41.000Z
2020-11-27T11:38:49.000Z
/***************************************************************** | | Neptune - Trust Anchors | | This file is automatically generated by a script, do not edit! | | Copyright (c) 2002-2010, Axiomatic Systems, LLC. | All rights reserved. | | Redistribution and use in source and binary forms, with or without | modification, are permitted provided that the following conditions are met: | * Redistributions of source code must retain the above copyright | notice, this list of conditions and the following disclaimer. | * Redistributions in binary form must reproduce the above copyright | notice, this list of conditions and the following disclaimer in the | documentation and/or other materials provided with the distribution. | * Neither the name of Axiomatic Systems nor the | names of its contributors may be used to endorse or promote products | derived from this software without specific prior written permission. | | THIS SOFTWARE IS PROVIDED BY AXIOMATIC SYSTEMS ''AS IS'' AND ANY | EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE | DISCLAIMED. IN NO EVENT SHALL AXIOMATIC SYSTEMS BE LIABLE FOR ANY | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | ****************************************************************/ /* Equifax Secure Global eBusiness CA */ const unsigned char NptTlsTrustAnchor_Base_0033_Data[660] = { 0x30,0x82,0x02,0x90,0x30,0x82,0x01,0xf9 ,0xa0,0x03,0x02,0x01,0x02,0x02,0x01,0x01 ,0x30,0x0d,0x06,0x09,0x2a,0x86,0x48,0x86 ,0xf7,0x0d,0x01,0x01,0x04,0x05,0x00,0x30 ,0x5a,0x31,0x0b,0x30,0x09,0x06,0x03,0x55 ,0x04,0x06,0x13,0x02,0x55,0x53,0x31,0x1c ,0x30,0x1a,0x06,0x03,0x55,0x04,0x0a,0x13 ,0x13,0x45,0x71,0x75,0x69,0x66,0x61,0x78 ,0x20,0x53,0x65,0x63,0x75,0x72,0x65,0x20 ,0x49,0x6e,0x63,0x2e,0x31,0x2d,0x30,0x2b ,0x06,0x03,0x55,0x04,0x03,0x13,0x24,0x45 ,0x71,0x75,0x69,0x66,0x61,0x78,0x20,0x53 ,0x65,0x63,0x75,0x72,0x65,0x20,0x47,0x6c ,0x6f,0x62,0x61,0x6c,0x20,0x65,0x42,0x75 ,0x73,0x69,0x6e,0x65,0x73,0x73,0x20,0x43 ,0x41,0x2d,0x31,0x30,0x1e,0x17,0x0d,0x39 ,0x39,0x30,0x36,0x32,0x31,0x30,0x34,0x30 ,0x30,0x30,0x30,0x5a,0x17,0x0d,0x32,0x30 ,0x30,0x36,0x32,0x31,0x30,0x34,0x30,0x30 ,0x30,0x30,0x5a,0x30,0x5a,0x31,0x0b,0x30 ,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02 ,0x55,0x53,0x31,0x1c,0x30,0x1a,0x06,0x03 ,0x55,0x04,0x0a,0x13,0x13,0x45,0x71,0x75 ,0x69,0x66,0x61,0x78,0x20,0x53,0x65,0x63 ,0x75,0x72,0x65,0x20,0x49,0x6e,0x63,0x2e ,0x31,0x2d,0x30,0x2b,0x06,0x03,0x55,0x04 ,0x03,0x13,0x24,0x45,0x71,0x75,0x69,0x66 ,0x61,0x78,0x20,0x53,0x65,0x63,0x75,0x72 ,0x65,0x20,0x47,0x6c,0x6f,0x62,0x61,0x6c ,0x20,0x65,0x42,0x75,0x73,0x69,0x6e,0x65 ,0x73,0x73,0x20,0x43,0x41,0x2d,0x31,0x30 ,0x81,0x9f,0x30,0x0d,0x06,0x09,0x2a,0x86 ,0x48,0x86,0xf7,0x0d,0x01,0x01,0x01,0x05 ,0x00,0x03,0x81,0x8d,0x00,0x30,0x81,0x89 ,0x02,0x81,0x81,0x00,0xba,0xe7,0x17,0x90 ,0x02,0x65,0xb1,0x34,0x55,0x3c,0x49,0xc2 ,0x51,0xd5,0xdf,0xa7,0xd1,0x37,0x8f,0xd1 ,0xe7,0x81,0x73,0x41,0x52,0x60,0x9b,0x9d ,0xa1,0x17,0x26,0x78,0xad,0xc7,0xb1,0xe8 ,0x26,0x94,0x32,0xb5,0xde,0x33,0x8d,0x3a ,0x2f,0xdb,0xf2,0x9a,0x7a,0x5a,0x73,0x98 ,0xa3,0x5c,0xe9,0xfb,0x8a,0x73,0x1b,0x5c ,0xe7,0xc3,0xbf,0x80,0x6c,0xcd,0xa9,0xf4 ,0xd6,0x2b,0xc0,0xf7,0xf9,0x99,0xaa,0x63 ,0xa2,0xb1,0x47,0x02,0x0f,0xd4,0xe4,0x51 ,0x3a,0x12,0x3c,0x6c,0x8a,0x5a,0x54,0x84 ,0x70,0xdb,0xc1,0xc5,0x90,0xcf,0x72,0x45 ,0xcb,0xa8,0x59,0xc0,0xcd,0x33,0x9d,0x3f ,0xa3,0x96,0xeb,0x85,0x33,0x21,0x1c,0x3e ,0x1e,0x3e,0x60,0x6e,0x76,0x9c,0x67,0x85 ,0xc5,0xc8,0xc3,0x61,0x02,0x03,0x01,0x00 ,0x01,0xa3,0x66,0x30,0x64,0x30,0x11,0x06 ,0x09,0x60,0x86,0x48,0x01,0x86,0xf8,0x42 ,0x01,0x01,0x04,0x04,0x03,0x02,0x00,0x07 ,0x30,0x0f,0x06,0x03,0x55,0x1d,0x13,0x01 ,0x01,0xff,0x04,0x05,0x30,0x03,0x01,0x01 ,0xff,0x30,0x1f,0x06,0x03,0x55,0x1d,0x23 ,0x04,0x18,0x30,0x16,0x80,0x14,0xbe,0xa8 ,0xa0,0x74,0x72,0x50,0x6b,0x44,0xb7,0xc9 ,0x23,0xd8,0xfb,0xa8,0xff,0xb3,0x57,0x6b ,0x68,0x6c,0x30,0x1d,0x06,0x03,0x55,0x1d ,0x0e,0x04,0x16,0x04,0x14,0xbe,0xa8,0xa0 ,0x74,0x72,0x50,0x6b,0x44,0xb7,0xc9,0x23 ,0xd8,0xfb,0xa8,0xff,0xb3,0x57,0x6b,0x68 ,0x6c,0x30,0x0d,0x06,0x09,0x2a,0x86,0x48 ,0x86,0xf7,0x0d,0x01,0x01,0x04,0x05,0x00 ,0x03,0x81,0x81,0x00,0x30,0xe2,0x01,0x51 ,0xaa,0xc7,0xea,0x5f,0xda,0xb9,0xd0,0x65 ,0x0f,0x30,0xd6,0x3e,0xda,0x0d,0x14,0x49 ,0x6e,0x91,0x93,0x27,0x14,0x31,0xef,0xc4 ,0xf7,0x2d,0x45,0xf8,0xec,0xc7,0xbf,0xa2 ,0x41,0x0d,0x23,0xb4,0x92,0xf9,0x19,0x00 ,0x67,0xbd,0x01,0xaf,0xcd,0xe0,0x71,0xfc ,0x5a,0xcf,0x64,0xc4,0xe0,0x96,0x98,0xd0 ,0xa3,0x40,0xe2,0x01,0x8a,0xef,0x27,0x07 ,0xf1,0x65,0x01,0x8a,0x44,0x2d,0x06,0x65 ,0x75,0x52,0xc0,0x86,0x10,0x20,0x21,0x5f ,0x6c,0x6b,0x0f,0x6c,0xae,0x09,0x1c,0xaf ,0xf2,0xa2,0x18,0x34,0xc4,0x75,0xa4,0x73 ,0x1c,0xf1,0x8d,0xdc,0xef,0xad,0xf9,0xb3 ,0x76,0xb4,0x92,0xbf,0xdc,0x95,0x10,0x1e ,0xbe,0xcb,0xc8,0x3b,0x5a,0x84,0x60,0x19 ,0x56,0x94,0xa9,0x55}; const unsigned int NptTlsTrustAnchor_Base_0033_Size = 660;
44.383333
79
0.756102
Dschee
148dcb479dd24e71423dbf1afe5f7108364acfa3
1,266
cpp
C++
test/node_test/fasta_ops.cpp
danielsundfeld/astar_msa
f4f5c90c9c8b1da76eee2229657427cd4db632a7
[ "MIT" ]
2
2019-04-13T23:31:06.000Z
2020-12-21T15:33:55.000Z
test/node_test/fasta_ops.cpp
danielsundfeld/astar_msa
f4f5c90c9c8b1da76eee2229657427cd4db632a7
[ "MIT" ]
null
null
null
test/node_test/fasta_ops.cpp
danielsundfeld/astar_msa
f4f5c90c9c8b1da76eee2229657427cd4db632a7
[ "MIT" ]
null
null
null
#include <iostream> #include <map> #include "backtrace.h" #include "HeuristicHPair.h" #include "read_fasta.h" using namespace std; #define N_SEQ 4 void test_backtrace(bool add_dumb = false) { Node<N_SEQ> n = Sequences::get_initial_node<N_SEQ>(); std::map< Coord<N_SEQ>, Node<N_SEQ> > ClosedList; ClosedList[n.pos] = n; if (add_dumb) { vector< Node<N_SEQ> > v; n.getNeigh(&v); n = v[0]; ClosedList[n.pos] = n; } while (!(Sequences::is_final(n.pos))) { vector< Node<N_SEQ> > v; n.getNeigh(&v); Node<N_SEQ> min; min.set_max(); for (auto &it : v) if (min.get_f() > it.get_f()) min = it; n = min; ClosedList[n.pos] = n; } backtrace(&ClosedList); } void test_all_backtrace() { test_backtrace(true); test_backtrace(false); } int main(void) { if (read_fasta_file("arq.fasta")) { cout << "Error loading fasta arq.fasta\n"; return -1; } if (Sequences::get_seq_num() != N_SEQ) { cout << "Invalid number of sequences in arq.fasta. Expected: " << N_SEQ << endl; return -1; } HeuristicHPair::getInstance()->init(); test_all_backtrace(); return 0; }
19.181818
88
0.560032
danielsundfeld
14914f9ad0fb8aee7826dd233c109057a134d9ec
16,474
cpp
C++
tcltk/tcltk.cpp
AmziLS/interfaces
d96e3d9f42bfd25c28348a3f22163582c1867b3d
[ "MIT" ]
10
2016-04-16T23:15:29.000Z
2022-02-28T21:56:48.000Z
tcltk/tcltk.cpp
AmziLS/interfaces
d96e3d9f42bfd25c28348a3f22163582c1867b3d
[ "MIT" ]
8
2016-04-16T15:29:15.000Z
2021-05-09T20:53:22.000Z
tcltk/tcltk.cpp
AmziLS/interfaces
d96e3d9f42bfd25c28348a3f22163582c1867b3d
[ "MIT" ]
7
2016-04-18T04:03:36.000Z
2021-05-07T00:54:05.000Z
// tcltk.cpp : Defines the entry point for the DLL application. // #ifdef _UNICODE #ifndef UNICODE #define UNICODE #endif #endif #include "stdafx.h" #include "stdio.h" #include "amzi.h" #include <tchar.h> #include "tcl.h" #include "tk.h" #include <vector> TF EXPFUNC p_tcl_main(ENGid); TF EXPFUNC p_tcl_init(ENGid); TF EXPFUNC p_tk_mainloop(ENGid); TF EXPFUNC p_tcl_eval(ENGid); TF EXPFUNC p_tcl_evalfile(ENGid); TF EXPFUNC p_tcl_finish(ENGid); TF EXPFUNC p_tcl_exit(ENGid); PRED_INIT extPreds[] = { {_T("tcl_init"), 3, p_tcl_init}, {_T("tk_mainloop"), 0, p_tk_mainloop}, {_T("tcl_finish"), 1, p_tcl_finish}, {_T("tcl_eval"), 3, p_tcl_eval}, {_T("tcl_evalfile"), 3, p_tcl_evalfile}, {NULL, 0, NULL} }; #ifdef _WIN32 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD dwReason, LPVOID lpRes) { switch(dwReason) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } #endif /* _WIN32 */ //------------------------------------------- // Required LSX Initialization Function // #ifdef _WIN32 extern "C" __declspec(dllexport) RC EXPFUNC InitPreds(ENGid eid, void* p) #else extern "C" RC EXPFUNC InitPreds(ENGid eid, void* p) #endif { RC rc; _TCHAR buf[80]; rc = lsInitPreds(eid, extPreds); if (rc) { #ifdef _WIN32 _stprintf(buf, _T("Error #%d Loading atcltk Predicates"), rc); MessageBox(NULL, buf, "atcltk lsx", MB_OK); #else printf(_T("Error #%d Loading atcltk Predicates"), rc); #endif } //else // MessageBox(NULL, "ATclTk Predicates Loaded", "ATCLTK LSX", MB_OK); return 0; } //----------------------------------------------------------- // Tcl/Tk -> Prolog functions // std::vector<TERM> g_called_terms; // A stack of called terms // ls_call int tcl_ls_call(ClientData eng, Tcl_Interp *terp, int objc, Tcl_Obj *CONST objv[]) { TERM t; char *query; Tcl_Obj *result; query = Tcl_GetString(objv[1]); RC rc = lsCallStr(eng, &t, query); result = Tcl_GetObjResult(terp); if (rc == TRUE) { Tcl_SetIntObj(result, (int)t); return TCL_OK; } else if (rc == FALSE) { Tcl_SetIntObj(result, 0); return TCL_OK; } else { char *message = Tcl_Alloc(256); lsGetExceptMsg(eng, message, 255); Tcl_ResetResult(terp); Tcl_AppendStringsToObj(result, "Prolog error: ", message, NULL); Tcl_Free(message); return TCL_ERROR; } } // ls_exec int tcl_ls_exec(ClientData eng, Tcl_Interp *terp, int objc, Tcl_Obj *CONST objv[]) { TERM t; char *query; Tcl_Obj *result; query = Tcl_GetString(objv[1]); RC rc = lsExecStr(eng, &t, query); result = Tcl_GetObjResult(terp); if (rc == TRUE) { Tcl_SetIntObj(result, (int)t); return TCL_OK; } else if (rc == FALSE) { Tcl_SetIntObj(result, 0); return TCL_OK; } else { char *message = Tcl_Alloc(256); lsGetExceptMsg(eng, message, 255); Tcl_ResetResult(terp); Tcl_AppendStringsToObj(result, "Prolog error: ", message, NULL); Tcl_Free(message); return TCL_ERROR; } } // ls_redo int tcl_ls_redo(ClientData eng, Tcl_Interp *terp, int objc, Tcl_Obj *CONST objv[]) { Tcl_Obj *result; int it; result = Tcl_GetObjResult(terp); Tcl_GetIntFromObj(terp, objv[1], &it); if (it == 0) { Tcl_SetIntObj(result, 0); return TCL_OK; } else { TF tf = lsRedo(eng); if (tf == TRUE) { Tcl_SetIntObj(result, it); return TCL_OK; } else if (tf == FALSE) { Tcl_SetIntObj(result, 0); return TCL_OK; } else { char message[256]; lsGetExceptMsg(eng, message, 255); Tcl_ResetResult(terp); Tcl_AppendStringsToObj(result, "Prolog error: ", message, NULL); return TCL_ERROR; } } } // ls_clearcall int tcl_ls_clearcall(ClientData eng, Tcl_Interp *terp, int objc, Tcl_Obj *CONST objv[]) { Tcl_Obj *result; int it; result = Tcl_GetObjResult(terp); Tcl_GetIntFromObj(terp, objv[1], &it); if (it == 0) { Tcl_SetIntObj(result, 0); return TCL_OK; } else { TF tf = lsClearCall(eng); Tcl_SetIntObj(result, 0); return TCL_OK; } } // ls_getstrarg term i // returns string value of term's ith argument (starting at 1) int tcl_ls_getstrarg(ClientData eng, Tcl_Interp *terp, int objc, Tcl_Obj *CONST objv[]) { TERM t, targ; int it; int i; char s[512]; Tcl_Obj *result; Tcl_GetIntFromObj(terp, objv[1], &it); Tcl_GetIntFromObj(terp, objv[2], &i); result = Tcl_GetObjResult(terp); if (it == 0) { Tcl_SetStringObj(result, "", -1); return TCL_OK; } else { t = (TERM) it; lsGetArg(eng, t, i, cTERM, &targ); lsTermToStr(eng, targ, s, 511); Tcl_SetStringObj(result, s, -1); return TCL_OK; } } // ls_termtostr term // returns string value of term int tcl_ls_termtostr(ClientData eng, Tcl_Interp *terp, int objc, Tcl_Obj *CONST objv[]) { TERM t; int it; char s[512]; Tcl_Obj *result; Tcl_GetIntFromObj(terp, objv[1], &it); result = Tcl_GetObjResult(terp); if (it == 0) { Tcl_SetStringObj(result, "", -1); return TCL_OK; } else { t = (TERM) it; lsTermToStr(eng, t, s, 511); Tcl_SetStringObj(result, s, -1); return TCL_OK; } } // ls_termtostrq term // returns quoted string value of term suitable for sending back to Prolog int tcl_ls_termtostrq(ClientData eng, Tcl_Interp *terp, int objc, Tcl_Obj *CONST objv[]) { TERM t; int it; char s[512]; Tcl_Obj *result; Tcl_GetIntFromObj(terp, objv[1], &it); result = Tcl_GetObjResult(terp); if (it == 0) { Tcl_SetStringObj(result, "", -1); return TCL_OK; } else { t = (TERM) it; lsTermToStrQ(eng, t, s, 511); Tcl_SetStringObj(result, s, -1); return TCL_OK; } } // The Prolog query returned a list of the form [varname, value, ...] // if there were any variables bindings. Map them to a Tcl list, // and return. The first name=value pair is result and either true/false. int map_prolog_tcl_lists(Tcl_Interp *terp, ClientData eng, TF tf, TERM vqt) { TERM varlist; // the [varname, value, ...] list TERM elem; // an element in the var list int i; int rlen; // length of result varname, value list char *answer; char elemstr[512]; Tcl_Obj *result; Tcl_Obj **tclobjs; // Get the result object for this interpreter. result = Tcl_GetObjResult(terp); // The query succeeded if (tf == TRUE) { // Get the length of the result list lsGetArg(eng, vqt, 2, cINT, &rlen); // Allocate an array of Tcl_Objects to put in the list tclobjs = (Tcl_Obj**)Tcl_Alloc( (rlen+2) * sizeof(Tcl_Obj*) ); // Set the first name value pair to 'result' 'true' tclobjs[0] = Tcl_NewStringObj("result", -1); tclobjs[1] = Tcl_NewStringObj("true", -1); // Get the [varname, value, ...] list from Prolog lsGetArg(eng, vqt, 3, cTERM, &varlist); // Populate the array of Tcl objects with the Prolog // list elements. for (i=0; i<rlen; i++) { // Get the next element, might be a name or a // value but treat them alike. lsGetHead(eng, varlist, cTERM, &elem); lsTermToStr(eng, elem, elemstr, 511); // Put it in the array. tclobjs[i+2] = Tcl_NewStringObj(elemstr, -1); // Get the tail of the list for next iteration. varlist = lsGetTail(eng, varlist); } Tcl_SetListObj(result, rlen+2, tclobjs); return TCL_OK; } else if (tf == FALSE) { g_called_terms.pop_back(); // remove the last called term // Allocate an array of Tcl_Objects to put in the list tclobjs = (Tcl_Obj**)Tcl_Alloc( 2 * sizeof(Tcl_Obj*) ); // Set the first name value pair to 'result' 'false' tclobjs[0] = Tcl_NewStringObj("result", -1); tclobjs[1] = Tcl_NewStringObj("false", -1); Tcl_SetListObj(result, 2, tclobjs); return TCL_OK; } else { answer = Tcl_Alloc(300); strcpy(answer, "Logic Server Error: "); char *message = Tcl_Alloc(256); lsGetExceptMsg(eng, message, 255); strcat(answer, message); Tcl_SetStringObj(result, answer, -1); Tcl_Free(message); return TCL_ERROR; } } // ls_query option string // This is the high-level query command that returns a list of variable names // and values. It is thought this approach will replace other logic server // calls in the future. If there are no variables, it returns "yes", // and if the query failed, it returns "no". int tcl_ls_query (ClientData eng, Tcl_Interp *terp, int objc, Tcl_Obj *CONST objv[]) { TERM vqt; // the varlist query term char *varlist_query; char *query; char *option; int qlen; TF tf; // Get the option, either once, first, next or clear option = Tcl_GetStringFromObj(objv[1], NULL); if ( 0 == strcmp(option, "once") ) { // Get the user's query and embedded it in a call to // varlist_query/3 which will return a list of variables // and their bindings. query = Tcl_GetStringFromObj(objv[2], &qlen); varlist_query = Tcl_Alloc(qlen + 50); sprintf(varlist_query, "varlist_query(`%s`, L, V)", query); // don't make variable names longer unless you up varlist query tf = lsExecStr(eng, &vqt, varlist_query); Tcl_Free(varlist_query); return map_prolog_tcl_lists(terp, eng, tf, vqt); } else if ( 0 == strcmp(option, "first") ) { // Get the user's query and embedded it in a call to // varlist_query/3 which will return a list of variables // and their bindings. query = Tcl_GetStringFromObj(objv[2], &qlen); varlist_query = Tcl_Alloc(qlen + 50); sprintf(varlist_query, "varlist_query(`%s`, L, V)", query); // don't make variable names longer unless you up varlist query tf = lsCallStr(eng, &vqt, varlist_query); Tcl_Free(varlist_query); g_called_terms.push_back(vqt); // save as the last called term, for ls_query_next return map_prolog_tcl_lists(terp, eng, tf, vqt); } else if ( 0 == strcmp(option, "next") ) { if (g_called_terms.empty() == true) { Tcl_Obj *result = Tcl_GetObjResult(terp); Tcl_SetStringObj(result, "No active query to redo", -1); return TCL_ERROR; } vqt = g_called_terms.back(); // from the saved list tf = lsRedo(eng); return map_prolog_tcl_lists(terp, eng, tf, vqt); } else if ( 0 == strcmp(option, "clear") ) { if (g_called_terms.empty() == true) { Tcl_Obj *result = Tcl_GetObjResult(terp); Tcl_SetStringObj(result, "No active query to clear", -1); return TCL_ERROR; } g_called_terms.pop_back(); // clear the query term lsClearCall(eng); return TCL_OK; } else { Tcl_Obj *result = Tcl_GetObjResult(terp); Tcl_SetStringObj(result, "Unknown ls_query option", -1); return TCL_ERROR; } } //------------------------------------------------------------ // Prolog -> Tck/Tk extended predicates // // tcl_init(-TclInterpreter, +TclLib, -Result) // TclInterpreter - The address returned for future calls. // TclLib - The location of the Tcl libraries. Standards // are 'amzi', 'tcl', 'here'. Otherwise, the path. // The directory structure is TclLib/tcl and // TclLib/tk, except if 'tcl', in which case it uses // whereever Tcl is installed on the machine. // Result - The return result from the interpreter. TF EXPFUNC p_tcl_init(ENGid CurEng) { Tcl_Interp *terp; char msg[120]; const char *amzi_dir; char library[700]; char tcl_lib[500]; Tcl_FindExecutable("atcltk.lsx"); terp = Tcl_CreateInterp(); // New query interface Tcl_CreateObjCommand(terp, "ls_query", tcl_ls_query, CurEng, NULL); // Classic Logic Server calls Tcl_CreateObjCommand(terp, "ls_call", tcl_ls_call, CurEng, NULL); Tcl_CreateObjCommand(terp, "ls_exec", tcl_ls_exec, CurEng, NULL); Tcl_CreateObjCommand(terp, "ls_redo", tcl_ls_redo, CurEng, NULL); Tcl_CreateObjCommand(terp, "ls_clearcall", tcl_ls_clearcall, CurEng, NULL); Tcl_CreateObjCommand(terp, "ls_termtostr", tcl_ls_termtostr, CurEng, NULL); Tcl_CreateObjCommand(terp, "ls_termtostrq", tcl_ls_termtostrq, CurEng, NULL); Tcl_CreateObjCommand(terp, "ls_getstrarg", tcl_ls_getstrarg, CurEng, NULL); lsGetParm(CurEng, 2, cSTR, tcl_lib); if ( 0 == strcmp(tcl_lib, "amzi") ) { amzi_dir = Tcl_GetVar(terp, "env(AMZI_DIR)", TCL_GLOBAL_ONLY); strcpy(library, amzi_dir); strcat(library, "\\lsapis\\tcltk\\lib\\tcl"); Tcl_SetVar(terp, "tcl_library", library, TCL_GLOBAL_ONLY); strcpy(library, amzi_dir); strcat(library, "\\lsapis\\tcltk\\lib\\tk"); Tcl_SetVar(terp, "tk_library", library, TCL_GLOBAL_ONLY); } else if ( 0 == strcmp(tcl_lib, "here") ) { strcpy(library, ".\\lib\\tcl"); Tcl_SetVar(terp, "tcl_library", library, TCL_GLOBAL_ONLY); strcpy(library, ".\\lib\\tk"); Tcl_SetVar(terp, "tk_library", library, TCL_GLOBAL_ONLY); } else if ( 0 == strcmp(tcl_lib, "tcl") ) ; else { strcpy(library, tcl_lib); strcat(library, "\\lib\\tcl"); Tcl_SetVar(terp, "tcl_library", library, TCL_GLOBAL_ONLY); strcpy(library, tcl_lib); strcat(library, "\\lib\\tk"); Tcl_SetVar(terp, "tk_library", library, TCL_GLOBAL_ONLY); } if (Tcl_Init(terp) == TCL_ERROR) { strcpy(msg, "Tcl Init: "); strncat(msg, terp->result, 100); lsErrRaise(CurEng, msg); } if (Tk_Init(terp) == TCL_ERROR) { strcpy(msg, "Tk Init: "); strncat(msg, terp->result, 100); lsErrRaise(CurEng, msg); } lsUnifyParm(CurEng, 1, cADDR, &terp); lsUnifyParm(CurEng, 3, cASTR, terp->result); return TRUE; } TF EXPFUNC p_tk_mainloop(ENGid CurEng) { Tk_MainLoop(); return TRUE; } TF EXPFUNC p_tcl_eval(ENGid CurEng) { Tcl_Interp *terp = NULL; size_t len; char *buffer; //char buffer[10000]; int rc; lsGetParm(CurEng, 1, cADDR, &terp); len = 3 * lsStrParmLen(CurEng, 2); // blatent hack in case utf8io flag set buffer = (char*)malloc( (len+1)*sizeof(char) ); lsGetParm(CurEng, 2, cASTR, buffer); Tcl_Preserve(terp); rc = Tcl_Eval(terp, buffer); Tcl_Release(terp); if (rc == TCL_OK) { lsUnifyParm(CurEng, 3, cASTR, terp->result); return TRUE; } else { lsErrRaise(CurEng, terp->result); return FALSE; } } TF EXPFUNC p_tcl_evalfile(ENGid CurEng) { Tcl_Interp *terp = NULL; char *buffer; int rc; size_t len; char msg[120]; lsGetParm(CurEng, 1, cADDR, &terp); len = lsStrParmLen(CurEng, 2); buffer = (char*)malloc( (len+1)*sizeof(char) ); lsGetParm(CurEng, 2, cASTR, buffer); Tcl_Preserve(terp); rc = Tcl_EvalFile(terp, buffer); Tcl_Release(terp); if (rc == TCL_OK) { lsUnifyParm(CurEng, 3, cASTR, terp->result); return TRUE; } else { strcpy(msg, "Tcl_EvalFile: "); strncat(msg, terp->result, 100); lsErrRaise(CurEng, msg); return FALSE; } } // tcl_finish(TclInterpreter) // Just wind down the interpreter, DON'T exit, as that // will kill the calling process as well. This, the // atcltk LSX, stays memory resident until the Amzi! // engine actually shuts down. TF EXPFUNC p_tcl_finish(ENGid CurEng) { Tcl_Interp *terp = NULL; lsGetParm(CurEng, 1, cADDR, &terp); Tcl_DeleteInterp(terp); return TRUE; }
27.140033
131
0.596698
AmziLS
14927b706a1076e80750788c83f9b1a0186efd28
448
cpp
C++
codes/ZOJ/zoj3819.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/ZOJ/zoj3819.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/ZOJ/zoj3819.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; int N, M, A, B; int main () { int cas; scanf("%d", &cas); while (cas--) { int x; scanf("%d%d", &N, &M); A = B = 0; for (int i = 1; i < N; i++) { scanf("%d", &x); A += x; } for (int i = 0; i < M; i++) { scanf("%d", &x); B += x; } int l = B / M + 1; int r = A / (N-1) + (A % (N-1) ? 0 : -1); printf("%d %d\n", l, r); } return 0; }
14.933333
43
0.424107
JeraKrs
1495d1290cb6b621306cfdae87ff1345e269c2b8
26,033
cpp
C++
applications/mne_scan/plugins/neuromag/neuromag.cpp
MagCPP/mne-cpp
05f634a8401b20226bd719254a5da227e67a379b
[ "BSD-3-Clause" ]
null
null
null
applications/mne_scan/plugins/neuromag/neuromag.cpp
MagCPP/mne-cpp
05f634a8401b20226bd719254a5da227e67a379b
[ "BSD-3-Clause" ]
null
null
null
applications/mne_scan/plugins/neuromag/neuromag.cpp
MagCPP/mne-cpp
05f634a8401b20226bd719254a5da227e67a379b
[ "BSD-3-Clause" ]
null
null
null
//============================================================================================================= /** * @file neuromag.cpp * @author Christoph Dinh <chdinh@nmr.mgh.harvard.edu>; * Lorenz Esch <Lorenz.Esch@tu-ilmenau.de>; * Matti Hamalainen <msh@nmr.mgh.harvard.edu> * @version 1.0 * @date October, 2016 * * @section LICENSE * * Copyright (C) 2016, Christoph Dinh, Lorenz Esch and Matti Hamalainen. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that * the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and * the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of MNE-CPP authors nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * * @brief Definition of the Neuromag class. * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include "neuromag.h" #include "neuromagproducer.h" #include "FormFiles/neuromagsetupwidget.h" #include <fiff/fiff_dir_node.h> #include <fiff/fiff_stream.h> #include <scMeas/realtimemultisamplearray.h> #include <disp/viewers/projectsettingsview.h> #include <fiff/fiff_info.h> #include <utils/ioutils.h> #include <communication/rtClient/rtcmdclient.h> #include <disp3D/viewers/hpiview.h> //************************************************************************************************************* //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QDir> #include <QSettings> #include <QMessageBox> //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace NEUROMAGPLUGIN; using namespace UTILSLIB; using namespace SCSHAREDLIB; using namespace IOBUFFER; using namespace SCMEASLIB; using namespace FIFFLIB; using namespace DISPLIB; using namespace DISP3DLIB; //************************************************************************************************************* //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= Neuromag::Neuromag() : m_sNeuromagClientAlias("mne_scan") , m_pRtCmdClient(NULL) , m_bCmdClientIsConnected(false) , m_sNeuromagIP("172.21.16.88")//("127.0.0.1") , m_pNeuromagProducer(new NeuromagProducer(this)) , m_iBufferSize(-1) , m_pRawMatrixBuffer_In(0) , m_bIsRunning(false) , m_sFiffHeader(QCoreApplication::applicationDirPath() + "/resources/mne_scan/plugins/neuromag/header.fif") , m_iActiveConnectorId(0) , m_bWriteToFile(false) , m_iRecordingMSeconds(5*60*1000) { m_pActionSetupProject = new QAction(QIcon(":/images/database.png"), tr("Setup Project"),this); m_pActionSetupProject->setStatusTip(tr("Setup Project")); connect(m_pActionSetupProject.data(), &QAction::triggered, this, &Neuromag::showProjectDialog); addPluginAction(m_pActionSetupProject); m_pActionRecordFile = new QAction(QIcon(":/images/record.png"), tr("Start Recording"),this); m_pActionRecordFile->setStatusTip(tr("Start Recording")); connect(m_pActionRecordFile.data(), &QAction::triggered, this, &Neuromag::toggleRecordingFile); addPluginAction(m_pActionRecordFile); //Init HPI m_pActionComputeHPI = new QAction(QIcon(":/images/latestFiffInfoHPI.png"), tr("Compute HPI"),this); m_pActionComputeHPI->setStatusTip(tr("Compute HPI")); connect(m_pActionComputeHPI.data(), &QAction::triggered, this, &Neuromag::showHPIDialog); addPluginAction(m_pActionComputeHPI); //Init recording timers m_pRecordTimer = QSharedPointer<QTimer>(new QTimer(this)); m_pRecordTimer->setSingleShot(true); connect(m_pRecordTimer.data(), &QTimer::timeout, this, &Neuromag::toggleRecordingFile); m_pBlinkingRecordButtonTimer = QSharedPointer<QTimer>(new QTimer(this)); connect(m_pBlinkingRecordButtonTimer.data(), &QTimer::timeout, this, &Neuromag::changeRecordingButton); m_pUpdateTimeInfoTimer = QSharedPointer<QTimer>(new QTimer(this)); connect(m_pUpdateTimeInfoTimer.data(), &QTimer::timeout, this, &Neuromag::onRecordingRemainingTimeChange); } //************************************************************************************************************* Neuromag::~Neuromag() { if(m_pNeuromagProducer->isRunning() || this->isRunning()) stop(); } //************************************************************************************************************* void Neuromag::clear() { m_pFiffInfo.reset(); m_iBufferSize = -1; } //************************************************************************************************************* QSharedPointer<SCSHAREDLIB::IPlugin> Neuromag::clone() const { QSharedPointer<Neuromag> pNeuromagClone(new Neuromag()); return pNeuromagClone; } //************************************************************************************************************* void Neuromag::init() { //Neuromag data Path QString sNeuromagDataPath = QDir::homePath() + "/NeuromagData"; if(!QDir(sNeuromagDataPath).exists()) { QDir().mkdir(sNeuromagDataPath); } //Test Project QSettings settings; QString sCurrentProject = settings.value(QString("Plugin/%1/currentProject").arg(getName()), "TestProject").toString(); if(!QDir(sNeuromagDataPath+"/"+sCurrentProject).exists()) { QDir().mkdir(sNeuromagDataPath+"/"+sCurrentProject); } //Test Subject QString sCurrentSubject = settings.value(QString("Plugin/%1/currentSubject").arg(getName()), "TestSubject").toString(); if(!QDir(sNeuromagDataPath+"/"+sCurrentProject+"/"+sCurrentSubject).exists()) { QDir().mkdir(sNeuromagDataPath+"/"+sCurrentProject+"/"+sCurrentSubject); } m_pProjectSettingsView = QSharedPointer<ProjectSettingsView>::create(sNeuromagDataPath, sCurrentProject, sCurrentSubject, ""); m_sRecordFile = m_pProjectSettingsView->getCurrentFileName(); connect(m_pProjectSettingsView.data(), &ProjectSettingsView::timerChanged, this, &Neuromag::setRecordingTimerChanged); connect(m_pProjectSettingsView.data(), &ProjectSettingsView::recordingTimerStateChanged, this, &Neuromag::setRecordingTimerStateChanged); m_pProjectSettingsView->hide(); // Start NeuromagProducer m_pNeuromagProducer->start(); //init channels when fiff info is available connect(this, &Neuromag::fiffInfoAvailable, this, &Neuromag::initConnector); //Try to connect the cmd client on start up using localhost connection this->connectCmdClient(); } //************************************************************************************************************* void Neuromag::unload() { } //************************************************************************************************************* void Neuromag::showProjectDialog() { if(m_pProjectSettingsView) { m_pProjectSettingsView->show(); } } //************************************************************************************************************* void Neuromag::splitRecordingFile() { qDebug() << "Neuromag::splitRecordingFile - Splitting recording file"; ++m_iSplitCount; QString nextFileName = m_sRecordFile.remove("_raw.fif"); nextFileName += QString("-%1_raw.fif").arg(m_iSplitCount); // Write the link to the next file qint32 data; m_pOutfid->start_block(FIFFB_REF); data = FIFFV_ROLE_NEXT_FILE; m_pOutfid->write_int(FIFF_REF_ROLE,&data); m_pOutfid->write_string(FIFF_REF_FILE_NAME, nextFileName); m_pOutfid->write_id(FIFF_REF_FILE_ID);//ToDo meas_id data = m_iSplitCount - 1; m_pOutfid->write_int(FIFF_REF_FILE_NUM, &data); m_pOutfid->end_block(FIFFB_REF); //finish file m_pOutfid->finish_writing_raw(); //start next file m_qFileOut.setFileName(nextFileName); RowVectorXd cals; m_pOutfid = FiffStream::start_writing_raw(m_qFileOut, *m_pFiffInfo, cals); fiff_int_t first = 0; m_pOutfid->write_int(FIFF_FIRST_SAMPLE, &first); } //************************************************************************************************************* void Neuromag::toggleRecordingFile() { //Setup writing to file if(m_bWriteToFile) { m_mutex.lock(); m_pOutfid->finish_writing_raw(); m_mutex.unlock(); m_bWriteToFile = false; m_iSplitCount = 0; //Stop record timer m_pRecordTimer->stop(); m_pUpdateTimeInfoTimer->stop(); m_pBlinkingRecordButtonTimer->stop(); m_pActionRecordFile->setIcon(QIcon(":/images/record.png")); } else { m_iSplitCount = 0; if(!m_pFiffInfo) { QMessageBox msgBox; msgBox.setText("FiffInfo missing!"); msgBox.setWindowFlags(Qt::WindowStaysOnTopHint); msgBox.exec(); return; } if(m_pFiffInfo->dev_head_t.trans.isIdentity()) { QMessageBox msgBox; msgBox.setText("It seems that no HPI fitting was performed. This is your last chance!"); msgBox.setInformativeText(" Do you want to continue without HPI fitting?"); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setWindowFlags(Qt::WindowStaysOnTopHint); int ret = msgBox.exec(); if(ret == QMessageBox::No) return; } //Initiate the stream for writing to the fif file if(m_pProjectSettingsView) { m_sRecordFile = m_pProjectSettingsView->getCurrentFileName(); } m_qFileOut.setFileName(m_sRecordFile); if(m_qFileOut.exists()) { QMessageBox msgBox; msgBox.setText("The file you want to write already exists."); msgBox.setInformativeText("Do you want to overwrite this file?"); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setWindowFlags(Qt::WindowStaysOnTopHint); int ret = msgBox.exec(); if(ret == QMessageBox::No) return; } //Set all projectors to zero before writing to file because we always write the raw data for(int i = 0; i<m_pFiffInfo->projs.size(); i++) { m_pFiffInfo->projs[i].active = false; } m_mutex.lock(); RowVectorXd cals; m_pOutfid = FiffStream::start_writing_raw(m_qFileOut, *m_pFiffInfo, cals); fiff_int_t first = 0; m_pOutfid->write_int(FIFF_FIRST_SAMPLE, &first); m_mutex.unlock(); m_bWriteToFile = true; //Start timers for record button blinking, recording timer and updating the elapsed time in the proj widget m_pBlinkingRecordButtonTimer->start(500); m_recordingStartedTime.restart(); m_pUpdateTimeInfoTimer->start(1000); if(m_bUseRecordTimer) { m_pRecordTimer->start(m_iRecordingMSeconds); } } } //************************************************************************************************************* void Neuromag::setRecordingTimerChanged(int timeMSecs) { //If the recording time is changed during the recording, change the timer if(m_bWriteToFile) { m_pRecordTimer->setInterval(timeMSecs-m_recordingStartedTime.elapsed()); } m_iRecordingMSeconds = timeMSecs; } //************************************************************************************************************* void Neuromag::setRecordingTimerStateChanged(bool state) { m_bUseRecordTimer = state; } //************************************************************************************************************* void Neuromag::changeConnector(qint32 p_iNewConnectorId) { if(p_iNewConnectorId != m_iActiveConnectorId) { // read meas info (*m_pRtCmdClient)["selcon"].pValues()[0].setValue(p_iNewConnectorId); (*m_pRtCmdClient)["selcon"].send(); m_iActiveConnectorId = p_iNewConnectorId; // clear all and request everything new clear(); // // request available commands // m_pRtCmdClient->requestCommands(); // // Read Info // if(!m_pFiffInfo) requestInfo(); // // Read Buffer Size // m_iBufferSize = m_pRtCmdClient->requestBufsize(); emit cmdConnectionChanged(m_bCmdClientIsConnected); } } //************************************************************************************************************* bool Neuromag::start() { // //Check if the thread is already or still running. This can happen if the start button is pressed immediately after the stop button was pressed. In this case the stopping process is not finished yet but the start process is initiated. // if(this->isRunning()) { // QThread::wait(); // } if(m_bCmdClientIsConnected && m_pFiffInfo) { // Initialize real time measurements init(); //Set buffer size (*m_pRtCmdClient)["bufsize"].pValues()[0].setValue(m_iBufferSize); (*m_pRtCmdClient)["bufsize"].send(); // Buffer m_pRawMatrixBuffer_In = QSharedPointer<RawMatrixBuffer>(new RawMatrixBuffer(8,m_pFiffInfo->nchan,m_iBufferSize)); m_bIsRunning = true; // Start threads QThread::start(); m_pNeuromagProducer->start(); while(!m_pNeuromagProducer->m_bFlagMeasuring) msleep(1); // Start Measurement at rt_Server // start measurement (*m_pRtCmdClient)["start"].pValues()[0].setValue(m_pNeuromagProducer->m_iDataClientId); (*m_pRtCmdClient)["start"].send(); return true; } else { if(!m_pFiffInfo) { qWarning()<<"Neuromag::start - FiffInfo is empty (NULL)."; } if(!m_bCmdClientIsConnected) { qWarning()<<"Neuromag::start - m_bCmdClientIsConnected is false."; } return false; } } //************************************************************************************************************* bool Neuromag::stop() { if(m_pNeuromagProducer->isRunning()) { m_pNeuromagProducer->stop(); } //Wait until this thread (TMSI) is stopped m_bIsRunning = false; if(this->isRunning()) { //In case the semaphore blocks the thread -> Release the QSemaphore and let it exit from the pop function (acquire statement) m_pRawMatrixBuffer_In->releaseFromPop(); m_pRawMatrixBuffer_In->clear(); m_pRTMSA_Neuromag->data()->clear(); } if(m_pHPIWidget) { m_pHPIWidget->hide(); } return true; } //************************************************************************************************************* IPlugin::PluginType Neuromag::getType() const { return _ISensor; } //************************************************************************************************************* QString Neuromag::getName() const { return "Neuromag"; } //************************************************************************************************************* QWidget* Neuromag::setupWidget() { NeuromagSetupWidget* widget = new NeuromagSetupWidget(this);//widget is later distroyed by CentralWidget - so it has to be created everytime new return widget; } //************************************************************************************************************* bool Neuromag::readProjectors() { QFile t_headerFiffFile(m_sFiffHeader); // // Open the file // FiffStream::SPtr t_pStream(new FiffStream(&t_headerFiffFile)); QString t_sFileName = t_pStream->streamName(); printf("Opening header data %s...\n",t_sFileName.toUtf8().constData()); if(!t_pStream->open()) { return false; } QList<FiffProj> q_ListProj = t_pStream->read_proj(t_pStream->dirtree()); if (q_ListProj.size() == 0) { printf("Could not find projectors\n"); return false; } m_pFiffInfo->projs = q_ListProj; // // Activate the projection items // for (qint32 k = 0; k < m_pFiffInfo->projs.size(); ++k) { m_pFiffInfo->projs[k].active = true; } //garbage collecting t_pStream->close(); return true; } //************************************************************************************************************* void Neuromag::connectCmdClient() { if(m_pRtCmdClient.isNull()) m_pRtCmdClient = QSharedPointer<RtCmdClient>(new RtCmdClient); else if(m_bCmdClientIsConnected) this->disconnectCmdClient(); m_pRtCmdClient->connectToHost(m_sNeuromagIP); m_pRtCmdClient->waitForConnected(1000); if(m_pRtCmdClient->state() == QTcpSocket::ConnectedState) { m_mutex.lock(); if(!m_bCmdClientIsConnected) { // // request available commands // m_pRtCmdClient->requestCommands(); // // set cmd client is connected // m_bCmdClientIsConnected = true; // // Read Info // if(!m_pFiffInfo) requestInfo(); // This will read projectors from an external file and replace the one received from mne_rt_server //if(m_pFiffInfo) // readProjectors(); // // Read Connectors // if(m_qMapConnectors.size() == 0) m_iActiveConnectorId = m_pRtCmdClient->requestConnectors(m_qMapConnectors); QMap<qint32, QString>::const_iterator it; for(it = m_qMapConnectors.begin(); it != m_qMapConnectors.end(); ++it) if(it.value().compare("Neuromag Connector") == 0 && m_iActiveConnectorId != it.key()) changeConnector(it.key()); // // Read Buffer Size // m_iBufferSize = m_pRtCmdClient->requestBufsize(); emit cmdConnectionChanged(m_bCmdClientIsConnected); } m_mutex.unlock(); } } //************************************************************************************************************* void Neuromag::disconnectCmdClient() { if(m_bCmdClientIsConnected) { m_pRtCmdClient->disconnectFromHost(); m_pRtCmdClient->waitForDisconnected(); m_mutex.lock(); m_bCmdClientIsConnected = false; m_mutex.unlock(); emit cmdConnectionChanged(m_bCmdClientIsConnected); } } //************************************************************************************************************* void Neuromag::requestInfo() { while(!(m_pNeuromagProducer->m_iDataClientId > -1 && m_bCmdClientIsConnected)) qWarning() << "NeuromagProducer is not running! Retry..."; if(m_pNeuromagProducer->m_iDataClientId > -1 && m_bCmdClientIsConnected) { // read meas info (*m_pRtCmdClient)["measinfo"].pValues()[0].setValue(m_pNeuromagProducer->m_iDataClientId); (*m_pRtCmdClient)["measinfo"].send(); m_pNeuromagProducer->m_mutex.lock(); m_pNeuromagProducer->m_bFlagInfoRequest = true; m_pNeuromagProducer->m_mutex.unlock(); } else qWarning() << "NeuromagProducer is not connected!"; } //************************************************************************************************************* void Neuromag::run() { MatrixXf matValue; qint32 size = 0; while(m_bIsRunning) { if(m_pRawMatrixBuffer_In) { //pop matrix matValue = m_pRawMatrixBuffer_In->pop(); //Write raw data to fif file if(m_bWriteToFile) { size += matValue.rows()*matValue.cols() * 4; if(size > MAX_DATA_LEN) { size = 0; this->splitRecordingFile(); } m_mutex.lock(); if(m_pOutfid) { m_pOutfid->write_raw_buffer(matValue.cast<double>()); } m_mutex.unlock(); } else { size = 0; } if(m_pRTMSA_Neuromag) { m_pRTMSA_Neuromag->data()->setValue(this->calibrate(matValue)); } } } } //************************************************************************************************************* MatrixXd Neuromag::calibrate(const MatrixXf& data) { MatrixXd one; if(m_pFiffInfo && m_sparseMatCals.cols() == m_pFiffInfo->nchan) { one = m_sparseMatCals*data.cast<double>(); } else { one = data.cast<double>(); } return one; } //************************************************************************************************************* void Neuromag::changeRecordingButton() { if(m_iBlinkStatus == 0) { m_pActionRecordFile->setIcon(QIcon(":/images/record.png")); m_iBlinkStatus = 1; } else { m_pActionRecordFile->setIcon(QIcon(":/images/record_active.png")); m_iBlinkStatus = 0; } } //************************************************************************************************************* void Neuromag::onRecordingRemainingTimeChange() { m_pProjectSettingsView->setRecordingElapsedTime(m_recordingStartedTime.elapsed()); } //************************************************************************************************************* void Neuromag::initConnector() { if(m_pFiffInfo) { m_pRTMSA_Neuromag = PluginOutputData<RealTimeMultiSampleArray>::create(this, "Realtime", "MNE Rt Client"); m_pRTMSA_Neuromag->data()->initFromFiffInfo(m_pFiffInfo); m_pRTMSA_Neuromag->data()->setMultiArraySize(1); m_pRTMSA_Neuromag->data()->setVisibility(true); m_pRTMSA_Neuromag->data()->setXMLLayoutFile("./resources/mne_scan/plugins/Neuromag/VectorViewLayout.xml"); m_outputConnectors.append(m_pRTMSA_Neuromag); //Add the calibration factors m_cals = RowVectorXd(m_pFiffInfo->nchan); m_cals.setZero(); for (qint32 k = 0; k < m_pFiffInfo->nchan; ++k) { m_cals[k] = m_pFiffInfo->chs[k].range*m_pFiffInfo->chs[k].cal; } //Initialize the data and calibration vector typedef Eigen::Triplet<double> T; std::vector<T> tripletList; tripletList.reserve(m_pFiffInfo->nchan); for(qint32 i = 0; i < m_pFiffInfo->nchan; ++i) { tripletList.push_back(T(i, i, this->m_cals[i])); } m_sparseMatCals = SparseMatrix<double>(m_pFiffInfo->nchan, m_pFiffInfo->nchan); m_sparseMatCals.setFromTriplets(tripletList.begin(), tripletList.end()); } } //************************************************************************************************************* void Neuromag::showHPIDialog() { if(!m_pFiffInfo) { QMessageBox msgBox; msgBox.setText("FiffInfo missing!"); msgBox.exec(); return; } else { if (!m_pHPIWidget) { m_pHPIWidget = QSharedPointer<HpiView>(new HpiView(m_pFiffInfo)); } if (!m_pHPIWidget->isVisible()) { m_pHPIWidget->show(); m_pHPIWidget->raise(); } } } //************************************************************************************************************* void Neuromag::updateHPI(const MatrixXf& matData) { if(m_pFiffInfo && m_pHPIWidget) { m_pHPIWidget->setData(this->calibrate(matData)); } }
32.828499
240
0.529021
MagCPP
149615a9e12e70d87e9a90b214a1835100b8f7e5
6,271
cpp
C++
2006 - Task1 {12 of 14} [a]/src/particles.cpp
retgone/cmc-cg
7e5a76992e524958353ee799092f810681a13107
[ "MIT" ]
null
null
null
2006 - Task1 {12 of 14} [a]/src/particles.cpp
retgone/cmc-cg
7e5a76992e524958353ee799092f810681a13107
[ "MIT" ]
null
null
null
2006 - Task1 {12 of 14} [a]/src/particles.cpp
retgone/cmc-cg
7e5a76992e524958353ee799092f810681a13107
[ "MIT" ]
null
null
null
#include <stdio.h> #include <gl\glut.h> #include <windows.h> #define N 10000 typedef struct { float x,y; float x1,y1; float randomx,randomy; float x2,y2; float r,g,b; float s; float s1; float l; float l1; bool living; bool update; } TParticle; TParticle System[N]; int SystemType; float t, tt; int w_x, w_y; bool time_on=true; float kuchki[801]; void reinit_particle(int n, int type) { if(type==0) // snow { System[n].x=800.0*rand()/RAND_MAX; System[n].y=600; System[n].x1=0; System[n].y1=-300.0*rand()/RAND_MAX; System[n].randomx=80.0*rand()/RAND_MAX; System[n].randomy=0; System[n].x2=0; System[n].y2=0; System[n].b=0.5+0.5*rand()/RAND_MAX; System[n].r=System[n].b/2; System[n].g=System[n].b/2; System[n].s=1+8*rand()/RAND_MAX; System[n].s1=-0.3-3.0*rand()/RAND_MAX; System[n].l=1*rand()/RAND_MAX; System[n].l1=System[n].s1/System[n].s+2.0*rand()/RAND_MAX; System[n].update=true; System[n].living=true; } else if(type==1) //waterfall { System[n].x=0; System[n].y=600; System[n].x1=300+200*rand()/RAND_MAX; System[n].y1=-60-300*rand()/RAND_MAX; System[n].randomx=150*rand()/RAND_MAX; System[n].randomy=150*rand()/RAND_MAX; System[n].x2=0; System[n].y2=-600; System[n].b=(float)rand()/RAND_MAX; System[n].r=System[n].b/4; System[n].g=System[n].b/4; System[n].l=1+6.0*rand()/RAND_MAX; System[n].l1=-1; System[n].s=1+6*rand()/RAND_MAX; System[n].s1=0; System[n].update=true; System[n].living=true; } } void move_system() { for(int i=0;i<N;i++) { if(!System[i].living) { reinit_particle(i,SystemType); } else { if(System[i].update) { System[i].x+=tt*(System[i].x1+(1.0-2.0*rand()/RAND_MAX)*System[i].randomx); System[i].y+=tt*(System[i].y1+(1.0-2.0*rand()/RAND_MAX)*System[i].randomy); System[i].x1+=tt*System[i].x2; System[i].y1+=tt*System[i].y2; System[i].l+=tt*System[i].l1; System[i].s+=tt*System[i].s1; if(System[i].s<0.5 || System[i].l<0) System[i].living=false; } } } } void system_special_handler() { if(SystemType==1) { for(int i=0; i<N; i++) { if(System[i].living && System[i].y<0) { System[i].y=0.001; if(i%5==0) { System[i].s/=2; System[i].y1*=-0.3; System[i].x1*=1-2.0*rand()/RAND_MAX; } else { System[i].y1=0; System[i].y2=0; System[i].randomy=0; System[i].randomx=0; System[i].x1*=0.8; if(rand()>RAND_MAX/2) System[i].x1*=-1; } } } } else if(SystemType==0) { for(int i=0;i<801;i++) { kuchki[i]=max(0,kuchki[i]-2*tt); if(i!=0 && i!=800) kuchki[i]=(kuchki[i]+kuchki[i+1]+kuchki[i-1])/3; } for(int i=0;i<N;i++) { if(System[i].update) { if(System[i].x>0 && System[i].x<800) { int index=max(0,min(800,(int)System[i].x)); if(System[i].y<=kuchki[(int)System[i].x]) { if(System[i].s<2) System[i].living=false; else { System[i].update=false; int jmin=max(0,System[i].x-System[i].s*0.25); int jmax=min(800,System[i].x+System[i].s*0.25); for(int j=jmin;j<jmax;j++) kuchki[j]+=System[i].s*0.2; } } } } else { System[i].y-=2*tt; if(System[i].y<-3) System[i].living=false; } } } } void reinit_system(int type) { SystemType=type; for(int i=0; i<N; i++) System[i].living=false; for(int i=0;i<=800;i++) kuchki[i]=0; tt=1/30.0; for(int i=0; i<120; i++) { move_system(); system_special_handler(); } } void draw_system() { for(int i=0; i<N; i++) { if(System[i].living) { glColor3f(System[i].r,System[i].g,System[i].b); glPointSize(System[i].s); glBegin(GL_POINTS); glVertex3f(System[i].x,System[i].y,0); glEnd(); } } } void do_display() { glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0,800,0,600,0.1,100); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(0,0,1,0,0,0,0,1,0); if(time_on) { move_system(); system_special_handler(); } draw_system(); glutSwapBuffers(); } void do_idle() { static int prevt=timeGetTime(); tt=(timeGetTime()-prevt)/1000.0; t+=tt; if(tt>1.0/70.0) { if(tt>0.05) tt=0.05; prevt=timeGetTime(); glutPostRedisplay(); } } void do_init() { srand(timeGetTime()); glClearColor(0,0,0,0); glEnable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glPolygonMode(GL_FRONT_AND_BACK,GL_FILL); glShadeModel(GL_SMOOTH); glHint(GL_POINT_SMOOTH_HINT,GL_NICEST); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); } void do_mouse(int button, int state, int x, int y) { static int n=0; n=(n+1)%N; reinit_particle(n,SystemType); System[n].x=x; System[n].y=600-y; } void do_keydown(unsigned char key, int x, int y) { if(key==27) exit(0); if(key==' ') time_on=!time_on; if(key=='w' || key=='W') reinit_system(1); if(key=='s' || key=='S') reinit_system(0); } void do_reshape(int x, int y) { w_x=x; w_y=y; glViewport(0,0,w_x,w_y); } int main(int argc, char** argv) { glutInit(&argc,argv); glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB); glutInitWindowSize(800,600); glutCreateWindow("Particle System"); DEVMODE devmode; memset(&devmode,0,sizeof(devmode)); devmode.dmSize=sizeof(devmode); devmode.dmPelsWidth=800; devmode.dmPelsHeight=600; devmode.dmBitsPerPel=32; devmode.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT; ChangeDisplaySettings(&devmode,CDS_FULLSCREEN); glutFullScreen(); glutReshapeFunc(do_reshape); glutIdleFunc(do_idle); glutDisplayFunc(do_display); glutMouseFunc(do_mouse); glutKeyboardFunc(do_keydown); srand(GetTickCount()); glClearColor(0,0,0,0); glHint(GL_POINT_SMOOTH_HINT,GL_NICEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_POINT_SMOOTH); reinit_system(0); glutMainLoop(); return 0; }
20.294498
80
0.580928
retgone
1499a3ec7e786ff93a5109b744596e59a10baf58
3,849
hpp
C++
examples/sill/vr-puzzle/objects/panel.hpp
Breush/lava
1b1b1f0785300b93b4a9f35fca4490502fea6552
[ "MIT" ]
15
2018-02-26T08:20:03.000Z
2022-03-06T03:25:46.000Z
examples/sill/vr-puzzle/objects/panel.hpp
Breush/lava
1b1b1f0785300b93b4a9f35fca4490502fea6552
[ "MIT" ]
32
2018-02-26T08:26:38.000Z
2020-09-12T17:09:38.000Z
examples/sill/vr-puzzle/objects/panel.hpp
Breush/lava
1b1b1f0785300b93b4a9f35fca4490502fea6552
[ "MIT" ]
null
null
null
#pragma once #include "./object.hpp" #include <cstdint> #include <glm/glm.hpp> #include <lava/core/ray.hpp> #include <vector> class Brick; class Barrier; class Panel : public Object { public: using SolvedChangedCallback = std::function<void(bool)>; struct SnappingPoint { lava::Transform worldTransform; glm::uvec2 coordinates = glm::uvec2(-1u, -1u); bool hasBrickSnapped = false; }; struct SnappingInfo { SnappingPoint* point = nullptr; bool validForBrick = false; }; public: Panel(GameState& gameState); void clear(bool removeFromLevel = true) final; void unserialize(const nlohmann::json& data) final; nlohmann::json serialize() const final; void consolidateReferences() final; // Editor controls void uiWidgets(std::vector<UiWidget>& widgets) final; /// Update extent and associated materials visuals. This also resets all rules. const glm::uvec2& extent() const { return m_extent; } void extent(const glm::uvec2& extent); /// Checks whether the user is allowed to snap brick to this panel. bool userInteractionAllowed() const; /// Find the closest snapping point to is valid for the brick. SnappingPoint* closestSnappingPoint(const Brick& brick, const glm::vec3& position, float minDistance = 0.1f); /// Find the closest snapping point. SnappingInfo rayHitSnappingPoint(const Brick& brick, const lava::Ray& ray); /// An un-powered panel is black and has no interaction. bool powered() const { return m_powered; } void powered(bool powered); const std::string& substanceRevealNeeded() const { return m_substanceRevealNeeded; } void substanceRevealNeeded(const std::string& substanceRevealNeeded) { m_substanceRevealNeeded = substanceRevealNeeded; } const std::string& substanceFreedOnSolve() const { return m_substanceFreedOnSolve; } void substanceFreedOnSolve(const std::string& substanceFreedOnSolve) { m_substanceFreedOnSolve = substanceFreedOnSolve; } const std::string& substanceRevealedOnSolve() const { return m_substanceRevealedOnSolve; } void substanceRevealedOnSolve(const std::string& substanceRevealedOnSolve) { m_substanceRevealedOnSolve = substanceRevealedOnSolve; } /// Be warn whenever this panel solved status changed. void onSolvedChanged(SolvedChangedCallback callback); /// Whether this panel is currently solved. bool solved() const { return m_solved; } /// Hijack the system to make the game believe the panel is solved. bool pretendSolved() const { return m_pretendSolved; } void pretendSolved(bool pretendSolved); lava::magma::Material& borderMaterial() { return *m_borderMaterial; } // Callback used by Brick. void snappedBricksChanged() { updateSolved(); } protected: void updateBorderMeshPrimitive(); void updateSnappingPoints(); void updateFromSnappedBricks(); bool isSnappingPointValid(const Brick& brick, const SnappingPoint& snappingPoint); void updateSolved(); private: bool m_consolidated = false; bool m_powered = false; bool m_solved = false; bool m_pretendSolved = false; // Configuration glm::uvec2 m_extent = {3u, 3u}; std::string m_substanceRevealNeeded; std::string m_substanceFreedOnSolve; std::string m_substanceRevealedOnSolve; // Data std::vector<std::vector<SnappingPoint>> m_snappingPoints; // Mesh lava::magma::MaterialPtr m_material = nullptr; lava::magma::MaterialPtr m_borderMaterial = nullptr; std::vector<SolvedChangedCallback> m_solvedChangedCallbacks; }; Panel* findPanelByName(GameState& gameState, const std::string& name); Panel* findPanel(GameState& gameState, const lava::sill::Entity& entity); uint32_t findPanelIndex(GameState& gameState, const lava::sill::Entity& entity);
34.061947
137
0.725383
Breush
149fb188dbbeb85ee898b8261a0697093f0bdcd6
620
cpp
C++
sort/insertSort.cpp
ctrlzhang/algorithm
4db12ea6246b7bd6ac4ab9296de4e736f73a0bf0
[ "Apache-2.0" ]
1
2017-05-08T15:41:17.000Z
2017-05-08T15:41:17.000Z
sort/insertSort.cpp
ctrlzhang/algorithm
4db12ea6246b7bd6ac4ab9296de4e736f73a0bf0
[ "Apache-2.0" ]
null
null
null
sort/insertSort.cpp
ctrlzhang/algorithm
4db12ea6246b7bd6ac4ab9296de4e736f73a0bf0
[ "Apache-2.0" ]
2
2016-09-05T17:12:08.000Z
2021-11-21T11:29:42.000Z
#include <iostream> #include <vector> using namespace std; void output(vector<int>& v) { for(vector<int>::iterator it = v.begin(); it != v.end(); it++) { cout<<*it<<" "; } } //递增排序 //排序第i个元素时, 判断前i-1个数是否大于它,如果大于则进行移位,直到找到比它小的数为止. void insertSort(vector<int>& v) { int len = v.size(); if(0 == len) return; for(int i=1; i<len; i++) { int k = v[i]; int j = i-1; while(j>=0 && v[j] > k) { v[j+1] = v[j--]; } v[j+1] = k; } } int main(int argc, char* argv[]) { int a[] = {10, 4, 5, 2, 1, 19, 3, 5, 7}; vector<int> v(a, a+sizeof(a)/sizeof(int)); insertSort(v); output(v); cout<<endl; return 0; }
17.714286
65
0.548387
ctrlzhang
14a044d7937bb9f54c50ac95a5cbb2f6ca6e9f9c
1,553
cpp
C++
code-forces/631 Div 2/C.cpp
ErickJoestar/competitive-programming
76afb766dbc18e16315559c863fbff19a955a569
[ "MIT" ]
1
2020-04-23T00:35:38.000Z
2020-04-23T00:35:38.000Z
code-forces/631 Div 2/C.cpp
ErickJoestar/competitive-programming
76afb766dbc18e16315559c863fbff19a955a569
[ "MIT" ]
null
null
null
code-forces/631 Div 2/C.cpp
ErickJoestar/competitive-programming
76afb766dbc18e16315559c863fbff19a955a569
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define ENDL '\n' #define deb(u) cout << #u " : " << (u) << ENDL; #define deba(alias, u) cout << alias << ": " << (u) << ENDL; #define debp(u, v) cout << u << " : " << v << ENDL; #define pb push_back #define F first #define S second #define lli long long #define pii pair<int, int> #define pll pair<lli, lli> #define ALL(a) (a).begin(), (a).end() #define FOR(i, a, n) for (int i = (a); i < (n); ++i) #define FORN(i, a, n) for (int i = (a)-1; i >= n; --i) #define INF 100001 #define IO \ ios_base::sync_with_stdio(false); \ cin.tie(0); \ cout.tie(0) using namespace std; int main() { IO; int n, m, i; cin >> n >> m; vector<int> vec(n + 1); vector<int> pos(m + 1); vector<int> mx(m + 2, INF); int maxMovements = INF; FOR(i, 1, m + 1) { cin >> vec[i]; maxMovements = min(maxMovements, n - vec[i] - i + 1); if (maxMovements < 0) { cout << -1 << ENDL; return 0; } } int desplaced = 0; int toComplete = n - vec[m] - m + 1; FORN(i, m + 1, 1) { mx[i] = min(mx[i + 1], n - vec[i] - i + 1); // debp(i, mx[i]); } FOR(i, 1, m) { pos[i] = desplaced + i; if (toComplete > 0) { int dist = min(toComplete, vec[i] - 1); dist = min(dist, mx[i + 1] - desplaced); desplaced += dist; toComplete -= dist; } } pos[m] = desplaced + m; if (toComplete > 0) { cout << -1 << ENDL; } else { FOR(i, 1, m + 1) { cout << pos[i] << " "; } } return 0; }
21.273973
60
0.479717
ErickJoestar
14a070e817b850c2a7f9f7088589aadf5f2da3cd
27
cpp
C++
modules/stitching/test/test_precomp.cpp
emaknyus/OpenCV-2.4.3-custom
a0e0cd505560dcc0f13cb7ea4c5506e0251a21e7
[ "MIT" ]
3
2015-08-29T06:56:58.000Z
2016-11-15T10:35:59.000Z
modules/stitching/test/test_precomp.cpp
emaknyus/OpenCV-2.4.3-custom
a0e0cd505560dcc0f13cb7ea4c5506e0251a21e7
[ "MIT" ]
null
null
null
modules/stitching/test/test_precomp.cpp
emaknyus/OpenCV-2.4.3-custom
a0e0cd505560dcc0f13cb7ea4c5506e0251a21e7
[ "MIT" ]
null
null
null
#include "test_precomp.hpp"
27
27
0.814815
emaknyus
14a15b05801440ee3bdbcbc407921b544dbac3d1
3,413
cpp
C++
lib/ast/expression/identifier.cpp
Shachar/practical-sa
01ad8a5d60d2cb09760a38acf229331885dae538
[ "BSL-1.0" ]
1
2020-02-01T18:05:43.000Z
2020-02-01T18:05:43.000Z
lib/ast/expression/identifier.cpp
Shachar/practical-sa
01ad8a5d60d2cb09760a38acf229331885dae538
[ "BSL-1.0" ]
17
2019-03-13T08:51:37.000Z
2020-12-05T18:18:44.000Z
lib/ast/expression/identifier.cpp
Shachar/practical
01ad8a5d60d2cb09760a38acf229331885dae538
[ "BSL-1.0" ]
1
2018-09-25T15:30:50.000Z
2018-09-25T15:30:50.000Z
/* This file is part of the Practical programming langauge. https://github.com/Practical/practical-sa * * To the extent header files enjoy copyright protection, this file is file is copyright (C) 2018-2019 by its authors * You can see the file's authors in the AUTHORS file in the project's home repository. * * This is available under the Boost license. The license's text is available under the LICENSE file in the project's * home directory. */ #include "ast/expression/identifier.h" #include "ast/pointers.h" #include <practical/errors.h> using namespace PracticalSemanticAnalyzer; namespace AST::ExpressionImpl { Identifier::Identifier( const NonTerminals::Identifier &parserIdentifier ) : parserIdentifier( parserIdentifier ) { } String Identifier::getName() const { return parserIdentifier.identifier->text; } SourceLocation Identifier::getLocation() const { return parserIdentifier.identifier->location; } void Identifier::buildASTImpl( LookupContext &lookupContext, ExpectedResult expectedResult, Weight &weight, Weight weightLimit ) { identifier = lookupContext.lookupIdentifier( parserIdentifier.identifier->text ); if( identifier==nullptr ) { throw SymbolNotFound( parserIdentifier.identifier->text, parserIdentifier.identifier->location ); } struct Visitor { Identifier *_this; ExpectedResult &expectedResult; void operator()( const LookupContext::Variable &var ) { _this->metadata.type = downCast( var.type->addFlags( StaticType::Flags::Reference ) ); _this->metadata.valueRange = var.type->defaultRange(); } void operator()( const LookupContext::Function &func ) { ASSERT( !expectedResult )<<"TODO implement choosing overload based on expected result"; _this->metadata.type = LookupContext::genericFunctionType(); _this->metadata.valueRange = LookupContext::genericFunctionRange(); } void operator()( const StructMember &member ) { ABORT()<<"TODO implement"; } }; std::visit( Visitor{._this=this, .expectedResult=expectedResult}, *identifier ); } ExpressionId Identifier::codeGenImpl( PracticalSemanticAnalyzer::FunctionGen *functionGen ) const { struct Visitor { PracticalSemanticAnalyzer::FunctionGen *functionGen; ExpressionId operator()( const LookupContext::Variable &var ) { if( var.lvalueId!=ExpressionId() ) { if( var.type->getFlags() & StaticType::Flags::Reference ) { // If the identifier is itself of _type_ reference, we need one derference automatically ExpressionId resultId = allocateId(); functionGen->dereferencePointer( resultId, var.type, var.lvalueId ); return resultId; } else { return var.lvalueId; } } ABORT()<<"TODO implement by name identifier lookup"; } ExpressionId operator()( const LookupContext::Function &func ) { ABORT()<<"Code gen called for function name"; } ExpressionId operator()( const StructMember &member ) { ABORT()<<"TODO implement"; } }; return std::visit( Visitor{.functionGen = functionGen}, *identifier ); } } // namespace AST::ExpressionImpl
34.826531
117
0.660123
Shachar
14a198806ac7d6336ad6b324700767668772d933
4,494
cpp
C++
src/utilities/optimization.cpp
cmccomb/CISAT
45b6864fc8c83eb1b8eee56f0f74912fecd3973d
[ "MIT" ]
1
2021-08-30T23:06:03.000Z
2021-08-30T23:06:03.000Z
src/utilities/optimization.cpp
THREDgroup/CISAT-cpp
45b6864fc8c83eb1b8eee56f0f74912fecd3973d
[ "MIT" ]
2
2021-11-21T18:02:11.000Z
2022-03-28T20:51:58.000Z
src/utilities/optimization.cpp
THREDgroup/CISAT-cpp
45b6864fc8c83eb1b8eee56f0f74912fecd3973d
[ "MIT" ]
null
null
null
#include "../../include/utilities/optimization.hpp" // Compute the x value fo the optimum of a linear regression std::vector<long double> quad_max(std::vector<long double> x, std::vector<long double> y){ // Initialize things std::vector< std::vector<long double> > A(3, std::vector<long double>(4, 0.0)); std::vector<long double> xx; long double n = 0.0; long double x1 = 0.0; long double x2 = 0.0; long double x3 = 0.0; long double x4 = 0.0; long double y1 = 0.0; long double yx1 = 0.0; long double yx2 = 0.0; // Calculate some sums that will be necessary for(int i=0; i < x.size(); i++) { n += 1; x1 += x[i]; x2 += x[i]*x[i]; x3 += x[i]*x[i]*x[i]; x4 += x[i]*x[i]*x[i]*x[i]; y1 += y[i]; yx1 += y[i]*x[i]; yx2 += y[i]*x[i]*x[i]; } // Make a matrix A[0][0] = n; A[1][0] = x1; A[0][1] = x1; A[0][2] = x2; A[1][1] = x2; A[2][0] = x2; A[1][2] = x3; A[2][1] = x3; A[2][2] = x4; A[0][3] = y1; A[1][3] = yx1; A[2][3] = yx2; xx = gauss(A); long double x_loc; long double x_min = vector_minimum(x); long double x_max = vector_maximum(x); // Check to make sure the equation is concave up if(xx[2] > 0){ x_loc = -xx[1]/(2*xx[2]); } else { if ((xx[0] + x_min*xx[1] +x_min*x_min*xx[2]) > (xx[0] + x_max*xx[1] +x_max*x_max*xx[2]) ) { x_loc = x_max; } else { x_loc = x_min; } } // Check to make sure the solution is in the trust region x_loc = std::min(x_loc, x_max); x_loc = std::max(x_loc, x_min); // Compute the r-squared value long double sse_mean = 0; long double sse_reg = 0; long double my = mean(y); for(int i=0; i < y.size(); i++){ sse_mean += std::pow(y[i] - my, 2); sse_reg += std::pow(xx[0] + x[i]*xx[1] +x[i]*x[i]*xx[2] - y[i], 2); } std::vector<long double> results; results.push_back(x_loc); results.push_back(xx[0] + x_loc*xx[1] +x_loc*x_loc*xx[2]); results.push_back(my); results.push_back(1.0 - sse_reg/sse_mean); return results; } // This performs a Pareto comparison (minimization) between two vectors. Returns: // +1 if x is pareto-better than y // 0 if neither pareto-dominates the other // -1 if y is pareto-better than x long double pareto_comparison(std::vector<long double> x, std::vector<long double> y) { // Define a few things long double comparison = 0; long double n = x.size(); // Do the comparison for (int i=0; i<n; i++){ if(x[i] < y[i]){ comparison += 1; }else if(x[i] > y[i]) { comparison -= 1; } } // Figure out what the comparison means if(comparison == n) { return +1; }else if(comparison == -n) { return -1; }else{ return comparison/n; } } // Computes the pareto front for a set of data std::vector<bool> get_pareto_front(std::vector< std::vector<long double> > y){ std::vector<bool> is_pareto(y.size(), true); int counter = 0; for(int i=0; i<y.size(); i++) { for (int j=0; j<y.size(); j++) { // Reset the counter counter = 0; // Compare points i and j on every criteria for (int k=0; k<y[0].size(); k++) { if (y[i][k] >= y[j][k]) { counter++; } } // If point j is better than point i for all criteria, remove point i from pareto if (counter == y[0].size()) { is_pareto[i] = false; break; } } } return is_pareto; } // Returns the pareto tiers for a data set std::vector<int> get_pareto_tiers(std::vector< std::vector<long double> > y){ // Make a vector to save tiers std::vector<int> tiers(y.size(), 0); std::vector<bool> is_pareto(y.size(), false); std::vector<long double> replacement(y[0].size(), LDBL_MAX); int pareto_counter = 0; int tier_counter = 0; // while (pareto_counter != y.size()) { // Get the current tier is_pareto = get_pareto_front(y); tier_counter++; for (int i =0; i < y.size(); i++) { if (is_pareto[i]){ y[i] = replacement; tiers[i] = tier_counter; pareto_counter++; } } } return tiers; }
27.402439
99
0.515354
cmccomb
14a261a651c714cd1411c26155d2b273271b5ce5
2,109
cpp
C++
Greedy/minnoofjumps.cpp
UltraProton/Placement-Prepration
cc70f174c4410c254ce0469737a884fffdc81164
[ "MIT" ]
null
null
null
Greedy/minnoofjumps.cpp
UltraProton/Placement-Prepration
cc70f174c4410c254ce0469737a884fffdc81164
[ "MIT" ]
3
2020-05-08T18:02:51.000Z
2020-05-09T08:37:35.000Z
Greedy/minnoofjumps.cpp
UltraProton/PlacementPrep
cc70f174c4410c254ce0469737a884fffdc81164
[ "MIT" ]
null
null
null
/* https://www.youtube.com/watch?v=vBdo7wtwlXs https://www.geeksforgeeks.org/minimum-number-jumps-reach-endset-2on-solution/ : Good Explanation. */ #include<bits/stdc++.h> using namespace std; int min_jumps(vector<int> &V); int main(int argc, char const *argv[]) { /* code */ vector<int> V; int t=0,n=0,x=0; cin>>t; while(t>0){ V.clear(); cin>>n; while(n>0){ cin>>x; V.emplace_back(x); n--; } // for(auto ele: V){ // cout<<ele<<" "; // } int ans=INT_MAX; cout<<min_jumps(V)<<endl; t--; } return 0; } int min_jumps(vector<int> &V){ int n=V.size(); if(n<1){ return -1; } if(n==1){ return 0; } int ladder_left=V[0]; int max_ladder=V[0]; //* Stores the max possible index reachable in the input int n_jumps=1; for(int i=1;i<n;i++){ if(i==n-1){ //* We have reached the end of the array so we have our answer so return jumps we have till now return n_jumps; } if(V[i] +i > max_ladder){ //* Build up the ladder max_ladder=V[i] + i; } ladder_left--; //* We have utilized stair on the ladder if(ladder_left==0){ //* If the ladder left is zero n_jumps++; //* We need to jump again i.e we have used all the stairs in the previous jump /* If no more steps are remaining (i.e. steps=0, then we must have used a jump.Therefore increase jump. Since we know that it is possible somehow to reach maxladder, ! we again initialize the steps to the number of steps to reach maxladder from position i. But before re-initializing step, we also check whether a step is becoming zero or negative. In this case, It is not possible to reach further. */ if(i>=max_ladder){ return -1; } ladder_left=max_ladder-i; } } return n_jumps; }
22.43617
121
0.528687
UltraProton
14a29a020d6cf0293e7e4e5f233bddd86703de7d
329
hpp
C++
src/widgets/accountswitchwidget.hpp
alexandera3/chatterino2
41fbcc738b34a19f66eef3cca8d5dea0b89e07a3
[ "MIT" ]
1
2018-03-24T18:40:00.000Z
2018-03-24T18:40:00.000Z
src/widgets/accountswitchwidget.hpp
alexandera3/chatterino2
41fbcc738b34a19f66eef3cca8d5dea0b89e07a3
[ "MIT" ]
null
null
null
src/widgets/accountswitchwidget.hpp
alexandera3/chatterino2
41fbcc738b34a19f66eef3cca8d5dea0b89e07a3
[ "MIT" ]
null
null
null
#pragma once #include <QListWidget> namespace chatterino { namespace widgets { class AccountSwitchWidget : public QListWidget { Q_OBJECT public: explicit AccountSwitchWidget(QWidget *parent = nullptr); void refresh(); private: void refreshSelection(); }; } // namespace widgets } // namespace chatterino
14.304348
60
0.723404
alexandera3
14a570a607a83734c6186e19afcd3d3e18f4beff
22,587
cc
C++
test/src/unit-dimension.cc
upj977155/TileDB
1c96c6a0c030e058930ff9d47409865fbfe2178f
[ "MIT" ]
1,478
2017-06-15T13:58:50.000Z
2022-03-30T13:46:00.000Z
test/src/unit-dimension.cc
upj977155/TileDB
1c96c6a0c030e058930ff9d47409865fbfe2178f
[ "MIT" ]
1,435
2017-05-25T01:16:18.000Z
2022-03-31T21:57:06.000Z
test/src/unit-dimension.cc
upj977155/TileDB
1c96c6a0c030e058930ff9d47409865fbfe2178f
[ "MIT" ]
169
2017-06-09T18:35:45.000Z
2022-03-13T01:11:18.000Z
/** * @file unit-dimension.cc * * @section LICENSE * * The MIT License * * @copyright Copyright (c) 2020-2021 TileDB, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @section DESCRIPTION * * Tests the `Dimension` class. */ #include "test/src/helpers-dimension.h" #include "tiledb/sm/array_schema/dimension.h" #include "tiledb/sm/enums/datatype.h" #include "tiledb/sm/misc/hilbert.h" #include <catch.hpp> #include <iostream> using namespace tiledb; using namespace tiledb::common; using namespace tiledb::sm; using namespace tiledb::test; TEST_CASE( "Dimension: Test map_to_uint64, integers", "[dimension][map_to_uint64][int]") { // Create dimensions Dimension d1("d1", Datatype::INT32); int32_t dom1[] = {0, 100}; d1.set_domain(dom1); Dimension d2("d2", Datatype::INT32); int32_t dom2[] = {0, 200}; d2.set_domain(dom2); // Create 2D hilbert curve (auxiliary here) Hilbert h(2); auto bits = h.bits(); uint64_t coords[2]; auto max_bucket_val = ((uint64_t)1 << bits) - 1; // Map (1, 1) int32_t dv = 1; auto v = d1.map_to_uint64(&dv, sizeof(int32_t), bits, max_bucket_val); CHECK(v == 21474836); coords[0] = v; dv = 1; v = d2.map_to_uint64(&dv, sizeof(int32_t), bits, max_bucket_val); CHECK(v == 10737418); coords[1] = v; auto hv = h.coords_to_hilbert(coords); CHECK(hv == 972175364522868); // Map (1, 3) dv = 1; v = d1.map_to_uint64(&dv, sizeof(int32_t), bits, max_bucket_val); CHECK(v == 21474836); coords[0] = v; dv = 3; v = d2.map_to_uint64(&dv, sizeof(int32_t), bits, max_bucket_val); CHECK(v == 32212254); coords[1] = v; hv = h.coords_to_hilbert(coords); CHECK(hv == 673795214387276); // Map (4, 2) dv = 4; v = d1.map_to_uint64(&dv, sizeof(int32_t), bits, max_bucket_val); CHECK(v == 85899345); coords[0] = v; dv = 2; v = d2.map_to_uint64(&dv, sizeof(int32_t), bits, max_bucket_val); CHECK(v == 21474836); coords[1] = v; hv = h.coords_to_hilbert(coords); CHECK(hv == 15960414315352633); // Map (5, 4) dv = 5; v = d1.map_to_uint64(&dv, sizeof(int32_t), bits, max_bucket_val); CHECK(v == 107374182); coords[0] = v; dv = 4; v = d2.map_to_uint64(&dv, sizeof(int32_t), bits, max_bucket_val); CHECK(v == 42949672); coords[1] = v; hv = h.coords_to_hilbert(coords); CHECK(hv == 14307296941447292); // Map (2, 1) dv = 2; v = d1.map_to_uint64(&dv, sizeof(int32_t), bits, max_bucket_val); CHECK(v == 42949672); coords[0] = v; dv = 1; v = d2.map_to_uint64(&dv, sizeof(int32_t), bits, max_bucket_val); CHECK(v == 10737418); coords[1] = v; hv = h.coords_to_hilbert(coords); CHECK(hv == 1282377960629798); // Map (2, 2) dv = 2; v = d1.map_to_uint64(&dv, sizeof(int32_t), bits, max_bucket_val); CHECK(v == 42949672); coords[0] = v; dv = 2; v = d2.map_to_uint64(&dv, sizeof(int32_t), bits, max_bucket_val); CHECK(v == 21474836); coords[1] = v; hv = h.coords_to_hilbert(coords); CHECK(hv == 2093929125029754); // Map (3, 7) dv = 3; v = d1.map_to_uint64(&dv, sizeof(int32_t), bits, max_bucket_val); CHECK(v == 64424509); coords[0] = v; dv = 7; v = d2.map_to_uint64(&dv, sizeof(int32_t), bits, max_bucket_val); CHECK(v == 75161927); coords[1] = v; hv = h.coords_to_hilbert(coords); CHECK(hv == 8953131325824998); // Map (7, 7) dv = 7; v = d1.map_to_uint64(&dv, sizeof(int32_t), bits, max_bucket_val); CHECK(v == 150323855); coords[0] = v; dv = 7; v = d2.map_to_uint64(&dv, sizeof(int32_t), bits, max_bucket_val); CHECK(v == 75161927); coords[1] = v; hv = h.coords_to_hilbert(coords); CHECK(hv == 34410827116042986); } TEST_CASE( "Dimension: Test map_to_uint64, int32, negative", "[dimension][map_to_uint64][int32][negative]") { // Create dimensions Dimension d1("d1", Datatype::INT32); int32_t dom1[] = {-50, 50}; d1.set_domain(dom1); Dimension d2("d2", Datatype::INT32); int32_t dom2[] = {-100, 100}; d2.set_domain(dom2); // Create 2D hilbert curve (auxiliary here) Hilbert h(2); auto bits = h.bits(); uint64_t coords[2]; auto max_bucket_val = ((uint64_t)1 << bits) - 1; // Map (-49, -99) int32_t dv = -49; auto v = d1.map_to_uint64(&dv, sizeof(int32_t), bits, max_bucket_val); CHECK(v == 21474836); coords[0] = v; dv = -99; v = d2.map_to_uint64(&dv, sizeof(int32_t), bits, max_bucket_val); CHECK(v == 10737418); coords[1] = v; auto hv = h.coords_to_hilbert(coords); CHECK(hv == 972175364522868); // Map (-49, -97) dv = -49; v = d1.map_to_uint64(&dv, sizeof(int32_t), bits, max_bucket_val); CHECK(v == 21474836); coords[0] = v; dv = -97; v = d2.map_to_uint64(&dv, sizeof(int32_t), bits, max_bucket_val); CHECK(v == 32212254); coords[1] = v; hv = h.coords_to_hilbert(coords); CHECK(hv == 673795214387276); // Map (-46, -98) dv = -46; v = d1.map_to_uint64(&dv, sizeof(int32_t), bits, max_bucket_val); CHECK(v == 85899345); coords[0] = v; dv = -98; v = d2.map_to_uint64(&dv, sizeof(int32_t), bits, max_bucket_val); CHECK(v == 21474836); coords[1] = v; hv = h.coords_to_hilbert(coords); CHECK(hv == 15960414315352633); // Map (-45, -96) dv = -45; v = d1.map_to_uint64(&dv, sizeof(int32_t), bits, max_bucket_val); CHECK(v == 107374182); coords[0] = v; dv = -96; v = d2.map_to_uint64(&dv, sizeof(int32_t), bits, max_bucket_val); CHECK(v == 42949672); coords[1] = v; hv = h.coords_to_hilbert(coords); CHECK(hv == 14307296941447292); // Map (-48, -99) dv = -48; v = d1.map_to_uint64(&dv, sizeof(int32_t), bits, max_bucket_val); CHECK(v == 42949672); coords[0] = v; dv = -99; v = d2.map_to_uint64(&dv, sizeof(int32_t), bits, max_bucket_val); CHECK(v == 10737418); coords[1] = v; hv = h.coords_to_hilbert(coords); CHECK(hv == 1282377960629798); // Map (-48, -98) dv = -48; v = d1.map_to_uint64(&dv, sizeof(int32_t), bits, max_bucket_val); CHECK(v == 42949672); coords[0] = v; dv = -98; v = d2.map_to_uint64(&dv, sizeof(int32_t), bits, max_bucket_val); CHECK(v == 21474836); coords[1] = v; hv = h.coords_to_hilbert(coords); CHECK(hv == 2093929125029754); // Map (-47, -93) dv = -47; v = d1.map_to_uint64(&dv, sizeof(int32_t), bits, max_bucket_val); CHECK(v == 64424509); coords[0] = v; dv = -93; v = d2.map_to_uint64(&dv, sizeof(int32_t), bits, max_bucket_val); CHECK(v == 75161927); coords[1] = v; hv = h.coords_to_hilbert(coords); CHECK(hv == 8953131325824998); // Map (-43, -93) dv = -43; v = d1.map_to_uint64(&dv, sizeof(int32_t), bits, max_bucket_val); CHECK(v == 150323855); coords[0] = v; dv = -93; v = d2.map_to_uint64(&dv, sizeof(int32_t), bits, max_bucket_val); CHECK(v == 75161927); coords[1] = v; hv = h.coords_to_hilbert(coords); CHECK(hv == 34410827116042986); } TEST_CASE( "Dimension: Test map_to_uint64, float32", "[dimension][map_to_uint64][float32") { // Create dimensions Dimension d1("d1", Datatype::FLOAT32); float dom1[] = {0.0f, 1.0f}; d1.set_domain(dom1); Dimension d2("d2", Datatype::FLOAT32); float dom2[] = {0.0f, 2.0f}; d2.set_domain(dom2); // Create 2D hilbert curve (auxiliary here) Hilbert h(2); auto bits = h.bits(); uint64_t coords[2]; auto max_bucket_val = ((uint64_t)1 << bits) - 1; // Map (0.1f, 0.3f) float dv = 0.1f; auto v = d1.map_to_uint64(&dv, sizeof(float), bits, max_bucket_val); CHECK(v == 214748367); coords[0] = v; dv = 0.3f; v = d2.map_to_uint64(&dv, sizeof(float), bits, max_bucket_val); CHECK(v == 322122559); coords[1] = v; auto hv = h.coords_to_hilbert(coords); CHECK(hv == 141289400074368426); // Map (0.1f, 0.1f) dv = 0.1f; v = d1.map_to_uint64(&dv, sizeof(float), bits, max_bucket_val); CHECK(v == 214748367); coords[0] = v; dv = 0.1f; v = d2.map_to_uint64(&dv, sizeof(float), bits, max_bucket_val); CHECK(v == 107374183); coords[1] = v; hv = h.coords_to_hilbert(coords); CHECK(hv == 31040194354799722); // Map (0.5f, 0.4f) dv = 0.5f; v = d1.map_to_uint64(&dv, sizeof(float), bits, max_bucket_val); CHECK(v == 1073741823); coords[0] = v; dv = 0.4f; v = d2.map_to_uint64(&dv, sizeof(float), bits, max_bucket_val); CHECK(v == 429496735); coords[1] = v; hv = h.coords_to_hilbert(coords); CHECK(hv == 474732384249878186); // Map (0.4f, 0.2f) dv = 0.4f; v = d1.map_to_uint64(&dv, sizeof(float), bits, max_bucket_val); CHECK(v == 858993471); coords[0] = v; dv = 0.2f; v = d2.map_to_uint64(&dv, sizeof(float), bits, max_bucket_val); CHECK(v == 214748367); coords[1] = v; hv = h.coords_to_hilbert(coords); CHECK(hv == 429519776226080170); // Map (0.2f, 0.1f) dv = 0.2f; v = d1.map_to_uint64(&dv, sizeof(float), bits, max_bucket_val); CHECK(v == 429496735); coords[0] = v; dv = 0.1f; v = d2.map_to_uint64(&dv, sizeof(float), bits, max_bucket_val); CHECK(v == 107374183); coords[1] = v; hv = h.coords_to_hilbert(coords); CHECK(hv == 276927224145762282); // Map (0.2f, 0.2f) dv = 0.2f; v = d1.map_to_uint64(&dv, sizeof(float), bits, max_bucket_val); CHECK(v == 429496735); coords[0] = v; dv = 0.2f; v = d2.map_to_uint64(&dv, sizeof(float), bits, max_bucket_val); CHECK(v == 214748367); coords[1] = v; hv = h.coords_to_hilbert(coords); CHECK(hv == 230584300921369344); // Map (0.3f, 0.7f) dv = 0.3f; v = d1.map_to_uint64(&dv, sizeof(float), bits, max_bucket_val); CHECK(v == 644245119); coords[0] = v; dv = 0.7f; v = d2.map_to_uint64(&dv, sizeof(float), bits, max_bucket_val); CHECK(v == 751619263); coords[1] = v; hv = h.coords_to_hilbert(coords); CHECK(hv == 607500946658220714); // Map (0.7f, 0.7f) dv = 0.7f; v = d1.map_to_uint64(&dv, sizeof(float), bits, max_bucket_val); CHECK(v == 1503238527); coords[0] = v; dv = 0.7f; v = d2.map_to_uint64(&dv, sizeof(float), bits, max_bucket_val); CHECK(v == 751619263); coords[1] = v; hv = h.coords_to_hilbert(coords); CHECK(hv == 4004185071769213610); // (0.1f, 0.1f) -> 31040194354799722 // (0.1f, 0.3f) -> 141289400074368426 // (0.2f, 0.2f) -> 230584300921369344 // (0.2f, 0.1f) -> 276927224145762282 // (0.4f, 0.2f) -> 429519776226080170 // (0.5f, 0.4f) -> 474732384249878186 // (0.3f, 0.7f) -> 607500946658220714 // (0.7f, 0.7f) -> 4004185071769213610 } TEST_CASE( "Dimension: Test map_to_uint64, string", "[dimension][map_to_uint64][string]") { // Create dimensions Dimension d1("d1", Datatype::STRING_ASCII); Dimension d2("d2", Datatype::STRING_ASCII); // Create 2D hilbert curve (auxiliary here) Hilbert h(2); auto bits = h.bits(); auto max_bucket_val = ((uint64_t)1 << bits) - 1; uint64_t coords[2]; // Map (1a, cat) std::string dv = "1a"; auto v = d1.map_to_uint64(dv.data(), dv.size(), bits, max_bucket_val); CHECK(v == 414220288); coords[0] = v; dv = "cat"; v = d2.map_to_uint64(dv.data(), dv.size(), bits, max_bucket_val); CHECK(v == 833665536); coords[1] = v; auto hv = h.coords_to_hilbert(coords); CHECK(hv == 919167533801450154); // Map (dog, stop) dv = "dog"; v = d1.map_to_uint64(dv.data(), dv.size(), bits, max_bucket_val); CHECK(v == 842511232); coords[0] = v; dv = "stop"; v = d2.map_to_uint64(dv.data(), dv.size(), bits, max_bucket_val); CHECK(v == 968505272); coords[1] = v; hv = h.coords_to_hilbert(coords); CHECK(hv == 785843883856635242); // Map (camel, stock) dv = "camel"; v = d1.map_to_uint64(dv.data(), dv.size(), bits, max_bucket_val); CHECK(v == 833664690); coords[0] = v; dv = "stock"; v = d2.map_to_uint64(dv.data(), dv.size(), bits, max_bucket_val); CHECK(v == 968505265); coords[1] = v; hv = h.coords_to_hilbert(coords); CHECK(hv == 785914162406170797); // Map (33, t1) dv = "33"; v = d1.map_to_uint64(dv.data(), dv.size(), bits, max_bucket_val); CHECK(v == 429490176); coords[0] = v; dv = "t1"; v = d2.map_to_uint64(dv.data(), dv.size(), bits, max_bucket_val); CHECK(v == 974684160); coords[1] = v; hv = h.coords_to_hilbert(coords); CHECK(hv == 877430626372812800); // Map (blue, ac3) dv = "blue"; v = d1.map_to_uint64(dv.data(), dv.size(), bits, max_bucket_val); CHECK(v == 825637554); coords[0] = v; dv = "ace"; v = d2.map_to_uint64(dv.data(), dv.size(), bits, max_bucket_val); CHECK(v == 816951936); coords[1] = v; hv = h.coords_to_hilbert(coords); CHECK(hv == 721526731798250756); // Map (az, yellow) dv = "az"; v = d1.map_to_uint64(dv.data(), dv.size(), bits, max_bucket_val); CHECK(v == 817692672); coords[0] = v; dv = "yellow"; v = d2.map_to_uint64(dv.data(), dv.size(), bits, max_bucket_val); CHECK(v == 1018345014); coords[1] = v; hv = h.coords_to_hilbert(coords); CHECK(hv == 788282729955763606); // Map (star, red) dv = "star"; v = d1.map_to_uint64(dv.data(), dv.size(), bits, max_bucket_val); CHECK(v == 968503481); coords[0] = v; dv = "red"; v = d2.map_to_uint64(dv.data(), dv.size(), bits, max_bucket_val); CHECK(v == 959623680); coords[1] = v; hv = h.coords_to_hilbert(coords); CHECK(hv == 757250025264009195); // Map (urn, grey) dv = "urn"; v = d1.map_to_uint64(dv.data(), dv.size(), bits, max_bucket_val); CHECK(v == 985216768); coords[0] = v; dv = "grey"; v = d2.map_to_uint64(dv.data(), dv.size(), bits, max_bucket_val); CHECK(v == 867775164); coords[1] = v; hv = h.coords_to_hilbert(coords); CHECK(hv == 741275904800572752); // (blue, ace) -> 721526731798250756 // (urn, grey) -> 741275904800572752 // (star, red) -> 757250025264009195 // (dog, stop) -> 785843883856635242 // (camel, stock) -> 785914162406170797 // (az, yellow) -> 788282729955763606 // (33, t1) -> 877430626372812800 // (1a, cat) -> 919167533801450154 } TEST_CASE( "Dimension: Test map_from_uint64, int32", "[dimension][map_from_uint64][int32]") { // Create dimensions Dimension d1("d1", Datatype::INT32); int32_t dom1[] = {0, 100}; d1.set_domain(dom1); // Set number of buckets Hilbert h(2); auto bits = h.bits(); auto max_bucket_val = ((uint64_t)1 << bits) - 1; auto val = d1.map_from_uint64(64424509, bits, max_bucket_val); auto val_int32 = *(const int32_t*)(val.data()); CHECK(val_int32 == 3); val = d1.map_from_uint64(42949672, bits, max_bucket_val); val_int32 = *(const int32_t*)(val.data()); CHECK(val_int32 == 2); } TEST_CASE( "Dimension: Test map_from_uint64, int32, negative", "[dimension][map_from_uint64][int32][negative]") { // Create dimensions Dimension d1("d1", Datatype::INT32); int32_t dom1[] = {-50, 50}; d1.set_domain(dom1); // Set number of buckets Hilbert h(2); auto bits = h.bits(); auto max_bucket_val = ((uint64_t)1 << bits) - 1; auto val = d1.map_from_uint64(64424509, bits, max_bucket_val); auto val_int32 = *(const int32_t*)(val.data()); CHECK(val_int32 == -47); val = d1.map_from_uint64(42949672, bits, max_bucket_val); val_int32 = *(const int32_t*)(val.data()); CHECK(val_int32 == -48); } TEST_CASE( "Dimension: Test map_from_uint64, float32", "[dimension][map_from_uint64][float32]") { // Create dimensions Dimension d1("d1", Datatype::FLOAT32); float dom1[] = {0.0f, 1.0f}; d1.set_domain(dom1); // Set number of buckets Hilbert h(2); auto bits = h.bits(); auto max_bucket_val = ((uint64_t)1 << bits) - 1; auto val = d1.map_from_uint64(1503238527, bits, max_bucket_val); auto val_int32 = *(const float*)(val.data()); CHECK(round(100 * val_int32) == 70); val = d1.map_from_uint64(429496735, bits, max_bucket_val); val_int32 = *(const float*)(val.data()); CHECK(round(100 * val_int32) == 20); } TEST_CASE( "Dimension: Test map_from_uint64, string", "[dimension][map_from_uint64][string]") { // Create dimensions Dimension d1("d1", Datatype::STRING_ASCII); // Set number of buckets Hilbert h(2); auto bits = h.bits(); auto max_bucket_val = ((uint64_t)1 << bits) - 1; std::string v_str = std::string("star\0\0\0\0", 8); auto v = d1.map_to_uint64(v_str.data(), v_str.size(), bits, max_bucket_val); auto val = d1.map_from_uint64(v, bits, max_bucket_val); auto val_str = std::string((const char*)(val.data()), 8); CHECK(val_str == v_str); v_str = std::string("blue\0\0\0\0", 8); v = d1.map_to_uint64(v_str.data(), v_str.size(), bits, max_bucket_val); val = d1.map_from_uint64(v, bits, max_bucket_val); val_str = std::string((const char*)(val.data()), 4); CHECK(val_str == std::string("blud", 4)); v_str = std::string("yellow\0\0", 8); v = d1.map_to_uint64(v_str.data(), v_str.size(), bits, max_bucket_val); val = d1.map_from_uint64(v, bits, max_bucket_val); val_str = std::string((const char*)(val.data()), 4); CHECK(val_str == std::string("yell", 4)); } template <typename T> void test_int_max_tile_extent_value() { T min = std::numeric_limits<T>::min() + std::is_signed<T>::value; T max = std::numeric_limits<T>::max() - !std::is_signed<T>::value; typedef typename std::make_unsigned<T>::type tile_extent_t; T max_extent = (tile_extent_t)max - (tile_extent_t)min + 1; auto tile_idx = Dimension::tile_idx(max, min, max_extent); CHECK(Dimension::tile_coord_low(tile_idx, min, max_extent) == min); CHECK(Dimension::tile_coord_high(tile_idx, min, max_extent) == max); CHECK(Dimension::round_to_tile(min, min, max_extent) == min); CHECK(Dimension::round_to_tile(max, min, max_extent) == min); } template <typename T> void test_int_min_tile_extent_value() { T min = std::numeric_limits<T>::min(); T max = std::numeric_limits<T>::max(); T min_extent = 1; auto tile_idx = Dimension::tile_idx(max, min, min_extent); CHECK(Dimension::tile_coord_low(0, min, min_extent) == min); CHECK(Dimension::tile_coord_high(tile_idx, min, min_extent) == max); CHECK(Dimension::round_to_tile(min, min, min_extent) == min); CHECK(Dimension::round_to_tile(max, min, min_extent) == max); } TEST_CASE( "test max tile extent for integer values", "[dimension][integral][max][tile_extent]") { test_int_max_tile_extent_value<int8_t>(); test_int_max_tile_extent_value<int16_t>(); test_int_max_tile_extent_value<int32_t>(); test_int_max_tile_extent_value<int64_t>(); test_int_max_tile_extent_value<uint8_t>(); test_int_max_tile_extent_value<uint16_t>(); test_int_max_tile_extent_value<uint32_t>(); test_int_max_tile_extent_value<uint64_t>(); } TEST_CASE( "test min tile extent for integer values", "[dimension][integral][min][tile_extent]") { test_int_min_tile_extent_value<int8_t>(); test_int_min_tile_extent_value<int16_t>(); test_int_min_tile_extent_value<int32_t>(); test_int_min_tile_extent_value<int64_t>(); test_int_min_tile_extent_value<uint8_t>(); test_int_min_tile_extent_value<uint16_t>(); test_int_min_tile_extent_value<uint32_t>(); test_int_min_tile_extent_value<uint64_t>(); } template <class T> double basic_verify_overlap_ratio( T range1_low, T range1_high, T range2_low, T range2_high) { auto r1 = TypedRange<T>(range1_low, range1_high); auto r2 = TypedRange<T>(range2_low, range2_high); Dimension d("foo", RangeTraits<T>::datatype); auto ratio = d.overlap_ratio(r1, r2); CHECK(0.0 <= ratio); CHECK(ratio <= 1.0); return ratio; } /** * The denominator of the ratio is computed as range2_high - range2_low. For a * k-bit signed integer, the largest this value can take is 2^k-1, which is * larger than the maximum signed value of 2^(k-1)-1. */ TEST_CASE( "Range<int32_t>.overlap_ratio: denominator overflow", "[dimension][overlap_ratio][signed][integral]") { typedef int32_t T; auto min = std::numeric_limits<T>::min(); auto max = std::numeric_limits<T>::max(); basic_verify_overlap_ratio<T>(min / 3, 1, min + 1, max); } /** * Denominator overflow for an unsigned integral type. */ TEST_CASE( "Range<uint32_t>.overlap_ratio: denominator overflow", "[dimension][overlap_ratio][unsigned][integral]") { typedef uint32_t T; auto min = std::numeric_limits<T>::min(); auto max = std::numeric_limits<T>::max(); basic_verify_overlap_ratio<T>(0, 1, min + 1, max); } /** * Denominator overflow for double. */ TEST_CASE( "Range<double>.overlap_ratio: denominator overflow", "[dimension][overlap_ratio][signed][floating]") { typedef double T; auto min = std::numeric_limits<T>::min(); auto max = std::numeric_limits<T>::max(); basic_verify_overlap_ratio<T>(0, 1, min + 1, max); } TEST_CASE( "Range<uint32_t>.overlap_ratio: max base range", "[dimension][overlap_ratio][unsigned][integral]") { typedef uint32_t T; auto min = std::numeric_limits<T>::min(); auto max = std::numeric_limits<T>::max(); basic_verify_overlap_ratio<T>(min, min + 1, min, max); } TEST_CASE( "Range<uint32_t>.overlap_ratio: max both ranges", "[dimension][overlap_ratio][unsigned][integral]") { typedef uint32_t T; auto min = std::numeric_limits<T>::min(); auto max = std::numeric_limits<T>::max(); basic_verify_overlap_ratio<T>(min, max, min, max); } TEST_CASE( "Range<int32_t>.overlap_ratio: over-by-1 legit-max base range", "[dimension][overlap_ratio][signed][integral]") { typedef int32_t T; auto max = std::numeric_limits<T>::max(); basic_verify_overlap_ratio<T>(0, 1, -1, max); } TEST_CASE( "Range<int32_t>.overlap_ratio: legit-max base range", "[dimension][overlap_ratio][signed][integral]") { typedef int32_t T; auto max = std::numeric_limits<T>::max(); basic_verify_overlap_ratio<T>(0, 1, -2, max - 2); }
30.075899
80
0.655067
upj977155
14a58602f94849d1dd58e119706d3cad7d6d97db
1,219
hpp
C++
android-31/android/widget/PopupMenu.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-30/android/widget/PopupMenu.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-29/android/widget/PopupMenu.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#pragma once #include "../../JObject.hpp" namespace android::content { class Context; } namespace android::view { class MenuInflater; } namespace android::view { class View; } namespace android::widget { class PopupMenu : public JObject { public: // Fields // QJniObject forward template<typename ...Ts> explicit PopupMenu(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {} PopupMenu(QJniObject obj); // Constructors PopupMenu(android::content::Context arg0, android::view::View arg1); PopupMenu(android::content::Context arg0, android::view::View arg1, jint arg2); PopupMenu(android::content::Context arg0, android::view::View arg1, jint arg2, jint arg3, jint arg4); // Methods void dismiss() const; JObject getDragToOpenListener() const; jint getGravity() const; JObject getMenu() const; android::view::MenuInflater getMenuInflater() const; void inflate(jint arg0) const; void setForceShowIcon(jboolean arg0) const; void setGravity(jint arg0) const; void setOnDismissListener(JObject arg0) const; void setOnMenuItemClickListener(JObject arg0) const; void show() const; }; } // namespace android::widget
24.877551
150
0.722724
YJBeetle
14a9fc4a6d57febc22fff3c5fddc3a34c43aa414
2,440
hpp
C++
src/mlpack/core/data/detect_file_type.hpp
florian-rosenthal/mlpack
4287a89886e39703571165ef1d40693eb51d22c6
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
src/mlpack/core/data/detect_file_type.hpp
florian-rosenthal/mlpack
4287a89886e39703571165ef1d40693eb51d22c6
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
src/mlpack/core/data/detect_file_type.hpp
florian-rosenthal/mlpack
4287a89886e39703571165ef1d40693eb51d22c6
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
/** * @file core/data/detect_file_type.hpp * @author Conrad Sanderson * @author Ryan Curtin * * Functionality to guess the type of a file by inspecting it. Parts of the * implementation are adapted from the Armadillo sources and relicensed to be a * part of mlpack with permission from Conrad. * * mlpack is free software; you may redistribute it and/or modify it under the * terms of the 3-clause BSD license. You should have received a copy of the * 3-clause BSD license along with mlpack. If not, see * http://www.opensource.org/licenses/BSD-3-Clause for more information. */ #ifndef MLPACK_CORE_DATA_DETECT_FILE_TYPE_HPP #define MLPACK_CORE_DATA_DETECT_FILE_TYPE_HPP #include "types.hpp" namespace mlpack { namespace data { /** * Given a file type, return a logical name corresponding to that file type. * * @param type Type to get the logical name of. */ std::string GetStringType(const FileType& type); /** * Given an istream, attempt to guess the file type. This is taken originally * from Armadillo's function guess_file_type_internal(), but we avoid using * internal Armadillo functionality. * * If the file is detected as a CSV, and the CSV is detected to have a header * row, the stream `f` will be fast-forwarded to point at the second line of the * file. * * @param f Opened istream to look into to guess the file type. */ FileType GuessFileType(std::istream& f); /** * Attempt to auto-detect the type of a file given its extension, and by * inspecting the parts of the file to disambiguate between types when * necessary. (For instance, a .csv file could be delimited by spaces, commas, * or tabs.) This is meant to be used during loading. * * If the file is detected as a CSV, and the CSV is detected to have a header * row, `stream` will be fast-forwarded to point at the second line of the file. * * @param stream Opened file stream to look into for autodetection. * @param filename Name of the file. * @return The detected file type. arma::file_type_unknown if unknown. */ FileType AutoDetect(std::fstream& stream, const std::string& filename); /** * Return the type based only on the extension. * * @param filename Name of the file whose type we should detect. * @return Detected type of file. arma::file_type_unknown if unknown. */ FileType DetectFromExtension(const std::string& filename); } // namespace data } // namespace mlpack #endif
34.366197
80
0.732787
florian-rosenthal
14ab8f8117b58d88bd17a201b705485e4db16e65
1,288
cpp
C++
luogu/codes/P2257.cpp
Tony031218/OI
562f5f45d0448f4eab77643b99b825405a123d92
[ "MIT" ]
1
2021-02-22T03:39:24.000Z
2021-02-22T03:39:24.000Z
luogu/codes/P2257.cpp
Tony031218/OI
562f5f45d0448f4eab77643b99b825405a123d92
[ "MIT" ]
null
null
null
luogu/codes/P2257.cpp
Tony031218/OI
562f5f45d0448f4eab77643b99b825405a123d92
[ "MIT" ]
null
null
null
/************************************************************* * > File Name : P2257.cpp * > Author : Tony * > Created Time : 2019/05/12 16:30:54 **************************************************************/ #include <bits/stdc++.h> using namespace std; const int maxn = 10000010; bool vis[maxn]; long long sum[maxn]; int mu[maxn], primes[maxn], g[maxn], cnt; void get_mu(int n) { mu[1] = 1; for (int i = 2; i <= n; ++i) { if (!vis[i]) { primes[++cnt] = i; mu[i] = -1; } for (int j = 1; j <= cnt && primes[j] * i <= n; ++j) { vis[primes[j] * i] = 1; if (i % primes[j] == 0) break; else mu[i * primes[j]] = -mu[i]; } } for (int j = 1; j <= cnt; ++j) for (int i = 1; i * primes[j] <= n; ++i) g[i * primes[j]] += mu[i]; for (int i = 1; i <= n; ++i) sum[i] = sum[i - 1] + (long long)g[i]; } int n, m; int main() { int T; scanf("%d", &T); get_mu(maxn - 10); while (T--) { scanf("%d %d", &n, &m); if (n > m) swap(n, m); long long ans = 0; for (int l = 1, r; l <= n; l = r + 1) { r = min(n / (n / l), m / (m / l)); ans += 1LL * (n / l) * (m / l) * (sum[r] - sum[l - 1]); } printf("%lld\n", ans); } return 0; }
26.285714
67
0.373447
Tony031218
14b207650eb27bb54fc06198c3e103cc38f0205e
1,172
cpp
C++
2.5/The_Castle.cpp
tangxiangru/NOIP
6c756df37e5cb6105f5d5eb0fd9b03a4ef8407e4
[ "MIT" ]
1
2020-10-12T12:00:08.000Z
2020-10-12T12:00:08.000Z
2.5/The_Castle.cpp
tangxiangru/NOIP
6c756df37e5cb6105f5d5eb0fd9b03a4ef8407e4
[ "MIT" ]
null
null
null
2.5/The_Castle.cpp
tangxiangru/NOIP
6c756df37e5cb6105f5d5eb0fd9b03a4ef8407e4
[ "MIT" ]
null
null
null
#include <algorithm> #include <cstdlib> #include <cstring> #include <cstdio> #include <queue> using namespace std; const int X[] = {0,-1,0,1}; const int Y[] = {-1,0,1,0}; bool a[51][51][4],vis[51][51]; int n,m,ans = 0,Max = -999999; struct Queue { int x,y; }; queue<Queue> Q; inline void bfs(int x,int y) { bool cnt[51][51]; memset(cnt,false,sizeof(cnt)); Q.push((Queue){x,y}); vis[x][y] = true; cnt[x][y] = true; while (!Q.empty()) { Queue now = Q.front(); Q.pop(); for (int i = 0;i < 4;i++) if (a[now.x][now.y][i]) { Queue next; next.x = now.x+X[i]; next.y = now.y+Y[i]; if (next.x <= 0 || next.x > n || next.y <= 0 || next.x > m || vis[next.x][next.y]) continue; Q.push(next); vis[next.x][next.y] = true; cnt[next.x][next.y] = true; } } int sum = 0; for (int i = 1;i <= n;i++) for (int j = 1;j <= m;j++) if (cnt[i][j]) sum++; Max = max(Max,sum); } int main() { memset(a,true,sizeof(a)); scanf("%d%d",&n,&m); for (int i = 1;i <= n;i++) for (int j = 1,x;j <= m;j++) { scanf("%d",&x); int t = 0; while (x) { a[i][j][t++] = !(x%2); x /= 2; } } for (int i = 1;i <= n;i++) for (int j = 1;j <= m;j++) if (!vis[i][j]) { bfs(i,j); ans++; } printf("%d\n%d",ans,Max); return 0; }
19.213115
92
0.533276
tangxiangru
14b4597bd451cfac22908ca005596b2b7439e30f
2,340
hxx
C++
Legolas/BlockMatrix/Structures/Diagonal/DiagonalScalarParallelMultOperator.hxx
LaurentPlagne/Legolas
fdf533528baf7ab5fcb1db15d95d2387b3e3723c
[ "MIT" ]
null
null
null
Legolas/BlockMatrix/Structures/Diagonal/DiagonalScalarParallelMultOperator.hxx
LaurentPlagne/Legolas
fdf533528baf7ab5fcb1db15d95d2387b3e3723c
[ "MIT" ]
null
null
null
Legolas/BlockMatrix/Structures/Diagonal/DiagonalScalarParallelMultOperator.hxx
LaurentPlagne/Legolas
fdf533528baf7ab5fcb1db15d95d2387b3e3723c
[ "MIT" ]
1
2021-02-11T14:43:25.000Z
2021-02-11T14:43:25.000Z
#ifndef __DIAGONALSCALARPARALLELMULTOPERATOR_HXX__ #define __DIAGONALSCALARPARALLELMULTOPERATOR_HXX__ #include "Legolas/Vector/Vector.hxx" #include "Legolas/BlockMatrix/ScalarMatrixMultOperator.hxx" namespace Legolas{ template <class SCALAR_MATRIX, class V1D> class AddMultLineOperator{ const SCALAR_MATRIX & A_; const double & a_; const V1D & X_; V1D & Y_; public: AddMultLineOperator(const SCALAR_MATRIX & A, const double & a, const V1D & X, V1D & Y):A_(A),a_(a),X_(X),Y_(Y){} inline void operator()(const my_tbb::blocked_range<int> & r) const { for (int i=r.begin() ; i!=r.end() ; i++){ Y_[i]+=a_*A_.diagonalGetElement(i)*X_[i]; } } }; template <class SCALAR_MATRIX, class V1D> class MultLineOperator{ const SCALAR_MATRIX & A_; const V1D & X_; V1D & Y_; public: MultLineOperator(const SCALAR_MATRIX & A, const V1D & X, V1D & Y):A_(A),X_(X),Y_(Y){} inline void operator()(const my_tbb::blocked_range<int> & r) const { for (int i=r.begin() ; i!=r.end() ; i++){ Y_[i]=A_.diagonalGetElement(i)*X_[i]; } } }; struct DiagonalScalarParallelMultOperator{ template <class SCALAR_MATRIX> class Engine : public ScalarMatrixMultOperator<SCALAR_MATRIX>{ typedef typename SCALAR_MATRIX::RealType RealType; typedef Legolas::MultiVector<RealType,1> V1D; public: inline std::string name( void ) const { return "DiagonalScalarParallelMultOperator" ;} virtual VirtualMultOperator * clone( void ) const { return new Engine(*this); } //Y+=a*A*X void addMult(const SCALAR_MATRIX & A, const double & a, const V1D & X, V1D & Y){ my_tbb::parallel_for(my_tbb::blocked_range<int>(0,A.nrows(),100),AddMultLineOperator<SCALAR_MATRIX,V1D>(A,a,X,Y)); // const int n=A.nrows(); // RealType factor(a); // for (int i=0 ; i < n ; i++ ){ // Y[i]+=factor*A.diagonalGetElement(i)*X[i]; // } } //Y=A*X void mult(const SCALAR_MATRIX & A, const V1D & X, V1D & Y){ my_tbb::parallel_for(my_tbb::blocked_range<int>(0,A.nrows(),100),MultLineOperator<SCALAR_MATRIX,V1D>(A,X,Y)); // const int n=A.nrows(); // for (int i=0 ; i < n ; i++ ){ // Y[i]=A.diagonalGetElement(i)*X[i]; // } } }; }; } #endif
25.434783
115
0.626068
LaurentPlagne
14b522395448cf47de148b9af2a1c0c2aad1fb4a
918
cpp
C++
src/RenderHandler.cpp
dfrancio/cef-pdf
a382911640d55d1f82ff1999d668fc519c54bfb8
[ "MIT" ]
71
2016-08-24T18:17:30.000Z
2022-03-31T06:09:18.000Z
src/RenderHandler.cpp
dfrancio/cef-pdf
a382911640d55d1f82ff1999d668fc519c54bfb8
[ "MIT" ]
34
2017-03-14T05:10:28.000Z
2021-06-09T10:19:46.000Z
src/RenderHandler.cpp
dfrancio/cef-pdf
a382911640d55d1f82ff1999d668fc519c54bfb8
[ "MIT" ]
34
2016-12-20T10:15:10.000Z
2022-03-31T06:09:21.000Z
#include "RenderHandler.h" namespace cefpdf { RenderHandler::RenderHandler() { m_viewWidth = 128; m_viewHeight = 128; } void RenderHandler::SetViewWidth(int viewWidth) { m_viewWidth = viewWidth; DLOG(INFO) << "View width: " << m_viewWidth; } void RenderHandler::SetViewHeight(int viewHeight) { m_viewHeight = viewHeight; DLOG(INFO) << "View height: " << m_viewHeight; } // CefRenderHandler methods: // ------------------------------------------------------------------------- void RenderHandler::GetViewRect(CefRefPtr<CefBrowser> browser, CefRect& rect) { rect.x = 0; rect.y = 0; rect.width = m_viewWidth; rect.height = m_viewHeight; } void RenderHandler::OnPaint( CefRefPtr<CefBrowser> browser, CefRenderHandler::PaintElementType type, const CefRenderHandler::RectList& dirtyRects, const void* buffer, int width, int height ) { } } // namespace cefpdf
21.348837
77
0.641612
dfrancio
14b61556befaa28ce8995c44aa3556a7df239f75
16,740
cpp
C++
src/kits/tracker/TextWidget.cpp
chamalwr/haiku
b2bf76c43decc3fc2de50c4750f830b16807ddef
[ "MIT" ]
2
2020-02-02T06:48:30.000Z
2020-04-05T13:58:32.000Z
src/kits/tracker/TextWidget.cpp
honza1a/haiku
3959883f5047e803205668d4eb7d083b2d81e2da
[ "MIT" ]
null
null
null
src/kits/tracker/TextWidget.cpp
honza1a/haiku
3959883f5047e803205668d4eb7d083b2d81e2da
[ "MIT" ]
1
2019-01-15T10:32:43.000Z
2019-01-15T10:32:43.000Z
/* Open Tracker License Terms and Conditions Copyright (c) 1991-2000, Be Incorporated. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice applies to all licensees and shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL BE INCORPORATED BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of Be Incorporated shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Be Incorporated. Tracker(TM), Be(R), BeOS(R), and BeIA(TM) are trademarks or registered trademarks of Be Incorporated in the United States and other countries. Other brand product names are registered trademarks or trademarks of their respective holders. All rights reserved. */ #include "TextWidget.h" #include <string.h> #include <stdlib.h> #include <Alert.h> #include <Catalog.h> #include <Debug.h> #include <Directory.h> #include <MessageFilter.h> #include <ScrollView.h> #include <TextView.h> #include <Volume.h> #include <Window.h> #include "Attributes.h" #include "ContainerWindow.h" #include "Commands.h" #include "FSUtils.h" #include "PoseView.h" #include "Utilities.h" #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "TextWidget" const float kWidthMargin = 20; // #pragma mark - BTextWidget BTextWidget::BTextWidget(Model* model, BColumn* column, BPoseView* view) : fText(WidgetAttributeText::NewWidgetText(model, column, view)), fAttrHash(column->AttrHash()), fAlignment(column->Alignment()), fEditable(column->Editable()), fVisible(true), fActive(false), fSymLink(model->IsSymLink()), fLastClickedTime(0) { } BTextWidget::~BTextWidget() { if (fLastClickedTime != 0) fParams.poseView->SetTextWidgetToCheck(NULL, this); delete fText; } int BTextWidget::Compare(const BTextWidget& with, BPoseView* view) const { return fText->Compare(*with.fText, view); } const char* BTextWidget::Text(const BPoseView* view) const { StringAttributeText* textAttribute = dynamic_cast<StringAttributeText*>(fText); if (textAttribute == NULL) return NULL; return textAttribute->ValueAsText(view); } float BTextWidget::TextWidth(const BPoseView* pose) const { return fText->Width(pose); } float BTextWidget::PreferredWidth(const BPoseView* pose) const { return fText->PreferredWidth(pose) + 1; } BRect BTextWidget::ColumnRect(BPoint poseLoc, const BColumn* column, const BPoseView* view) { if (view->ViewMode() != kListMode) { // ColumnRect only makes sense in list view, return // CalcRect otherwise return CalcRect(poseLoc, column, view); } BRect result; result.left = column->Offset() + poseLoc.x; result.right = result.left + column->Width(); result.bottom = poseLoc.y + roundf((view->ListElemHeight() + view->FontHeight()) / 2); result.top = result.bottom - view->FontHeight(); return result; } BRect BTextWidget::CalcRectCommon(BPoint poseLoc, const BColumn* column, const BPoseView* view, float textWidth) { BRect result; if (view->ViewMode() == kListMode) { poseLoc.x += column->Offset(); switch (fAlignment) { case B_ALIGN_LEFT: result.left = poseLoc.x; result.right = result.left + textWidth + 1; break; case B_ALIGN_CENTER: result.left = poseLoc.x + (column->Width() / 2) - (textWidth / 2); if (result.left < 0) result.left = 0; result.right = result.left + textWidth + 1; break; case B_ALIGN_RIGHT: result.right = poseLoc.x + column->Width(); result.left = result.right - textWidth - 1; if (result.left < 0) result.left = 0; break; default: TRESPASS(); break; } result.bottom = poseLoc.y + roundf((view->ListElemHeight() + view->FontHeight()) / 2); } else { if (view->ViewMode() == kIconMode) { // large/scaled icon mode result.left = poseLoc.x + (view->IconSizeInt() - textWidth) / 2; } else { // mini icon mode result.left = poseLoc.x + B_MINI_ICON + kMiniIconSeparator; } result.right = result.left + textWidth; result.bottom = poseLoc.y + view->IconPoseHeight(); } result.top = result.bottom - view->FontHeight(); return result; } BRect BTextWidget::CalcRect(BPoint poseLoc, const BColumn* column, const BPoseView* view) { return CalcRectCommon(poseLoc, column, view, fText->Width(view)); } BRect BTextWidget::CalcOldRect(BPoint poseLoc, const BColumn* column, const BPoseView* view) { return CalcRectCommon(poseLoc, column, view, fText->CurrentWidth()); } BRect BTextWidget::CalcClickRect(BPoint poseLoc, const BColumn* column, const BPoseView* view) { BRect result = CalcRect(poseLoc, column, view); if (result.Width() < kWidthMargin) { // if resulting rect too narrow, make it a bit wider // for comfortable clicking if (column != NULL && column->Width() < kWidthMargin) result.right = result.left + column->Width(); else result.right = result.left + kWidthMargin; } return result; } void BTextWidget::CheckExpiration() { if (IsEditable() && fParams.pose->IsSelected() && fLastClickedTime) { bigtime_t doubleClickSpeed; get_click_speed(&doubleClickSpeed); bigtime_t delta = system_time() - fLastClickedTime; if (delta > doubleClickSpeed) { // at least 'doubleClickSpeed' microseconds ellapsed and no click // was registered since. fLastClickedTime = 0; StartEdit(fParams.bounds, fParams.poseView, fParams.pose); } } else { fLastClickedTime = 0; fParams.poseView->SetTextWidgetToCheck(NULL); } } void BTextWidget::CancelWait() { fLastClickedTime = 0; fParams.poseView->SetTextWidgetToCheck(NULL); } void BTextWidget::MouseUp(BRect bounds, BPoseView* view, BPose* pose, BPoint) { // Register the time of that click. The PoseView, through its Pulse() // will allow us to StartEdit() if no other click have been registered since // then. // TODO: re-enable modifiers, one should be enough view->SetTextWidgetToCheck(NULL); if (IsEditable() && pose->IsSelected()) { bigtime_t doubleClickSpeed; get_click_speed(&doubleClickSpeed); if (fLastClickedTime == 0) { fLastClickedTime = system_time(); if (fLastClickedTime - doubleClickSpeed < pose->SelectionTime()) fLastClickedTime = 0; } else fLastClickedTime = 0; if (fLastClickedTime == 0) return; view->SetTextWidgetToCheck(this); fParams.pose = pose; fParams.bounds = bounds; fParams.poseView = view; } else fLastClickedTime = 0; } static filter_result TextViewFilter(BMessage* message, BHandler**, BMessageFilter* filter) { uchar key; if (message->FindInt8("byte", (int8*)&key) != B_OK) return B_DISPATCH_MESSAGE; ThrowOnAssert(filter != NULL); BContainerWindow* window = dynamic_cast<BContainerWindow*>( filter->Looper()); ThrowOnAssert(window != NULL); BPoseView* poseView = window->PoseView(); ThrowOnAssert(poseView != NULL); if (key == B_RETURN || key == B_ESCAPE) { poseView->CommitActivePose(key == B_RETURN); return B_SKIP_MESSAGE; } if (key == B_TAB) { if (poseView->ActivePose()) { if (message->FindInt32("modifiers") & B_SHIFT_KEY) poseView->ActivePose()->EditPreviousWidget(poseView); else poseView->ActivePose()->EditNextWidget(poseView); } return B_SKIP_MESSAGE; } // the BTextView doesn't respect window borders when resizing itself; // we try to work-around this "bug" here. // find the text editing view BView* scrollView = poseView->FindView("BorderView"); if (scrollView != NULL) { BTextView* textView = dynamic_cast<BTextView*>( scrollView->FindView("WidgetTextView")); if (textView != NULL) { BRect textRect = textView->TextRect(); BRect rect = scrollView->Frame(); if (rect.right + 5 > poseView->Bounds().right || rect.left - 5 < 0) textView->MakeResizable(true, NULL); if (textRect.Width() + 10 < rect.Width()) { textView->MakeResizable(true, scrollView); // make sure no empty white space stays on the right textView->ScrollToOffset(0); } } } return B_DISPATCH_MESSAGE; } void BTextWidget::StartEdit(BRect bounds, BPoseView* view, BPose* pose) { view->SetTextWidgetToCheck(NULL, this); if (!IsEditable() || IsActive()) return; BEntry entry(pose->TargetModel()->EntryRef()); if (entry.InitCheck() == B_OK && !ConfirmChangeIfWellKnownDirectory(&entry, kRename)) { return; } // get bounds with full text length BRect rect(bounds); BRect textRect(bounds); rect.OffsetBy(-2, -1); rect.right += 1; BFont font; view->GetFont(&font); BTextView* textView = new BTextView(rect, "WidgetTextView", textRect, &font, 0, B_FOLLOW_ALL, B_WILL_DRAW); textView->SetWordWrap(false); DisallowMetaKeys(textView); fText->SetUpEditing(textView); textView->AddFilter(new BMessageFilter(B_KEY_DOWN, TextViewFilter)); rect.right = rect.left + textView->LineWidth() + 3; // center new width, if necessary if (view->ViewMode() == kIconMode || (view->ViewMode() == kListMode && fAlignment == B_ALIGN_CENTER)) { rect.OffsetBy(bounds.Width() / 2 - rect.Width() / 2, 0); } rect.bottom = rect.top + textView->LineHeight() + 1; textRect = rect.OffsetToCopy(2, 1); textRect.right -= 3; textRect.bottom--; textView->SetTextRect(textRect); BPoint origin = view->LeftTop(); textRect = view->Bounds(); bool hitBorder = false; if (rect.left <= origin.x) rect.left = origin.x + 1, hitBorder = true; if (rect.right >= textRect.right) rect.right = textRect.right - 1, hitBorder = true; textView->MoveTo(rect.LeftTop()); textView->ResizeTo(rect.Width(), rect.Height()); BScrollView* scrollView = new BScrollView("BorderView", textView, 0, 0, false, false, B_PLAIN_BORDER); view->AddChild(scrollView); // configure text view switch (view->ViewMode()) { case kIconMode: textView->SetAlignment(B_ALIGN_CENTER); break; case kMiniIconMode: textView->SetAlignment(B_ALIGN_LEFT); break; case kListMode: textView->SetAlignment(fAlignment); break; } textView->MakeResizable(true, hitBorder ? NULL : scrollView); view->SetActivePose(pose); // tell view about pose SetActive(true); // for widget textView->SelectAll(); textView->MakeFocus(); // make this text widget invisible while we edit it SetVisible(false); ASSERT(view->Window() != NULL); // how can I not have a Window here??? if (view->Window()) { // force immediate redraw so TextView appears instantly view->Window()->UpdateIfNeeded(); } } void BTextWidget::StopEdit(bool saveChanges, BPoint poseLoc, BPoseView* view, BPose* pose, int32 poseIndex) { // find the text editing view BView* scrollView = view->FindView("BorderView"); ASSERT(scrollView != NULL); if (scrollView == NULL) return; BTextView* textView = dynamic_cast<BTextView*>( scrollView->FindView("WidgetTextView")); ASSERT(textView != NULL); if (textView == NULL) return; BColumn* column = view->ColumnFor(fAttrHash); ASSERT(column != NULL); if (column == NULL) return; if (saveChanges && fText->CommitEditedText(textView)) { // we have an actual change, re-sort view->CheckPoseSortOrder(pose, poseIndex); } // make text widget visible again SetVisible(true); view->Invalidate(ColumnRect(poseLoc, column, view)); // force immediate redraw so TEView disappears scrollView->RemoveSelf(); delete scrollView; ASSERT(view->Window() != NULL); view->Window()->UpdateIfNeeded(); view->MakeFocus(); SetActive(false); } void BTextWidget::CheckAndUpdate(BPoint loc, const BColumn* column, BPoseView* view, bool visible) { BRect oldRect; if (view->ViewMode() != kListMode) oldRect = CalcOldRect(loc, column, view); if (fText->CheckAttributeChanged() && fText->CheckViewChanged(view) && visible) { BRect invalRect(ColumnRect(loc, column, view)); if (view->ViewMode() != kListMode) invalRect = invalRect | oldRect; view->Invalidate(invalRect); } } void BTextWidget::SelectAll(BPoseView* view) { BTextView* text = dynamic_cast<BTextView*>( view->FindView("WidgetTextView")); if (text != NULL) text->SelectAll(); } void BTextWidget::Draw(BRect eraseRect, BRect textRect, float, BPoseView* view, BView* drawView, bool selected, uint32 clipboardMode, BPoint offset, bool direct) { textRect.OffsetBy(offset); if (direct) { // draw selection box if selected if (selected) { drawView->SetDrawingMode(B_OP_COPY); // eraseRect.OffsetBy(offset); // drawView->FillRect(eraseRect, B_SOLID_LOW); drawView->FillRect(textRect, B_SOLID_LOW); } else drawView->SetDrawingMode(B_OP_OVER); // set high color rgb_color highColor; if (view->IsDesktopWindow()) { if (selected) highColor = ui_color(B_DOCUMENT_BACKGROUND_COLOR); else highColor = view->DeskTextColor(); } else if (selected && view->Window()->IsActive()) { highColor = ui_color(B_DOCUMENT_BACKGROUND_COLOR); } else highColor = kBlack; if (clipboardMode == kMoveSelectionTo && !selected) { drawView->SetDrawingMode(B_OP_ALPHA); drawView->SetBlendingMode(B_PIXEL_ALPHA, B_ALPHA_OVERLAY); highColor.alpha = 64; } drawView->SetHighColor(highColor); } BPoint loc; loc.y = textRect.bottom - view->FontInfo().descent; loc.x = textRect.left + 1; const char* fittingText = fText->FittingText(view); // TODO: Comparing view and drawView here to avoid rendering // the text outline when producing a drag bitmap. The check is // not fully correct, since an offscreen view is also used in some // other rare cases (something to do with columns). But for now, this // fixes the broken drag bitmaps when dragging icons from the Desktop. if (!selected && view == drawView && view->WidgetTextOutline()) { // draw a halo around the text by using the "false bold" // feature for text rendering. Either black or white is used for // the glow (whatever acts as contrast) with a some alpha value, drawView->SetDrawingMode(B_OP_ALPHA); drawView->SetBlendingMode(B_CONSTANT_ALPHA, B_ALPHA_OVERLAY); BFont font; drawView->GetFont(&font); rgb_color textColor = ui_color(B_PANEL_TEXT_COLOR); if (view->IsDesktopWindow()) textColor = view->DeskTextColor(); if (textColor.Brightness() < 100) { // dark text on light outline rgb_color glowColor = ui_color(B_SHINE_COLOR); font.SetFalseBoldWidth(2.0); drawView->SetFont(&font, B_FONT_FALSE_BOLD_WIDTH); glowColor.alpha = 30; drawView->SetHighColor(glowColor); drawView->DrawString(fittingText, loc); font.SetFalseBoldWidth(1.0); drawView->SetFont(&font, B_FONT_FALSE_BOLD_WIDTH); glowColor.alpha = 65; drawView->SetHighColor(glowColor); drawView->DrawString(fittingText, loc); font.SetFalseBoldWidth(0.0); drawView->SetFont(&font, B_FONT_FALSE_BOLD_WIDTH); } else { // light text on dark outline rgb_color outlineColor = kBlack; font.SetFalseBoldWidth(1.0); drawView->SetFont(&font, B_FONT_FALSE_BOLD_WIDTH); outlineColor.alpha = 30; drawView->SetHighColor(outlineColor); drawView->DrawString(fittingText, loc); font.SetFalseBoldWidth(0.0); drawView->SetFont(&font, B_FONT_FALSE_BOLD_WIDTH); outlineColor.alpha = 200; drawView->SetHighColor(outlineColor); drawView->DrawString(fittingText, loc + BPoint(1, 1)); } drawView->SetDrawingMode(B_OP_OVER); drawView->SetHighColor(textColor); } drawView->DrawString(fittingText, loc); if (fSymLink && (fAttrHash == view->FirstColumn()->AttrHash())) { // TODO: // this should be exported to the WidgetAttribute class, probably // by having a per widget kind style if (direct) { rgb_color underlineColor = drawView->HighColor(); underlineColor.alpha = 180; drawView->SetHighColor(underlineColor); drawView->SetDrawingMode(B_OP_ALPHA); drawView->SetBlendingMode(B_CONSTANT_ALPHA, B_ALPHA_OVERLAY); } textRect.right = textRect.left + fText->Width(view); // only underline text part drawView->StrokeLine(textRect.LeftBottom(), textRect.RightBottom(), B_MIXED_COLORS); } }
25.833333
81
0.715352
chamalwr
14bd38aa46db310723c4430892aeb68defd03777
4,619
cpp
C++
tests/Switch.Core.UnitTests/Switch/System/Globalization/NumberStylesTest.cpp
victor-timoshin/Switch
8e8e687a8bdc4f79d482680da3968e9b3e464b8b
[ "MIT" ]
4
2020-02-11T13:22:58.000Z
2022-02-24T00:37:43.000Z
tests/Switch.Core.UnitTests/Switch/System/Globalization/NumberStylesTest.cpp
sgf/Switch
8e8e687a8bdc4f79d482680da3968e9b3e464b8b
[ "MIT" ]
null
null
null
tests/Switch.Core.UnitTests/Switch/System/Globalization/NumberStylesTest.cpp
sgf/Switch
8e8e687a8bdc4f79d482680da3968e9b3e464b8b
[ "MIT" ]
2
2020-02-01T02:19:01.000Z
2021-12-30T06:44:00.000Z
#include <Switch/System/Enum.hpp> #include <Switch/System/Globalization/NumberStyles.hpp> #include <Switch/System/String.hpp> #include <gtest/gtest.h> using namespace System; namespace SwitchUnitTests { TEST(NumberStylesTest, None) { ASSERT_EQ(0, (int32)System::Globalization::NumberStyles::None); ASSERT_EQ("None", Enum<System::Globalization::NumberStyles>(System::Globalization::NumberStyles::None).ToString()); } TEST(NumberStylesTest, AllowLeadingWhite) { ASSERT_EQ(1, (int32)System::Globalization::NumberStyles::AllowLeadingWhite); ASSERT_EQ("AllowLeadingWhite", Enum<System::Globalization::NumberStyles>(System::Globalization::NumberStyles::AllowLeadingWhite).ToString()); } TEST(NumberStylesTest, AllowTrailingWhite) { ASSERT_EQ(2, (int32)System::Globalization::NumberStyles::AllowTrailingWhite); ASSERT_EQ("AllowTrailingWhite", Enum<System::Globalization::NumberStyles>(System::Globalization::NumberStyles::AllowTrailingWhite).ToString()); } TEST(NumberStylesTest, AllowLeadingSign) { ASSERT_EQ(4, (int32)System::Globalization::NumberStyles::AllowLeadingSign); ASSERT_EQ("AllowLeadingSign", Enum<System::Globalization::NumberStyles>(System::Globalization::NumberStyles::AllowLeadingSign).ToString()); } TEST(NumberStylesTest, Integer) { ASSERT_EQ(7, (int32)System::Globalization::NumberStyles::Integer); ASSERT_EQ("Integer", Enum<System::Globalization::NumberStyles>(System::Globalization::NumberStyles::Integer).ToString()); } TEST(NumberStylesTest, AllowTrailingSign) { ASSERT_EQ(8, (int32)System::Globalization::NumberStyles::AllowTrailingSign); ASSERT_EQ("AllowTrailingSign", Enum<System::Globalization::NumberStyles>(System::Globalization::NumberStyles::AllowTrailingSign).ToString()); } TEST(NumberStylesTest, AllowParentheses) { ASSERT_EQ(16, (int32)System::Globalization::NumberStyles::AllowParentheses); ASSERT_EQ("AllowParentheses", Enum<System::Globalization::NumberStyles>(System::Globalization::NumberStyles::AllowParentheses).ToString()); } TEST(NumberStylesTest, AllowDecimalPoint) { ASSERT_EQ(32, (int32)System::Globalization::NumberStyles::AllowDecimalPoint); ASSERT_EQ("AllowDecimalPoint", Enum<System::Globalization::NumberStyles>(System::Globalization::NumberStyles::AllowDecimalPoint).ToString()); } TEST(NumberStylesTest, AllowThousands) { ASSERT_EQ(64, (int32)System::Globalization::NumberStyles::AllowThousands); ASSERT_EQ("AllowThousands", Enum<System::Globalization::NumberStyles>(System::Globalization::NumberStyles::AllowThousands).ToString()); } TEST(NumberStylesTest, Number) { ASSERT_EQ(111, (int32)System::Globalization::NumberStyles::Number); ASSERT_EQ("Number", Enum<System::Globalization::NumberStyles>(System::Globalization::NumberStyles::Number).ToString()); } TEST(NumberStylesTest, AllowExponent) { ASSERT_EQ(128, (int32)System::Globalization::NumberStyles::AllowExponent); ASSERT_EQ("AllowExponent", Enum<System::Globalization::NumberStyles>(System::Globalization::NumberStyles::AllowExponent).ToString()); } TEST(NumberStylesTest, Float) { ASSERT_EQ(167, (int32)System::Globalization::NumberStyles::Float); ASSERT_EQ("Float", Enum<System::Globalization::NumberStyles>(System::Globalization::NumberStyles::Float).ToString()); } TEST(NumberStylesTest, AllowCurrencySymbol) { ASSERT_EQ(256, (int32)System::Globalization::NumberStyles::AllowCurrencySymbol); ASSERT_EQ("AllowCurrencySymbol", Enum<System::Globalization::NumberStyles>(System::Globalization::NumberStyles::AllowCurrencySymbol).ToString()); } TEST(NumberStylesTest, Currency) { ASSERT_EQ(383, (int32)System::Globalization::NumberStyles::Currency); ASSERT_EQ("Currency", Enum<System::Globalization::NumberStyles>(System::Globalization::NumberStyles::Currency).ToString()); } TEST(NumberStylesTest, Any) { ASSERT_EQ(511, (int32)System::Globalization::NumberStyles::Any); ASSERT_EQ("Any", Enum<System::Globalization::NumberStyles>(System::Globalization::NumberStyles::Any).ToString()); } TEST(NumberStylesTest, AllowHexSpecifier) { ASSERT_EQ(512, (int32)System::Globalization::NumberStyles::AllowHexSpecifier); ASSERT_EQ("AllowHexSpecifier", Enum<System::Globalization::NumberStyles>(System::Globalization::NumberStyles::AllowHexSpecifier).ToString()); } TEST(NumberStylesTest, HexNumber) { ASSERT_EQ(515, (int32)System::Globalization::NumberStyles::HexNumber); ASSERT_EQ("HexNumber", Enum<System::Globalization::NumberStyles>(System::Globalization::NumberStyles::HexNumber).ToString()); } }
49.138298
149
0.766183
victor-timoshin
14bdbaec9186b1069678dce4f7cc0bcfa3b1260d
852
cpp
C++
Modules/QtWidgetsExt/src/QmitkBasePropertyView.cpp
zhaomengxiao/MITK
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2022-03-03T12:03:32.000Z
2022-03-03T12:03:32.000Z
Modules/QtWidgetsExt/src/QmitkBasePropertyView.cpp
zhaomengxiao/MITK
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2021-12-22T10:19:02.000Z
2021-12-22T10:19:02.000Z
Modules/QtWidgetsExt/src/QmitkBasePropertyView.cpp
zhaomengxiao/MITK_lancet
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2020-11-27T09:41:18.000Z
2020-11-27T09:41:18.000Z
/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkBasePropertyView.h" QmitkBasePropertyView::QmitkBasePropertyView(const mitk::BaseProperty *property, QWidget *parent) : QLabel(parent), PropertyView(property) { PropertyChanged(); } QmitkBasePropertyView::~QmitkBasePropertyView() { } void QmitkBasePropertyView::PropertyChanged() { if (m_Property) setText(m_Property->GetValueAsString().c_str()); } void QmitkBasePropertyView::PropertyRemoved() { m_Property = nullptr; setText("n/a"); }
24.342857
97
0.625587
zhaomengxiao
14c2de86fec62941afab35329bd60105459b236d
5,674
cpp
C++
Source/Tools/MeshGenerators.cpp
enci/Osmium
48d8b78ed31ffa532e05dc8c06b644f6f5791814
[ "MIT" ]
6
2017-05-28T18:26:35.000Z
2019-12-09T15:28:37.000Z
Source/Tools/MeshGenerators.cpp
enci/Osmium
48d8b78ed31ffa532e05dc8c06b644f6f5791814
[ "MIT" ]
null
null
null
Source/Tools/MeshGenerators.cpp
enci/Osmium
48d8b78ed31ffa532e05dc8c06b644f6f5791814
[ "MIT" ]
5
2018-03-09T09:02:57.000Z
2020-07-31T23:34:26.000Z
#include <Tools/MeshGenerators.h> #include <cstdint> #include <unordered_map> #include <vector> using namespace Osm; using namespace std; ////////////////////////////////////////////////////////////////////////////////////////// /// Generate Icosphere /// Based on code Written by Frank McCoy for Seed of Andromeda /// https://pastebin.com/aFdWi5eQ ////////////////////////////////////////////////////////////////////////////////////////// const static float GOLDEN_RATIO = 1.61803398875f; const static int NUM_ICOSOHEDRON_VERTICES = 12; const static Vector3 ICOSOHEDRON_VERTICES[12] = { Vector3(-1.0f, GOLDEN_RATIO, 0.0f), Vector3(1.0f, GOLDEN_RATIO, 0.0f), Vector3(-1.0f, -GOLDEN_RATIO, 0.0f), Vector3(1.0f, -GOLDEN_RATIO, 0.0f), Vector3(0.0f, -1.0f, GOLDEN_RATIO), Vector3(0.0f, 1.0f, GOLDEN_RATIO), Vector3(0.0f, -1.0, -GOLDEN_RATIO), Vector3(0.0f, 1.0f, -GOLDEN_RATIO), Vector3(GOLDEN_RATIO, 0.0f, -1.0f), Vector3(GOLDEN_RATIO, 0.0f, 1.0f), Vector3(-GOLDEN_RATIO, 0.0f, -1.0f), Vector3(-GOLDEN_RATIO, 0.0, 1.0f) }; const static int NUM_ICOSOHEDRON_INDICES = 60; const static uint32_t ICOSOHEDRON_INDICES[60] = { 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11, 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8, 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9, 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1 }; // Hash functions for the unordered map class Vec3KeyFuncs { public: ushort operator()(const Vector3& k) const { return (ushort)(std::hash<float>()(k.x) ^ std::hash<float>()(k.y) ^ std::hash<float>()(k.z)); } bool operator() (const Vector3& a, const Vector3& b)const { return a.x == b.x && a.y == b.y && a.z == b.z; } }; inline Vector3 findMidpoint(Vector3 vertex1, Vector3 vertex2) { Vector3 mid = Lerp(vertex1, vertex2, 0.5f); mid.Normalize(); return mid; } void Osm::GenerateIcosphere( float size, int resolution, vector<VertexFormat>& vertices, vector<ushort>& indices) { if (resolution < 0) return; std::vector<ushort> newIndices; newIndices.reserve(256); std::unordered_map<Vector3, ushort, Vec3KeyFuncs, Vec3KeyFuncs> vertexLookup; indices.resize(NUM_ICOSOHEDRON_INDICES); for (ushort i = 0; i < NUM_ICOSOHEDRON_INDICES; i++) { indices[i] = ICOSOHEDRON_INDICES[i]; } vertices.resize(NUM_ICOSOHEDRON_VERTICES); for (ushort i = 0; i < NUM_ICOSOHEDRON_VERTICES; i++) { Vector3 pos = ICOSOHEDRON_VERTICES[i]; pos.Normalize(); vertices[i].Position = pos; vertices[i].Normal = pos; vertexLookup[pos] = i; } for (ushort i = 0; i < (ushort)resolution; i++) { for (ushort j = 0; j < (ushort)indices.size(); j += 3) { /* j mp12 mp13 j+1 mp23 j+2 */ // Defined in counter clockwise order Vector3 vertex1 = vertices[indices[j + 0]].Position; Vector3 vertex2 = vertices[indices[j + 1]].Position; Vector3 vertex3 = vertices[indices[j + 2]].Position; Vector3 midPoint12 = findMidpoint(vertex1, vertex2); Vector3 midPoint23 = findMidpoint(vertex2, vertex3); Vector3 midPoint13 = findMidpoint(vertex1, vertex3); ushort mp12Index; ushort mp23Index; ushort mp13Index; auto iter = vertexLookup.find(midPoint12); if (iter != vertexLookup.end()) { // It is in the map mp12Index = iter->second; } else { // Not in the map mp12Index = (ushort)vertices.size(); vertices.push_back({ midPoint12, midPoint12, Vector2(0,0) }); vertexLookup[midPoint12] = mp12Index; } iter = vertexLookup.find(midPoint23); if (iter != vertexLookup.end()) { // It is in the map mp23Index = iter->second; } else { // Not in the map mp23Index = (ushort)vertices.size(); vertices.push_back({ midPoint23, midPoint23, Vector2(0,0) }); vertexLookup[midPoint23] = mp23Index; } iter = vertexLookup.find(midPoint13); if (iter != vertexLookup.end()) { // It is in the map mp13Index = iter->second; } else { // Not in the map mp13Index = (ushort)vertices.size(); vertices.push_back({ midPoint13, midPoint13, Vector2(0,0) }); vertexLookup[midPoint13] = mp13Index; } newIndices.push_back(indices[j]); newIndices.push_back(mp12Index); newIndices.push_back(mp13Index); newIndices.push_back(mp12Index); newIndices.push_back(indices[j + 1]); newIndices.push_back(mp23Index); newIndices.push_back(mp13Index); newIndices.push_back(mp23Index); newIndices.push_back(indices[j + 2]); newIndices.push_back(mp12Index); newIndices.push_back(mp23Index); newIndices.push_back(mp13Index); } indices.swap(newIndices); newIndices.clear(); } for (ushort i = 0; i < (ushort)vertices.size(); i++) { vertices[i].Position *= size; } } void Osm::GeneratePlane( float size, int resolution, vector<VertexFormat>& vertices, vector<ushort>& indices) { if (resolution < 1) return; vertices.resize((resolution + 1) * (resolution + 1)); indices.reserve(resolution * resolution * 6); float d = size / resolution; float y = -size * 0.5f; for(int i = 0; i <= resolution; i++) { float x = -size * 0.5f; for(int j = 0; j <= resolution; j++) { vertices[i * (resolution + 1) + j].Position = Vector3(x, 0.0f, y); vertices[i * (resolution + 1) + j].Normal = Vector3(0.0f, 1.0f, 0.0f); x += d; } y += d; } for (int i = 0; i < resolution; i++) { for (int j = 0; j < resolution; j++) { ushort idx = i * (resolution + 1) + j; indices.push_back(idx); indices.push_back(idx + 2 + resolution); indices.push_back(idx + 1); indices.push_back(idx); indices.push_back(idx + 1 + resolution); indices.push_back(idx + 2 + resolution); } } }
22.515873
95
0.626013
enci
14c3c1b6adbfada42dd9740c7832189b98e97fd6
2,256
cpp
C++
samples/snippets/cpp/VS_Snippets_CLR_System/System.Decimal.ConvFrom.Others/CPP/cfromdouble.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
421
2018-04-01T01:57:50.000Z
2022-03-28T15:24:42.000Z
samples/snippets/cpp/VS_Snippets_CLR_System/System.Decimal.ConvFrom.Others/CPP/cfromdouble.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
5,797
2018-04-02T21:12:23.000Z
2022-03-31T23:54:38.000Z
samples/snippets/cpp/VS_Snippets_CLR_System/System.Decimal.ConvFrom.Others/CPP/cfromdouble.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
1,482
2018-03-31T11:26:20.000Z
2022-03-30T22:36:45.000Z
//<Snippet2> // Example of the explicit conversion from double to Decimal. using namespace System; #define formatter "{0,25:E16}{1,33}" // Get the exception type name; remove the namespace prefix. String^ GetExceptionType( Exception^ ex ) { String^ exceptionType = ex->GetType()->ToString(); return exceptionType->Substring( exceptionType->LastIndexOf( '.' ) + 1 ); } // Convert the double argument; catch exceptions that are thrown. void DecimalFromDouble( double argument ) { Object^ decValue; // Convert the double argument to a Decimal value. try { decValue = (Decimal)argument; } catch ( Exception^ ex ) { decValue = GetExceptionType( ex ); } Console::WriteLine( formatter, argument, decValue ); } int main() { Console::WriteLine( "This example of the explicit conversion from double " "to Decimal \ngenerates the following output.\n" ); Console::WriteLine( formatter, "double argument", "Decimal value" ); Console::WriteLine( formatter, "---------------", "-------------" ); // Convert double values and display the results. DecimalFromDouble( 1.234567890123E-30 ); DecimalFromDouble( 1.2345678901234E-25 ); DecimalFromDouble( 1.23456789012345E-20 ); DecimalFromDouble( 1.234567890123456E-10 ); DecimalFromDouble( 1.2345678901234567 ); DecimalFromDouble( 1.23456789012345678E+12 ); DecimalFromDouble( 1.234567890123456789E+28 ); DecimalFromDouble( 1.234567890123456789E+30 ); } /* This example of the explicit conversion from double to Decimal generates the following output. double argument Decimal value --------------- ------------- 1.2345678901230000E-030 0 1.2345678901233999E-025 0.0000000000000000000000001235 1.2345678901234499E-020 0.0000000000000000000123456789 1.2345678901234560E-010 0.000000000123456789012346 1.2345678901234567E+000 1.23456789012346 1.2345678901234568E+012 1234567890123.46 1.2345678901234568E+028 12345678901234600000000000000 1.2345678901234569E+030 OverflowException */ //</Snippet2>
33.671642
78
0.651152
hamarb123
14c67907fc2d20f44c22ce15f73b414fa95903bb
1,609
hpp
C++
src/state_machine/BeagleBone_black/src/sensors/fake_batteries.hpp
Hyp-ed/testing-proto-2018
d283de2e6e1257de6fa7718ee67240e2179c73b6
[ "Apache-2.0" ]
null
null
null
src/state_machine/BeagleBone_black/src/sensors/fake_batteries.hpp
Hyp-ed/testing-proto-2018
d283de2e6e1257de6fa7718ee67240e2179c73b6
[ "Apache-2.0" ]
1
2018-11-12T17:59:29.000Z
2018-11-12T18:37:08.000Z
src/state_machine/BeagleBone_black/src/sensors/fake_batteries.hpp
Hyp-ed/testing-proto-2018
d283de2e6e1257de6fa7718ee67240e2179c73b6
[ "Apache-2.0" ]
null
null
null
/* * Author: Jack Horsburgh * Organisation: HYPED * Date: 17/07/18 * Description: Main class for fake IMUs. * * Copyright 2018 HYPED * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef BEAGLEBONE_BLACK_SENSORS_FAKE_BATTERIES_HPP_ #define BEAGLEBONE_BLACK_SENSORS_FAKE_BATTERIES_HPP_ #include <string> #include <vector> #include "utils/concurrent/thread.hpp" #include "data/data.hpp" #include "sensors/interface.hpp" namespace hyped { using utils::Logger; using data::Data; namespace sensors { class FakeBatteries : public BMSInterface { public: FakeBatteries(Logger& log, bool is_high_voltage, bool is_nominal); void getData(Battery* battery) override; bool isOnline() override; private: void init(); bool checkTime(); Data& data_; bool is_started_; bool is_high_voltage_; uint64_t ref_time_; uint16_t voltage_; int16_t current_; int8_t temperature_; uint8_t charge_; uint16_t low_voltage_cell_; uint16_t high_voltage_cell_; }; }} // namespace hyped::sensors #endif // BEAGLEBONE_BLACK_SENSORS_FAKE_BATTERIES_HPP_
25.140625
78
0.742076
Hyp-ed
14c84882dc4e333afeb410379a70f4b7f15fccf0
13,556
cpp
C++
NE/HyperNEAT/NEAT/src/NEAT_CoEvoGeneticGeneration.cpp
LMBernardo/HyperNEAT
8ebee6fda17dcf20dd0c6c081dc8681557c1faad
[ "BSD-3-Clause" ]
null
null
null
NE/HyperNEAT/NEAT/src/NEAT_CoEvoGeneticGeneration.cpp
LMBernardo/HyperNEAT
8ebee6fda17dcf20dd0c6c081dc8681557c1faad
[ "BSD-3-Clause" ]
null
null
null
NE/HyperNEAT/NEAT/src/NEAT_CoEvoGeneticGeneration.cpp
LMBernardo/HyperNEAT
8ebee6fda17dcf20dd0c6c081dc8681557c1faad
[ "BSD-3-Clause" ]
null
null
null
#include "NEAT_Defines.h" #include "NEAT_CoEvoGeneticGeneration.h" #include "NEAT_GeneticLinkGene.h" #include "NEAT_Globals.h" #ifdef EPLEX_INTERNAL #define DEBUG_REMOVE_STALE_TESTS (1) //Because you need to recompute fitnesses every time a test is deleted, delete a bunch at a time. #define DEBUG_MIN_TEST_ALERT_SIZE (15) #define DEBUG_MIN_TEST_SIZE (10) namespace NEAT { CoEvoGeneticGeneration::CoEvoGeneticGeneration(int _generationNumber,boost::shared_ptr<CoEvoExperiment> _experiment) : GeneticGeneration(_generationNumber), experiment(_experiment) {} CoEvoGeneticGeneration::CoEvoGeneticGeneration( CoEvoGeneticGeneration *previousGeneration, const vector<boost::shared_ptr<GeneticIndividual> > &newIndividuals, int _generationNumber, const vector<boost::shared_ptr<GeneticIndividual> > &newTests, const vector< vector<bool> > &newTestResults, const vector< vector<double> > &newTestFitnesses, boost::shared_ptr<CoEvoExperiment> _experiment ) : GeneticGeneration(previousGeneration,newIndividuals,_generationNumber), tests(newTests), testResults(newTestResults), testFitnesses(newTestFitnesses), experiment(_experiment) {} boost::shared_ptr<GeneticGeneration> CoEvoGeneticGeneration::produceNextGeneration( const vector<boost::shared_ptr<GeneticIndividual> > &newIndividuals, int _generationNumber ) { return boost::shared_ptr<GeneticGeneration>( new CoEvoGeneticGeneration( this, newIndividuals, _generationNumber, tests, testResults, testFitnesses, experiment ) ); } CoEvoGeneticGeneration::CoEvoGeneticGeneration( TiXmlElement *generationElement, boost::shared_ptr<CoEvoExperiment> _experiment ) : GeneticGeneration(generationElement), experiment(_experiment) { TiXmlElement *individualElement = generationElement->FirstChildElement("Test"); while ( individualElement!=NULL ) { tests.push_back(boost::shared_ptr<GeneticIndividual>(new GeneticIndividual(individualElement))); individualElement = individualElement->NextSiblingElement("Test"); } } CoEvoGeneticGeneration::CoEvoGeneticGeneration(const CoEvoGeneticGeneration &other) : GeneticGeneration(other), tests(other.tests), testResults(other.testResults), testFitnesses(other.testFitnesses), experiment(other.experiment) { } CoEvoGeneticGeneration& CoEvoGeneticGeneration::operator=(const CoEvoGeneticGeneration &other) { GeneticGeneration::operator=(other); tests = other.tests; testResults = other.testResults; testFitnesses = other.testFitnesses; experiment = other.experiment; return *this; } CoEvoGeneticGeneration::~CoEvoGeneticGeneration() {} boost::shared_ptr<GeneticIndividual> CoEvoGeneticGeneration::addTest(boost::shared_ptr<GeneticIndividual> test) { boost::shared_ptr<GeneticIndividual> newTest( new GeneticIndividual(*(test.get())) ); tests.push_back(newTest); vector<bool> tmpResults; vector<double> tmpFitnesses; for (int a=0;a<(int)tests.size();a++) { tmpResults.push_back(false); tmpFitnesses.push_back(0.0); } for (int a=0;a<(int)testResults.size();a++) { testResults[a].push_back(false); testFitnesses[a].push_back(0.0); } testResults.push_back(tmpResults); testFitnesses.push_back(tmpFitnesses); return newTest; } void CoEvoGeneticGeneration::removeTest(int index) { /* vector<boost::shared_ptr<GeneticIndividual> >::iterator loc = find(tests.begin(),tests.end(),test); if (loc != tests.end()) { tests.erase(loc); } */ cout << "Removing test\n"; for (int a=0;a<getTestCount();a++) { if (a==index) { continue; } testResults[a].erase(testResults[a].begin()+index); testFitnesses[a].erase(testFitnesses[a].begin()+index); } tests.erase(tests.begin()+index); testResults.erase(testResults.begin()+index); testFitnesses.erase(testFitnesses.begin()+index); //recompute the new fitnesses for (int a=0;a<getTestCount();a++) { boost::shared_ptr<GeneticIndividual> testA = getTest(a); testA->setFitness(0); for (int b=0;b<getTestCount();b++) { if (b==a) continue; //boost::shared_ptr<GeneticIndividual> testB = getTest(b); testA->reward(testFitnesses[a][b]); } } } double CoEvoGeneticGeneration::getAverageTestFitness() { double avgFitness=0.0; for (int a=0;a<getTestCount();a++) { avgFitness += getTest(a)->getFitness(); } avgFitness /= getTestCount(); return avgFitness; } double CoEvoGeneticGeneration::getMaxTestFitness() { double maxFitness=0.0; for (int a=0;a<getTestCount();a++) { maxFitness = max(maxFitness,getTest(a)->getFitness()); } return maxFitness; } void CoEvoGeneticGeneration::replaceLowestTest(boost::shared_ptr<GeneticIndividual> indToReplace) { if (getTestCount()==0) { throw CREATE_LOCATEDEXCEPTION_INFO("Tried to replace a test when there weren't any tests!"); } int lowestFitnessIndex=0; double lowestFitness=getTest(0)->getFitness(); for (int a=1;a<getTestCount();a++) { if (lowestFitness > getTest(a)->getFitness()) { lowestFitness = getTest(a)->getFitness(); lowestFitnessIndex = a; } } tests.erase(tests.begin()+lowestFitnessIndex); addTest(indToReplace); } void CoEvoGeneticGeneration::dump(TiXmlElement *generationElement,bool includeGenes) { GeneticGeneration::dump(generationElement,includeGenes); for (int a=0;a<(int)tests.size();a++) { TiXmlElement *individualElement = new TiXmlElement("Test"); tests[a]->dump(individualElement,includeGenes); generationElement->LinkEndChild(individualElement); } } void CoEvoGeneticGeneration::dumpBest(TiXmlElement *generationElement,bool includeGenes) { GeneticGeneration::dumpBest(generationElement,includeGenes); } void CoEvoGeneticGeneration::cleanup() { GeneticGeneration::cleanup(); //Blow away all the tests. tests.clear(); } void CoEvoGeneticGeneration::bootstrap() { //Play all the tests against each other. cout << "Bootstrapping tests..."; for (int a=0;a<getTestCount();a++) { boost::shared_ptr<GeneticIndividual> testA = getTest(a); testA->setFitness(0.0); } for (int a=0;a<getTestCount();a++) { boost::shared_ptr<GeneticIndividual> testA = getTest(a); for (int b=(a+1);b<getTestCount();b++) { boost::shared_ptr<GeneticIndividual> testB = getTest(b); pair<double,double> rewards = experiment->playGame( testA, testB ); testA->reward(rewards.first); testB->reward(rewards.second); if (rewards.first > rewards.second) { /* NOTE: I'm not really interested in tieing. If two players tie, I don't really care what happens. Basically, try to make games which do not have ties in fitness very often! */ testResults[a][b] = true; testResults[b][a] = false; } else { testResults[a][b] = false; testResults[b][a] = true; } testFitnesses[a][b] = rewards.first; testFitnesses[b][a] = rewards.second; } cout << "Test fitness: " << getTest(a)->getFitness() << endl; } } void CoEvoGeneticGeneration::updateTests() { //Here's my first shot at co-evolution //First, get the max fitness of the test cases. double maxFitness = getMaxTestFitness(); for (int a=0;a<(int)individuals.size();a++) { boost::shared_ptr<GeneticIndividual> individual = individuals[a]; //If the individual is better than the best test case if (individual->getFitness() >= maxFitness) { cout << "***Adding Test*** Individual: " << individual->getFitness() << " Max: " << maxFitness << endl; //Add the individual boost::shared_ptr<GeneticIndividual> test = addTest(individual); /* NOTE: Because of this next line, new tests need to be added to the end of the vector! */ int newTestIndex = getTestCount()-1; //Play games so that it's still true that all tests have played each other //This is important because it's needed for the other tests' fitnesses to be accurate. test->setFitness(0); for (int a=0;a<getTestCount();a++) { boost::shared_ptr<GeneticIndividual> testA = getTest(a); if (test != getTest(a)) { //cout << "*"; pair<double,double> rewards = experiment->playGame( test, testA ); test->reward(rewards.first); testA->reward(rewards.second); /* NOTE: I'm not really interested in tieing. If two players tie, I don't really care what happens. Basically, try to make games which do not have ties in fitness very often! */ if (rewards.first > rewards.second) { testResults[a][newTestIndex] = true; testResults[newTestIndex][a] = false; } else { testResults[a][newTestIndex] = false; testResults[newTestIndex][a] = true; } testFitnesses[a][newTestIndex] = rewards.first; testFitnesses[newTestIndex][a] = rewards.second; } } //Only allow adding one individual every generation break; } } #if DEBUG_REMOVE_STALE_TESTS if ( (getTestCount()>=DEBUG_MIN_TEST_ALERT_SIZE) ) { for (int a=0;a<getTestCount()&&(getTestCount()>DEBUG_MIN_TEST_SIZE);a++) { for (int b=0;b<getTestCount();b++) { if (a==b) continue; if (getTestResult(a,b)) { //a has won a match, we can't delete a (yet). break; } else if (b+1==getTestCount()) { //a has never won a match, delete a removeTest(a); a--; } } } for (int a=0;a<getTestCount()&&(getTestCount()>DEBUG_MIN_TEST_SIZE);a++) { for (int b=a+1;b<getTestCount();b++) { if (a==b) continue; bool doRemoveTest=true; for (int t=0;t<getTestCount();t++) { if (t==a || t==b) continue; if (getTestResult(t,a) != getTestResult(t,b)) { doRemoveTest=false; break; } } if (doRemoveTest) { //test results are the same, delete removeTest(a); a--; break; } } } while ( (getTestCount()>DEBUG_MIN_TEST_SIZE) ) { //we still need to remove some tests, remove older tests first removeTest(0); } } #endif } bool CoEvoGeneticGeneration::getTestResult(int t1,int t2) { return testResults[t1][t2]; } } #endif
29.793407
120
0.516377
LMBernardo
14c863c239a2f8f64e038c34f13b47fc25fc2656
15,202
cc
C++
src/ui/scenic/lib/flatland/renderer/vk_renderer.cc
billchen1977/fuchsia
d443f9c7b03ad317d1700c2c9457be8ed1147b86
[ "BSD-2-Clause" ]
null
null
null
src/ui/scenic/lib/flatland/renderer/vk_renderer.cc
billchen1977/fuchsia
d443f9c7b03ad317d1700c2c9457be8ed1147b86
[ "BSD-2-Clause" ]
null
null
null
src/ui/scenic/lib/flatland/renderer/vk_renderer.cc
billchen1977/fuchsia
d443f9c7b03ad317d1700c2c9457be8ed1147b86
[ "BSD-2-Clause" ]
null
null
null
// Copyright 2020 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/ui/scenic/lib/flatland/renderer/vk_renderer.h" #include <zircon/pixelformat.h> #include "src/ui/lib/escher/escher.h" #include "src/ui/lib/escher/impl/vulkan_utils.h" #include "src/ui/lib/escher/renderer/render_funcs.h" #include "src/ui/lib/escher/util/image_utils.h" #include "src/ui/lib/escher/util/trace_macros.h" namespace escher { namespace { TexturePtr CreateDepthTexture(Escher* escher, const ImagePtr& output_image) { TexturePtr depth_buffer; RenderFuncs::ObtainDepthTexture( escher, output_image->use_protected_memory(), output_image->info(), escher->device()->caps().GetMatchingDepthStencilFormat().value, depth_buffer); return depth_buffer; } } // anonymous namespace } // namespace escher namespace flatland { VkRenderer::VkRenderer(escher::EscherWeakPtr escher) : escher_(std::move(escher)), compositor_(escher::RectangleCompositor(escher_.get())) {} VkRenderer::~VkRenderer() { auto vk_device = escher_->vk_device(); auto vk_loader = escher_->device()->dispatch_loader(); for (auto& [_, vk_collection] : vk_collection_map_) { vk_device.destroyBufferCollectionFUCHSIA(vk_collection, nullptr, vk_loader); } } bool VkRenderer::ImportBufferCollection( sysmem_util::GlobalBufferCollectionId collection_id, fuchsia::sysmem::Allocator_Sync* sysmem_allocator, fidl::InterfaceHandle<fuchsia::sysmem::BufferCollectionToken> token) { return RegisterCollection(collection_id, sysmem_allocator, std::move(token), escher::RectangleCompositor::kTextureUsageFlags); } void VkRenderer::ReleaseBufferCollection(sysmem_util::GlobalBufferCollectionId collection_id) { // Multiple threads may be attempting to read/write from the various maps, // lock this function here. // TODO(fxbug.dev/44335): Convert this to a lock-free structure. std::unique_lock<std::mutex> lock(lock_); auto collection_itr = collection_map_.find(collection_id); // If the collection is not in the map, then there's nothing to do. if (collection_itr == collection_map_.end()) { return; } // Erase the sysmem collection from the map. collection_map_.erase(collection_id); // Grab the vulkan collection and DCHECK since there should always be // a vk collection to correspond with the buffer collection. We then // delete it using the vk device. auto vk_itr = vk_collection_map_.find(collection_id); FX_DCHECK(vk_itr != vk_collection_map_.end()); auto vk_device = escher_->vk_device(); auto vk_loader = escher_->device()->dispatch_loader(); vk_device.destroyBufferCollectionFUCHSIA(vk_itr->second, nullptr, vk_loader); vk_collection_map_.erase(collection_id); } bool VkRenderer::RegisterCollection( sysmem_util::GlobalBufferCollectionId collection_id, fuchsia::sysmem::Allocator_Sync* sysmem_allocator, fidl::InterfaceHandle<fuchsia::sysmem::BufferCollectionToken> token, vk::ImageUsageFlags usage) { TRACE_DURATION("flatland", "VkRenderer::RegisterCollection"); auto vk_device = escher_->vk_device(); auto vk_loader = escher_->device()->dispatch_loader(); FX_DCHECK(vk_device); FX_DCHECK(collection_id != sysmem_util::kInvalidId); // Check for a null token here before we try to duplicate it to get the // vulkan token. if (!token.is_valid()) { FX_LOGS(ERROR) << "Token is invalid."; return sysmem_util::kInvalidId; } auto vk_constraints = escher::RectangleCompositor::GetDefaultImageConstraints(vk::Format::eB8G8R8A8Unorm, usage); // Create a duped vulkan token. fuchsia::sysmem::BufferCollectionTokenSyncPtr vulkan_token; { // TODO(fxbug.dev/51213): See if this can become asynchronous. fuchsia::sysmem::BufferCollectionTokenSyncPtr sync_token = token.BindSync(); zx_status_t status = sync_token->Duplicate(std::numeric_limits<uint32_t>::max(), vulkan_token.NewRequest()); FX_DCHECK(status == ZX_OK); // Reassign the channel to the non-sync interface handle. token = sync_token.Unbind(); } // Create the sysmem buffer collection. We do this before creating the vulkan collection below, // since New() checks if the incoming token is of the wrong type/malicious. auto result = BufferCollectionInfo::New(sysmem_allocator, std::move(token)); if (result.is_error()) { FX_LOGS(ERROR) << "Unable to register collection."; return false; } // Create the vk_collection and set its constraints. vk::BufferCollectionFUCHSIA vk_collection; { vk::BufferCollectionCreateInfoFUCHSIA buffer_collection_create_info; buffer_collection_create_info.collectionToken = vulkan_token.Unbind().TakeChannel().release(); vk_collection = escher::ESCHER_CHECKED_VK_RESULT( vk_device.createBufferCollectionFUCHSIA(buffer_collection_create_info, nullptr, vk_loader)); auto vk_result = vk_device.setBufferCollectionConstraintsFUCHSIA(vk_collection, vk_constraints, vk_loader); FX_DCHECK(vk_result == vk::Result::eSuccess); } // Multiple threads may be attempting to read/write from |collection_map_| so we // lock this function here. // TODO(fxbug.dev/44335): Convert this to a lock-free structure. std::unique_lock<std::mutex> lock(lock_); collection_map_[collection_id] = std::move(result.value()); vk_collection_map_[collection_id] = std::move(vk_collection); return true; } bool VkRenderer::ImportImage(const ImageMetadata& metadata) { std::unique_lock<std::mutex> lock(lock_); const auto& collection_itr = collection_map_.find(metadata.collection_id); if (collection_itr == collection_map_.end()) { FX_LOGS(ERROR) << "Collection with id " << metadata.collection_id << " does not exist."; return false; } auto& collection = collection_itr->second; if (!collection.BuffersAreAllocated()) { FX_LOGS(ERROR) << "Buffers for collection " << metadata.collection_id << " have not been allocated."; return false; } const auto& sysmem_info = collection.GetSysmemInfo(); const auto vmo_count = sysmem_info.buffer_count; auto image_constraints = sysmem_info.settings.image_format_constraints; if (texture_map_.find(metadata.identifier) != texture_map_.end() || render_target_map_.find(metadata.identifier) != render_target_map_.end()) { FX_LOGS(ERROR) << "An image with this identifier already exists."; return false; } if (metadata.vmo_index >= vmo_count) { FX_LOGS(ERROR) << "CreateImage failed, vmo_index " << metadata.vmo_index << " must be less than vmo_count " << vmo_count; return false; } if (metadata.width < image_constraints.min_coded_width || metadata.width > image_constraints.max_coded_width) { FX_LOGS(ERROR) << "CreateImage failed, width " << metadata.width << " is not within valid range [" << image_constraints.min_coded_width << "," << image_constraints.max_coded_width << "]"; return false; } if (metadata.height < image_constraints.min_coded_height || metadata.height > image_constraints.max_coded_height) { FX_LOGS(ERROR) << "CreateImage failed, height " << metadata.height << " is not within valid range [" << image_constraints.min_coded_height << "," << image_constraints.max_coded_height << "]"; return false; } if (metadata.is_render_target) { auto image = ExtractImage(metadata, escher::RectangleCompositor::kRenderTargetUsageFlags); image->set_swapchain_layout(vk::ImageLayout::eColorAttachmentOptimal); render_target_map_[metadata.identifier] = image; depth_target_map_[metadata.identifier] = escher::CreateDepthTexture(escher_.get(), image); pending_render_targets_.insert(metadata.identifier); } else { texture_map_[metadata.identifier] = ExtractTexture(metadata); pending_textures_.insert(metadata.identifier); } return true; } void VkRenderer::ReleaseImage(sysmem_util::GlobalImageId image_id) { std::unique_lock<std::mutex> lock(lock_); if (texture_map_.find(image_id) != texture_map_.end()) { texture_map_.erase(image_id); } else if (render_target_map_.find(image_id) != render_target_map_.end()) { render_target_map_.erase(image_id); depth_target_map_.erase(image_id); } } escher::ImagePtr VkRenderer::ExtractImage(ImageMetadata metadata, vk::ImageUsageFlags usage) { TRACE_DURATION("flatland", "VkRenderer::ExtractImage"); auto vk_device = escher_->vk_device(); auto vk_loader = escher_->device()->dispatch_loader(); GpuImageInfo gpu_info; auto collection_itr = collection_map_.find(metadata.collection_id); FX_DCHECK(collection_itr != collection_map_.end()); auto& collection = collection_itr->second; auto vk_itr = vk_collection_map_.find(metadata.collection_id); FX_DCHECK(vk_itr != vk_collection_map_.end()); auto vk_collection = vk_itr->second; // Create the GPU info from the server side collection. gpu_info = GpuImageInfo::New(vk_device, vk_loader, collection.GetSysmemInfo(), vk_collection, metadata.vmo_index); FX_DCHECK(gpu_info.GetGpuMem()); // Create and return an escher image. auto image_ptr = escher::image_utils::NewImage( vk_device, gpu_info.NewVkImageCreateInfo(metadata.width, metadata.height, usage), gpu_info.GetGpuMem(), escher_->resource_recycler()); FX_DCHECK(image_ptr); return image_ptr; } bool VkRenderer::RegisterRenderTargetCollection( sysmem_util::GlobalBufferCollectionId collection_id, fuchsia::sysmem::Allocator_Sync* sysmem_allocator, fidl::InterfaceHandle<fuchsia::sysmem::BufferCollectionToken> token) { return RegisterCollection(collection_id, sysmem_allocator, std::move(token), escher::RectangleCompositor::kRenderTargetUsageFlags); } void VkRenderer::DeregisterRenderTargetCollection( sysmem_util::GlobalBufferCollectionId collection_id) { ReleaseBufferCollection(collection_id); } escher::TexturePtr VkRenderer::ExtractTexture(ImageMetadata metadata) { auto image = ExtractImage(metadata, escher::RectangleCompositor::kTextureUsageFlags); auto texture = escher::Texture::New(escher_->resource_recycler(), image, vk::Filter::eNearest); FX_DCHECK(texture); return texture; } void VkRenderer::Render(const ImageMetadata& render_target, const std::vector<Rectangle2D>& rectangles, const std::vector<ImageMetadata>& images, const std::vector<zx::event>& release_fences) { TRACE_DURATION("flatland", "VkRenderer::Render"); // Escher's frame class acts as a command buffer manager that we use to create a // command buffer and submit it to the device queue once we are done. auto frame = escher_->NewFrame("flatland::VkRenderer", ++frame_number_); auto command_buffer = frame->cmds(); // Copy over the texture and render target data to local containers that do not need // to be accessed via a lock. We're just doing a shallow copy via the copy assignment // operator since the texture and render target data is just referenced through pointers. // We manually unlock the lock after copying over the data. std::unique_lock<std::mutex> lock(lock_); const auto local_texture_map = texture_map_; const auto local_render_target_map = render_target_map_; const auto local_depth_target_map = depth_target_map_; // After moving, the original containers are emptied. const auto local_pending_textures = std::move(pending_textures_); const auto local_pending_render_targets = std::move(pending_render_targets_); lock.unlock(); // Transition pending images to their correct layout // TODO(fxbug.dev/52196): The way we are transitioning image layouts here and in the rest of // scenic is incorrect for "external" images. It just happens to be working by luck on our current // hardware. for (auto texture_id : local_pending_textures) { FX_DCHECK(local_texture_map.find(texture_id) != local_texture_map.end()); const auto texture = local_texture_map.at(texture_id); command_buffer->impl()->TransitionImageLayout(texture->image(), vk::ImageLayout::eUndefined, vk::ImageLayout::eShaderReadOnlyOptimal); } for (auto target_id : local_pending_render_targets) { FX_DCHECK(local_render_target_map.find(target_id) != local_render_target_map.end()); const auto target = local_render_target_map.at(target_id); command_buffer->impl()->TransitionImageLayout(target, vk::ImageLayout::eUndefined, vk::ImageLayout::eColorAttachmentOptimal); } std::vector<const escher::TexturePtr> textures; std::vector<escher::RectangleCompositor::ColorData> color_data; for (const auto& image : images) { // Pass the texture into the above vector to keep it alive outside of this loop. FX_DCHECK(local_texture_map.find(image.identifier) != local_texture_map.end()); textures.emplace_back(local_texture_map.at(image.identifier)); // TODO(fxbug.dev/52632): We are hardcoding the multiply color and transparency flag for now. // Eventually these will be exposed in the API. color_data.emplace_back( escher::RectangleCompositor::ColorData(glm::vec4(1.f), image.has_transparency)); } // Grab the output image and use it to generate a depth texture. The depth texture needs to // be the same width and height as the output image. FX_DCHECK(local_render_target_map.find(render_target.identifier) != local_render_target_map.end()); const auto output_image = local_render_target_map.at(render_target.identifier); const auto depth_texture = local_depth_target_map.at(render_target.identifier); // Now the compositor can finally draw. compositor_.DrawBatch(command_buffer, rectangles, textures, color_data, output_image, depth_texture); // Create vk::semaphores from the zx::events. std::vector<escher::SemaphorePtr> semaphores; for (auto& fence_original : release_fences) { // Since the original fences are passed in by const reference, we // duplicate them here so that the duped fences can be moved into // the create info struct of the semaphore. zx::event fence_copy; auto status = fence_original.duplicate(ZX_RIGHT_SAME_RIGHTS, &fence_copy); FX_DCHECK(status == ZX_OK); auto sema = escher::Semaphore::New(escher_->vk_device()); vk::ImportSemaphoreZirconHandleInfoFUCHSIA info; info.semaphore = sema->vk_semaphore(); info.handle = fence_copy.release(); info.handleType = vk::ExternalSemaphoreHandleTypeFlagBits::eTempZirconEventFUCHSIA; auto result = escher_->vk_device().importSemaphoreZirconHandleFUCHSIA( info, escher_->device()->dispatch_loader()); FX_DCHECK(result == vk::Result::eSuccess); semaphores.emplace_back(sema); } // Submit the commands and wait for them to finish. frame->EndFrame(semaphores, nullptr); } void VkRenderer::WaitIdle() { escher_->vk_device().waitIdle(); } } // namespace flatland
43.065156
100
0.732667
billchen1977
14c950d0b8ce318cf5c83c58303cff74797b0106
40,974
cpp
C++
src/ossim/support_data/ossimRpfFrame.cpp
rkanavath/ossim18
d2e8204d11559a6a868755a490f2ec155407fa96
[ "MIT" ]
null
null
null
src/ossim/support_data/ossimRpfFrame.cpp
rkanavath/ossim18
d2e8204d11559a6a868755a490f2ec155407fa96
[ "MIT" ]
null
null
null
src/ossim/support_data/ossimRpfFrame.cpp
rkanavath/ossim18
d2e8204d11559a6a868755a490f2ec155407fa96
[ "MIT" ]
1
2019-09-25T00:43:35.000Z
2019-09-25T00:43:35.000Z
//******************************************************************* // // License: MIT // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // // Description: This class give the capability to access tiles from an // rpf file. // //******************************************************************** // $Id: ossimRpfFrame.cpp 23664 2015-12-14 14:17:27Z dburken $ #include <ossim/support_data/ossimRpfFrame.h> #include <ossim/support_data/ossimRpfHeader.h> #include <ossim/support_data/ossimRpfAttributes.h> #include <ossim/support_data/ossimRpfAttributeOffsetRecord.h> #include <ossim/support_data/ossimRpfAttributeSectionSubheader.h> #include <ossim/support_data/ossimRpfCoverageSection.h> #include <ossim/support_data/ossimRpfImageDescriptionSubheader.h> #include <ossim/support_data/ossimRpfImageDisplayParameterSubheader.h> #include <ossim/support_data/ossimRpfMaskSubheader.h> #include <ossim/support_data/ossimRpfCompressionSection.h> #include <ossim/support_data/ossimRpfColorGrayscaleSubheader.h> #include <ossim/support_data/ossimRpfColorGrayscaleOffsetRecord.h> #include <ossim/support_data/ossimRpfColorConverterSubsection.h> #include <ossim/support_data/ossimRpfColorConverterTable.h> #include <ossim/support_data/ossimRpfColorGrayscaleTable.h> #include <ossim/support_data/ossimRpfLocationSection.h> #include <ossim/support_data/ossimRpfColorConverterSubsection.h> #include <ossim/support_data/ossimRpfConstants.h> #include <ossim/support_data/ossimRpfReplaceUpdateRecord.h> #include <ossim/support_data/ossimRpfReplaceUpdateSectionSubheader.h> #include <ossim/support_data/ossimNitfFile.h> #include <ossim/support_data/ossimNitfFileHeader.h> #include <ossim/support_data/ossimNitfTagInformation.h> #include <ossim/base/ossimEndian.h> #include <ossim/base/ossimErrorCodes.h> #include <ossim/base/ossimTrace.h> #include <istream> #include <ostream> static const ossimTrace traceDebug("ossimRpfFrame:debug"); std::ostream& operator <<(std::ostream& out, const ossimRpfFrame& data) { data.print(out); return out; } ossimRpfFrame::ossimRpfFrame() :theHeader(0), theFilename(""), theCoverage(0), theAttributes(0), theImageDescriptionSubheader(0), theMaskSubheader(0), theImageDisplayParameterSubheader(0), theCompressionSection(0), theColorGrayscaleSubheader(0), theColorConverterSubsection(0), theNitfFile(0), theSubframeMaskTable(0), theSubframeTransparencyMaskTable(0), theReplaceUpdateTable(0) { } ossimRpfFrame::~ossimRpfFrame() { deleteAll(); } std::ostream& ossimRpfFrame::print(std::ostream& out, const std::string& prefix) const { if (traceDebug()) { out << "begin_rpf_frame_print:\n"; } if(theHeader) { theHeader->print(out, prefix); } out << prefix << "filename: " << theFilename << "\n"; if ( theReplaceUpdateTable.valid() ) { theReplaceUpdateTable->print(out, prefix); } if (traceDebug()) { if(theCoverage) { theCoverage->print(out, prefix); } } if(theAttributes) { theAttributes->print(out, prefix); } if (traceDebug()) { if(theImageDescriptionSubheader) { theImageDescriptionSubheader->print(out, prefix); } if(theMaskSubheader) { out << *theMaskSubheader << endl; } if(theImageDisplayParameterSubheader) { out << *theImageDisplayParameterSubheader << endl; } if(theCompressionSection) { out << *theCompressionSection << endl; } if(theColorGrayscaleSubheader) { out << *theColorGrayscaleSubheader << endl; } if(theColorConverterSubsection) { out << *theColorConverterSubsection << endl; } copy(theColorGrayscaleTable.begin(), theColorGrayscaleTable.end(), ostream_iterator<ossimRpfColorGrayscaleTable>(out, "\n")); if(theImageDescriptionSubheader&& !(theImageDescriptionSubheader->isSubframeMaskTableOffsetNull())) { out << "Subframe Mask Table:" << endl; unsigned long spectralIndex; unsigned long rowIndex; unsigned long colIndex; // first loop through the Mask table and allocate while we do it for(spectralIndex = 0; spectralIndex < theImageDescriptionSubheader->getNumberOfSpectralGroups(); ++spectralIndex) { for(rowIndex = 0; rowIndex < theImageDescriptionSubheader->getNumberOfSubframesVertical(); ++rowIndex) { for(colIndex = 0; colIndex < theImageDescriptionSubheader->getNumberOfSubframesHorizontal(); ++colIndex) { if( theSubframeMaskTable[spectralIndex][rowIndex][colIndex] == OSSIM_RPF_ULONG_NULL) { out << "NULL "; } else { out << theSubframeMaskTable[spectralIndex][rowIndex][colIndex] << " "; } } out << endl; } } } if(theImageDescriptionSubheader&& !(theImageDescriptionSubheader->isTransparencyMaskTableOffsetNull())) { out << "Transparency Mask Table:" << endl; unsigned long spectralIndex; unsigned long rowIndex; unsigned long colIndex; // first loop through the Mask table and allocate while we do it for(spectralIndex = 0; spectralIndex < theImageDescriptionSubheader->getNumberOfSpectralGroups(); ++spectralIndex) { for(rowIndex = 0; rowIndex < theImageDescriptionSubheader->getNumberOfSubframesVertical(); ++rowIndex) { for(colIndex = 0; colIndex < theImageDescriptionSubheader->getNumberOfSubframesHorizontal(); ++colIndex) { if( theSubframeTransparencyMaskTable[spectralIndex][rowIndex][colIndex] == OSSIM_RPF_ULONG_NULL) { out << "NULL "; } else { out << theSubframeTransparencyMaskTable[spectralIndex][rowIndex][colIndex] << " "; } } } } } out << "end_rpf_frame_print:\n"; } // matches: if (traceDebug()) out << std::endl; return out; } ossimErrorCode ossimRpfFrame::parseFile(const ossimFilename& filename, bool minimalParse) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimRpfFrame::parseFile: entered......" << std::endl; } ossimErrorCode result = ossimErrorCodes::OSSIM_OK; //Make sure any fileds have beend cleared clearFields(); // Make sure all data is deleted. The initialize call the // populate methods. These methods will re-allocate the information deleteAll(); theNitfFile = new ossimNitfFile; theNitfFile->parseFile(filename); const ossimRefPtr<ossimNitfFileHeader> nitfFileHeader = theNitfFile.valid() ? theNitfFile->getHeader() : 0; if(!nitfFileHeader) { theNitfFile = 0; return ossimErrorCodes::OSSIM_ERROR; } ossimNitfTagInformation info; nitfFileHeader->getTag(info, "RPFHDR"); theFilename = filename; if(info.getTagName() == "RPFHDR") { ifstream in(filename.c_str(), ios::in|ios::binary); // set the get pointer for the stream to the start // of the Rpf header data in.seekg(info.getTagDataOffset(), ios::beg); if(theHeader) delete theHeader; theHeader = new ossimRpfHeader; // if(theHeader->parseStream(in) != ossimErrorCodes::OSSIM_OK) theHeader->parseStream(in); if ( in.fail() ) { deleteAll(); return ossimErrorCodes::OSSIM_ERROR; } else // if(!in.fail()&&theHeader) { result = populateAttributeSection(in); // This is needed for ossim-rpf --list-frames so NOT put in full parse section. if(!in.fail()&&(result == ossimErrorCodes::OSSIM_OK)) { result = populateReplaceUpdateTable(in); } if ( minimalParse == false ) { if(!in.fail()&&(result == ossimErrorCodes::OSSIM_OK)) { populateCompressionSection(in); } if(!in.fail()&&(result == ossimErrorCodes::OSSIM_OK)) { result = populateCoverageSection(in); } if(!in.fail()&&(result == ossimErrorCodes::OSSIM_OK)) { result = populateImageSection(in); } if(!in.fail()&&(result == ossimErrorCodes::OSSIM_OK)) { result = populateColorGrayscaleSection(in); } if(!in.fail()&&(result == ossimErrorCodes::OSSIM_OK)) { result = populateMasks(in); } } } } else { return ossimErrorCodes::OSSIM_ERROR; } return ossimErrorCodes::OSSIM_OK; } bool ossimRpfFrame::hasSubframeMaskTable()const { if(theImageDescriptionSubheader) { return (!theImageDescriptionSubheader->isSubframeMaskTableOffsetNull()); } return false; } bool ossimRpfFrame::fillSubFrameBuffer(ossim_uint8* buffer, ossim_uint32 /* spectralGroup */, ossim_uint32 row, ossim_uint32 col)const { if(theImageDescriptionSubheader && theImageDisplayParameterSubheader&& theHeader&& (col < theImageDescriptionSubheader->getNumberOfSubframesHorizontal()) && (row < theImageDescriptionSubheader->getNumberOfSubframesVertical())) { ossimRpfComponentLocationRecord info; if(!theHeader->getLocationSection()->getComponent(OSSIM_RPF_SPATIAL_DATA_SUBSECTION, info)) { return false; } ossim_uint32 offset = info.m_componentLocation; ossim_uint32 bytesPerSubframe = 0; // note that the code length is bit encoded so we must devide by 8 // in order to get the byte offset instead of the bit offset. We // then add that to the start of the spatial data section which is // the current value of offset. bytesPerSubframe = (theImageDisplayParameterSubheader->getNumberOfImageRows()* theImageDisplayParameterSubheader->getNumberOfImageCodesPerRow()* theImageDisplayParameterSubheader->getImageCodeLength())/8; if(hasSubframeMaskTable()) { // check to see if the offset is NULL. If it is // then just return false to let the caller know that the // buffer did not exist. if(theSubframeMaskTable[0][row][col] != OSSIM_RPF_ULONG_NULL) { offset += theSubframeMaskTable[0][row][col]; } else { return false; } } else { ossim_uint32 bytes = bytesPerSubframe*(row*theImageDescriptionSubheader->getNumberOfSubframesHorizontal()+ col); offset += bytes; } // now since we have the adjustment and we got to this point then // we can read in the data into the destination buffer. ifstream in(theFilename.c_str(), ios::in|ios::binary); if(!in.fail()) { in.seekg(offset, ios::beg); in.read((char*)buffer, bytesPerSubframe); if(in.fail()) { return false; } } else { return false; } } else { // this is if it was not within the rows and cols of // the subframe or if the image description header didn't exist return false; } return true; } void ossimRpfFrame::clearFields() { theFilename = ""; } void ossimRpfFrame::deleteAll() { if(theHeader) { delete theHeader; theHeader = 0; } if(theAttributes) { delete theAttributes; theAttributes = 0; } if(theCoverage) { delete theCoverage; theCoverage = 0; } if(theImageDescriptionSubheader) { delete theImageDescriptionSubheader; theImageDescriptionSubheader = 0; } if(theMaskSubheader) { delete theMaskSubheader; theMaskSubheader = 0; } if(theImageDisplayParameterSubheader) { delete theImageDisplayParameterSubheader; theImageDisplayParameterSubheader = 0; } if(theCompressionSection) { delete theCompressionSection; theCompressionSection = 0; } if(theColorGrayscaleSubheader) { delete theColorGrayscaleSubheader; theColorGrayscaleSubheader = 0; } if(theColorConverterSubsection) { delete theColorConverterSubsection; theColorConverterSubsection = 0; } if (theNitfFile.valid()) { theNitfFile = 0; } } ossimErrorCode ossimRpfFrame::populateCoverageSection(istream& in) { if(theCoverage) delete theCoverage; theCoverage = 0; if(theHeader) { theCoverage = theHeader->getNewCoverageSection(in); } return ossimErrorCodes::OSSIM_OK; } ossimErrorCode ossimRpfFrame::populateCompressionSection(istream& in) { if(theCompressionSection) delete theCompressionSection; theCompressionSection = 0; if(theHeader) { theCompressionSection = theHeader->getNewCompressionSection(in); } return ossimErrorCodes::OSSIM_OK; } ossimErrorCode ossimRpfFrame::populateColorGrayscaleSection(istream& in) { ossimErrorCode resultError = ossimErrorCodes::OSSIM_OK; if(theColorGrayscaleSubheader) delete theColorGrayscaleSubheader; theColorGrayscaleSubheader = 0; if(theHeader) { theColorGrayscaleSubheader = theHeader->getNewColorGrayscaleSubheader(in); if(theColorGrayscaleSubheader) { const ossimRpfLocationSection* location = theHeader->getLocationSection(); if(location) { ossimRpfComponentLocationRecord component; if(location->getComponent(OSSIM_RPF_COLOR_CONVERTER_SUBSECTION, component)) { in.seekg(component.m_componentLocation,ios::beg); if(theColorConverterSubsection) delete theColorConverterSubsection; theColorConverterSubsection = new ossimRpfColorConverterSubsection; theColorConverterSubsection->setNumberOfColorConverterOffsetRecords( theColorGrayscaleSubheader->getNumberOfColorConverterOffsetRecords()); resultError = theColorConverterSubsection->parseStream(in, theHeader->getByteOrder()); } if(location->getComponent(OSSIM_RPF_COLORMAP_SUBSECTION, component)) { in.seekg(component.m_componentLocation, ios::beg); theColorGrayscaleTable.clear(); theColorGrayscaleTable.resize(theColorGrayscaleSubheader->getNumberOfColorGreyscaleOffsetRecords()); // we will ignore the offset table offset which is a 4 byte value // and ignore the offset record length which is a 2 byte value. // This is suppose to put us at the beginning of the // [color/grayscale offset record]. The total number of // these offset records is found in the [color/grayscale section // subheader. in.ignore(6); for(ossim_uint32 index = 0; index < theColorGrayscaleSubheader->getNumberOfColorGreyscaleOffsetRecords(); ++index) { ossimRpfColorGrayscaleOffsetRecord grayscaleOffsetRecord; if(grayscaleOffsetRecord.parseStream(in, theHeader->getByteOrder()) == ossimErrorCodes::OSSIM_OK) { ossim_uint32 rememberLocation = in.tellg(); in.seekg(grayscaleOffsetRecord.getColorGrayscaleTableOffset()+component.m_componentLocation, ios::beg); theColorGrayscaleTable[index].setTableData(grayscaleOffsetRecord.getColorGrayscaleTableId(), grayscaleOffsetRecord.getNumberOfColorGrayscaleRecords()); theColorGrayscaleTable[index].parseStream(in, theHeader->getByteOrder()); in.seekg(rememberLocation, ios::beg); } else { return ossimErrorCodes::OSSIM_ERROR; } } } } } } return resultError; } ossimErrorCode ossimRpfFrame::populateImageSection(istream& in) { ossimErrorCode result = ossimErrorCodes::OSSIM_OK; if(theImageDescriptionSubheader) delete theImageDescriptionSubheader; theImageDescriptionSubheader = 0; if(theHeader&&in) { // get the subheader information. theImageDescriptionSubheader = theHeader->getNewImageDescriptionSubheader(in); // need to do something with the table before going to the display. if(theImageDescriptionSubheader &&(!theImageDescriptionSubheader->isSubframeMaskTableOffsetNull())) { if(theMaskSubheader) delete theMaskSubheader; // need to get the mask subheader theMaskSubheader = new ossimRpfMaskSubheader; // seek to the start of the subheader in.seekg(theImageDescriptionSubheader->getEndOffset() + theImageDescriptionSubheader->getSubframeMaskTableOffset(), ios::beg); // get the information result = theMaskSubheader->parseStream(in, theHeader->getByteOrder()); } if(theImageDisplayParameterSubheader) delete theImageDisplayParameterSubheader; // Get the display parameter header theImageDisplayParameterSubheader = theHeader->getNewImageDisplayParameterSubheader(in); } return result; } ossimErrorCode ossimRpfFrame::populateAttributeSection(istream& in) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimRpfFrame::populateAttributeSection: entered ..." << std::endl; } ossimRpfAttributeSectionSubheader* temp = 0; const ossimRpfLocationSection* location = theHeader->getLocationSection(); if(location) { ossimRpfComponentLocationRecord component; if(location->getComponent(OSSIM_RPF_ATTRIBUTE_SECTION_SUBHEADER, component)) { temp = new ossimRpfAttributeSectionSubheader; in.seekg(component.m_componentLocation, std::ios::beg); if(temp->parseStream(in, theHeader->getByteOrder()) != ossimErrorCodes::OSSIM_OK) { delete temp; temp =0; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimRpfFrame::populateAttributeSection: leaving 1 ..." << std::endl; } return ossimErrorCodes::OSSIM_ERROR; } } } if(!in.fail()&&temp) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG: Has attribute section" << std::endl; } if(theAttributes) delete theAttributes; theAttributes = new ossimRpfAttributes; ossimRpfAttributeOffsetRecord record; ossim_uint64 locationAttributeSubsection = in.tellg(); ossim_uint64 absoluteAddresToTable = locationAttributeSubsection + temp->getAttributeOffsetTableOffset(); ossimEndian anEndian; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG: Number of attributes = " << temp->getNumberOfAttributeOffsetRecords() << std::endl; } in.seekg(absoluteAddresToTable, ios::beg); for(ossim_uint32 index = 0; index < temp->getNumberOfAttributeOffsetRecords(); index++) { if((!in.fail())&& record.parseStream(in, theHeader->getByteOrder()) == ossimErrorCodes::OSSIM_OK) { // make sure we save the current position. The attribute // parser in the switch/case will change the location and // we must come back to the start of the next record. ossim_uint64 currentLocation = in.tellg(); // go to the location of the start of the attribute. in.seekg(locationAttributeSubsection + record.getAttributeRecordOffset(), ios::beg); if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG: Parsing attribute number " << index << " with id = " << record.getAttributeId() << std::endl; } // allocate some temporary space for the string type // attributes. char tempString[50]; if(!theAttributes->getAttributeFlag(record.getAttributeId())) { theAttributes->setAttributeFlag(record.getAttributeId(), true); switch(record.getAttributeId()) { case 1: { in.read((char*)tempString, 8); tempString[8] = '\0'; theAttributes->theCurrencyDate = tempString; break; } case 2: { in.read((char*)tempString, 8); tempString[8] = '\0'; theAttributes->theProductionDate = tempString; break; } case 3: { in.read((char*)tempString, 8); tempString[8] = '\0'; theAttributes->theSignificantDate = tempString; break; } case 4: { in.read((char*)tempString, 10); theAttributes->theChartSeriesCode = ossimString(tempString, &tempString[10]); in.read((char*)tempString, 8); theAttributes->theMapDesignationCode = ossimString(tempString, &tempString[8]); in.read((char*)tempString, 4); theAttributes->theOldHorDatum = ossimString(tempString, &tempString[4]); in.read((char*)tempString, 7); theAttributes->theEdition = ossimString(tempString, &tempString[7]); break; } case 5: { in.read((char*)tempString, 2); theAttributes->theProjectionCode = ossimString(tempString, &tempString[2]); theAttributes->theProjectionCode = theAttributes->theProjectionCode.upcase(); if((theAttributes->theProjectionCode == "AC") || (theAttributes->theProjectionCode == "LE") || (theAttributes->theProjectionCode == "PG")) { in.read((char*)&(theAttributes->theProjectionA), 4); in.read((char*)&(theAttributes->theProjectionB), 4); in.read((char*)&(theAttributes->theProjectionC), 4); in.read((char*)&(theAttributes->theProjectionD), 4); } else if((theAttributes->theProjectionCode == "RB") || (theAttributes->theProjectionCode == "OC") || (theAttributes->theProjectionCode == "TC")) { in.read((char*)&(theAttributes->theProjectionA), 4); in.read((char*)&(theAttributes->theProjectionB), 4); in.read((char*)&(theAttributes->theProjectionC), 4); } else if((theAttributes->theProjectionCode == "AL") || (theAttributes->theProjectionCode == "MC") || (theAttributes->theProjectionCode == "OD") || (theAttributes->theProjectionCode == "PH")) { in.read((char*)&(theAttributes->theProjectionA), 4); in.read((char*)&(theAttributes->theProjectionB), 4); } else if((theAttributes->theProjectionCode == "UT")) { in.read((char*)&(theAttributes->theProjectionA), 4); } if(anEndian.getSystemEndianType() != theHeader->getByteOrder()) { anEndian.swap(theAttributes->theProjectionA); anEndian.swap(theAttributes->theProjectionB); anEndian.swap(theAttributes->theProjectionC); anEndian.swap(theAttributes->theProjectionD); } break; } case 6: { in.read((char*)tempString, 4); theAttributes->theVertDatumCode = ossimString(tempString, &tempString[4]); break; } case 7: { in.read((char*)tempString, 4); theAttributes->theHorDatumCode = ossimString(tempString, &tempString[4]); break; } case 8: { in.read((char*)&(theAttributes->theVertAbsAccuracy), 4); in.read((char*)&(theAttributes->theVertAbsUnits), 2); if(anEndian.getSystemEndianType() != theHeader->getByteOrder()) { anEndian.swap(theAttributes->theVertAbsAccuracy); anEndian.swap(theAttributes->theVertAbsUnits); } break; } case 9: { in.read((char*)&(theAttributes->theHorAbsAccuracy), 4); in.read((char*)&(theAttributes->theHorAbsUnits), 2); if(anEndian.getSystemEndianType() != theHeader->getByteOrder()) { anEndian.swap(theAttributes->theHorAbsAccuracy); anEndian.swap(theAttributes->theHorAbsUnits); } break; } case 10: { in.read((char*)&(theAttributes->theVertRelAccuracy), 4); in.read((char*)&(theAttributes->theVertRelUnits), 2); if(anEndian.getSystemEndianType() != theHeader->getByteOrder()) { anEndian.swap(theAttributes->theVertRelAccuracy); anEndian.swap(theAttributes->theVertRelUnits); } break; } case 11: { in.read((char*)&(theAttributes->theHorRelAccuracy), 4); in.read((char*)&(theAttributes->theHorRelUnits), 2); if(anEndian.getSystemEndianType() != theHeader->getByteOrder()) { anEndian.swap(theAttributes->theHorRelAccuracy); anEndian.swap(theAttributes->theHorRelUnits); } break; } case 12: { in.read((char*)tempString, 3); theAttributes->ellipsoidCode = ossimString(tempString, &tempString[3]); break; } case 13: { in.read((char*)tempString, 4); theAttributes->theSoundingDatumCode = ossimString(tempString, &tempString[4]); break; } case 14: { in.read((char*)&(theAttributes->theNavSystemCode), 2); if(anEndian.getSystemEndianType() != theHeader->getByteOrder()) { anEndian.swap(theAttributes->theNavSystemCode); } break; } case 15: { in.read((char*)tempString, 2); theAttributes->theGridCode = ossimString(tempString, &tempString[2]); break; } case 16: { in.read((char*)&(theAttributes->theEeasterlyMagChange), 4); in.read((char*)&(theAttributes->theEasterlyMagChangeUnits), 2); if(anEndian.getSystemEndianType() != theHeader->getByteOrder()) { anEndian.swap(theAttributes->theEeasterlyMagChange); anEndian.swap(theAttributes->theEasterlyMagChangeUnits); } break; } case 17: { in.read((char*)&(theAttributes->theWesterlyMagChange), 4); in.read((char*)&(theAttributes->theWesterlyMagChangeUnits), 2); if(anEndian.getSystemEndianType() != theHeader->getByteOrder()) { anEndian.swap(theAttributes->theWesterlyMagChange); anEndian.swap(theAttributes->theWesterlyMagChangeUnits); } break; } case 18: { in.read((char*)&(theAttributes->theMagAngle), 4); in.read((char*)&(theAttributes->theMagAngleUnits), 2); if(anEndian.getSystemEndianType() != theHeader->getByteOrder()) { anEndian.swap(theAttributes->theMagAngle); anEndian.swap(theAttributes->theMagAngleUnits); } break; } case 19: { in.read((char*)&(theAttributes->theGridConver), 4); in.read((char*)&(theAttributes->theGridConverUnits), 2); if(anEndian.getSystemEndianType() != theHeader->getByteOrder()) { anEndian.swap(theAttributes->theGridConver); anEndian.swap(theAttributes->theGridConverUnits); } break; } case 20: { in.read((char*)&(theAttributes->theHighElevation), 8); in.read((char*)&(theAttributes->theHighElevationUnits), 2); in.read((char*)&(theAttributes->theHighLat), 8); in.read((char*)&(theAttributes->theHighLon), 8); if(anEndian.getSystemEndianType() != theHeader->getByteOrder()) { anEndian.swap(theAttributes->theHighElevation); anEndian.swap(theAttributes->theHighElevationUnits); anEndian.swap(theAttributes->theHighLat); anEndian.swap(theAttributes->theHighLon); } break; } case 21: { in.read((char*)tempString, 12); theAttributes->theLegendFileName = ossimString(tempString, &tempString[12]); break; } case 22: { in.read((char*)tempString, 12); tempString[12] = '\0'; theAttributes->theDataSource = tempString; in.read((char*)&(theAttributes->theGsd), 4); if(anEndian.getSystemEndianType() != theHeader->getByteOrder()) { anEndian.swap(theAttributes->theGsd); } break; } case 23: { in.read((char*)&(theAttributes->theDataLevel), 2); if(anEndian.getSystemEndianType() != theHeader->getByteOrder()) { anEndian.swap(theAttributes->theDataLevel); } break; } } } in.seekg(currentLocation, ios::beg); } else { delete temp; temp = 0; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimRpfFrame::populateAttributeSection: leaving 2 ..." << std::endl; } return ossimErrorCodes::OSSIM_ERROR; } } } if(temp) delete temp; temp = 0; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimRpfFrame::populateAttributeSection: leaving OK ..." << std::endl; } return ossimErrorCodes::OSSIM_OK; } ossimErrorCode ossimRpfFrame::populateMasks(istream& in) { theSubframeMaskTable.clear(); theSubframeTransparencyMaskTable.clear(); if(!in) { return ossimErrorCodes::OSSIM_ERROR; } if(theImageDescriptionSubheader) { const ossimRpfLocationSection* location = theHeader->getLocationSection(); if(location) { ossimRpfComponentLocationRecord component; if(location->getComponent(OSSIM_RPF_MASK_SUBSECTION, component)) { // now allocate the space we need and then reader the table in theSubframeMaskTable.resize(theImageDescriptionSubheader->getNumberOfSpectralGroups()); theSubframeTransparencyMaskTable.resize(theImageDescriptionSubheader->getNumberOfSpectralGroups()); ossim_uint32 spectralIndex; ossim_uint32 rowIndex; ossim_uint32 colIndex; if(!theImageDescriptionSubheader->isSubframeMaskTableOffsetNull()) { // move get to the first byte of the Mask table. This is the offset from the // start of the maskSubsection. in.seekg(component.m_componentLocation + theImageDescriptionSubheader->getSubframeMaskTableOffset(), ios::beg); // first loop through the Mask table and allocate while we do it for(spectralIndex = 0; spectralIndex < theImageDescriptionSubheader->getNumberOfSpectralGroups(); ++spectralIndex) { // reserve space for the number of rows theSubframeMaskTable[spectralIndex].resize(theImageDescriptionSubheader->getNumberOfSubframesVertical()); for(rowIndex = 0; rowIndex < theImageDescriptionSubheader->getNumberOfSubframesVertical(); ++rowIndex) { // allocate the columns theSubframeMaskTable[spectralIndex][rowIndex].resize(theImageDescriptionSubheader->getNumberOfSubframesHorizontal()); for(colIndex = 0; colIndex < theImageDescriptionSubheader->getNumberOfSubframesHorizontal(); ++colIndex) { ossim_uint32 value; in.read((char*)&value, 4); ossimEndian anEndian; if(anEndian.getSystemEndianType() != theHeader->getByteOrder()) { anEndian.swap(value); } theSubframeMaskTable[spectralIndex][rowIndex][colIndex] = value; } } } } if(!theImageDescriptionSubheader->isTransparencyMaskTableOffsetNull()) { // move get to the first byte of the Mask table. This is the offset from the // start of the maskSubsection. in.seekg(component.m_componentLocation + theImageDescriptionSubheader->getTransparencyMaskTableOffset(),ios::beg); for(spectralIndex = 0; spectralIndex < theImageDescriptionSubheader->getNumberOfSpectralGroups(); ++spectralIndex) { // reserve space for the number of rows theSubframeTransparencyMaskTable[spectralIndex].resize(theImageDescriptionSubheader->getNumberOfSubframesVertical()); for(rowIndex = 0; rowIndex < theImageDescriptionSubheader->getNumberOfSubframesVertical(); ++rowIndex) { // allocate the columns theSubframeTransparencyMaskTable[spectralIndex][rowIndex].resize(theImageDescriptionSubheader->getNumberOfSubframesHorizontal()); for(colIndex = 0; colIndex < theImageDescriptionSubheader->getNumberOfSubframesHorizontal(); ++colIndex) { ossim_uint32 value; in.read((char*)&value, 4); ossimEndian anEndian; if(anEndian.getSystemEndianType() != theHeader->getByteOrder()) { anEndian.swap(value); } theSubframeTransparencyMaskTable[spectralIndex][rowIndex][colIndex] = value; } } } } } } } return ossimErrorCodes::OSSIM_OK; } ossimErrorCode ossimRpfFrame::populateReplaceUpdateTable(std::istream& in) { ossimErrorCode result = ossimErrorCodes::OSSIM_OK; const ossimRpfLocationSection* location = theHeader->getLocationSection(); if( location ) { if ( location->hasComponent(OSSIM_RPF_REPLACE_UPDATE_SECTION_SUBHEADER) ) { ossimRpfComponentLocationRecord component; if( location->getComponent(OSSIM_RPF_REPLACE_UPDATE_SECTION_SUBHEADER, component) ) { ossimRefPtr<ossimRpfReplaceUpdateSectionSubheader> hdr = new ossimRpfReplaceUpdateSectionSubheader(); in.seekg(component.m_componentLocation, ios::beg); if( hdr->parseStream( in, theHeader->getByteOrder() ) == ossimErrorCodes::OSSIM_OK ) { ossim_uint16 count = hdr->getNumberOfRecords(); if ( count ) { if ( theReplaceUpdateTable.valid() ) { theReplaceUpdateTable->clear(); } else { theReplaceUpdateTable = new ossimRpfReplaceUpdateTable(); } ossimRpfReplaceUpdateRecord record; for ( ossim_uint16 i = 0; i < count; ++i ) { if ( record.parseStream(in) == ossimErrorCodes::OSSIM_OK ) { theReplaceUpdateTable->addRecord( record ); } else { break; } } } } } } } if ( in.fail() ) { theReplaceUpdateTable = 0; result = ossimErrorCodes::OSSIM_ERROR; } return result; } // End: ossimRpfFrame::populateReplaceUpdateTable(std::istream& in) ossimRefPtr<ossimRpfReplaceUpdateTable> ossimRpfFrame::getRpfReplaceUpdateTable() const { return theReplaceUpdateTable; }
36.228117
150
0.540611
rkanavath
14cb0d85e26db90a55d88bcb36144c08a0c9b3a5
3,270
cpp
C++
3rd/loguru/loguru_bench/loguru_bench.cpp
akirallL/TurboTransformers
7ca851947b1ae3b08122c45cea0ceac48ee04c3b
[ "BSD-3-Clause" ]
null
null
null
3rd/loguru/loguru_bench/loguru_bench.cpp
akirallL/TurboTransformers
7ca851947b1ae3b08122c45cea0ceac48ee04c3b
[ "BSD-3-Clause" ]
72
2020-09-15T13:32:02.000Z
2021-01-01T08:06:16.000Z
3rd/loguru/loguru_bench/loguru_bench.cpp
akirallL/TurboTransformers
7ca851947b1ae3b08122c45cea0ceac48ee04c3b
[ "BSD-3-Clause" ]
1
2020-11-16T16:06:15.000Z
2020-11-16T16:06:15.000Z
#include <chrono> #include <cmath> #include <iomanip> #include <iostream> #include <vector> #define LOGURU_WITH_STREAMS 1 #define LOGURU_REDEFINE_ASSERT 1 #include "../loguru.cpp" const size_t kNumRuns = 10; const double kPi = 3.1415926535897932384626433; static long long now_ns() { using namespace std::chrono; return duration_cast<nanoseconds>(high_resolution_clock::now().time_since_epoch()).count(); } template<typename Function> void bench(const std::string& name, const Function& function, size_t num_iterations) { function(num_iterations); // Warm-up. printf("%-30s ", name.c_str()); fflush(stdout); std::vector<double> times; double sum = 0; for (size_t i = 0; i < kNumRuns; ++i) { auto start_ns = now_ns(); function(num_iterations); double total_time_sec = (now_ns() - start_ns) * 1e-9; times.push_back(total_time_sec / num_iterations); sum += times.back(); } double mean = sum / kNumRuns; double std_dev_sum = 0; for (double time : times) { std_dev_sum += (time - mean) * (time - mean); } double variance = std::sqrt(std_dev_sum / kNumRuns); printf("%6.3f ± %.3f μs per call\n", mean * 1e6, variance * 1e6); fflush(stdout); } // ---------------------------------------------------------------------------- void format_strings(size_t num_iterations) { for (size_t i = 0; i < num_iterations; ++i) { LOG_F(WARNING, "Some long, complex message."); } loguru::flush(); } void format_float(size_t num_iterations) { for (size_t i = 0; i < num_iterations; ++i) { LOG_F(WARNING, "%+05.3f", kPi); } loguru::flush(); } void stream_strings(size_t num_iterations) { for (size_t i = 0; i < num_iterations; ++i) { LOG_S(WARNING) << "Some long, complex message."; } loguru::flush(); } void stream_float(size_t num_iterations) { for (size_t i = 0; i < num_iterations; ++i) { LOG_S(WARNING) << std::setfill('0') << std::setw(5) << std::setprecision(3) << kPi; } loguru::flush(); } void raw_string_float(size_t num_iterations) { for (size_t i = 0; i < num_iterations; ++i) { RAW_LOG_F(WARNING, "Some long, complex message."); } loguru::flush(); } void error_context(size_t num_iterations) { for (size_t i = 0; i < num_iterations; ++i) { ERROR_CONTEXT("key", "value"); } } int main(int argc, char* argv[]) { const size_t kNumIterations = 50 * 1000; loguru::init(argc, argv); loguru::add_file("loguru_bench.log", loguru::Truncate, loguru::Verbosity_INFO); bench("ERROR_CONTEXT", error_context, kNumIterations * 100); loguru::g_flush_interval_ms = 200; bench("LOG_F string (buffered):", format_strings, kNumIterations); bench("LOG_F float (buffered):", format_float, kNumIterations); bench("LOG_S string (buffered):", stream_strings, kNumIterations); bench("LOG_S float (buffered):", stream_float, kNumIterations); bench("RAW_LOG_F (buffered):", raw_string_float, kNumIterations); loguru::g_flush_interval_ms = 0; bench("LOG_F string (unbuffered):", format_strings, kNumIterations); bench("LOG_F float (unbuffered):", format_float, kNumIterations); bench("LOG_S string (unbuffered):", stream_strings, kNumIterations); bench("LOG_S float (unbuffered):", stream_float, kNumIterations); bench("RAW_LOG_F (unbuffered):", raw_string_float, kNumIterations); }
26.803279
92
0.677676
akirallL
14ce62707fa849a51a268bc0db58153035cb6613
606
hpp
C++
include/GameCoreData.hpp
Ghabriel/CppGameArchitecture
1212cf1e140ba78d72f2aea2aff56ec8c3e23293
[ "Apache-2.0" ]
null
null
null
include/GameCoreData.hpp
Ghabriel/CppGameArchitecture
1212cf1e140ba78d72f2aea2aff56ec8c3e23293
[ "Apache-2.0" ]
null
null
null
include/GameCoreData.hpp
Ghabriel/CppGameArchitecture
1212cf1e140ba78d72f2aea2aff56ec8c3e23293
[ "Apache-2.0" ]
null
null
null
#ifndef GAME_CORE_DATA_HPP #define GAME_CORE_DATA_HPP #include "engine/entity-system/forward-declarations.hpp" #include "engine/input-system/forward-declarations.hpp" #include "engine/resource-system/forward-declarations.hpp" #include "engine/state-system/forward-declarations.hpp" struct GameCoreData { engine::entitysystem::ComponentManager* componentManager; engine::inputsystem::InputTracker* inputTracker; engine::inputsystem::InputDispatcher* inputDispatcher; engine::resourcesystem::ResourceStorage* resourceStorage; engine::statesystem::StateMachine* stateMachine; }; #endif
33.666667
61
0.805281
Ghabriel
14cebcd9b5cbcf2149bacc0e74f635c031f6c7b2
5,630
hpp
C++
libs/http/include/http/json_client.hpp
jinmannwong/ledger
f3b129c127e107603e08bb192eb695d23eb17dbc
[ "Apache-2.0" ]
null
null
null
libs/http/include/http/json_client.hpp
jinmannwong/ledger
f3b129c127e107603e08bb192eb695d23eb17dbc
[ "Apache-2.0" ]
null
null
null
libs/http/include/http/json_client.hpp
jinmannwong/ledger
f3b129c127e107603e08bb192eb695d23eb17dbc
[ "Apache-2.0" ]
2
2019-11-13T10:55:24.000Z
2019-11-13T11:37:09.000Z
#pragma once //------------------------------------------------------------------------------ // // Copyright 2018-2019 Fetch.AI Limited // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //------------------------------------------------------------------------------ #include "core/byte_array/const_byte_array.hpp" #include "http/method.hpp" #include "variant/variant.hpp" #include <cstdint> #include <memory> #include <string> #include <unordered_map> namespace fetch { namespace http { class HttpClientInterface; /** * The JsonHttpClient is an adapter around the normal HttpClient. It is used when interacting * with Json based APIs. Requests and response objects are converted from and to json before/after * the underlying HTTP calls */ class JsonClient { public: using Variant = variant::Variant; using ConstByteArray = byte_array::ConstByteArray; using Headers = std::unordered_map<std::string, std::string>; enum class ConnectionMode { HTTP, HTTPS }; // Helpers static JsonClient CreateFromUrl(std::string const &url); // Construction / Destruction JsonClient(ConnectionMode mode, std::string host); JsonClient(ConnectionMode mode, std::string host, uint16_t port); JsonClient(JsonClient const &) = delete; JsonClient(JsonClient &&) noexcept; ~JsonClient(); /// @name Action Methods /// @{ bool Get(ConstByteArray const &endpoint, Variant &response); bool Get(ConstByteArray const &endpoint, Headers const &headers, Variant &response); bool Post(ConstByteArray const &endpoint, Variant const &request, Variant &response); bool Post(ConstByteArray const &endpoint, Variant &response); bool Post(ConstByteArray const &endpoint, Headers const &headers, Variant const &request, Variant &response); bool Post(ConstByteArray const &endpoint, Headers const &headers, Variant &response); /// @} /// @name Accessors /// @{ HttpClientInterface const &underlying_client() const; /// @} // Operators JsonClient &operator=(JsonClient const &) = delete; JsonClient &operator=(JsonClient &&) = default; private: constexpr static char const *LOGGING_NAME = "JsonClient"; using ClientPtr = std::unique_ptr<HttpClientInterface>; bool Request(Method method, ConstByteArray const &endpoint, Headers const *headers, Variant const *request, Variant &response); ClientPtr client_; }; /** * Makes a GET request to the specified endpoint * * @param endpoint The target endpoint * @param response The output response * @return true if successful, otherwise false */ inline bool JsonClient::Get(ConstByteArray const &endpoint, Variant &response) { return Request(Method::GET, endpoint, nullptr, nullptr, response); } /** * Makes a GET request to the specified endpoint, with specified headers * * @param endpoint The target endpoint * @param headers The headers to be used in the request * @param response The output response * @return true if successful, otherwise false */ inline bool JsonClient::Get(ConstByteArray const &endpoint, Headers const &headers, Variant &response) { return Request(Method::GET, endpoint, &headers, nullptr, response); } /** * Makes a POST request to the specified endpoint with a specified payload * * @param endpoint The target endpoint * @param request The request payload to be sent * @param response The output response * @return true if successful, otherwise false */ inline bool JsonClient::Post(ConstByteArray const &endpoint, Variant const &request, Variant &response) { return Request(Method::POST, endpoint, nullptr, &request, response); } /** * Makes a POST request to the specified endpoint * * @param endpoint The target endpoint * @param response The output response * @return true if successful, otherwise false */ inline bool JsonClient::Post(ConstByteArray const &endpoint, Variant &response) { return Request(Method::POST, endpoint, nullptr, nullptr, response); } /** * Makes a POST request to the specified endpoint with a specified payload and headers * * @param endpoint The target endpoint * @param headers The headers to the used in the request * @param request The request to payload * @param response The output response * @return true if successful, otherwise false */ inline bool JsonClient::Post(ConstByteArray const &endpoint, Headers const &headers, Variant const &request, Variant &response) { return Request(Method::POST, endpoint, &headers, &request, response); } /** * Makes a POST request to the specified endpoint with a specified headers * * @param endpoint The target endpoint * @param headers The headers to be used in the request * @param response The output response * @return true if successful, otherwise false */ inline bool JsonClient::Post(ConstByteArray const &endpoint, Headers const &headers, Variant &response) { return Request(Method::POST, endpoint, &headers, nullptr, response); } } // namespace http } // namespace fetch
31.988636
98
0.698757
jinmannwong
14ced231dfbe72e0886d3ee40c261afe9e568401
20,004
cpp
C++
plugins/INPUT/inputdriverXWINMSG/src/inputdriverXWINMSG_CEventListner.cpp
amvb/GUCEF
08fd423bbb5cdebbe4b70df24c0ae51716b65825
[ "Apache-2.0" ]
5
2016-04-18T23:12:51.000Z
2022-03-06T05:12:07.000Z
plugins/INPUT/inputdriverXWINMSG/src/inputdriverXWINMSG_CEventListner.cpp
amvb/GUCEF
08fd423bbb5cdebbe4b70df24c0ae51716b65825
[ "Apache-2.0" ]
2
2015-10-09T19:13:25.000Z
2018-12-25T17:16:54.000Z
plugins/INPUT/inputdriverXWINMSG/src/inputdriverXWINMSG_CEventListner.cpp
amvb/GUCEF
08fd423bbb5cdebbe4b70df24c0ae51716b65825
[ "Apache-2.0" ]
15
2015-02-23T16:35:28.000Z
2022-03-25T13:40:33.000Z
/* * inputdriverXWINMSG: GUCEF input driver module for X11 * Copyright (C) 2002 - 2012. Dinand Vanvelzen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /*-------------------------------------------------------------------------// // // // INCLUDES // // // //-------------------------------------------------------------------------*/ #include "inputdriverXWINMSG_CEventListner.h" #define XK_MISCELLANY #define XK_TECHNICAL #define XK_LATIN1 #include "X11/keysymdef.h" /*-------------------------------------------------------------------------// // // // NAMESPACE // // // //-------------------------------------------------------------------------*/ namespace GUCEF { namespace INPUT { namespace XWINMSG { /*-------------------------------------------------------------------------// // // // UTILITIES // // // //-------------------------------------------------------------------------*/ CEventListner::CEventListner( ::Window window , const TInputCallbacks* callbacks ) : CObserver() , m_window( window ) , m_callbacks( *callbacks ) , m_mouseX( 0 ) , m_mouseY( 0 ) {GUCEF_TRACE; CORE::CX11EventDispatcher* eventDispatcher = CORE::CX11EventDispatcher::Instance(); ::Display* display = eventDispatcher->GetDisplay(); eventDispatcher->SubscribeOnBehalfOfWindow( *this, window ); ::XWindowAttributes windowAttributes; ::XGetWindowAttributes( display, window, &windowAttributes ); long eventMask = windowAttributes.your_event_mask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask | Button1MotionMask; ::XSelectInput( display, window, eventMask ); } /*--------------------------------------------------------------------------*/ CEventListner::~CEventListner() {GUCEF_TRACE; CORE::CX11EventDispatcher::Instance()->UnsubscribeOnBehalfOfWindow( *this, m_window ); } /*--------------------------------------------------------------------------*/ ::Window CEventListner::GetWindow( void ) const {GUCEF_TRACE; return m_window; } /*--------------------------------------------------------------------------*/ const TInputCallbacks* CEventListner::GetCallbacks( void ) const {GUCEF_TRACE; return &m_callbacks; } /*--------------------------------------------------------------------------*/ GUCEF::INPUT::KeyCode CEventListner::MapKeyCode( int x11KeyCode ) {GUCEF_TRACE; switch ( x11KeyCode ) { // XK_MISCELLANY case XK_BackSpace /* Back space, back char */ : return KEYCODE_TAB; case XK_Tab : return KEYCODE_TAB; case XK_Linefeed /* Linefeed, LF */ : return KEYCODE_UNASSIGNED; case XK_Clear : return KEYCODE_UNASSIGNED; case XK_Return /* Return, enter */ : return KEYCODE_RETURN; case XK_Pause : return KEYCODE_PAUSE; case XK_Scroll_Lock : return KEYCODE_SCROLL; case XK_Sys_Req : return KEYCODE_SYSRQ; case XK_Escape : return KEYCODE_ESCAPE; case XK_Delete /* Delete, rubout */ : return KEYCODE_DELETE; case XK_F1 : return KEYCODE_F1; case XK_F2 : return KEYCODE_F2; case XK_F3 : return KEYCODE_F3; case XK_F4 : return KEYCODE_F4; case XK_F5 : return KEYCODE_F5; case XK_F6 : return KEYCODE_F6; case XK_F7 : return KEYCODE_F7; case XK_F8 : return KEYCODE_F8; case XK_F9 : return KEYCODE_F9; case XK_F10 : return KEYCODE_F10; case XK_F11 : return KEYCODE_F11; case XK_F12 : return KEYCODE_F12; case XK_F13 : return KEYCODE_F13; case XK_F14 : return KEYCODE_F14; case XK_F15 : return KEYCODE_F15; // case XK_3270_Duplicate : return KEYCODE_UNASSIGNED; // case XK_3270_FieldMark : return KEYCODE_UNASSIGNED; // case XK_3270_Right2 : return KEYCODE_UNASSIGNED; // case XK_3270_Left2 : return KEYCODE_UNASSIGNED; // case XK_3270_BackTab : return KEYCODE_TAB; // case XK_3270_EraseEOF : return KEYCODE_UNASSIGNED; // case XK_3270_EraseInput : return KEYCODE_UNASSIGNED; // case XK_3270_Reset : return KEYCODE_UNASSIGNED; // case XK_3270_Quit : return KEYCODE_UNASSIGNED; // case XK_3270_PA1 : return KEYCODE_UNASSIGNED; // case XK_3270_PA2 : return KEYCODE_UNASSIGNED; // case XK_3270_PA3 : return KEYCODE_UNASSIGNED; // case XK_3270_Test : return KEYCODE_UNASSIGNED; // case XK_3270_Attn : return KEYCODE_UNASSIGNED; // case XK_3270_CursorBlink : return KEYCODE_UNASSIGNED; // case XK_3270_AltCursor : return KEYCODE_UNASSIGNED; // case XK_3270_KeyClick : return KEYCODE_UNASSIGNED; // case XK_3270_Jump : return KEYCODE_UNASSIGNED; // case XK_3270_Ident : return KEYCODE_UNASSIGNED; // case XK_3270_Rule : return KEYCODE_UNASSIGNED; // case XK_3270_Copy : return KEYCODE_UNASSIGNED; // case XK_3270_Play : return KEYCODE_PLAYPAUSE; // case XK_3270_Setup : return KEYCODE_UNASSIGNED; // case XK_3270_Record : return KEYCODE_UNASSIGNED; // case XK_3270_ChangeScreen : return KEYCODE_UNASSIGNED; // case XK_3270_DeleteWord : return KEYCODE_UNASSIGNED; // case XK_3270_ExSelect : return KEYCODE_UNASSIGNED; // case XK_3270_CursorSelect : return KEYCODE_UNASSIGNED; // case XK_3270_PrintScreen : return KEYCODE_UNASSIGNED; // case XK_3270_Enter : return KEYCODE_RETURN; // XK_LATIN1 case XK_space /* U+0020 SPACE */ : return KEYCODE_SPACE; case XK_exclam /* U+0021 EXCLAMATION MARK */ : return KEYCODE_UNASSIGNED; case XK_quotedbl /* U+0022 QUOTATION MARK */ : return KEYCODE_UNASSIGNED; case XK_numbersign /* U+0023 NUMBER SIGN */ : return KEYCODE_UNASSIGNED; case XK_dollar /* U+0024 DOLLAR SIGN */ : return KEYCODE_UNASSIGNED; case XK_percent /* U+0025 PERCENT SIGN */ : return KEYCODE_UNASSIGNED; case XK_ampersand /* U+0026 AMPERSAND */ : return KEYCODE_UNASSIGNED; case XK_apostrophe /* U+0027 APOSTROPHE */ : return KEYCODE_UNASSIGNED; // case XK_quoteright /* deprecated */ : return KEYCODE_UNASSIGNED; case XK_parenleft /* U+0028 LEFT PARENTHESIS */ : return KEYCODE_UNASSIGNED; case XK_parenright /* U+0029 RIGHT PARENTHESIS */ : return KEYCODE_UNASSIGNED; case XK_asterisk /* U+002A ASTERISK */ : return KEYCODE_UNASSIGNED; case XK_plus /* U+002B PLUS SIGN */ : return KEYCODE_ADD; case XK_comma /* U+002C COMMA */ : return KEYCODE_COMMA; case XK_minus /* U+002D HYPHEN-MINUS */ : return KEYCODE_MINUS; case XK_period /* U+002E FULL STOP */ : return KEYCODE_PERIOD; case XK_slash /* U+002F SOLIDUS */ : return KEYCODE_SLASH; case XK_0 /* U+0030 DIGIT ZERO */ : return KEYCODE_0; case XK_1 /* U+0031 DIGIT ONE */ : return KEYCODE_1; case XK_2 /* U+0032 DIGIT TWO */ : return KEYCODE_2; case XK_3 /* U+0033 DIGIT THREE */ : return KEYCODE_3; case XK_4 /* U+0034 DIGIT FOUR */ : return KEYCODE_4; case XK_5 /* U+0035 DIGIT FIVE */ : return KEYCODE_5; case XK_6 /* U+0036 DIGIT SIX */ : return KEYCODE_6; case XK_7 /* U+0037 DIGIT SEVEN */ : return KEYCODE_7; case XK_8 /* U+0038 DIGIT EIGHT */ : return KEYCODE_8; case XK_9 /* U+0039 DIGIT NINE */ : return KEYCODE_9; case XK_colon /* U+003A COLON */ : return KEYCODE_COLON; case XK_semicolon /* U+003B SEMICOLON */ : return KEYCODE_SEMICOLON; case XK_less /* U+003C LESS-THAN SIGN */ : return KEYCODE_UNASSIGNED; case XK_equal /* U+003D EQUALS SIGN */ : return KEYCODE_EQUALS; case XK_greater /* U+003E GREATER-THAN SIGN */ : return KEYCODE_UNASSIGNED; case XK_question /* U+003F QUESTION MARK */ : return KEYCODE_ABNT_C1; case XK_at /* U+0040 COMMERCIAL AT */ : return KEYCODE_AT; case XK_A /* U+0041 LATIN CAPITAL LETTER A */ : return KEYCODE_A; case XK_B /* U+0042 LATIN CAPITAL LETTER B */ : return KEYCODE_B; case XK_C /* U+0043 LATIN CAPITAL LETTER C */ : return KEYCODE_C; case XK_D /* U+0044 LATIN CAPITAL LETTER D */ : return KEYCODE_D; case XK_E /* U+0045 LATIN CAPITAL LETTER E */ : return KEYCODE_E; case XK_F /* U+0046 LATIN CAPITAL LETTER F */ : return KEYCODE_F; case XK_G /* U+0047 LATIN CAPITAL LETTER G */ : return KEYCODE_G; case XK_H /* U+0048 LATIN CAPITAL LETTER H */ : return KEYCODE_H; case XK_I /* U+0049 LATIN CAPITAL LETTER I */ : return KEYCODE_I; case XK_J /* U+004A LATIN CAPITAL LETTER J */ : return KEYCODE_J; case XK_K /* U+004B LATIN CAPITAL LETTER K */ : return KEYCODE_K; case XK_L /* U+004C LATIN CAPITAL LETTER L */ : return KEYCODE_L; case XK_M /* U+004D LATIN CAPITAL LETTER M */ : return KEYCODE_M; case XK_N /* U+004E LATIN CAPITAL LETTER N */ : return KEYCODE_N; case XK_O /* U+004F LATIN CAPITAL LETTER O */ : return KEYCODE_O; case XK_P /* U+0050 LATIN CAPITAL LETTER P */ : return KEYCODE_P; case XK_Q /* U+0051 LATIN CAPITAL LETTER Q */ : return KEYCODE_Q; case XK_R /* U+0052 LATIN CAPITAL LETTER R */ : return KEYCODE_R; case XK_S /* U+0053 LATIN CAPITAL LETTER S */ : return KEYCODE_S; case XK_T /* U+0054 LATIN CAPITAL LETTER T */ : return KEYCODE_T; case XK_U /* U+0055 LATIN CAPITAL LETTER U */ : return KEYCODE_U; case XK_V /* U+0056 LATIN CAPITAL LETTER V */ : return KEYCODE_V; case XK_W /* U+0057 LATIN CAPITAL LETTER W */ : return KEYCODE_W; case XK_X /* U+0058 LATIN CAPITAL LETTER X */ : return KEYCODE_X; case XK_Y /* U+0059 LATIN CAPITAL LETTER Y */ : return KEYCODE_Y; case XK_Z /* U+005A LATIN CAPITAL LETTER Z */ : return KEYCODE_Z; case XK_bracketleft /* U+005B LEFT SQUARE BRACKET */ : return KEYCODE_LBRACKET; case XK_backslash /* U+005C REVERSE SOLIDUS */ : return KEYCODE_BACKSLASH; case XK_bracketright /* U+005D RIGHT SQUARE BRACKET */ : return KEYCODE_RBRACKET; case XK_asciicircum /* U+005E CIRCUMFLEX ACCENT */ : return KEYCODE_PREVTRACK; case XK_underscore /* U+005F LOW LINE */ : return KEYCODE_UNASSIGNED; case XK_grave /* U+0060 GRAVE ACCENT */ : return KEYCODE_GRAVE; // case XK_quoteleft /* deprecated */ : return KEYCODE_UNASSIGNED; case XK_a /* U+0061 LATIN SMALL LETTER A */ : return KEYCODE_A; case XK_b /* U+0062 LATIN SMALL LETTER B */ : return KEYCODE_B; case XK_c /* U+0063 LATIN SMALL LETTER C */ : return KEYCODE_C; case XK_d /* U+0064 LATIN SMALL LETTER D */ : return KEYCODE_D; case XK_e /* U+0065 LATIN SMALL LETTER E */ : return KEYCODE_E; case XK_f /* U+0066 LATIN SMALL LETTER F */ : return KEYCODE_F; case XK_g /* U+0067 LATIN SMALL LETTER G */ : return KEYCODE_G; case XK_h /* U+0068 LATIN SMALL LETTER H */ : return KEYCODE_H; case XK_i /* U+0069 LATIN SMALL LETTER I */ : return KEYCODE_I; case XK_j /* U+006A LATIN SMALL LETTER J */ : return KEYCODE_J; case XK_k /* U+006B LATIN SMALL LETTER K */ : return KEYCODE_K; case XK_l /* U+006C LATIN SMALL LETTER L */ : return KEYCODE_L; case XK_m /* U+006D LATIN SMALL LETTER M */ : return KEYCODE_M; case XK_n /* U+006E LATIN SMALL LETTER N */ : return KEYCODE_N; case XK_o /* U+006F LATIN SMALL LETTER O */ : return KEYCODE_O; case XK_p /* U+0070 LATIN SMALL LETTER P */ : return KEYCODE_P; case XK_q /* U+0071 LATIN SMALL LETTER Q */ : return KEYCODE_Q; case XK_r /* U+0072 LATIN SMALL LETTER R */ : return KEYCODE_R; case XK_s /* U+0073 LATIN SMALL LETTER S */ : return KEYCODE_S; case XK_t /* U+0074 LATIN SMALL LETTER T */ : return KEYCODE_T; case XK_u /* U+0075 LATIN SMALL LETTER U */ : return KEYCODE_U; case XK_v /* U+0076 LATIN SMALL LETTER V */ : return KEYCODE_V; case XK_w /* U+0077 LATIN SMALL LETTER W */ : return KEYCODE_W; case XK_x /* U+0078 LATIN SMALL LETTER X */ : return KEYCODE_X; case XK_y /* U+0079 LATIN SMALL LETTER Y */ : return KEYCODE_Y; case XK_z /* U+007A LATIN SMALL LETTER Z */ : return KEYCODE_Z; case XK_braceleft /* U+007B LEFT CURLY BRACKET */ : return KEYCODE_UNASSIGNED; case XK_bar /* U+007C VERTICAL LINE */ : return KEYCODE_UNASSIGNED; case XK_braceright /* U+007D RIGHT CURLY BRACKET */ : return KEYCODE_UNASSIGNED; case XK_asciitilde /* U+007E TILDE */ : return KEYCODE_UNASSIGNED; case XK_leftarrow /* U+2190 LEFTWARDS ARROW */ : return KEYCODE_LEFT; case XK_uparrow /* U+2191 UPWARDS ARROW */ : return KEYCODE_UP; case XK_rightarrow /* U+2192 RIGHTWARDS ARROW */ : return KEYCODE_RIGHT; case XK_downarrow /* U+2193 DOWNWARDS ARROW */ : return KEYCODE_DOWN; default: return KEYCODE_UNASSIGNED; } } /*--------------------------------------------------------------------------*/ void CEventListner::OnX11Event( ::XEvent& event ) {GUCEF_TRACE; // We only care about input related events switch ( event.type ) { case KeyRelease: { m_callbacks.onKeyboardKeyUp( m_callbacks.userData, 0, MapKeyCode( ::XLookupKeysym( &event.xkey, 0 ) ), 0 ); return; } case KeyPress: { m_callbacks.onKeyboardKeyDown( m_callbacks.userData, 0, MapKeyCode( ::XLookupKeysym( &event.xkey, 0 ) ), 0 ); return; } case ButtonPress: { Int32 deltaX = event.xbutton.x - m_mouseX; Int32 deltaY = event.xbutton.y - m_mouseY; m_mouseX = event.xbutton.x; m_mouseY = event.xbutton.y; m_callbacks.onMouseMove( m_callbacks.userData, 0, m_mouseX, m_mouseY, deltaX, deltaY ); m_callbacks.onMouseButtonDown( m_callbacks.userData, 0, event.xbutton.button ); return; } case ButtonRelease: { Int32 deltaX = event.xbutton.x - m_mouseX; Int32 deltaY = event.xbutton.y - m_mouseY; m_mouseX = event.xbutton.x; m_mouseY = event.xbutton.y; m_callbacks.onMouseMove( m_callbacks.userData, 0, m_mouseX, m_mouseY, deltaX, deltaY ); m_callbacks.onMouseButtonUp( m_callbacks.userData, 0, event.xbutton.button ); return; } case LeaveNotify : case EnterNotify : { Int32 deltaX = event.xcrossing.x - m_mouseX; Int32 deltaY = event.xcrossing.y - m_mouseY; m_mouseX = event.xbutton.x; m_mouseY = event.xbutton.y; m_callbacks.onMouseMove( m_callbacks.userData, 0, m_mouseX, m_mouseY, deltaX, deltaY ); return; } case MotionNotify: { Int32 deltaX = event.xmotion.x - m_mouseX; Int32 deltaY = event.xmotion.y - m_mouseY; m_mouseX = event.xmotion.x; m_mouseY = event.xmotion.y; m_callbacks.onMouseMove( m_callbacks.userData, 0, m_mouseX, m_mouseY, deltaX, deltaY ); return; } } } // //typedef struct { // int type; /* of event */ // unsigned long serial; /* # of last request processed by server */ // Bool send_event; /* true if this came from a SendEvent request */ // Display *display; /* Display the event was read from */ // Window window; /* "event" window it is reported relative to */ // Window root; /* root window that the event occurred on */ // Window subwindow; /* child window */ // Time time; /* milliseconds */ // int x, y; /* pointer x, y coordinates in event window */ // int x_root, y_root; /* coordinates relative to root */ // unsigned int state; /* key or button mask */ // unsigned int button; /* detail */ // Bool same_screen; /* same screen flag */ //} XButtonEvent; //typedef XButtonEvent XButtonPressedEvent; //typedef XButtonEvent XButtonReleasedEvent; // //typedef struct { // int type; /* of event */ // unsigned long serial; /* # of last request processed by server */ // Bool send_event; /* true if this came from a SendEvent request */ // Display *display; /* Display the event was read from */ // Window window; /* "event" window reported relative to */ // Window root; /* root window that the event occurred on */ // Window subwindow; /* child window */ // Time time; /* milliseconds */ // int x, y; /* pointer x, y coordinates in event window */ // int x_root, y_root; /* coordinates relative to root */ // unsigned int state; /* key or button mask */ // char is_hint; /* detail */ // Bool same_screen; /* same screen flag */ //} XMotionEvent; //typedef XMotionEvent XPointerMovedEvent; /*--------------------------------------------------------------------------*/ void CEventListner::OnNotify( CORE::CNotifier* notifier , const CORE::CEvent& eventid , CORE::CICloneable* eventdata ) {GUCEF_TRACE; if ( CORE::CX11EventDispatcher::X11Event == eventid ) { CORE::CX11EventDispatcher::TX11EventData* x11data = (CORE::CX11EventDispatcher::TX11EventData*) eventdata; OnX11Event( x11data->GetData() ); } else if ( CORE::CX11EventDispatcher::SubscribeEvent == eventid ) { // Register our devices m_callbacks.onKeyboardAttached( m_callbacks.userData, 0 ); m_callbacks.onMouseAttached( m_callbacks.userData, 0 ); } else if ( CORE::CX11EventDispatcher::UnsubscribeEvent == eventid ) { // Register our devices m_callbacks.onKeyboardDetached( m_callbacks.userData, 0 ); m_callbacks.onMouseDetached( m_callbacks.userData, 0 ); } } /*-------------------------------------------------------------------------// // // // NAMESPACE // // // //-------------------------------------------------------------------------*/ }; /* namespace XWINMSG */ }; /* namespace INPUT */ }; /* namespace GUCEF */ /*-------------------------------------------------------------------------*/
47.29078
122
0.575685
amvb
14cf3c9cae5008c9ac61d5ac9691d2cca0f4ff19
8,437
cpp
C++
src/VboRectangleRenderer.cpp
fataris/ofxVboRenderer
30223cae622a9609a98c1d7c06ec3b93a0aba135
[ "MIT" ]
6
2018-04-24T03:37:13.000Z
2022-03-17T17:14:24.000Z
src/VboRectangleRenderer.cpp
fataris/ofxVboRenderer
30223cae622a9609a98c1d7c06ec3b93a0aba135
[ "MIT" ]
9
2018-04-16T14:20:57.000Z
2020-06-08T13:51:17.000Z
src/VboRectangleRenderer.cpp
fataris/ofxVboRenderer
30223cae622a9609a98c1d7c06ec3b93a0aba135
[ "MIT" ]
1
2019-05-09T11:04:00.000Z
2019-05-09T11:04:00.000Z
// // VboRectangleRenderer.cpp // example-simple // // Created by Hana on 2018/04/25. // // #include "VboRectangleRenderer.hpp" VboRectangleRenderer::VboRectangleRenderer() { initVbo(); initCount(); thick = 1.0; } void VboRectangleRenderer::setup() { setScreenSize(); initVbo(); } void VboRectangleRenderer::setup(float w, float h) { setScreenSize(w, h); initVbo(); } void VboRectangleRenderer::draw() { filledVbo.updateVertexData(filledPos.begin(), filledCounter.vertex); filledVbo.updateColorData(filledColors.begin(), filledCounter.color); filledVbo.updateIndexData(filledIndices.begin(), filledCounter.index); filledVbo.drawElements(GL_TRIANGLES, filledCounter.index); noFillVbo.updateVertexData(noFillPos.begin(), noFillCounter.vertex); noFillVbo.updateColorData(noFillColors.begin(), noFillCounter.color); noFillVbo.updateIndexData(noFillIndices.begin(), noFillCounter.index); glLineWidth(thick); noFillVbo.drawElements(GL_LINES, noFillCounter.index); initCount(); } void VboRectangleRenderer::square(float x, float y, float size, float angle, bool fill) { if (fill) { filledSquare(x, y, size, angle); } else { noFillSquare(x, y, size, angle); } } void VboRectangleRenderer::square(ofVec2f pos, float size, float angle, float fill) { square(pos.x, pos.y, size, angle, fill); } void VboRectangleRenderer::filledSquare(float x, float y, float size, float angle) { updateVerts(x, y, size, angle); addFilledRectangle(); } void VboRectangleRenderer::noFillSquare(float x, float y, float size, float angle) { updateVerts(x, y, size, angle); addNoFillRectangle(); } void VboRectangleRenderer::rectangle(float x1, float y1, float x2, float y2, float angle, bool fill) { if(fill) { filledRectangle(x1, y1, x2, y2, angle); } else { noFillRectangle(x1, y1, x2, y2, angle); } } void VboRectangleRenderer::rectangle(ofVec2f p1, ofVec2f p2, float angle, bool fill) { rectangle(p1.x, p1.y, p2.x, p2.y, angle, fill); } void VboRectangleRenderer::rectangle(ofVec2f pos, float w, float h, float angle, bool fill) { if(fill) { filledRectangle(pos, w, h, angle); } else { noFillRectangle(pos, w, h, angle); } } void VboRectangleRenderer::filledRectangle(float x1, float y1, float x2, float y2, float angle) { updateVerts(x1, y1, x2, y2, angle); addFilledRectangle(); } void VboRectangleRenderer::filledRectangle(ofVec2f pos, float w, float h, float angle) { updateVerts(pos, w, h, angle); addFilledRectangle(); } void VboRectangleRenderer::noFillRectangle(float x1, float y1, float x2, float y2, float angle) { updateVerts(x1, y1, x2, y2, angle); addNoFillRectangle(); } void VboRectangleRenderer::noFillRectangle(ofVec2f pos, float w, float h, float angle) { updateVerts(pos, w, h, angle); addNoFillRectangle(); } void VboRectangleRenderer::initVbo() { filledVbo.setVertexData(filledPos.begin(), VBORECTANGLE_VERTS_MAX, GL_DYNAMIC_DRAW); filledVbo.setColorData(filledColors.begin(), VBORECTANGLE_VERTS_MAX, GL_DYNAMIC_DRAW); filledVbo.setIndexData(filledIndices.begin(), VBORECTANGLE_INDICES_MAX, GL_DYNAMIC_DRAW); noFillVbo.setVertexData(noFillPos.begin(), VBORECTANGLE_VERTS_MAX, GL_DYNAMIC_DRAW); noFillVbo.setColorData(noFillColors.begin(), VBORECTANGLE_VERTS_MAX, GL_DYNAMIC_DRAW); noFillVbo.setIndexData(noFillIndices.begin(), VBORECTANGLE_INDICES_MAX, GL_DYNAMIC_DRAW); } void VboRectangleRenderer::initCount() { filledCounter.vertex = 0; filledCounter.color = 0; filledCounter.index = 0; filledCounter.num = 0; noFillCounter.vertex = 0; noFillCounter.color = 0; noFillCounter.index = 0; noFillCounter.num = 0; } void VboRectangleRenderer::updateVerts(float x, float y, float size, float angle) { //Calcurate half size tmpLength = width * size * 0.5; //Create square at center verts[0] = ofVec2f(-tmpLength, tmpLength); verts[1] = ofVec2f(tmpLength, tmpLength); verts[2] = ofVec2f(tmpLength, -tmpLength); verts[3] = ofVec2f(-tmpLength, -tmpLength); //Rotate and move tmpAngle = 360 * angle; center.set(x * width, y * height); for(int i = 0; i < RECTANGLE_VERTS_NUM; i++) { verts[i].rotate(tmpAngle); verts[i] += center; } } void VboRectangleRenderer::updateVerts(ofVec2f pos, float size, float angle) { updateVerts(pos.x, pos.y, size, angle); } void VboRectangleRenderer::updateVerts(float x1, float y1, float x2, float y2, float angle) { //Calcurate half width and height tmpWidth = width * abs(x2 - x1) * 0.5; tmpHeight = height * abs(y2 - y1) * 0.5; //Create rectangle at center verts[0] = ofVec2f(-tmpWidth, tmpHeight); verts[1] = ofVec2f(tmpWidth, tmpHeight); verts[2] = ofVec2f(tmpWidth, -tmpHeight); verts[3] = ofVec2f(-tmpWidth, -tmpHeight); //Rotate and move tmpAngle = 360.0 * angle; center.set( (x2 + x1) * width * 0.5, (y2 + y1) * height * 0.5); for(int i = 0; i < RECTANGLE_VERTS_NUM; i++) { verts[i].rotate(tmpAngle); verts[i] += center; } } void VboRectangleRenderer::updateVerts(ofVec2f p1, ofVec2f p2, float angle) { updateVerts(p1.x, p1.y, p2.x, p2.y, angle); } void VboRectangleRenderer::updateVerts(ofVec2f pos, float w, float h, float angle) { tmpWidth = w * 0.5 * width; tmpHeight = h * 0.5 * height; //Create square at center verts[0] = ofVec2f(-tmpWidth, tmpHeight); verts[1] = ofVec2f(tmpWidth, tmpHeight); verts[2] = ofVec2f(tmpWidth, -tmpHeight); verts[3] = ofVec2f(-tmpWidth, -tmpHeight); //rotate and move tmpAngle = 360.0 * angle; for(int i = 0; i < RECTANGLE_VERTS_NUM; i++) { verts[i].rotate(tmpAngle); verts[i].x += pos.x * width; verts[i].y += pos.y * height; } } void VboRectangleRenderer::addVertex(ofVec2f pos, bool filled) { if (filled) { addFilledVertex(pos); } else { addNoFillVertex(pos); } } void VboRectangleRenderer::addFilledVertex(ofVec2f pos) { filledPos[filledCounter.vertex] = pos; filledCounter.vertex++; } void VboRectangleRenderer::addNoFillVertex(ofVec2f pos) { noFillPos[noFillCounter.vertex] = pos; noFillCounter.vertex++; } void VboRectangleRenderer::addIndex(ofIndexType index, bool filled) { if (filled) { addFilledIndex(index); } else { addNoFillIndex(index); } } void VboRectangleRenderer::addFilledIndex(ofIndexType index) { filledIndices[filledCounter.index] = index; filledCounter.index++; } void VboRectangleRenderer::addNoFillIndex(ofIndexType index) { noFillIndices[noFillCounter.index] = index; noFillCounter.index++; } void VboRectangleRenderer::addColor(ofFloatColor _color, bool filled) { if (filled) { addFilledColor(_color); } else { addNoFillColor(_color); } } void VboRectangleRenderer::addFilledColor(ofFloatColor _color) { filledColors[filledCounter.color] = color; filledCounter.color++; } void VboRectangleRenderer::addNoFillColor(ofFloatColor _color) { noFillColors[noFillCounter.color] = color; noFillCounter.color++; } void VboRectangleRenderer::addFilledRectangle() { //Add vertices and color for(int i = 0; i < RECTANGLE_VERTS_NUM; i++) { addFilledVertex(verts[i]); addFilledColor(color); } //Set index; addFilledIndex(filledCounter.vertex - 4); addFilledIndex(filledCounter.vertex - 3); addFilledIndex(filledCounter.vertex - 2); addFilledIndex(filledCounter.vertex - 4); addFilledIndex(filledCounter.vertex - 2); addFilledIndex(filledCounter.vertex - 1); } void VboRectangleRenderer::addNoFillRectangle() { //Add vertices and color for(int i = 0; i < RECTANGLE_VERTS_NUM; i++) { addNoFillVertex(verts[i]); addNoFillColor(color); } //Set INDEX addNoFillIndex(noFillCounter.vertex - 4); addNoFillIndex(noFillCounter.vertex - 3); addNoFillIndex(noFillCounter.vertex - 3); addNoFillIndex(noFillCounter.vertex - 2); addNoFillIndex(noFillCounter.vertex - 2); addNoFillIndex(noFillCounter.vertex - 1); addNoFillIndex(noFillCounter.vertex - 1); addNoFillIndex(noFillCounter.vertex - 4); // noFillCounter.num++; }
29.5
105
0.679388
fataris
14d46fec7a9586b08ecd3f1f66a225c5bad3cfae
2,456
cpp
C++
day-04-puzzle-1/src/main.cpp
Nexxxy/advent2020-challenge
419fff10c35ba15d0d6b9d86974260ecc38ab5f8
[ "MIT" ]
null
null
null
day-04-puzzle-1/src/main.cpp
Nexxxy/advent2020-challenge
419fff10c35ba15d0d6b9d86974260ecc38ab5f8
[ "MIT" ]
null
null
null
day-04-puzzle-1/src/main.cpp
Nexxxy/advent2020-challenge
419fff10c35ba15d0d6b9d86974260ecc38ab5f8
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <list> #include <utilslib/Fileloader.h> #include <utilslib/StringHelper.h> #include <unordered_map> #define debug(x) using namespace std; int main() { cout << "Day 04 Puzzle 1" << std::endl; auto retList = FileLoader::ReadRecordFromFileWithBlankSpaceSeparator("input.txt"); list<unordered_map<string,string>*> database; unordered_map<string,string>* record; string key; // to store the key // step 1 : read whole file into inmem-database for (auto it = retList.begin(); it != retList.end(); it++) { // cout << (*it) << endl; // try to separate everything auto strList = StringHelper::SplitStringWithSeparator(*it, ' '); record = new unordered_map<string, string>(); for (auto listIt = strList.begin(); listIt != strList.end(); listIt++) { // we assume that there is a ':' // -> we will destroy *listIt string val -> but its not needed anymore -> no problem tho key = StringHelper::SplitStringOnPos(*listIt, StringHelper::GetPosInString(*listIt, ':')); (*record)[key] = *listIt; // cout << "< " << key << " - " << (*record)[key] << " >" << endl; } database.push_back(record); } // step 2 : check valid data-records // Mandatory : // byr (Birth Year) // iyr (Issue Year) // eyr (Expiration Year) // hgt (Height) // hcl (Hair Color) // ecl (Eye Color) // pid (Passport ID) // optional // cid (Country ID) is optional int validCounter = 0; for (auto it = database.begin(); it != database.end(); it++) { record = (*it); // check everything if (record->find("byr") == record->end()) continue; if (record->find("iyr") == record->end()) continue; if (record->find("eyr") == record->end()) continue; if (record->find("hgt") == record->end()) continue; if (record->find("hcl") == record->end()) continue; if (record->find("ecl") == record->end()) continue; if (record->find("pid") == record->end()) continue; // dont care for cid :) // valid ++ validCounter++; } cout << "Valid passports : " << validCounter << endl; return 0; }
31.088608
102
0.528094
Nexxxy
14ddfdc6b16b1a3eae546df4640fe4eab2672445
1,464
cpp
C++
StudentLoginDialog.cpp
WT-Project-Library/-
e20dbde7f205d5afe6c3588b81338c791ac9d1a3
[ "Apache-2.0" ]
null
null
null
StudentLoginDialog.cpp
WT-Project-Library/-
e20dbde7f205d5afe6c3588b81338c791ac9d1a3
[ "Apache-2.0" ]
null
null
null
StudentLoginDialog.cpp
WT-Project-Library/-
e20dbde7f205d5afe6c3588b81338c791ac9d1a3
[ "Apache-2.0" ]
null
null
null
#include "StudentLoginDialog.h" #include "ui_StudentLoginDialog.h" #include "UserSelectionDialog.h" #include <QDebug> #include <QMessageBox> #include <QtSql> StudentLoginDialog::StudentLoginDialog(QWidget *parent) : QDialog(parent), ui(new Ui::StudentLoginDialog) { ui->setupUi(this); } StudentLoginDialog::~StudentLoginDialog() { delete stu_main; delete ui; } QString StudentLoginDialog::st_id=" "; QString StudentLoginDialog::on_login_pushButton_2_clicked() { QString accounttext=ui->account_lineEdit->text(); st_id=accounttext; QString passwordtext=ui->password_lineEdit_2->text(); if(accounttext==NULL|passwordtext==NULL) { QMessageBox::warning(this,QStringLiteral("警告"),QStringLiteral("账户或密码为空"),QStringLiteral("确定")); } else { qDebug()<<accounttext<<" "<<passwordtext; QString S =QString("select * from user_stu where stu_id='%1' and stu_psd='%2' ").arg(accounttext).arg(passwordtext); QSqlQuery query; if(query.exec(S)&&query.next()) { qDebug()<<QStringLiteral("学生登录成功"); this->hide(); stu_main->show(); } else { QMessageBox::warning(this,QStringLiteral("警告"),QStringLiteral("账户或密码错误"),QStringLiteral("确定")); } } return st_id; } void StudentLoginDialog::closeEvent(QCloseEvent *) { UserSelectionDialog *userSel=new UserSelectionDialog; userSel->show(); }
26.142857
124
0.659836
WT-Project-Library
14df86b6626733915fcd0edc1732694df91316a8
4,977
cpp
C++
Source/demos.cpp
claytonkanderson/Fractus
c4012cc40ee81ac042edcc5461c48e02456bcbd0
[ "MIT" ]
null
null
null
Source/demos.cpp
claytonkanderson/Fractus
c4012cc40ee81ac042edcc5461c48e02456bcbd0
[ "MIT" ]
null
null
null
Source/demos.cpp
claytonkanderson/Fractus
c4012cc40ee81ac042edcc5461c48e02456bcbd0
[ "MIT" ]
null
null
null
// // demos.cpp // Fracturing // // Created by Clayton Anderson on 6/4/17. // Copyright © 2017 Clayton Anderson. All rights reserved. // #include "demos.hpp" void init(int demo, TetraGroupInits &inits) { switch (demo) { // Half broken fry case 0: inits.x_width = 40.0f; inits.y_width = 1.0f; inits.z_width = 1.0f; inits.height = 18.0f; inits.elastic = 12.00e+09; inits.poisson = 0.47f; inits.toughness = 5.17e+07; inits.div = ivec3(32,2,2); inits.center_pos = vec3(0,inits.height,0); inits.angular_vel = vec3(0, 1, 4); inits.com_vel = vec3(0, -70, 0); inits.theta = -0.5f; // Double check how the angles are done on the rest of them inits.phi = 0.0f; inits.model = rotate(mat4(1.0f),inits.theta,glm::vec3(0,0,1)); inits.model = rotate(mat4(1.0f),inits.phi,glm::vec3(0,1,0)) * inits.model; inits.model = translate(mat4(1.0f), inits.center_pos) * inits.model; break; // Plate broken by rotation case 1: inits.x_width = 20.0f; inits.y_width = 1.0f; inits.z_width = 20.0f; inits.height = 10.0f; inits.elastic = 2e+08; inits.poisson = 0.45f; inits.toughness = 2e+7; inits.div = ivec3(8,4,8); inits.center_pos = vec3(0,inits.height,0); inits.angular_vel = vec3(0, 15.45, 0); inits.com_vel = vec3(0, 0, 0); inits.theta = 0.0f; inits.phi = 0.0f; inits.model = rotate(mat4(1.0f),inits.theta,glm::vec3(0,0,1)); inits.model = rotate(mat4(1.0f),inits.phi,glm::vec3(0,1,0)) * inits.model; inits.model = translate(mat4(1.0f), inits.center_pos) * inits.model; break; // Cube semi-shattered case 2: inits.x_width = 10.0f; inits.y_width = 10.0f; inits.z_width = 10.0f; inits.height = 10.0f; inits.elastic = 4.52e+8; inits.poisson = 0.45f; inits.toughness = 1.01e+8; inits.div = ivec3(4,4,4); inits.center_pos = vec3(0,inits.height,0); inits.angular_vel = vec3(0, 1, 0); inits.com_vel = vec3(0, -45, 0); inits.model = rotate(mat4(1.0f),inits.theta,glm::vec3(0,0,1)); inits.model = rotate(mat4(1.0f),inits.phi,glm::vec3(0,1,0)) * inits.model; inits.model = translate(mat4(1.0f), inits.center_pos) * inits.model; break; // Single layer slab case 3: inits.x_width = 10.0f; inits.y_width = 1.0f; inits.z_width = 30.0f; inits.height = 10.0f; inits.elastic = 5.24e+08; inits.poisson = 0.45f; inits.toughness = 7.1e+7; inits.div = ivec3(8,2,8); inits.center_pos = vec3(0,inits.height,0); inits.angular_vel = vec3(5, 0, 0); inits.com_vel = vec3(0, -75, 0); inits.theta = 0.0f; inits.phi = 1.0f; inits.model = rotate(mat4(1.0f),inits.theta,glm::vec3(0,0,1)); inits.model = rotate(mat4(1.0f),inits.phi,glm::vec3(0,1,0)) * inits.model; inits.model = translate(mat4(1.0f), inits.center_pos) * inits.model; break; case 4: inits.x_width = 4.0f; inits.y_width = 2.0f; inits.z_width = 2.0f; inits.height = 7.0f; inits.elastic = 2e+07; inits.poisson = 0.45f; inits.toughness = 2.4e+6; inits.div = ivec3(2,2,1); inits.center_pos = vec3(0,inits.height,0); inits.angular_vel = vec3(0, 0, 0); inits.com_vel = vec3(0, -25, 0); inits.theta = 0.0f; inits.phi = 0.0f; inits.model = rotate(mat4(1.0f),inits.theta,glm::vec3(0,0,1)); inits.model = rotate(mat4(1.0f),inits.phi,glm::vec3(0,1,0)) * inits.model; inits.model = translate(mat4(1.0f), inits.center_pos) * inits.model; break; case 5: inits.x_width = 0.20f; inits.y_width = 0.20f; inits.z_width = 0.20f; inits.height = 1.0f; // Concrete inits.elastic = 2e10f; inits.poisson = 0.45f; inits.toughness = 1.4e+6; inits.div = ivec3(8, 8, 8); inits.center_pos = vec3(0, inits.height, 0); inits.angular_vel = vec3(0, 0, 0); inits.com_vel = vec3(0, 0, 0); inits.theta = 0.0f; inits.phi = 0.0f; inits.model = rotate(mat4(1.0f), inits.theta, glm::vec3(0, 0, 1)); inits.model = rotate(mat4(1.0f), inits.phi, glm::vec3(0, 1, 0)) * inits.model; inits.model = translate(mat4(1.0f), inits.center_pos) * inits.model; break; default: break; } }
36.595588
92
0.514366
claytonkanderson
14e4de99d662fdc480ee455e16333f4d86e65b0b
9,083
cpp
C++
c++/src/objtools/blast/seqdb_writer/writedb_gimask.cpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
31
2016-12-09T04:56:59.000Z
2021-12-31T17:19:10.000Z
c++/src/objtools/blast/seqdb_writer/writedb_gimask.cpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
6
2017-03-10T17:25:13.000Z
2021-09-22T15:49:49.000Z
c++/src/objtools/blast/seqdb_writer/writedb_gimask.cpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
20
2015-01-04T02:15:17.000Z
2021-12-03T02:31:43.000Z
/* $Id: writedb_gimask.cpp 177347 2009-11-30 18:43:57Z maning $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: Ning Ma * */ /// @file writedb_gimask.cpp /// Implementation for the CWriteDB_GiMask and related classes. #ifndef SKIP_DOXYGEN_PROCESSING static char const rcsid[] = "$Id: writedb_gimask.cpp 177347 2009-11-30 18:43:57Z maning $"; #endif /* SKIP_DOXYGEN_PROCESSING */ #include <ncbi_pch.hpp> #include <objtools/blast/seqdb_writer/writedb.hpp> #include "writedb_gimask.hpp" BEGIN_NCBI_SCOPE /// Import C++ std namespace. USING_SCOPE(std); #if ((!defined(NCBI_COMPILER_WORKSHOP) || (NCBI_COMPILER_VERSION > 550)) && \ (!defined(NCBI_COMPILER_MIPSPRO)) ) // CWriteDB_GiMask CWriteDB_GiMask::CWriteDB_GiMask(const string & maskname, const string & desc, Uint8 max_file_size): m_MaskName (maskname), m_MaxFileSize (max_file_size), m_DFile (new CWriteDB_GiMaskData(maskname, "gmd", 0, max_file_size)), m_DFile_LE (new CWriteDB_GiMaskData(maskname, "gnd", 0, max_file_size, true)), m_OFile (new CWriteDB_GiMaskOffset(maskname, "gmo", max_file_size)), m_OFile_LE (new CWriteDB_GiMaskOffset(maskname, "gno", max_file_size, true)), m_IFile (new CWriteDB_GiMaskIndex(maskname, "gmi", desc, max_file_size)), m_IFile_LE (new CWriteDB_GiMaskIndex(maskname, "gni", desc, max_file_size, true)) { } void CWriteDB_GiMask::ListFiles(vector<string> & files) const { if (!m_GiOffset.size()) return; files.push_back(m_IFile->GetFilename()); files.push_back(m_IFile_LE->GetFilename()); files.push_back(m_OFile->GetFilename()); files.push_back(m_OFile_LE->GetFilename()); files.push_back(m_DFile->GetFilename()); files.push_back(m_DFile_LE->GetFilename()); } void CWriteDB_GiMask::AddGiMask(const vector<int> & GIs, const TPairVector & mask) { if (!m_DFile->CanFit(mask.size())) { int index = m_DFile->GetIndex() + 1; m_DFile->Close(); m_DFile_LE->Close(); m_DFile.Reset(new CWriteDB_GiMaskData(m_MaskName, "gmd", index, m_MaxFileSize)); m_DFile_LE.Reset(new CWriteDB_GiMaskData(m_MaskName, "gnd", index, m_MaxFileSize, true)); } TOffset offset = m_DFile->GetOffset(); m_DFile->WriteMask(mask); m_DFile_LE->WriteMask(mask); ITERATE(vector<int>, gi, GIs) { m_GiOffset.push_back(pair<int, TOffset> (*gi, offset)); } } void CWriteDB_GiMask::Close() { if (!m_GiOffset.size()) { // un_used mask file m_MaskName = ""; return; } m_DFile->Close(); m_DFile_LE->Close(); int num_vols = m_DFile->GetIndex() + 1; if (num_vols == 1) { m_DFile->RenameSingle(); m_DFile_LE->RenameSingle(); } sort(m_GiOffset.begin(), m_GiOffset.end()); m_IFile->AddGIs(m_GiOffset, num_vols); m_IFile->Close(); m_IFile_LE->AddGIs(m_GiOffset, num_vols); m_IFile_LE->Close(); m_OFile->AddGIs(m_GiOffset); m_OFile->Close(); m_OFile_LE->AddGIs(m_GiOffset); m_OFile_LE->Close(); } // CWriteDB_GiMaskOffset CWriteDB_GiMaskOffset:: CWriteDB_GiMaskOffset(const string & maskname, const string & extn, Uint8 max_file_size, bool le) : CWriteDB_File (maskname, extn, -1, max_file_size, false), m_UseLE (le) { } void CWriteDB_GiMaskOffset::AddGIs(const TGiOffset & gi_offset) { CBlastDbBlob gis(kPageSize * kGISize); CBlastDbBlob offsets(kPageSize * kOffsetSize); if ( ! m_Created) { Create(); } int i = 0; ITERATE(TGiOffset, iter, gi_offset) { if (m_UseLE ) { gis.WriteInt4_LE(iter->first); offsets.WriteInt4_LE(iter->second.first); offsets.WriteInt4_LE(iter->second.second); } else { gis.WriteInt4(iter->first); offsets.WriteInt4(iter->second.first); offsets.WriteInt4(iter->second.second); } ++i; if (i== kPageSize) { Write(gis.Str()); Write(offsets.Str()); gis.Clear(); offsets.Clear(); i = 0; } } // flush the residual records if (i) { Write(gis.Str()); Write(offsets.Str()); gis.Clear(); offsets.Clear(); } } // CWriteDB_GiMaskIndex CWriteDB_GiMaskIndex:: CWriteDB_GiMaskIndex(const string & maskname, const string & extn, const string & desc, Uint8 max_file_size, bool le) : CWriteDB_GiMaskOffset (maskname, extn, max_file_size, le), m_Desc (desc) { m_Date = CTime(CTime::eCurrent).AsString(); } void CWriteDB_GiMaskIndex::AddGIs(const TGiOffset & gi_offset, int num_vols) { m_NumGIs = gi_offset.size(); m_NumIndex = m_NumGIs / kPageSize + 2; CBlastDbBlob gis(m_NumIndex * kGISize); CBlastDbBlob offsets(m_NumIndex * kOffsetSize); if ( ! m_Created) { Create(); } int i = 0; m_NumIndex = 0; ITERATE(TGiOffset, iter, gi_offset) { if (i % kPageSize && i < m_NumGIs-1) { ++i; continue; } ++i; if (m_UseLE ) { gis.WriteInt4_LE(iter->first); offsets.WriteInt4_LE(iter->second.first); offsets.WriteInt4_LE(iter->second.second); } else { gis.WriteInt4(iter->first); offsets.WriteInt4(iter->second.first); offsets.WriteInt4(iter->second.second); } ++m_NumIndex; } x_BuildHeaderFields(num_vols); Write(gis.Str()); Write(offsets.Str()); } void CWriteDB_GiMaskIndex::x_BuildHeaderFields(int num_vols) { const int kFormatVersion = 1; // SeqDB has one of these. CBlastDbBlob header; header.WriteInt4(kFormatVersion); header.WriteInt4(num_vols); header.WriteInt4(kGISize); header.WriteInt4(kOffsetSize); header.WriteInt4(kPageSize); header.WriteInt4(m_NumIndex); header.WriteInt4(m_NumGIs); header.WriteInt4(0); // index start will be calculated later header.WriteString(m_Desc, kStringFmt); header.WriteString(m_Date, kStringFmt); header.WritePadBytes(8, CBlastDbBlob::eString); Int4 size = header.GetWriteOffset(); header.WriteInt4(size, 28); Write(header.Str()); } // CWriteDB_GiMaskData CWriteDB_GiMaskData::CWriteDB_GiMaskData(const string & maskname, const string & extn, int index, Uint8 max_file_size, bool le) : CWriteDB_File (maskname, extn, index, max_file_size, false), m_DataLength (0), m_UseLE (le), m_Index (index) { } void CWriteDB_GiMaskData::WriteMask(const TPairVector & mask) { if (! mask.size()) return; if (! m_Created) Create(); CBlastDbBlob data; if (m_UseLE ) { data.WriteInt4_LE(mask.size()); ITERATE(TPairVector, range, mask) { data.WriteInt4_LE(range->first); data.WriteInt4_LE(range->second); } } else { data.WriteInt4(mask.size()); ITERATE(TPairVector, range, mask) { data.WriteInt4(range->first); data.WriteInt4(range->second); } } Write(data.Str()); m_DataLength += (1+2*mask.size()) * 4; } #endif END_NCBI_SCOPE
30.076159
97
0.58648
OpenHero
14e6bbe3312fbce04a09fc46ba4853c8a5b6fa39
4,910
cpp
C++
src/slg/textures/densitygrid.cpp
LuxRender/LuxRays
edb001ddeb744b534f6fe98c7b789d4635196718
[ "Apache-2.0" ]
null
null
null
src/slg/textures/densitygrid.cpp
LuxRender/LuxRays
edb001ddeb744b534f6fe98c7b789d4635196718
[ "Apache-2.0" ]
null
null
null
src/slg/textures/densitygrid.cpp
LuxRender/LuxRays
edb001ddeb744b534f6fe98c7b789d4635196718
[ "Apache-2.0" ]
null
null
null
/*************************************************************************** * Copyright 1998-2013 by authors (see AUTHORS.txt) * * * * This file is part of LuxRender. * * * * 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 "slg/textures/densitygrid.h" using namespace std; using namespace luxrays; using namespace slg; //------------------------------------------------------------------------------ // Densitygrid texture //------------------------------------------------------------------------------ DensityGridTexture::DensityGridTexture(const TextureMapping3D *mp, const u_int nx, const u_int ny, const u_int nz, const float *dt, const std::string wrapmode) : mapping(mp), nx(nx), ny(ny), nz(nz), data(nx*ny*nz), wrapMode(WRAP_REPEAT) { data.assign(dt, dt + nx * ny * nz); if(wrapmode == "black") { wrapMode = WRAP_BLACK; } else if(wrapmode == "white") { wrapMode = WRAP_WHITE; } else if(wrapmode == "clamp") wrapMode = WRAP_CLAMP; } float DensityGridTexture::GetFloatValue(const HitPoint &hitPoint) const { const Point P(mapping->Map(hitPoint)); float x, y, z; int vx, vy, vz; switch (wrapMode) { case WRAP_REPEAT: x = P.x * nx; vx = luxrays::Floor2Int(x); x -= vx; vx = luxrays::Mod(vx, nx); y = P.y * ny; vy = luxrays::Floor2Int(y); y -= vy; vy = luxrays::Mod(vy, ny); z = P.z * nz; vz = luxrays::Floor2Int(z); z -= vz; vz = luxrays::Mod(vz, nz); break; case WRAP_BLACK: if (P.x < 0.f || P.x >= 1.f || P.y < 0.f || P.y >= 1.f || P.z < 0.f || P.z >= 1.f) return 0.f; x = P.x * nx; vx = luxrays::Floor2Int(x); x -= vx; y = P.y * ny; vy = luxrays::Floor2Int(y); y -= vy; z = P.z * nz; vz = luxrays::Floor2Int(z); z -= vz; break; case WRAP_WHITE: if (P.x < 0.f || P.x >= 1.f || P.y < 0.f || P.y >= 1.f || P.z < 0.f || P.z >= 1.f) return 1.f; x = P.x * nx; vx = luxrays::Floor2Int(x); x -= vx; y = P.y * ny; vy = luxrays::Floor2Int(y); y -= vy; z = P.z * nz; vz = luxrays::Floor2Int(z); z -= vz; break; case WRAP_CLAMP: x = luxrays::Clamp(P.x, 0.f, 1.f) * nx; vx = min(luxrays::Floor2Int(x), nx - 1); x -= vx; y = luxrays::Clamp(P.y, 0.f, 1.f) * ny; vy = min(luxrays::Floor2Int(P.y * ny), ny - 1); y -= vy; z = luxrays::Clamp(P.z, 0.f, 1.f) * nz; vz = min(luxrays::Floor2Int(P.z * nz), nz - 1); z -= vz; break; default: return 0.f; } // Trilinear interpolation of the grid element return luxrays::Lerp(z, luxrays::Lerp(y, luxrays::Lerp(x, D(vx, vy, vz), D(vx + 1, vy, vz)), luxrays::Lerp(x, D(vx, vy + 1, vz), D(vx + 1, vy + 1, vz))), luxrays::Lerp(y, luxrays::Lerp(x, D(vx, vy, vz + 1), D(vx + 1, vy, vz + 1)), luxrays::Lerp(x, D(vx, vy + 1, vz + 1), D(vx + 1, vy + 1, vz + 1)))); } Spectrum DensityGridTexture::GetSpectrumValue(const HitPoint &hitPoint) const { return Spectrum(GetFloatValue(hitPoint)); } Properties DensityGridTexture::ToProperties(const ImageMapCache &imgMapCache) const { Properties props; std::string wrap = ""; switch (wrapMode) { default: case WRAP_REPEAT: wrap = "repeat"; break; case WRAP_BLACK: wrap = "black"; break; case WRAP_WHITE: wrap = "white"; break; case WRAP_CLAMP: wrap = "clamp"; break; } const string name = GetName(); props.Set(Property("scene.textures." + name + ".type")("densitygrid")); props.Set(Property("scene.textures." + name + ".nx")(nx)); props.Set(Property("scene.textures." + name + ".ny")(ny)); props.Set(Property("scene.textures." + name + ".nz")(nz)); props.Set(Property("scene.textures." + name + ".wrap")(wrap)); props.Set(Property("scene.textures." + name + ".data")(data)); props.Set(mapping->ToProperties("scene.textures." + name + ".mapping")); return props; }
33.401361
148
0.504277
LuxRender
14e8c15a409c955d43e54ecb387ca1e958012c3a
536
cpp
C++
runtime/gen9/windows/command_stream_receiver_gen9.cpp
FelipeMLopez/compute-runtime
3e3d2d3b3ac9129b1ee9c4251a2586fef0b300b8
[ "MIT" ]
3
2019-09-20T23:26:36.000Z
2019-10-03T17:44:12.000Z
runtime/gen9/windows/command_stream_receiver_gen9.cpp
FelipeMLopez/compute-runtime
3e3d2d3b3ac9129b1ee9c4251a2586fef0b300b8
[ "MIT" ]
1
2019-09-17T08:06:24.000Z
2019-09-17T08:06:24.000Z
runtime/gen9/windows/command_stream_receiver_gen9.cpp
FelipeMLopez/compute-runtime
3e3d2d3b3ac9129b1ee9c4251a2586fef0b300b8
[ "MIT" ]
3
2019-05-16T07:22:51.000Z
2019-11-11T03:05:32.000Z
/* * Copyright (C) 2017-2019 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "runtime/command_stream/command_stream_receiver_with_aub_dump.inl" #include "runtime/os_interface/windows/device_command_stream.inl" #include "runtime/os_interface/windows/wddm_device_command_stream.inl" namespace NEO { template class DeviceCommandStreamReceiver<SKLFamily>; template class WddmCommandStreamReceiver<SKLFamily>; template class CommandStreamReceiverWithAUBDump<WddmCommandStreamReceiver<SKLFamily>>; } // namespace NEO
29.777778
86
0.828358
FelipeMLopez
14e8c38a3a573ca9e4496c00194d04a7328c9e04
500
cpp
C++
GameEngine/GameEngineRendererTileMap.cpp
AnWooJin/Portfolio
612c1b9d29f552d1bba586f461babf7dff3a1e4e
[ "MIT" ]
null
null
null
GameEngine/GameEngineRendererTileMap.cpp
AnWooJin/Portfolio
612c1b9d29f552d1bba586f461babf7dff3a1e4e
[ "MIT" ]
null
null
null
GameEngine/GameEngineRendererTileMap.cpp
AnWooJin/Portfolio
612c1b9d29f552d1bba586f461babf7dff3a1e4e
[ "MIT" ]
null
null
null
#include "GameEngineRendererTileMap.h" float4 GameEngineRendererTileMap::GetWorldPosition(int _X, int _Y) { float4 ReturnPos = TileSize_; ReturnPos.x = static_cast<float>(_X); ReturnPos.y = static_cast<float>(_Y); ReturnPos += TileSizeHalf_; return ReturnPos; } TileIndex GameEngineRendererTileMap::GetTileIndex(const float4& _Pos) { return { static_cast<int>(_Pos.x / TileSize_.x), static_cast<int>(_Pos.y / TileSize_.y) }; } void GameEngineRendererTileMap::DeleteTile(int _X, int _Y) { }
23.809524
91
0.762
AnWooJin
14f7a7bd37c60ef554110a65a077cefb846bf3ee
4,463
cpp
C++
3rdparty/bgfx/3rdparty/glslang/hlsl/hlslAttributes.cpp
Pength-TH/egal-D-engine
f16a8def566f678cb324bd901768d32f4412396f
[ "Apache-2.0" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
3rdparty/bgfx/3rdparty/glslang/hlsl/hlslAttributes.cpp
Pength-TH/egal-D-engine
f16a8def566f678cb324bd901768d32f4412396f
[ "Apache-2.0" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
3rdparty/bgfx/3rdparty/glslang/hlsl/hlslAttributes.cpp
Pength-TH/egal-D-engine
f16a8def566f678cb324bd901768d32f4412396f
[ "Apache-2.0" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// // Copyright (C) 2016 LunarG, Inc. // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // // Neither the name of Google, Inc., nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // #include "hlslAttributes.h" #include <cstdlib> #include <cctype> namespace glslang { // Map the given string to an attribute enum from TAttributeType, // or EatNone if invalid. TAttributeType TAttributeMap::attributeFromName(const TString& name) { // These are case insensitive. TString lowername(name); std::transform(lowername.begin(), lowername.end(), lowername.begin(), ::tolower); if (lowername == "allow_uav_condition") return EatAllow_uav_condition; else if (lowername == "branch") return EatBranch; else if (lowername == "call") return EatCall; else if (lowername == "domain") return EatDomain; else if (lowername == "earlydepthstencil") return EatEarlyDepthStencil; else if (lowername == "fastopt") return EatFastOpt; else if (lowername == "flatten") return EatFlatten; else if (lowername == "forcecase") return EatForceCase; else if (lowername == "instance") return EatInstance; else if (lowername == "maxtessfactor") return EatMaxTessFactor; else if (lowername == "maxvertexcount") return EatMaxVertexCount; else if (lowername == "numthreads") return EatNumThreads; else if (lowername == "outputcontrolpoints") return EatOutputControlPoints; else if (lowername == "outputtopology") return EatOutputTopology; else if (lowername == "partitioning") return EatPartitioning; else if (lowername == "patchconstantfunc") return EatPatchConstantFunc; else if (lowername == "unroll") return EatUnroll; else if (lowername == "loop") return EatLoop; else return EatNone; } // Look up entry, inserting if it's not there, and if name is a valid attribute name // as known by attributeFromName. TAttributeType TAttributeMap::setAttribute(const TString* name, TIntermAggregate* value) { if (name == nullptr) return EatNone; const TAttributeType attr = attributeFromName(*name); if (attr != EatNone) attributes[attr] = value; return attr; } // Look up entry (const version), and return aggregate node. This cannot change the map. const TIntermAggregate* TAttributeMap::operator[](TAttributeType attr) const { const auto entry = attributes.find(attr); return (entry == attributes.end()) ? nullptr : entry->second; } // True if entry exists in map (even if value is nullptr) bool TAttributeMap::contains(TAttributeType attr) const { return attributes.find(attr) != attributes.end(); } } // end namespace glslang
37.504202
93
0.661887
Pength-TH
14f87362d74b39aaa3988c8a920f3757daee774e
1,650
cpp
C++
DataStructure2/Wk3SortII/peanuts.cpp
pmdiano/Coursera
37c29c88200facc157613dc9722d4ffb61716eb6
[ "MIT" ]
2
2016-03-07T04:56:30.000Z
2016-03-13T09:27:49.000Z
DataStructure2/Wk3SortII/peanuts.cpp
pmdiano/Coursera
37c29c88200facc157613dc9722d4ffb61716eb6
[ "MIT" ]
null
null
null
DataStructure2/Wk3SortII/peanuts.cpp
pmdiano/Coursera
37c29c88200facc157613dc9722d4ffb61716eb6
[ "MIT" ]
null
null
null
//+----------------------------------------------------------------------------- // // File: peanuts.cpp // // Synopsis: Sort II, problem 2. Also POJ 1928 // // Author: Qirong Ma, 10/23/2015 // //------------------------------------------------------------------------------ #include <cstdio> #include "../../include/sort.h" inline int abs(int x) { return x > 0 ? x : -x; } struct peanut { int i; int j; int num; peanut(){} bool operator<(const peanut& p2) const {return num > p2.num;} bool operator>=(const peanut& p2) const {return num <= p2.num;} bool operator<=(const peanut& p2) const {return num >= p2.num;} } field[2500]; int cost[2500], count[2500]; int solve() { int M, N, K, l, i, j; scanf("%d%d%d", &M, &N, &K); for (i = 1, l=0; i <= M; i++) for (j = 1; j <= N; j++) { scanf("%d", &field[l].num); field[l].i = i; field[l].j = j; l++; } quickSort(field, l); cost[0] = 1 + (field[0].i-1) + 1; count[0] = field[0].num; for (i = 1; i < l; i++) { cost[i] = cost[i-1] + 1 + abs(field[i].i - field[i-1].i) + abs(field[i].j - field[i-1].j); count[i] = count[i-1] + field[i].num; } for (i = 0; i < l; i++) cost[i] = cost[i] + (field[i].i - 1) + 1; // for (i = 0; i < l; i++) // printf("count[%d]=%d, cost[%d]=%d\n", i, count[i], i, cost[i]); int left, right, mid; left = 0; right = l-1; while (left <= right) { mid = (left+right)/2; if (K == cost[mid]) return count[mid]; else if (K < cost[mid]) right = mid - 1; else left = mid + 1; } return count[right]; } int main() { int T; scanf("%d", &T); while (T--) printf("%d\n", solve()); return 0; }
22
80
0.461818
pmdiano
14ffb8ceb61d5c90bc7a061fdcc54684f2948d23
2,080
hpp
C++
include/util/logsafely.hpp
BaroboRobotics/cxx-util
624813d244ac5a3e6e4ffb16b7e0ac96b5c200cd
[ "BSL-1.0" ]
null
null
null
include/util/logsafely.hpp
BaroboRobotics/cxx-util
624813d244ac5a3e6e4ffb16b7e0ac96b5c200cd
[ "BSL-1.0" ]
null
null
null
include/util/logsafely.hpp
BaroboRobotics/cxx-util
624813d244ac5a3e6e4ffb16b7e0ac96b5c200cd
[ "BSL-1.0" ]
1
2018-11-13T15:02:23.000Z
2018-11-13T15:02:23.000Z
// Copyright (c) 2014-2016 Barobo, Inc. // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef UTIL_LOGSAFELY_HPP #define UTIL_LOGSAFELY_HPP #include <boost/log/attributes/clock.hpp> #include <boost/log/attributes/timer.hpp> #include <boost/log/utility/formatting_ostream.hpp> #include <boost/log/utility/manipulators/to_log.hpp> #include <iomanip> namespace util { // Boost.Log uses Boost.DateTime's ptime class for clock and timer values. // DateTime uses setlocale(), which is not thread-safe under Windows XP. To // avoid setlocale() related crashes, we provide a pair of safe operator<< // overloads for formatting Boost.Log clocks and timers according to ISO 8601. // To select these overloads, our formatter would use the form: // expr::attr<attrs::timer::value_type, LogSafely>("Timeline") // or // expr::attr<attrs::clock::value_type, LogSafely>("TimeStamp") struct LogSafely; using FormatStream = boost::log::formatting_ostream; using TimerValueType = boost::log::attributes::timer::value_type; using SafeTimerToLogManip = boost::log::to_log_manip<TimerValueType, LogSafely>; FormatStream& operator<< (FormatStream& os, const SafeTimerToLogManip& manip) { auto& t = manip.get(); os << std::setfill('0') << std::setw(2) << t.hours() << ":" << std::setw(2) << t.minutes() << ":" << std::setw(2) << t.seconds() << "." << std::setw(6) << t.fractional_seconds(); return os; } using LocalClockValueType = boost::log::attributes::local_clock::value_type; using SafeLocalClockToLogManip = boost::log::to_log_manip<LocalClockValueType, LogSafely>; FormatStream& operator<< (FormatStream& os, const SafeLocalClockToLogManip& manip) { auto& t = manip.get(); os << std::setfill('0') << std::setw(4) << t.date().year() << '-' << std::setw(2) << int(t.date().month()) << '-' << std::setw(2) << t.date().day() << 'T' << SafeTimerToLogManip{t.time_of_day()}; return os; } } // namespace util #endif
34.666667
90
0.692788
BaroboRobotics
0901209d8a26340698eca08d2acbfcc1c4fb30d3
599
cpp
C++
src/core/Command.cpp
jalowiczor/beeon-gateway-with-nemea-sources
195d8209302a42e03bafe33811236d7aeedb188d
[ "BSD-3-Clause" ]
7
2018-06-09T05:55:59.000Z
2021-01-05T05:19:02.000Z
src/core/Command.cpp
jalowiczor/beeon-gateway-with-nemea-sources
195d8209302a42e03bafe33811236d7aeedb188d
[ "BSD-3-Clause" ]
1
2019-12-25T10:39:06.000Z
2020-01-03T08:35:29.000Z
src/core/Command.cpp
jalowiczor/beeon-gateway-with-nemea-sources
195d8209302a42e03bafe33811236d7aeedb188d
[ "BSD-3-Clause" ]
11
2018-05-10T08:29:05.000Z
2020-01-22T20:49:32.000Z
#include "core/Command.h" #include "core/CommandSender.h" #include "util/ClassInfo.h" using namespace BeeeOn; using namespace std; Command::Command(): m_sendingHandler(NULL) { } string Command::name() const { return ClassInfo::forPointer(this).name(); } Command::~Command() { } void Command::setSendingHandler(CommandHandler *sender) { m_sendingHandler = sender; } CommandHandler* Command::sendingHandler() const { return m_sendingHandler; } string Command::toString() const { return name(); } Result::Ptr Command::deriveResult(Answer::Ptr answer) const { return new Result(answer); }
14.609756
59
0.737896
jalowiczor
0905a471db81d446dd3904a71a8f82efc028fe4f
10,028
hpp
C++
Lodestar/blocks/std/SumBlock.hpp
helkebir/Lodestar
6b325d3e7a388676ed31d44eac1146630ee4bb2c
[ "BSD-3-Clause" ]
4
2020-06-05T14:08:23.000Z
2021-06-26T22:15:31.000Z
Lodestar/blocks/std/SumBlock.hpp
helkebir/Lodestar
6b325d3e7a388676ed31d44eac1146630ee4bb2c
[ "BSD-3-Clause" ]
2
2021-06-25T15:14:01.000Z
2021-07-01T17:43:20.000Z
Lodestar/blocks/std/SumBlock.hpp
helkebir/Lodestar
6b325d3e7a388676ed31d44eac1146630ee4bb2c
[ "BSD-3-Clause" ]
1
2021-06-16T03:15:23.000Z
2021-06-16T03:15:23.000Z
// // Created by Hamza El-Kebir on 12/23/21. // #ifndef LODESTAR_SUMBLOCK_HPP #define LODESTAR_SUMBLOCK_HPP #include "Lodestar/blocks/Block.hpp" #include "Lodestar/aux/TemplateTools.hpp" namespace ls { namespace blocks { namespace std { enum class SumBlockOperator { Plus, Minus }; struct SumBlockOperatorHelper { template<unsigned int N> static typename ls::aux::TemplateTools::repeat<SumBlockOperator, N, ::std::tuple>::type repeatTuple(SumBlockOperator value = SumBlockOperator::Plus) { typename ls::aux::TemplateTools::repeat<SumBlockOperator, N, ::std::tuple>::type tuple{}; repeatTupleImpl<N, N - 1>(tuple, value); return tuple; } template<unsigned int N, int TIdx = N - 1, typename ::std::enable_if<(TIdx > 0), bool>::type * = nullptr> static void repeatTupleImpl( typename ls::aux::TemplateTools::repeat<SumBlockOperator, N, ::std::tuple>::type &tuple, SumBlockOperator value) { ::std::get<TIdx>(tuple) = value; return repeatTupleImpl<N, TIdx - 1>(tuple, value); } template<unsigned int N, int TIdx = N - 1, typename ::std::enable_if<(TIdx == 0), bool>::type * = nullptr> static void repeatTupleImpl( typename ls::aux::TemplateTools::repeat<SumBlockOperator, N, ::std::tuple>::type &tuple, SumBlockOperator value) { ::std::get<0>(tuple) = value; } template<unsigned int N, int TIdx = N - 1, typename ::std::enable_if<( TIdx < 0), bool>::type * = nullptr> static void repeatTupleImpl( typename ls::aux::TemplateTools::repeat<SumBlockOperator, N, ::std::tuple>::type &tuple, SumBlockOperator value) { return; } static inline int interpret(SumBlockOperator value) { switch (value) { default: case SumBlockOperator::Plus: return 1; case SumBlockOperator::Minus: return -1; } } }; template<typename TType, unsigned int N> class SumBlock : public Block< typename ls::aux::TemplateTools::repeat<TType, N, ::std::tuple>::type, ::std::tuple<TType>, ::std::tuple<::std::array<SumBlockOperator, N>, TType> > { public: using Base = Block< typename ls::aux::TemplateTools::repeat<TType, N, ::std::tuple>::type, ::std::tuple<TType>, ::std::tuple<::std::array<SumBlockOperator, N>, TType> >; using Ops = SumBlockOperator; static constexpr const SumBlockOperator Plus = SumBlockOperator::Plus; static constexpr const SumBlockOperator Minus = SumBlockOperator::Minus; // template <int TIdx> // using Base::template o<TIdx>; // using Base::getInput; // template <size_t TIdx> // auto i() const // { // auto i_impl = Base::template i<size_t>(); // // i_impl(); // } SumBlock() { (this->template p<0>()).fill(SumBlockOperator::Plus); bindEquation(); // getInput<0>(); // getInput<0>(); // Base::template i<0>(); // this->equation = [&](Base & b) { // b.template o<0>() = sum(); // }; } template<typename... TOperators> SumBlock(Ops op, TOperators... ops) { (this->template p<0>()).fill(SumBlockOperator::Plus); setOperators(op, ops...); bindEquation(); } template<int TIdx = 0, typename... TOperators, typename ::std::enable_if< TIdx < N, bool>::type * = nullptr> void setOperators(Ops op, TOperators... ops) { static_assert( ls::aux::TemplateTraits::allSame<SumBlockOperator, TOperators...>::value, "Operators must all be SumBlockOperator values." ); (this->template p<0>())[TIdx] = op; return setOperators<TIdx + 1>(ops...); } template<int TIdx = 0, typename... TOperators, typename ::std::enable_if< TIdx >= N, bool>::type * = nullptr> void setOperators(Ops op, TOperators... ops) { return; } template<int TIdx = 0, typename ::std::enable_if< TIdx < N, bool>::type * = nullptr> void setOperators(Ops op) { (this->template p<0>())[TIdx] = op; } template<int TIdx = 0, typename ::std::enable_if< TIdx >= N, bool>::type * = nullptr> void setOperators(Ops op) { return; } TType & zero() { return this->template p<1>(); } protected: void bindEquation() { this->equation = ::std::bind( &SumBlock<TType, N>::triggerFunction, this, ::std::placeholders::_1); } void triggerFunction(Base &b) { b.template o<0>() = sum(zero()); } template<unsigned int TIdx = Base::kIns - 1> typename ::std::enable_if<(TIdx > 0), TType>::type sum(TType value) { return sum<TIdx - 1>( value + SumBlockOperatorHelper::interpret( (this->template p<0>())[TIdx]) * this->template i<TIdx>()); } template<unsigned int TIdx = Base::kIns - 1> typename ::std::enable_if<(TIdx == 0), TType>::type sum(TType value) { return value + SumBlockOperatorHelper::interpret( (this->template p<0>())[TIdx]) * this->template i<TIdx>(); } template<unsigned int TIdx = Base::kIns - 1> typename ::std::enable_if<(TIdx < 0), TType>::type sum(TType value) { return value; } }; } template<typename TType, unsigned int N> class BlockTraits<std::SumBlock<TType, N>> { public: static constexpr const BlockType blockType = BlockType::SumBlock; enum { directFeedthrough = true }; using type = std::SumBlock<TType, N>; using Base = typename type::Base; enum { kIns = Base::kIns, kOuts = Base::kOuts, kPars = Base::kPars }; static const ::std::array<::std::string, kIns> inTypes; static const ::std::array<::std::string, kOuts> outTypes; static const ::std::array<::std::string, kPars> parTypes; static const ::std::array<::std::string, 2> templateTypes; }; template<typename TType, unsigned int N> const ::std::array<::std::string, BlockTraits<std::SumBlock<TType, N>>::kIns> BlockTraits<std::SumBlock<TType, N>>::inTypes = ls::aux::TemplateTools::create_array<BlockTraits<std::SumBlock<TType, N>>::kIns>( demangle(typeid(TType).name()) ); template<typename TType, unsigned int N> const ::std::array<::std::string, BlockTraits<std::SumBlock<TType, N>>::kOuts> BlockTraits<std::SumBlock<TType, N>>::outTypes = {demangle(typeid(TType).name())}; template<typename TType, unsigned int N> const ::std::array<::std::string, BlockTraits<std::SumBlock<TType, N>>::kPars> BlockTraits<std::SumBlock<TType, N>>::parTypes = {demangle( typeid(::std::array<std::SumBlockOperator, N>).name() ), demangle(typeid(TType).name())}; template<typename TType, unsigned int N> const ::std::array<::std::string, 2> BlockTraits<std::SumBlock<TType, N>>::templateTypes = {demangle(typeid(TType).name()), "unsigned int"}; } } #endif //LODESTAR_SUMBLOCK_HPP
38.129278
135
0.425608
helkebir
0908867f775345b4e3166649ba72f743eaad37af
8,481
cpp
C++
src/ripple/app/paths/cursor/DeliverNodeReverse.cpp
DEEPSPACE007/DsDeFi-Exchange
777486b799bae42a4297f9524f3ff30e0b149ef7
[ "Unlicense" ]
null
null
null
src/ripple/app/paths/cursor/DeliverNodeReverse.cpp
DEEPSPACE007/DsDeFi-Exchange
777486b799bae42a4297f9524f3ff30e0b149ef7
[ "Unlicense" ]
null
null
null
src/ripple/app/paths/cursor/DeliverNodeReverse.cpp
DEEPSPACE007/DsDeFi-Exchange
777486b799bae42a4297f9524f3ff30e0b149ef7
[ "Unlicense" ]
null
null
null
#include <ripple/app/paths/cursor/EffectiveRate.h> #include <ripple/app/paths/cursor/RippleLiquidity.h> #include <ripple/basics/Log.h> namespace ripple { namespace path { TER PathCursor::deliverNodeReverseImpl ( AccountID const& uOutAccountID, STAmount const& saOutReq, STAmount& saOutAct, bool callerHasLiquidity ) const { TER resultCode = tesSUCCESS; saOutAct.clear (saOutReq); JLOG (j_.trace()) << "deliverNodeReverse>" << " saOutAct=" << saOutAct << " saOutReq=" << saOutReq << " saPrvDlvReq=" << previousNode().saRevDeliver; assert (saOutReq != beast::zero); int loopCount = 0; auto viewJ = rippleCalc_.logs_.journal ("View"); while (saOutAct < saOutReq) { if (++loopCount > (multiQuality_ ? CALC_NODE_DELIVER_MAX_LOOPS_MQ : CALC_NODE_DELIVER_MAX_LOOPS)) { JLOG (j_.warn()) << "loop count exceeded"; return telFAILED_PROCESSING; } resultCode = advanceNode (saOutAct, true, callerHasLiquidity); if (resultCode != tesSUCCESS || !node().offerIndex_) break; auto const xferRate = effectiveRate ( node().issue_, uOutAccountID, node().offerOwnerAccount_, node().transferRate_); JLOG (j_.trace()) << "deliverNodeReverse:" << " offerOwnerAccount_=" << node().offerOwnerAccount_ << " uOutAccountID=" << uOutAccountID << " node().issue_.account=" << node().issue_.account << " xferRate=" << xferRate; if (!multiQuality_) { if (!node().rateMax) { JLOG (j_.trace()) << "Set initial rate"; node().rateMax = xferRate; } else if (xferRate > node().rateMax) { JLOG (j_.trace()) << "Offer exceeds initial rate: " << *node().rateMax; break; } else if (xferRate < node().rateMax) { JLOG (j_.trace()) << "Reducing rate: " << *node().rateMax; node().rateMax = xferRate; } } STAmount saOutPassReq = std::min ( std::min (node().saOfferFunds, node().saTakerGets), saOutReq - saOutAct); STAmount saOutPassAct = saOutPassReq; STAmount saOutPlusFees = multiplyRound ( saOutPassAct, xferRate, false); JLOG (j_.trace()) << "deliverNodeReverse:" << " saOutReq=" << saOutReq << " saOutAct=" << saOutAct << " node().saTakerGets=" << node().saTakerGets << " saOutPassAct=" << saOutPassAct << " saOutPlusFees=" << saOutPlusFees << " node().saOfferFunds=" << node().saOfferFunds; if (saOutPlusFees > node().saOfferFunds) { saOutPlusFees = node().saOfferFunds; auto fee = divideRound (saOutPlusFees, xferRate, true); saOutPassAct = std::min (saOutPassReq, fee); JLOG (j_.trace()) << "deliverNodeReverse: Total exceeds fees:" << " saOutPassAct=" << saOutPassAct << " saOutPlusFees=" << saOutPlusFees << " node().saOfferFunds=" << node().saOfferFunds; } auto outputFee = mulRound ( saOutPassAct, node().saOfrRate, node().saTakerPays.issue (), true); if (*stAmountCalcSwitchover == false && ! outputFee) { JLOG (j_.fatal()) << "underflow computing outputFee " << "saOutPassAct: " << saOutPassAct << " saOfrRate: " << node ().saOfrRate; return telFAILED_PROCESSING; } STAmount saInPassReq = std::min (node().saTakerPays, outputFee); STAmount saInPassAct; JLOG (j_.trace()) << "deliverNodeReverse:" << " outputFee=" << outputFee << " saInPassReq=" << saInPassReq << " node().saOfrRate=" << node().saOfrRate << " saOutPassAct=" << saOutPassAct << " saOutPlusFees=" << saOutPlusFees; if (!saInPassReq) { JLOG (j_.debug()) << "deliverNodeReverse: micro offer is unfunded."; node().bEntryAdvance = true; continue; } else if (!isXRP(previousNode().account_)) { saInPassAct = saInPassReq; JLOG (j_.trace()) << "deliverNodeReverse: account --> OFFER --> ? :" << " saInPassAct=" << saInPassAct; } else { resultCode = increment(-1).deliverNodeReverseImpl( node().offerOwnerAccount_, saInPassReq, saInPassAct, saOutAct > beast::zero); if (fix1141(view().info().parentCloseTime)) { if (resultCode == tecPATH_DRY && saOutAct > beast::zero) { resultCode = tesSUCCESS; break; } } JLOG (j_.trace()) << "deliverNodeReverse: offer --> OFFER --> ? :" << " saInPassAct=" << saInPassAct; } if (resultCode != tesSUCCESS) break; if (saInPassAct < saInPassReq) { auto outputRequirements = divRound (saInPassAct, node ().saOfrRate, node ().saTakerGets.issue (), true); saOutPassAct = std::min (saOutPassReq, outputRequirements); auto outputFees = multiplyRound (saOutPassAct, xferRate, true); saOutPlusFees = std::min (node().saOfferFunds, outputFees); JLOG (j_.trace()) << "deliverNodeReverse: adjusted:" << " saOutPassAct=" << saOutPassAct << " saOutPlusFees=" << saOutPlusFees; } else { assert (saInPassAct == saInPassReq); } node().bFundsDirty = true; resultCode = accountSend(view(), node().offerOwnerAccount_, node().issue_.account, saOutPassAct, viewJ); if (resultCode != tesSUCCESS) break; STAmount saTakerGetsNew = node().saTakerGets - saOutPassAct; STAmount saTakerPaysNew = node().saTakerPays - saInPassAct; if (saTakerPaysNew < beast::zero || saTakerGetsNew < beast::zero) { JLOG (j_.warn()) << "deliverNodeReverse: NEGATIVE:" << " node().saTakerPaysNew=" << saTakerPaysNew << " node().saTakerGetsNew=" << saTakerGetsNew; resultCode = telFAILED_PROCESSING; break; } node().sleOffer->setFieldAmount (sfTakerGets, saTakerGetsNew); node().sleOffer->setFieldAmount (sfTakerPays, saTakerPaysNew); view().update (node().sleOffer); if (saOutPassAct == node().saTakerGets) { JLOG (j_.debug()) << "deliverNodeReverse: offer became unfunded."; node().bEntryAdvance = true; } else { assert (saOutPassAct < node().saTakerGets); } saOutAct += saOutPassAct; previousNode().saRevDeliver += saInPassAct; } if (saOutAct > saOutReq) { JLOG (j_.warn()) << "deliverNodeReverse: TOO MUCH:" << " saOutAct=" << saOutAct << " saOutReq=" << saOutReq; } assert(saOutAct <= saOutReq); if (resultCode == tesSUCCESS && !saOutAct) resultCode = tecPATH_DRY; JLOG (j_.trace()) << "deliverNodeReverse<" << " saOutAct=" << saOutAct << " saOutReq=" << saOutReq << " saPrvDlvReq=" << previousNode().saRevDeliver; return resultCode; } TER PathCursor::deliverNodeReverse ( AccountID const& uOutAccountID, STAmount const& saOutReq, STAmount& saOutAct ) const { for (int i = nodeIndex_; i >= 0 && !node (i).isAccount(); --i) node (i).directory.restart (multiQuality_); return deliverNodeReverseImpl(uOutAccountID, saOutReq, saOutAct, false); } } }
27.625407
83
0.507605
DEEPSPACE007
090a56c8f9757ef3572a33b3fc745852b5bf2c80
3,071
cc
C++
common_video/vplib/main/test/tester_main.cc
stoiczek/WebRTC
6d8190b8c89b3bee9c5ee9eabbd9d67169449f8c
[ "BSD-3-Clause" ]
1
2017-02-08T09:47:04.000Z
2017-02-08T09:47:04.000Z
common_video/vplib/main/test/tester_main.cc
stoiczek/WebRTC
6d8190b8c89b3bee9c5ee9eabbd9d67169449f8c
[ "BSD-3-Clause" ]
null
null
null
common_video/vplib/main/test/tester_main.cc
stoiczek/WebRTC
6d8190b8c89b3bee9c5ee9eabbd9d67169449f8c
[ "BSD-3-Clause" ]
5
2015-10-30T17:35:19.000Z
2021-06-04T01:39:27.000Z
/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "vplib.h" #include "test_util.h" using namespace webrtc; int ParseArguments(int argc, char **argv, CmdArgs& args) { int i = 1; while (i < argc) { if (argv[i][0] != '-') { return -1; } switch (argv[i][1]) { case 'w': { int w = atoi(argv[i+1]); if (w < 1) return -1; args.width = w; break; } case 'h': { int h = atoi(argv[i+1]); if (h < 1) return -1; args.height = h; break; } case 'x': { int x = atoi(argv[i+1]); if (x < 1) return -1; args.dstWidth = x; break; } case 'y': { int y = atoi(argv[i+1]); if (y < 1) return -1; args.dstHeight = y; break; } case 'm': // interpolation method { int m = atoi(argv[i+1]); if (m < 0) return -1; args.intMethod = m; break; } case 'i': { args.inputFile = argv[i+1]; break; } case 'o': args.outputFile = argv[i+1]; break; case 'n': { int n = atoi(argv[i+1]); if (n < 1) return -1; args.testNum = n; break; } default: return -1; } i += 2; } return 0; } int main(int argc, char **argv) { CmdArgs args; if (ParseArguments(argc, argv, args) != 0) { printf("Unable to parse input arguments\n"); printf("args: -n <test #> -w <width> -h <height> " "-x <destination width> -y <destination height> -f <fps> " "-b <bps> -m <method> -i <input file> -o <output file>\n"); return -1; } int ret = -1; switch (args.testNum) { printf("\n"); case 1: printf("VPLIB Interpolation Test\n"); ret = interpolationTest(args); break; case 2: printf("VPLIB Scale Test\n"); ret = scale_test(); break; case 3: printf("VPLIB Convert Test\n"); ret = convert_test(args); break; default: ret = -1; break; } if (ret != 0) { printf("Test failed!\n"); return -1; } return 0; }
22.91791
74
0.426571
stoiczek
090ddea4a0bf2ef240c18645dfec0add11327364
3,071
hpp
C++
openvxpp/fixed_reference.hpp
Gooeen/openvxpp
699f10531fb3c98ec271cde76abb90e1affbe324
[ "Apache-2.0" ]
null
null
null
openvxpp/fixed_reference.hpp
Gooeen/openvxpp
699f10531fb3c98ec271cde76abb90e1affbe324
[ "Apache-2.0" ]
null
null
null
openvxpp/fixed_reference.hpp
Gooeen/openvxpp
699f10531fb3c98ec271cde76abb90e1affbe324
[ "Apache-2.0" ]
null
null
null
/************************************************************************* * Copyright (c) 2016, Gooeen. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *************************************************************************/ #ifndef __OPENVX_CPP_FIXED_REFERENCE_HPP__ #define __OPENVX_CPP_FIXED_REFERENCE_HPP__ #include <stdexcept> #include "image_data.hpp" namespace ovx { template <typename T> class fixed_reference { public: typedef T type; public: fixed_reference(type &ref) noexcept; fixed_reference(const fixed_reference &ref) noexcept; fixed_reference(type &&) = delete; fixed_reference & operator=(const fixed_reference &rhs) noexcept; type & operator=(const type &image); type & get(void) const noexcept; operator type&() const noexcept; private: T *m_image; }; template <typename T> fixed_reference<T> imfix(T &elem) noexcept; template <typename T> fixed_reference<T> imfix(fixed_reference<T> &x) noexcept; template <typename T> void imfix(const T &&) = delete; } template<typename T> inline ovx::fixed_reference<T>::fixed_reference(type &ref) noexcept : m_image(&ref) { } template<typename T> inline ovx::fixed_reference<T>::fixed_reference(const fixed_reference &ref) noexcept : m_image(ref.m_image) { } template<typename T> inline ovx::fixed_reference<T> & ovx::fixed_reference<T>::operator=(const fixed_reference &rhs) noexcept { m_image = rhs.m_image; return *this; } template<typename T> inline typename ovx::fixed_reference<T>::type & ovx::fixed_reference<T>::operator=(const type &image) { if (image.width() != m_image->width() || image.height() != m_image->height()) { throw std::invalid_argument("Difference size between two images."); } auto planes = image.plane_count(); vx_rectangle_t rect{ 0, 0, image.width(), image.height() }; for (decltype(planes) index = 0; index < planes; ++index) { image_data<void *> data(*m_image, rect, index, VX_WRITE_ONLY); copy_image_data(data, image, index, VX_READ_ONLY); } return *m_image; } template<typename T> inline typename ovx::fixed_reference<T>::type & ovx::fixed_reference<T>::get(void) const noexcept { return *m_image; } template<typename T> inline ovx::fixed_reference<T>::operator type&() const noexcept { return *m_image; } template<typename T> ovx::fixed_reference<T> ovx::imfix(T &elem) noexcept { return fixed_reference<T>(elem); } template<typename T> ovx::fixed_reference<T> ovx::imfix(fixed_reference<T> &x) noexcept { return fixed_reference<T>(x); } #endif // !__OPENVX_CPP_FIXED_REFERENCE_HPP__
24.96748
104
0.702377
Gooeen
091267cf9d8abfbb5c084d94d6e12323bdef8b36
448
cpp
C++
code/error_messages.cpp
ldionne/cppcon-2015-hana
f917c492ff14953bad8d08bd43d53e907ccfb2ee
[ "MIT" ]
5
2015-09-24T15:43:27.000Z
2017-04-15T20:39:35.000Z
code/error_messages.cpp
ldionne/hana-cppcon-2015
f917c492ff14953bad8d08bd43d53e907ccfb2ee
[ "MIT" ]
null
null
null
code/error_messages.cpp
ldionne/hana-cppcon-2015
f917c492ff14953bad8d08bd43d53e907ccfb2ee
[ "MIT" ]
null
null
null
// Copyright Louis Dionne 2015 // Distributed under the Boost Software License, Version 1.0. #include <boost/hana.hpp> #include <boost/mpl/int.hpp> #include <boost/mpl/reverse.hpp> namespace hana = boost::hana; namespace mpl = boost::mpl; #if 0 // sample(error_messages-then) using xs = mpl::reverse<mpl::int_<1>>::type; // end-sample #endif #if 0 // sample(error_messages-now) auto xs = hana::reverse(1); // end-sample #endif int main() { }
17.92
61
0.700893
ldionne
0913d9a9dff27eb13f3f5b7d9f778012f13aa351
2,160
cpp
C++
settings.cpp
appetizerteam/SayCheesePhotoManager
f7871c1fb79f7519662f06223be822992f21363a
[ "Apache-2.0" ]
null
null
null
settings.cpp
appetizerteam/SayCheesePhotoManager
f7871c1fb79f7519662f06223be822992f21363a
[ "Apache-2.0" ]
null
null
null
settings.cpp
appetizerteam/SayCheesePhotoManager
f7871c1fb79f7519662f06223be822992f21363a
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2014 Team APPetizer * Author: Jesse Alas * * 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 "settings.h" #include <QDebug> #include <QDir> SayCheesePhotoManager::Settings::Settings(QObject *parent) : QObject(parent) { this->settings = new QSettings(this); } QString SayCheesePhotoManager::Settings::getPhotosDirectory(bool& ok) const { // Load the standard photo directory. QString defaultPhotosDirectory = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation); // Load the saved photo directory. auto photoDirectory = this->settings->value(PhotosDirectoryKey, defaultPhotosDirectory).toString(); // If no default photo directory exists (is empty) and there is no saved photo directory, // then this method cannot return an proper value. Return a blank line and set ok to false. if (defaultPhotosDirectory.isEmpty()) { qDebug() << "SayCheesePhotoManager::Settings(Could not find suitable photos directory)"; ok = false; // Flags the error. return ""; } ok = true; // Flags that the method found a suitable directory. return photoDirectory; } void SayCheesePhotoManager::Settings::savePhotosDirectory(const QString &photoDirectoryPath) { // Check if the directory exists. If it does not, then print an error to the console and return. QDir photosDir(photoDirectoryPath); if (!photosDir.exists()) { qDebug() << "SayCheesePhotoManager::Settings(Cannot save invalid photo directory:" << photoDirectoryPath << ")"; return; } this->settings->setValue(PhotosDirectoryKey, photosDir.absolutePath()); }
36.610169
120
0.724537
appetizerteam
0913fc3173bec626b6d857c244b97c6af53c38e6
39,042
cpp
C++
src/untrusted/enclave/performance/Measurements.cpp
Artraxon/sgx-radix-hash-join
e23247fb985f621752bb8247874ca0c9f1cce0bc
[ "MIT" ]
null
null
null
src/untrusted/enclave/performance/Measurements.cpp
Artraxon/sgx-radix-hash-join
e23247fb985f621752bb8247874ca0c9f1cce0bc
[ "MIT" ]
null
null
null
src/untrusted/enclave/performance/Measurements.cpp
Artraxon/sgx-radix-hash-join
e23247fb985f621752bb8247874ca0c9f1cce0bc
[ "MIT" ]
null
null
null
/** * @author Claude Barthels <claudeb@inf.ethz.ch> * (c) 2016, ETH Zurich, Systems Group * */ #include "Measurements.h" #include "Enclave_u.h" #include <app/App.h> #define MSG_TAG_RESULTS 154895 #include <core/Configuration.h> #include <utils/Debug.h> #include <data/Tuple.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <mpi.h> #include <unistd.h> #include <papi.h> #include <sys/stat.h> struct timeval hpcjoin::performance::Measurements::joinStart; struct timeval hpcjoin::performance::Measurements::joinStop; struct timeval hpcjoin::performance::Measurements::histogramComputationStart; struct timeval hpcjoin::performance::Measurements::histogramComputationStop; struct timeval hpcjoin::performance::Measurements::networkPartitioningStart; struct timeval hpcjoin::performance::Measurements::networkPartitioningStop; struct timeval hpcjoin::performance::Measurements::localProcessingStart; struct timeval hpcjoin::performance::Measurements::localProcessingStop; struct timeval hpcjoin::performance::Measurements::windowAllocationStart; struct timeval hpcjoin::performance::Measurements::windowAllocationStop; struct timeval hpcjoin::performance::Measurements::waitingForNetworkCompletionStart; struct timeval hpcjoin::performance::Measurements::waitingForNetworkCompletionStop; struct timeval hpcjoin::performance::Measurements::localProcessingPreparationsStart; struct timeval hpcjoin::performance::Measurements::localProcessingPreparationsStop; struct timeval hpcjoin::performance::Measurements::unsealingStart; struct timeval hpcjoin::performance::Measurements::unsealingStop; struct timeval hpcjoin::performance::Measurements::histogramLocalHistogramComputationStart; struct timeval hpcjoin::performance::Measurements::histogramLocalHistogramComputationStop; struct timeval hpcjoin::performance::Measurements::histogramGlobalHistogramComputationStart; struct timeval hpcjoin::performance::Measurements::histogramGlobalHistogramComputationStop; struct timeval hpcjoin::performance::Measurements::histogramAssignmentStart; struct timeval hpcjoin::performance::Measurements::histogramAssignmentStop; struct timeval hpcjoin::performance::Measurements::histogramOffsetComputationStart; struct timeval hpcjoin::performance::Measurements::histogramOffsetComputationStop; struct timeval hpcjoin::performance::Measurements::histogramLocalSgxHistogramComputationStart; struct timeval hpcjoin::performance::Measurements::histogramLocalSgxHistogramComputationStop; struct timeval hpcjoin::performance::Measurements::histogramGlobalSgxHistogramComputationStart; struct timeval hpcjoin::performance::Measurements::histogramGlobalSgxHistogramComputationStop; struct timeval hpcjoin::performance::Measurements::histogramSgxOffsetComputationStart; struct timeval hpcjoin::performance::Measurements::histogramSgxOffsetComputationStop; struct timeval hpcjoin::performance::Measurements::networkPartitioningMemoryAllocationStart; struct timeval hpcjoin::performance::Measurements::networkPartitioningMemoryAllocationStop; struct timeval hpcjoin::performance::Measurements::networkPartitioningMainPartitioningStart; struct timeval hpcjoin::performance::Measurements::networkPartitioningMainPartitioningStop; struct timeval hpcjoin::performance::Measurements::networkPartitioningFlushPartitioningStart; struct timeval hpcjoin::performance::Measurements::networkPartitioningFlushPartitioningStop; struct timeval hpcjoin::performance::Measurements::networkPartitioningWindowPutStart; struct timeval hpcjoin::performance::Measurements::networkPartitioningWindowPutStop; struct timeval hpcjoin::performance::Measurements::networkPartitioningWindowWaitStart; struct timeval hpcjoin::performance::Measurements::networkPartitioningWindowWaitStop; struct timeval hpcjoin::performance::Measurements::networkPartitioningWindowSealStart; struct timeval hpcjoin::performance::Measurements::networkPartitioningWindowSealStop; struct timeval hpcjoin::performance::Measurements::localPartitioningTaskStart; struct timeval hpcjoin::performance::Measurements::localPartitioningTaskStop; struct timeval hpcjoin::performance::Measurements::localPartitioningHistogramComputationStart; struct timeval hpcjoin::performance::Measurements::localPartitioningHistogramComputationStop; struct timeval hpcjoin::performance::Measurements::localPartitioningOffsetComputationStart; struct timeval hpcjoin::performance::Measurements::localPartitioningOffsetComputationStop; struct timeval hpcjoin::performance::Measurements::localPartitioningMemoryAllocationStart; struct timeval hpcjoin::performance::Measurements::localPartitioningMemoryAllocationStop; struct timeval hpcjoin::performance::Measurements::localPartitioningPartitioningStart; struct timeval hpcjoin::performance::Measurements::localPartitioningPartitioningStop; struct timeval hpcjoin::performance::Measurements::buildProbeTaskStart; struct timeval hpcjoin::performance::Measurements::buildProbeTaskStop; struct timeval hpcjoin::performance::Measurements::buildProbeMemoryAllocationStart; struct timeval hpcjoin::performance::Measurements::buildProbeMemoryAllocationStop; struct timeval hpcjoin::performance::Measurements::buildProbeBuildStart; struct timeval hpcjoin::performance::Measurements::buildProbeBuildStop; struct timeval hpcjoin::performance::Measurements::buildProbeProbeStart; struct timeval hpcjoin::performance::Measurements::buildProbeProbeStop; uint64_t ** hpcjoin::performance::Measurements::serizlizedResults; namespace hpcjoin { namespace performance { /************************************************************/ uint64_t Measurements::resultCounter; uint64_t Measurements::totalCycles; uint64_t Measurements::totalTime; uint64_t Measurements::phaseTimes[3]; void Measurements::saveResultCounter(uint64_t counter){ resultCounter = counter; } void Measurements::startJoin() { gettimeofday(&joinStart, NULL); int event = PAPI_TOT_CYC; PAPI_start_counters(&event, 1); } void Measurements::stopJoin() { gettimeofday(&joinStop, NULL); totalTime = timeDiff(joinStop, joinStart); long_long value; int ret = 0; if ((ret = PAPI_stop_counters(&value, 1)) != PAPI_OK) { value = 0; } totalCycles = value; } void Measurements::startHistogramComputation() { gettimeofday(&histogramComputationStart, NULL); } void Measurements::stopHistogramComputation() { gettimeofday(&histogramComputationStop, NULL); phaseTimes[0] = timeDiff(histogramComputationStop, histogramComputationStart); } void Measurements::startNetworkPartitioning() { gettimeofday(&networkPartitioningStart, NULL); } void Measurements::stopNetworkPartitioning() { gettimeofday(&networkPartitioningStop, NULL); phaseTimes[1] = timeDiff(networkPartitioningStop, networkPartitioningStart); } void Measurements::startLocalProcessing() { gettimeofday(&localProcessingStart, NULL); } void Measurements::stopLocalProcessing() { gettimeofday(&localProcessingStop, NULL); phaseTimes[2] = timeDiff(localProcessingStop, localProcessingStart); } void Measurements::storePhaseData() { fprintf(performanceOutputFile, "CTOTAL\t%lu\tcycles\n", totalCycles); fprintf(performanceOutputFile, "JTOTAL\t%lu\tus\n", totalTime); fprintf(performanceOutputFile, "JHIST\t%lu\tus\n", phaseTimes[0]); fprintf(performanceOutputFile, "JMPI\t%lu\tus\n", phaseTimes[1]); fprintf(performanceOutputFile, "JPROC\t%lu\tus\n", phaseTimes[2]); } /************************************************************/ uint64_t Measurements::specialTimes[4]; void Measurements::startWindowAllocation() { gettimeofday(&windowAllocationStart, NULL); } void Measurements::stopWindowAllocation() { gettimeofday(&windowAllocationStop, NULL); specialTimes[0] = timeDiff(windowAllocationStop, windowAllocationStart); } void Measurements::startWaitingForNetworkCompletion() { gettimeofday(&waitingForNetworkCompletionStart, NULL); } void Measurements::stopWaitingForNetworkCompletion() { gettimeofday(&waitingForNetworkCompletionStop, NULL); specialTimes[1] = timeDiff(waitingForNetworkCompletionStop, waitingForNetworkCompletionStart); } void Measurements::startLocalProcessingPreparations() { gettimeofday(&localProcessingPreparationsStart, NULL); } void Measurements::stopLocalProcessingPreparations() { gettimeofday(&localProcessingPreparationsStop, NULL); specialTimes[2] = timeDiff(localProcessingPreparationsStop, localProcessingPreparationsStart); } void Measurements::startUnsealing(){ gettimeofday(&unsealingStart, NULL); } void Measurements::stopUnsealing(){ gettimeofday(&unsealingStop, NULL); specialTimes[3] = timeDiff(unsealingStop, unsealingStart); } void Measurements::storeSpecialData() { fprintf(performanceOutputFile, "SWINALLOC\t%lu\tus\n", specialTimes[0]); fprintf(performanceOutputFile, "SNETCOMPL\t%lu\tus\n", specialTimes[1]); fprintf(performanceOutputFile, "SLOCPREP\t%lu\tus\n", specialTimes[2]); fprintf(performanceOutputFile, "SUNSEAL\t%lu\tus\n", specialTimes[3]); } /************************************************************/ uint64_t Measurements::histogramLocalHistogramComputationIdx = 0; uint64_t Measurements::histogramLocalHistogramComputationTimes[2]; uint64_t Measurements::histogramLocalHistogramComputationElements[2]; uint64_t Measurements::histogramGlobalHistogramComputationIdx = 0; uint64_t Measurements::histogramGlobalHistogramComputationTimes[2]; uint64_t Measurements::histogramAssignmentComputationTime; uint64_t Measurements::histogramOffsetComputationIdx = 0; uint64_t Measurements::histogramOffsetComputationTimes[2]; void Measurements::startHistogramLocalHistogramComputation() { gettimeofday(&histogramLocalHistogramComputationStart, NULL); } void Measurements::stopHistogramLocalHistogramComputation(uint64_t numberOfElemenets) { gettimeofday(&histogramLocalHistogramComputationStop, NULL); uint64_t time = timeDiff(histogramLocalHistogramComputationStop, histogramLocalHistogramComputationStart); JOIN_ASSERT(histogramLocalHistogramComputationIdx < 2, "Performance", "Index out of bounds"); histogramLocalHistogramComputationTimes[histogramLocalHistogramComputationIdx] = time; histogramLocalHistogramComputationElements[histogramLocalHistogramComputationIdx] = numberOfElemenets; ++histogramLocalHistogramComputationIdx; } void Measurements::startHistogramGlobalHistogramComputation() { gettimeofday(&histogramGlobalHistogramComputationStart, NULL); } void Measurements::stopHistogramGlobalHistogramComputation() { gettimeofday(&histogramGlobalHistogramComputationStop, NULL); uint64_t time = timeDiff(histogramGlobalHistogramComputationStop, histogramGlobalHistogramComputationStart); JOIN_ASSERT(histogramGlobalHistogramComputationIdx < 2, "Performance", "Index out of bounds"); histogramGlobalHistogramComputationTimes[histogramGlobalHistogramComputationIdx] = time; ++histogramGlobalHistogramComputationIdx; } void Measurements::startHistogramAssignmentComputation() { gettimeofday(&histogramAssignmentStart, NULL); } void Measurements::stopHistogramAssignmentComputation() { gettimeofday(&histogramAssignmentStop, NULL); histogramAssignmentComputationTime = timeDiff(histogramAssignmentStop, histogramAssignmentStop); } void Measurements::startHistogramOffsetComputation() { gettimeofday(&histogramOffsetComputationStart, NULL); } void Measurements::stopHistogramOffsetComputation() { gettimeofday(&histogramOffsetComputationStop, NULL); uint64_t time = timeDiff(histogramOffsetComputationStop, histogramOffsetComputationStart); JOIN_ASSERT(histogramOffsetComputationIdx < 2, "Performance", "Index out of bounds"); histogramOffsetComputationTimes[histogramOffsetComputationIdx] = time; ++histogramOffsetComputationIdx; } void Measurements::storeHistogramComputationData() { fprintf(performanceOutputFile, "HILOCAL\t%lu\tus\n", histogramLocalHistogramComputationTimes[0]); fprintf(performanceOutputFile, "HOLOCELEM\t%lu\ttuples\n", histogramLocalHistogramComputationElements[0]); fprintf(performanceOutputFile, "HILOCRATE\t%.2f\tMbytes/sec\n", ((double) histogramLocalHistogramComputationElements[0] * sizeof(hpcjoin::data::Tuple)) / histogramLocalHistogramComputationTimes[0]); fprintf(performanceOutputFile, "HOLOCAL\t%lu\tus\n", histogramLocalHistogramComputationTimes[1]); fprintf(performanceOutputFile, "HOLOCELEM\t%lu\ttuples\n", histogramLocalHistogramComputationElements[1]); fprintf(performanceOutputFile, "HOLOCRATE\t%.2f\tMbytes/sec\n", ((double) histogramLocalHistogramComputationElements[1] * sizeof(hpcjoin::data::Tuple)) / histogramLocalHistogramComputationTimes[1]); fprintf(performanceOutputFile, "HIGLOBAL\t%lu\tus\n", histogramGlobalHistogramComputationTimes[0]); fprintf(performanceOutputFile, "HOGLOBAL\t%lu\tus\n", histogramGlobalHistogramComputationTimes[1]); fprintf(performanceOutputFile, "HASSIGN\t%lu\tus\n", histogramAssignmentComputationTime); fprintf(performanceOutputFile, "HIOFFCOMP\t%lu\tus\n", histogramOffsetComputationTimes[0]); fprintf(performanceOutputFile, "HOOFFCOMP\t%lu\tus\n", histogramOffsetComputationTimes[1]); } /************************************************************/ uint64_t Measurements::histogramLocalSgxHistogramComputationIdx = 0; uint64_t Measurements::histogramLocalSgxHistogramComputationTimes[2]; uint64_t Measurements::histogramLocalSgxHistogramComputationElements[2]; uint64_t Measurements::histogramGlobalSgxHistogramComputationIdx = 0; uint64_t Measurements::histogramGlobalSgxHistogramComputationTimes[2]; uint64_t Measurements::histogramSgxOffsetComputationIdx = 0; uint64_t Measurements::histogramSgxOffsetComputationTimes[2]; void Measurements::startSgxHistogramLocalSgxHistogramComputation() { gettimeofday(&histogramLocalSgxHistogramComputationStart, NULL); } void Measurements::stopSgxHistogramLocalSgxHistogramComputation(uint64_t numberOfElemenets) { gettimeofday(&histogramLocalSgxHistogramComputationStop, NULL); uint64_t time = timeDiff(histogramLocalSgxHistogramComputationStop, histogramLocalSgxHistogramComputationStart); JOIN_ASSERT(histogramLocalSgxHistogramComputationIdx < 2, "Performance", "Index out of bounds"); histogramLocalSgxHistogramComputationTimes[histogramLocalSgxHistogramComputationIdx] = time; histogramLocalSgxHistogramComputationElements[histogramLocalSgxHistogramComputationIdx] = numberOfElemenets; ++histogramLocalSgxHistogramComputationIdx; } void Measurements::startSgxHistogramGlobalSgxHistogramComputation() { gettimeofday(&histogramGlobalSgxHistogramComputationStart, NULL); } void Measurements::stopSgxHistogramGlobalSgxHistogramComputation() { gettimeofday(&histogramGlobalSgxHistogramComputationStop, NULL); uint64_t time = timeDiff(histogramGlobalSgxHistogramComputationStop, histogramGlobalSgxHistogramComputationStart); JOIN_ASSERT(histogramGlobalSgxHistogramComputationIdx < 2, "Performance", "Index out of bounds"); histogramGlobalSgxHistogramComputationTimes[histogramGlobalSgxHistogramComputationIdx] = time; ++histogramGlobalSgxHistogramComputationIdx; } void Measurements::startSgxHistogramOffsetComputation() { gettimeofday(&histogramSgxOffsetComputationStart, NULL); } void Measurements::stopSgxHistogramOffsetComputation() { gettimeofday(&histogramSgxOffsetComputationStop, NULL); uint64_t time = timeDiff(histogramSgxOffsetComputationStop, histogramSgxOffsetComputationStart); JOIN_ASSERT(histogramSgxOffsetComputationIdx < 2, "Performance", "Index out of bounds"); histogramSgxOffsetComputationTimes[histogramSgxOffsetComputationIdx] = time; ++histogramSgxOffsetComputationIdx; } void Measurements::storeSgxHistogramComputationData() { fprintf(performanceOutputFile, "HSGXILOCAL\t%lu\tus\n", histogramLocalSgxHistogramComputationTimes[0]); fprintf(performanceOutputFile, "HSGXOLOCELEM\t%lu\ttuples\n", histogramLocalSgxHistogramComputationElements[0]); fprintf(performanceOutputFile, "HSGXILOCRATE\t%.2f\tMbytes/sec\n", ((double) histogramLocalSgxHistogramComputationElements[0]) / histogramLocalSgxHistogramComputationTimes[0]); fprintf(performanceOutputFile, "HSGXOLOCAL\t%lu\tus\n", histogramLocalSgxHistogramComputationTimes[1]); fprintf(performanceOutputFile, "HSGXOLOCELEM\t%lu\ttuples\n", histogramLocalSgxHistogramComputationElements[1]); fprintf(performanceOutputFile, "HSGXOLOCRATE\t%.2f\tMbytes/sec\n", ((double) histogramLocalSgxHistogramComputationElements[1]) / histogramLocalSgxHistogramComputationTimes[1]); fprintf(performanceOutputFile, "HSGXIGLOBAL\t%lu\tus\n", histogramGlobalSgxHistogramComputationTimes[0]); fprintf(performanceOutputFile, "HSGXOGLOBAL\t%lu\tus\n", histogramGlobalSgxHistogramComputationTimes[1]); fprintf(performanceOutputFile, "HSGXIOFFCOMP\t%lu\tus\n", histogramSgxOffsetComputationTimes[0]); fprintf(performanceOutputFile, "HSGXOOFFCOMP\t%lu\tus\n", histogramSgxOffsetComputationTimes[1]); } /************************************************************/ uint64_t Measurements::networkPartitioningMemoryAllocationIdx = 0; uint64_t Measurements::networkPartitioningMemoryAllocationTimes[2]; uint64_t Measurements::networkPartitioningMainPartitioningIdx = 0; uint64_t Measurements::networkPartitioningMainPartitioningTimes[2]; uint64_t Measurements::networkPartitioningFlushPartitioningIdx = 0; uint64_t Measurements::networkPartitioningFlushPartitioningTimes[2]; uint64_t Measurements::networkPartitioningWindowPutCount = 0; uint64_t Measurements::networkPartitioningWindowPutTimeSum = 0; uint64_t Measurements::networkPartitioningWindowWaitCount = 0; uint64_t Measurements::networkPartitioningWindowWaitTimeSum = 0; uint64_t Measurements::networkPartitioningWindowSealCount = 0; uint64_t Measurements::networkPartitioningWindowSealTime = 0; void Measurements::startNetworkPartitioningMemoryAllocation() { gettimeofday(&networkPartitioningMemoryAllocationStart, NULL); } void Measurements::stopNetworkPartitioningMemoryAllocation(uint64_t numberOfElemenets) { gettimeofday(&networkPartitioningMemoryAllocationStop, NULL); uint64_t time = timeDiff(networkPartitioningMemoryAllocationStop, networkPartitioningMemoryAllocationStart); JOIN_ASSERT(networkPartitioningMemoryAllocationIdx < 2, "Performance", "Index out of bounds"); networkPartitioningMemoryAllocationTimes[networkPartitioningMemoryAllocationIdx] = time; ++networkPartitioningMemoryAllocationIdx; } void Measurements::startNetworkPartitioningMainPartitioning() { gettimeofday(&networkPartitioningMainPartitioningStart, NULL); } void Measurements::stopNetworkPartitioningMainPartitioning(uint64_t numberOfElemenets) { gettimeofday(&networkPartitioningMainPartitioningStop, NULL); uint64_t time = timeDiff(networkPartitioningMainPartitioningStop, networkPartitioningMainPartitioningStart); JOIN_ASSERT(networkPartitioningMainPartitioningIdx < 2, "Performance", "Index out of bounds"); networkPartitioningMainPartitioningTimes[networkPartitioningMainPartitioningIdx] = time; ++networkPartitioningMainPartitioningIdx; } void Measurements::startNetworkPartitioningFlushPartitioning() { gettimeofday(&networkPartitioningFlushPartitioningStart, NULL); } void Measurements::stopNetworkPartitioningFlushPartitioning() { gettimeofday(&networkPartitioningFlushPartitioningStop, NULL); uint64_t time = timeDiff(networkPartitioningFlushPartitioningStop, networkPartitioningFlushPartitioningStart); JOIN_ASSERT(networkPartitioningFlushPartitioningIdx < 2, "Performance", "Index out of bounds"); networkPartitioningFlushPartitioningTimes[networkPartitioningFlushPartitioningIdx] = time; ++networkPartitioningFlushPartitioningIdx; } void Measurements::startNetworkPartitioningWindowPut() { gettimeofday(&networkPartitioningWindowPutStart, NULL); } void Measurements::stopNetworkPartitioningWindowPut() { gettimeofday(&networkPartitioningWindowPutStop, NULL); uint64_t time = timeDiff(networkPartitioningWindowPutStop, networkPartitioningWindowPutStart); networkPartitioningWindowPutTimeSum += time; ++networkPartitioningWindowPutCount; } void Measurements::startNetworkPartitioningWindowWait() { gettimeofday(&networkPartitioningWindowWaitStart, NULL); } void Measurements::stopNetworkPartitioningWindowWait() { gettimeofday(&networkPartitioningWindowWaitStop, NULL); uint64_t time = timeDiff(networkPartitioningWindowWaitStop, networkPartitioningWindowWaitStart); networkPartitioningWindowWaitTimeSum += time; ++networkPartitioningWindowWaitCount; } void Measurements::startNetworkPartitioningSealing(){ gettimeofday(&networkPartitioningWindowSealStart, NULL); } void Measurements::stopNetworkPartitioningSealing(){ gettimeofday(&networkPartitioningWindowSealStop, NULL); uint64_t time = timeDiff(networkPartitioningWindowSealStop, networkPartitioningWindowSealStart); networkPartitioningWindowSealTime += time; ++networkPartitioningWindowSealCount; } void Measurements::storeNetworkPartitioningData() { fprintf(performanceOutputFile, "MIMEMALLOC\t%lu\tus\n", networkPartitioningMemoryAllocationTimes[0]); fprintf(performanceOutputFile, "MIMAINPART\t%lu\tus\n", networkPartitioningMainPartitioningTimes[0]); fprintf(performanceOutputFile, "MIFLUSHPART\t%lu\tus\n", networkPartitioningFlushPartitioningTimes[0]); fprintf(performanceOutputFile, "MOMEMALLOC\t%lu\tus\n", networkPartitioningMemoryAllocationTimes[1]); fprintf(performanceOutputFile, "MOMAINPART\t%lu\tus\n", networkPartitioningMainPartitioningTimes[1]); fprintf(performanceOutputFile, "MOFLUSHPART\t%lu\tus\n", networkPartitioningFlushPartitioningTimes[1]); fprintf(performanceOutputFile, "MWINPUT\t%lu\tus\n", networkPartitioningWindowPutTimeSum); fprintf(performanceOutputFile, "MWINPUTCNT\t%lu\tcalls\n", networkPartitioningWindowPutCount); fprintf(performanceOutputFile, "MWINWAIT\t%lu\tus\n", networkPartitioningWindowWaitTimeSum); fprintf(performanceOutputFile, "MWINWAITCNT\t%lu\tcalls\n", networkPartitioningWindowWaitCount); fprintf(performanceOutputFile, "MWSEAL\t%lu\tus\n", networkPartitioningWindowSealTime); fprintf(performanceOutputFile, "MWSEALCNT\t%lu\tcalls\n", networkPartitioningWindowSealCount); } /************************************************************/ uint64_t Measurements::localPartitioningTaskCount = 0; uint64_t Measurements::localPartitioningTaskTimeSum = 0; uint64_t Measurements::localPartitioningHistogramComputationCount = 0; uint64_t Measurements::localPartitioningHistogramComputationTimeSum = 0; uint64_t Measurements::localPartitioningHistogramComputationElementSum = 0; uint64_t Measurements::localPartitioningOffsetComputationCount = 0; uint64_t Measurements::localPartitioningOffsetComputationTimeSum = 0; uint64_t Measurements::localPartitioningMemoryAllocationCount = 0; uint64_t Measurements::localPartitioningMemoryAllocationTimeSum = 0; uint64_t Measurements::localPartitioningMemoryAllocationSizeSum = 0; uint64_t Measurements::localPartitioningPartitioningCount = 0; uint64_t Measurements::localPartitioningPartitioningTimeSum = 0; uint64_t Measurements::localPartitioningPartitioningElementSum = 0; void Measurements::startLocalPartitioningTask() { gettimeofday(&localPartitioningTaskStart, NULL); } void Measurements::stopLocalPartitioningTask() { gettimeofday(&localPartitioningTaskStop, NULL); uint64_t time = timeDiff(localPartitioningTaskStop, localPartitioningTaskStart); localPartitioningTaskTimeSum += time; ++localPartitioningTaskCount; } void Measurements::startLocalPartitioningHistogramComputation() { gettimeofday(&localPartitioningHistogramComputationStart, NULL); } void Measurements::stopLocalPartitioningHistogramComputation(uint64_t numberOfElemenets) { gettimeofday(&localPartitioningHistogramComputationStop, NULL); uint64_t time = timeDiff(localPartitioningHistogramComputationStop, localPartitioningHistogramComputationStart); localPartitioningHistogramComputationTimeSum += time; ++localPartitioningHistogramComputationCount; localPartitioningHistogramComputationElementSum += numberOfElemenets; } void Measurements::startLocalPartitioningOffsetComputation() { gettimeofday(&localPartitioningOffsetComputationStart, NULL); } void Measurements::stopLocalPartitioningOffsetComputation() { gettimeofday(&localPartitioningOffsetComputationStop, NULL); uint64_t time = timeDiff(localPartitioningOffsetComputationStop, localPartitioningOffsetComputationStart); localPartitioningOffsetComputationTimeSum += time; ++localPartitioningOffsetComputationCount; } void Measurements::startLocalPartitioningMemoryAllocation() { gettimeofday(&localPartitioningMemoryAllocationStart, NULL); } void Measurements::stopLocalPartitioningMemoryAllocation(uint64_t bufferSize) { gettimeofday(&localPartitioningMemoryAllocationStop, NULL); uint64_t time = timeDiff(localPartitioningMemoryAllocationStop, localPartitioningMemoryAllocationStart); localPartitioningMemoryAllocationTimeSum += time; ++localPartitioningMemoryAllocationCount; localPartitioningMemoryAllocationSizeSum += bufferSize; } void Measurements::startLocalPartitioningPartitioning() { gettimeofday(&localPartitioningPartitioningStart, NULL); } void Measurements::stopLocalPartitioningPartitioning(uint64_t numberOfElemenets) { gettimeofday(&localPartitioningPartitioningStop, NULL); uint64_t time = timeDiff(localPartitioningPartitioningStop, localPartitioningPartitioningStart); localPartitioningPartitioningTimeSum += time; ++localPartitioningPartitioningCount; localPartitioningPartitioningElementSum += numberOfElemenets; } void Measurements::storeLocalPartitioningData() { fprintf(performanceOutputFile, "LPTASKTIME\t%lu\tus\n", localPartitioningTaskTimeSum); fprintf(performanceOutputFile, "LPTASKCOUNT\t%lu\ttasks\n", localPartitioningTaskCount); fprintf(performanceOutputFile, "LPHISTCOMP\t%lu\tus\n", localPartitioningHistogramComputationTimeSum); fprintf(performanceOutputFile, "LPHISTELEM\t%lu\ttuples\n", localPartitioningHistogramComputationElementSum); fprintf(performanceOutputFile, "LPOFFSET\t%lu\tus\n", localPartitioningOffsetComputationTimeSum); fprintf(performanceOutputFile, "LPMEMALLOC\t%lu\tus\n", localPartitioningMemoryAllocationTimeSum); fprintf(performanceOutputFile, "LPMEMSIZE\t%lu\tbytes\n", localPartitioningMemoryAllocationSizeSum); fprintf(performanceOutputFile, "LPPART\t%lu\tus\n", localPartitioningPartitioningTimeSum); fprintf(performanceOutputFile, "LPELEMENTS\t%lu\ttuples\n", localPartitioningPartitioningElementSum); } /************************************************************/ uint64_t Measurements::buildProbeTaskCount = 0; uint64_t Measurements::buildProbeTaskTimeSum = 0; uint64_t Measurements::buildProbeMemoryAllocationCount = 0; uint64_t Measurements::buildProbeMemoryAllocationTimeSum = 0; uint64_t Measurements::buildProbeMemoryAllocationSizeSum = 0; uint64_t Measurements::buildProbeBuildCount = 0; uint64_t Measurements::buildProbeBuildTimeSum = 0; uint64_t Measurements::buildProbeBuildElementSum = 0; uint64_t Measurements::buildProbeProbeCount = 0; uint64_t Measurements::buildProbeProbeTimeSum = 0; uint64_t Measurements::buildProbeProbeElementSum = 0; void Measurements::startBuildProbeTask() { gettimeofday(&buildProbeTaskStart, NULL); } void Measurements::stopBuildProbeTask() { gettimeofday(&buildProbeTaskStop, NULL); uint64_t time = timeDiff(buildProbeTaskStop, buildProbeTaskStart); buildProbeTaskTimeSum += time; ++buildProbeTaskCount; } void Measurements::startBuildProbeMemoryAllocation() { gettimeofday(&buildProbeMemoryAllocationStart, NULL); } void Measurements::stopBuildProbeMemoryAllocation(uint64_t bufferSize) { gettimeofday(&buildProbeMemoryAllocationStop, NULL); uint64_t time = timeDiff(buildProbeMemoryAllocationStop, buildProbeMemoryAllocationStart); buildProbeMemoryAllocationTimeSum += time; ++buildProbeMemoryAllocationCount; buildProbeMemoryAllocationSizeSum += bufferSize; } void Measurements::startBuildProbeBuild() { gettimeofday(&buildProbeBuildStart, NULL); } void Measurements::stopBuildProbeBuild(uint64_t numberOfElemenets) { gettimeofday(&buildProbeBuildStop, NULL); uint64_t time = timeDiff(buildProbeBuildStop, buildProbeBuildStart); buildProbeBuildTimeSum += time; ++buildProbeBuildCount; buildProbeBuildElementSum += numberOfElemenets; } void Measurements::startBuildProbeProbe() { gettimeofday(&buildProbeProbeStart, NULL); } void Measurements::stopBuildProbeProbe(uint64_t numberOfElemenets) { gettimeofday(&buildProbeProbeStop, NULL); uint64_t time = timeDiff(buildProbeProbeStop, buildProbeProbeStart); buildProbeProbeTimeSum += time; ++buildProbeProbeCount; buildProbeProbeElementSum += numberOfElemenets; } void Measurements::storeBuildProbeData() { fprintf(performanceOutputFile, "BPTASKTIME\t%lu\tus\n", buildProbeTaskTimeSum); fprintf(performanceOutputFile, "BPTASKCOUNT\t%lu\ttasks\n", buildProbeTaskCount); fprintf(performanceOutputFile, "BPMEMALLOC\t%lu\tus\n", buildProbeMemoryAllocationTimeSum); fprintf(performanceOutputFile, "BPMEMSIZE\t%lu\tbytes\n", buildProbeMemoryAllocationSizeSum); fprintf(performanceOutputFile, "BPBUILD\t%lu\tus\n", buildProbeBuildTimeSum); fprintf(performanceOutputFile, "BPBUILDELEM\t%lu\ttuples\n", buildProbeBuildElementSum); fprintf(performanceOutputFile, "BPPROBE\t%lu\tus\n", buildProbeProbeTimeSum); fprintf(performanceOutputFile, "BPPROBEELEM\t%lu\ttuples\n", buildProbeProbeElementSum); } /************************************************************/ #define NUM_OF_RESULT_ELEMENTS 10 uint64_t* Measurements::serializeResults() { uint64_t *result = (uint64_t *) calloc(NUM_OF_RESULT_ELEMENTS, sizeof(uint64_t)); //ecall_getResultCounter(global_eid, result); result[0] = resultCounter; result[1] = totalTime; result[2] = phaseTimes[0]; result[3] = phaseTimes[1]; result[4] = phaseTimes[2]; result[5] = specialTimes[0]; result[6] = specialTimes[1]; result[7] = specialTimes[2]; result[8] = localPartitioningTaskTimeSum; result[9] = buildProbeTaskTimeSum; return result; } void Measurements::sendMeasurementsToAggregator() { uint32_t resultSize = NUM_OF_RESULT_ELEMENTS * sizeof(uint64_t); uint64_t *results = serializeResults(); MPI_Send(results, resultSize, MPI_BYTE, hpcjoin::core::Configuration::RESULT_AGGREGATION_NODE, MSG_TAG_RESULTS, MPI_COMM_WORLD); } void Measurements::receiveAllMeasurements(uint32_t numberOfNodes, uint32_t nodeId) { serizlizedResults = new uint64_t*[numberOfNodes]; for (uint32_t n = 0; n < numberOfNodes; ++n) { if (n == nodeId) { serizlizedResults[n] = serializeResults(); } else { uint32_t resultSize = NUM_OF_RESULT_ELEMENTS * sizeof(uint64_t); serizlizedResults[n] = (uint64_t *) calloc(resultSize, 1); MPI_Recv(serizlizedResults[n], resultSize, MPI_BYTE, n, MSG_TAG_RESULTS, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } } } void Measurements::printMeasurements(uint32_t numberOfNodes, uint32_t nodeId) { JOIN_ASSERT(nodeId == hpcjoin::core::Configuration::RESULT_AGGREGATION_NODE, "Measurements", "Only coordinator should print results"); receiveAllMeasurements(numberOfNodes, nodeId); printf("[RESULTS] Tuples:\t"); uint64_t totalNumberOfTuples = 0; for (uint32_t n = 0; n < numberOfNodes; ++n) { uint64_t numberOfTuples = serizlizedResults[n][0]; printf("%lu\t", numberOfTuples); totalNumberOfTuples += numberOfTuples; } printf("\n"); printf("[RESULTS] Join:\t"); uint64_t averageJoinTime = 0; for (uint32_t n = 0; n < numberOfNodes; ++n) { uint64_t joinTime = serizlizedResults[n][1]; printf("%.3f\t", ((double) joinTime) / 1000); averageJoinTime += joinTime; } printf("\n"); averageJoinTime /= numberOfNodes; printf("[RESULTS] Histogram:\t");\ uint64_t averageHistogramTime = 0; for (uint32_t n = 0; n < numberOfNodes; ++n) { uint64_t histogramTime = serizlizedResults[n][2]; printf("%.3f\t", ((double) histogramTime) / 1000); averageHistogramTime += histogramTime; } printf("\n"); averageHistogramTime /= numberOfNodes; printf("[RESULTS] Network:\t"); uint64_t averageNetworkTime = 0; for (uint32_t n = 0; n < numberOfNodes; ++n) { uint64_t networkTime = serizlizedResults[n][3]; printf("%.3f\t", ((double) networkTime) / 1000); averageNetworkTime += networkTime; } printf("\n"); averageNetworkTime /= numberOfNodes; printf("[RESULTS] Local:\t"); uint64_t averageLocalTime = 0; for (uint32_t n = 0; n < numberOfNodes; ++n) { uint64_t localTime = serizlizedResults[n][4]; printf("%.3f\t", ((double) localTime) / 1000); averageLocalTime += localTime; } printf("\n"); averageLocalTime /= numberOfNodes; printf("[RESULTS] WinAlloc:\t"); uint64_t averageWindowAllocTime = 0; for (uint32_t n = 0; n < numberOfNodes; ++n) { uint64_t windowAllocTime = serizlizedResults[n][5]; printf("%.3f\t", ((double) windowAllocTime) / 1000); averageWindowAllocTime += windowAllocTime; } printf("\n"); averageWindowAllocTime /= numberOfNodes; printf("[RESULTS] PartWait:\t"); uint64_t averagePartitionWaitingTime = 0; for (uint32_t n = 0; n < numberOfNodes; ++n) { uint64_t partitionWaitingTime = serizlizedResults[n][6]; printf("%.3f\t", ((double) partitionWaitingTime) / 1000); averagePartitionWaitingTime += partitionWaitingTime; } printf("\n"); averagePartitionWaitingTime /= numberOfNodes; printf("[RESULTS] LocalPrep:\t"); uint64_t averageLocalPreparationTime = 0; for (uint32_t n = 0; n < numberOfNodes; ++n) { uint64_t localPreparationTime = serizlizedResults[n][7]; printf("%.3f\t", ((double) localPreparationTime) / 1000); averageLocalPreparationTime += localPreparationTime; } printf("\n"); averageLocalPreparationTime /= numberOfNodes; printf("[RESULTS] LocalPart:\t"); uint64_t averageLocalPartitioningTime = 0; for (uint32_t n = 0; n < numberOfNodes; ++n) { uint64_t localPartitioningTime = serizlizedResults[n][8]; printf("%.3f\t", ((double) localPartitioningTime) / 1000); averageLocalPartitioningTime += localPartitioningTime; } printf("\n"); averageLocalPartitioningTime /= numberOfNodes; printf("[RESULTS] LocalBP:\t"); uint64_t averageLocalBuildProbeTime = 0; for (uint32_t n = 0; n < numberOfNodes; ++n) { uint64_t localBuildProbeTime = serizlizedResults[n][9]; printf("%.3f\t", ((double) localBuildProbeTime) / 1000); averageLocalBuildProbeTime += localBuildProbeTime; } printf("\n"); averageLocalBuildProbeTime /= numberOfNodes; printf("[RESULTS] Summary:\t%lu\t%.3f\t%.3f\t%.3f\t%.3f\n", totalNumberOfTuples, ((double) averageJoinTime) / 1000, ((double) averageHistogramTime) / 1000, ((double) averageNetworkTime) / 1000, ((double) averageLocalTime) / 1000); } FILE * Measurements::performanceOutputFile = NULL; FILE * Measurements::metaDataOutputFile = NULL; void Measurements::init(uint32_t nodeId, uint32_t numberOfNodes, std::string tag) { char cwdPath[1024]; memset(cwdPath, 0, 1024); char experimentFullPath[1024]; memset(experimentFullPath, 0, 1024); char performanceFullPath[1024]; memset(performanceFullPath, 0, 1024); char metaDataFullPath[1024]; memset(metaDataFullPath, 0, 1024); char *unused __attribute__((unused)); unused = getcwd(cwdPath, sizeof(cwdPath)); uint64_t experimentId = 0; if (nodeId == hpcjoin::core::Configuration::RESULT_AGGREGATION_NODE) { struct timeval currentTime; gettimeofday(&currentTime, NULL); experimentId = currentTime.tv_sec * 1000000L + currentTime.tv_usec; sprintf(experimentFullPath, "%s/%s-%d-%lu", cwdPath, tag.c_str(), numberOfNodes, experimentId); mkdir(experimentFullPath, S_IRUSR | S_IWUSR | S_IXUSR); } MPI_Bcast(&experimentId, 1, MPI_UINT64_T, hpcjoin::core::Configuration::RESULT_AGGREGATION_NODE, MPI_COMM_WORLD); sprintf(performanceFullPath, "%s/%s-%d-%lu/%d.perf", cwdPath, tag.c_str(), numberOfNodes, experimentId, nodeId); performanceOutputFile = fopen(performanceFullPath, "w"); sprintf(metaDataFullPath, "%s/%s-%d-%lu/%d.info", cwdPath, tag.c_str(), numberOfNodes, experimentId, nodeId); metaDataOutputFile = fopen(metaDataFullPath, "w"); if (nodeId == hpcjoin::core::Configuration::RESULT_AGGREGATION_NODE) { printf("[INFO] Experiment data located at %s\n", experimentFullPath); } } void Measurements::writeMetaData(const char* key, char* value) { fprintf(metaDataOutputFile, "%s\t%s\n", key, value); } void Measurements::writeMetaData(const char* key, uint64_t value) { fprintf(metaDataOutputFile, "%s\t%lu\n", key, value); } void Measurements::storeAllMeasurements() { storePhaseData(); storeSpecialData(); storeHistogramComputationData(); storeSgxHistogramComputationData(); storeNetworkPartitioningData(); storeLocalPartitioningData(); storeBuildProbeData(); fflush(performanceOutputFile); fclose(performanceOutputFile); fflush(metaDataOutputFile); fclose(metaDataOutputFile); } uint64_t Measurements::timeDiff(struct timeval stop, struct timeval start) { return (stop.tv_sec * 1000000L + stop.tv_usec) - (start.tv_sec * 1000000L + start.tv_usec); } /***************************************************************/ #define PAPI_COUNT 2 void Measurements::startHardwareCounters() { /* int events[] = { PAPI_L2_TCA, PAPI_L2_TCR, PAPI_L2_TCW, PAPI_L3_TCA, PAPI_L3_TCR, PAPI_L3_TCW, PAPI_L2_DCA, PAPI_L2_DCR, PAPI_L2_DCW, PAPI_L3_DCA, PAPI_L3_DCR, PAPI_L3_DCW, PAPI_L1_TCM, PAPI_L1_DCM, PAPI_L1_ICM, PAPI_L1_LDM, PAPI_L1_STM, PAPI_L2_TCM, PAPI_L2_DCM, PAPI_L2_ICM, PAPI_L2_LDM, PAPI_L2_STM, PAPI_L3_TCM, PAPI_L3_LDM, PAPI_TOT_CYC, PAPI_MEM_WCY, PAPI_RES_STL, PAPI_BR_CN, PAPI_BR_MSP, PAPI_BR_PRC, PAPI_LD_INS, PAPI_SR_INS, PAPI_TLB_DM, PAPI_TLB_IM};*/ int events[PAPI_COUNT] = { PAPI_L1_TCM, PAPI_L1_DCM }; int ret = 0; if ((ret = PAPI_start_counters(events, PAPI_COUNT)) != PAPI_OK) { fprintf(stderr, "PAPI failed to start counters: %s\n", PAPI_strerror(ret)); exit(1); } } void Measurements::printHardwareCounters(const char* name) { long_long values[PAPI_COUNT]; int ret = 0; if ((ret = PAPI_stop_counters(values, PAPI_COUNT)) != PAPI_OK) { fprintf(stderr, "PAPI failed to read counters: %s\n", PAPI_strerror(ret)); exit(1); } printf("[REPORT][%s] PAPI Values:", name); for (uint32_t i = 0; i < PAPI_COUNT; ++i) { printf("\t%lld", values[i]); } printf("\n"); } /***************************************************************/ int32_t parseInfoLine(char* line) { int32_t i = strlen(line); while (*line < '0' || *line > '9') line++; line[i - 3] = '\0'; i = atoi(line); return i; } void Measurements::printMemoryUtilization(const char* name) { FILE* file = fopen("/proc/self/status", "r"); uint64_t memory = -1; char line[128]; while (fgets(line, 128, file) != NULL) { if (strncmp(line, "VmSize:", 7) == 0) { memory = parseInfoLine(line); break; } } fclose(file); memory *= 1024; fprintf(stdout, "[MEMORY][%s] %lu bytes\n", name, memory); fflush(stdout); } } /* namespace performance */ } /* namespace enclave */
41.845659
156
0.796194
Artraxon
0916667834fac18c62e03b33a201fbbb9de34f2b
4,281
cpp
C++
src/lang/Argument.cpp
qcoreteam/zendAPI
b73fed92c2327d965bd545d5e34f8157e4389a6b
[ "Apache-2.0" ]
207
2017-09-15T03:06:08.000Z
2021-12-04T10:31:45.000Z
src/lang/Argument.cpp
zzusoftboy/zendAPI
b73fed92c2327d965bd545d5e34f8157e4389a6b
[ "Apache-2.0" ]
6
2017-09-11T05:34:21.000Z
2018-03-26T13:44:00.000Z
src/lang/Argument.cpp
zzusoftboy/zendAPI
b73fed92c2327d965bd545d5e34f8157e4389a6b
[ "Apache-2.0" ]
33
2017-09-15T06:47:01.000Z
2020-07-26T02:17:21.000Z
// @copyright 2017-2018 zzu_softboy <zzu_softboy@163.com> // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Created by softboy on 2017/07/26. #include "zapi/lang/Argument.h" namespace zapi { namespace lang { namespace internal { class ArgumentPrivate { public: ArgumentPrivate(const char *name, Type type, bool required = true, bool byReference = false, bool variadic = false); ArgumentPrivate(const char *name, const char *className, bool nullable = true, bool required = true, bool byReference = false, bool variadic = false); ArgumentPrivate(const ArgumentPrivate &other); Type m_type = Type::Null; bool m_nullable = false; bool m_required = true; bool m_byReference = false; bool m_variadic = false; const char *m_name = nullptr; const char *m_className = nullptr; }; ArgumentPrivate::ArgumentPrivate(const char *name, Type type, bool required, bool byReference, bool isVariadic) : m_type(type), m_required(required), m_byReference(byReference), m_variadic(isVariadic), m_name(name) {} ArgumentPrivate::ArgumentPrivate(const char *name, const char *className, bool nullable, bool required, bool byReference, bool isVariadic) : m_nullable(nullable), m_required(required), m_byReference(byReference), m_variadic(isVariadic), m_name(name), m_className(className) {} ArgumentPrivate::ArgumentPrivate(const ArgumentPrivate &other) : m_nullable(other.m_nullable), m_required(other.m_required), m_byReference(other.m_byReference), m_variadic(other.m_variadic), m_name(other.m_name), m_className(other.m_className) {} } // internal Argument::Argument(const char *name, Type type, bool required, bool byReference, bool isVariadic) : m_implPtr(new ArgumentPrivate(name, type, required, byReference, isVariadic)) {} Argument::Argument(const char *name, const char *className, bool nullable, bool required, bool byReference, bool isVariadic) : m_implPtr(new ArgumentPrivate(name, className, nullable, required, byReference, isVariadic)) {} Argument::Argument(const Argument &other) : m_implPtr(new ArgumentPrivate(*other.m_implPtr)) { } Argument::Argument(Argument &&other) ZAPI_DECL_NOEXCEPT : m_implPtr(std::move(other.m_implPtr)) { } Argument &Argument::operator=(const Argument &other) { if (this != &other) { m_implPtr.reset(new ArgumentPrivate(*other.m_implPtr)); } return *this; } Argument &Argument::operator=(Argument &&other) ZAPI_DECL_NOEXCEPT { assert(this != &other); m_implPtr = std::move(other.m_implPtr); return *this; } Argument::~Argument() {} bool Argument::isNullable() const { ZAPI_D(const Argument); return implPtr->m_nullable; } bool Argument::isReference() const { ZAPI_D(const Argument); return implPtr->m_byReference; } bool Argument::isRequired() const { ZAPI_D(const Argument); return implPtr->m_required; } bool Argument::isVariadic() const { ZAPI_D(const Argument); return implPtr->m_variadic; } const char *Argument::getName() const { ZAPI_D(const Argument); return implPtr->m_name; } Type Argument::getType() const { ZAPI_D(const Argument); return implPtr->m_type; } const char *Argument::getClassName() const { ZAPI_D(const Argument); return implPtr->m_className; } ValueArgument::~ValueArgument() {} RefArgument::~RefArgument() {} VariadicArgument::~VariadicArgument() {} } // lang } // zapi
25.945455
97
0.703107
qcoreteam
0920f7f128826c943e9e01c403dde27a32dbe9b7
1,229
hpp
C++
include/sprout/complex/log10.hpp
thinkoid/Sprout
a5a5944bb1779d3bb685087c58c20a4e18df2f39
[ "BSL-1.0" ]
4
2021-12-29T22:17:40.000Z
2022-03-23T11:53:44.000Z
dsp/lib/sprout/sprout/complex/log10.hpp
TheSlowGrowth/TapeLooper
ee8d8dccc27e39a6f6f6f435847e4d5e1b97c264
[ "MIT" ]
16
2021-10-31T21:41:09.000Z
2022-01-22T10:51:34.000Z
include/sprout/complex/log10.hpp
thinkoid/Sprout
a5a5944bb1779d3bb685087c58c20a4e18df2f39
[ "BSL-1.0" ]
null
null
null
/*============================================================================= Copyright (c) 2011-2019 Bolero MURAKAMI https://github.com/bolero-MURAKAMI/Sprout Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef SPROUT_COMPLEX_LOG10_HPP #define SPROUT_COMPLEX_LOG10_HPP #include <sprout/config.hpp> #include <sprout/math/constants.hpp> #include <sprout/math/isnan.hpp> #include <sprout/complex/complex.hpp> #include <sprout/complex/arithmetic_operators.hpp> #include <sprout/complex/log.hpp> namespace sprout { // // log10 // namespace detail { template<typename T> inline SPROUT_CONSTEXPR sprout::complex<T> log10_impl(sprout::complex<T> const& z) { return sprout::math::isnan(z.real()) || sprout::math::isnan(z.imag()) ? z : z / sprout::math::ln_ten<T>() ; } } // namespace detail template<typename T> inline SPROUT_CONSTEXPR sprout::complex<T> log10(sprout::complex<T> const& x) { return sprout::detail::log10_impl(sprout::log(x)); } } // namespace sprout #endif // #ifndef SPROUT_COMPLEX_LOG10_HPP
31.512821
79
0.637103
thinkoid
092252e814bd7a555f0215601ce80919563630bd
11,235
cpp
C++
modules/PhysiCell_various_outputs.cpp
matt-stack/PhysiCell_GPU
e1e07680b99f5c624448f2dfa607cfdbf0176c2f
[ "MIT" ]
3
2019-08-21T18:20:08.000Z
2019-09-06T18:18:54.000Z
modules/PhysiCell_various_outputs.cpp
matt-stack/PhysiCell_GPU
e1e07680b99f5c624448f2dfa607cfdbf0176c2f
[ "MIT" ]
null
null
null
modules/PhysiCell_various_outputs.cpp
matt-stack/PhysiCell_GPU
e1e07680b99f5c624448f2dfa607cfdbf0176c2f
[ "MIT" ]
2
2019-04-12T19:24:01.000Z
2020-03-14T22:53:17.000Z
/* ############################################################################### # If you use PhysiCell in your project, please cite PhysiCell and the version # # number, such as below: # # # # We implemented and solved the model using PhysiCell (Version x.y.z) [1]. # # # # [1] A Ghaffarizadeh, R Heiland, SH Friedman, SM Mumenthaler, and P Macklin, # # PhysiCell: an Open Source Physics-Based Cell Simulator for Multicellu- # # lar Systems, PLoS Comput. Biol. 14(2): e1005991, 2018 # # DOI: 10.1371/journal.pcbi.1005991 # # # # See VERSION.txt or call get_PhysiCell_version() to get the current version # # x.y.z. Call display_citations() to get detailed information on all cite-# # able software used in your PhysiCell application. # # # # Because PhysiCell extensively uses BioFVM, we suggest you also cite BioFVM # # as below: # # # # We implemented and solved the model using PhysiCell (Version x.y.z) [1], # # with BioFVM [2] to solve the transport equations. # # # # [1] A Ghaffarizadeh, R Heiland, SH Friedman, SM Mumenthaler, and P Macklin, # # PhysiCell: an Open Source Physics-Based Cell Simulator for Multicellu- # # lar Systems, PLoS Comput. Biol. 14(2): e1005991, 2018 # # DOI: 10.1371/journal.pcbi.1005991 # # # # [2] A Ghaffarizadeh, SH Friedman, and P Macklin, BioFVM: an efficient para- # # llelized diffusive transport solver for 3-D biological simulations, # # Bioinformatics 32(8): 1256-8, 2016. DOI: 10.1093/bioinformatics/btv730 # # # ############################################################################### # # # BSD 3-Clause License (see https://opensource.org/licenses/BSD-3-Clause) # # # # Copyright (c) 2015-2018, Paul Macklin and the PhysiCell Project # # All rights reserved. # # # # Redistribution and use in source and binary forms, with or without # # modification, are permitted provided that the following conditions are met: # # # # 1. Redistributions of source code must retain the above copyright notice, # # this list of conditions and the following disclaimer. # # # # 2. Redistributions in binary form must reproduce the above copyright # # notice, this list of conditions and the following disclaimer in the # # documentation and/or other materials provided with the distribution. # # # # 3. Neither the name of the copyright holder nor the names of its # # contributors may be used to endorse or promote products derived from this # # software without specific prior written permission. # # # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # # POSSIBILITY OF SUCH DAMAGE. # # # ############################################################################### */ #include "../core/PhysiCell.h" #include "./PhysiCell_various_outputs.h" #include "./PhysiCell_settings.h" namespace PhysiCell{ int writePov(std::vector<Cell*> all_cells, double timepoint, double scale) { std::string filename; filename.resize( 1024 ); // sprintf( (char*) filename.c_str() , "output//cells_%i.pov" , (int)round(timepoint) ); sprintf( (char*) filename.c_str() , "%s/cells_%i.pov" , PhysiCell_settings.folder.c_str() , (int)round(timepoint) ); std::ofstream povFile (filename.c_str(), std::ofstream::out); povFile<<"#include \"colors.inc\" \n"; povFile<<"#include \"header.inc\" \n"; for(int i=0;i<all_cells.size();i++) { std::string _nameCore; if( all_cells[i]->phenotype.cycle.pCycle_Model ) { int code= all_cells[i]->phenotype.cycle.current_phase().code; if (code ==PhysiCell_constants::Ki67_positive_premitotic || code==PhysiCell_constants::Ki67_positive_postmitotic || code==PhysiCell_constants::Ki67_positive || code==PhysiCell_constants::Ki67_negative || code==PhysiCell_constants::live) _nameCore="LIVE"; else if (code==PhysiCell_constants::apoptotic) _nameCore="APOP"; else if (code==PhysiCell_constants::necrotic_swelling || code==PhysiCell_constants::necrotic_lysed || code==PhysiCell_constants::necrotic) _nameCore="NEC"; else if (code==PhysiCell_constants::debris) _nameCore="DEBR"; else _nameCore="MISC"; } else if(all_cells[i]->type==PhysiCell_constants::TUMOR_TYPE) _nameCore="LIVE"; else if(all_cells[i]->type==PhysiCell_constants::VESSEL_TYPE) _nameCore="ENDO"; else _nameCore="MISC"; std::string center= "<" + std::to_string(all_cells[i]->position[0]/scale) + "," + std::to_string(all_cells[i]->position[1]/scale) +","+ std::to_string(all_cells[i]->position[2]/scale) +">"; std::string core = "sphere {\n\t" + center + "\n\t " + std::to_string( all_cells[i]->phenotype.geometry.radius/scale) + "\n\t FinishMacro ( " + center +","+ _nameCore+ "Finish,"+ _nameCore + "*1)\n}\n"; povFile<< core; } povFile<<"#include \"footer.inc\" \n"; povFile.close(); return 0; } int writeCellReport(std::vector<Cell*> all_cells, double timepoint) { std::string filename; filename.resize( 1024 ); // sprintf( (char*) filename.c_str() , "output//cells_%i.txt" , (int)round(timepoint) ); sprintf( (char*) filename.c_str() , "%s/cells_%i.txt" , PhysiCell_settings.folder.c_str() , (int)round(timepoint) ); std::ofstream povFile (filename.c_str(), std::ofstream::out); povFile<<"\tID\tx\ty\tz\tradius\tvolume_total\tvolume_nuclear_fluid\tvolume_nuclear_solid\tvolume_cytoplasmic_fluid\tvolume_cytoplasmic_solid\tvolume_calcified_fraction\tphenotype\telapsed_time\n"; int phenotype_code; for(int i=0;i<all_cells.size();i++) { phenotype_code = all_cells[i]->phenotype.cycle.current_phase().code; // phenotype_code = phases.size()>0?all_cells[i]->phenotype.cycle.phases[all_cells[i]->phenotype.current_phase_index].code:-1; povFile<<i<<"\t"<<all_cells[i]->ID<<"\t"<<all_cells[i]->position[0]<<"\t" << all_cells[i]->position[1] <<"\t"<< all_cells[i]->position[2]<<"\t"; povFile<<all_cells[i]->phenotype.geometry.radius<<"\t"<<all_cells[i]->phenotype.volume.total<<"\t"<<all_cells[i]->phenotype.volume.nuclear_fluid <<"\t"<<all_cells[i]->phenotype.volume.nuclear_solid<<"\t"<<all_cells[i]->phenotype.volume.cytoplasmic_fluid<<"\t"<< all_cells[i]->phenotype.volume.cytoplasmic_solid<<"\t"<<all_cells[i]->phenotype.volume.calcified_fraction<<"\t"<<phenotype_code<< // "\t"<< all_cells[i]->phenotype.cycle.phases[all_cells[i]->phenotype.current_phase_index].elapsed_time <<std::endl; "\t"<< all_cells[i]->phenotype.cycle.data.elapsed_time_in_phase <<std::endl; } povFile.close(); return 0; } void display_simulation_status( std::ostream& os ) { os << "current simulated time: " << PhysiCell_globals.current_time << " " << PhysiCell_settings.time_units << " (max: " << PhysiCell_settings.max_time << " " << PhysiCell_settings.time_units << ")" << std::endl; os << "total agents: " << all_cells->size() << std::endl; os << "interval wall time: "; BioFVM::TOC(); BioFVM::display_stopwatch_value( os , BioFVM::stopwatch_value() ); os << std::endl; BioFVM::TIC(); os << "total wall time: "; BioFVM::RUNTIME_TOC(); BioFVM::display_stopwatch_value( os , BioFVM::runtime_stopwatch_value() ); os << std::endl << std::endl; return; } void log_output(double t, int output_index, Microenvironment microenvironment, std::ofstream& report_file) { double scale=1000; int num_new_cells= 0; int num_deaths=0; // std::cout << "current simulated time: " << t << " minutes " << std::endl; // std::cout << "interval wall time: "; // BioFVM::TOC(); // BioFVM::display_stopwatch_value( std::cout , BioFVM::stopwatch_value() ); // std::cout << std::endl; // std::cout << "total wall time: "; // BioFVM::RUNTIME_TOC(); // BioFVM::display_stopwatch_value( std::cout , BioFVM::runtime_stopwatch_value() ); // std::cout << std::endl; std::cout << "time: "<<t<<std::endl; num_new_cells=t==0?all_basic_agents.size():((Cell_Container *)microenvironment.agent_container)->num_divisions_in_current_step; num_deaths=((Cell_Container *)microenvironment.agent_container)->num_deaths_in_current_step; std::cout<<"total number of agents (newly born, deaths): " << (*all_cells).size()<<"("<<num_new_cells<<", "<<num_deaths<<")" << std::endl; report_file<<t<<"\t"<<(*all_cells).size()<<"\t"<<num_new_cells<<"\t"<<num_deaths<<"\t"<<BioFVM::stopwatch_value()<< std::endl; // BioFVM::TIC(); ((Cell_Container *)microenvironment.agent_container)->num_divisions_in_current_step=0; ((Cell_Container *)microenvironment.agent_container)->num_deaths_in_current_step=0; writePov(*all_cells, t, scale); writeCellReport(*all_cells, t); std::string filename; filename.resize( 1024 , '\0' ); sprintf( (char*) filename.c_str() , "output%08d.mat" , output_index ); filename.resize( strlen( filename.c_str() ) ); // std::cout << "\tWriting to file " << filename << " ... " << std::endl; // microenvironment.write_to_matlab( filename ); return; } };
55.073529
239
0.579973
matt-stack
09241b471e4dd9dc4786bd4b41f6809c68b3931a
774
hpp
C++
include/sprout/array.hpp
thinkoid/Sprout
a5a5944bb1779d3bb685087c58c20a4e18df2f39
[ "BSL-1.0" ]
4
2021-12-29T22:17:40.000Z
2022-03-23T11:53:44.000Z
dsp/lib/sprout/sprout/array.hpp
TheSlowGrowth/TapeLooper
ee8d8dccc27e39a6f6f6f435847e4d5e1b97c264
[ "MIT" ]
16
2021-10-31T21:41:09.000Z
2022-01-22T10:51:34.000Z
include/sprout/array.hpp
thinkoid/Sprout
a5a5944bb1779d3bb685087c58c20a4e18df2f39
[ "BSL-1.0" ]
null
null
null
/*============================================================================= Copyright (c) 2011-2019 Bolero MURAKAMI https://github.com/bolero-MURAKAMI/Sprout Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef SPROUT_ARRAY_HPP #define SPROUT_ARRAY_HPP #include <sprout/config.hpp> #include <sprout/array/array.hpp> #include <sprout/array/comparison.hpp> #include <sprout/array/hash.hpp> #include <sprout/array/tuple.hpp> #include <sprout/array/make_array.hpp> #include <sprout/array/type_traits.hpp> #include <sprout/array/nested_array.hpp> #endif // #ifndef SPROUT_ARRAY_HPP
36.857143
79
0.621447
thinkoid
09249e72722845b4da44def8048b3c6fe5173a7e
759
cpp
C++
WordGenerator/main.cpp
Spheya/WordGenerator
92d992d3f1dbb230e609ce67b534aa71728c8227
[ "MIT" ]
21
2019-06-19T09:40:17.000Z
2021-09-22T10:11:50.000Z
WordGenerator/main.cpp
thobbs/WordGenerator
477c2e8a2e386be29c0832f504ceaec7ba6cba9f
[ "MIT" ]
2
2019-06-19T18:27:48.000Z
2019-06-19T23:23:31.000Z
WordGenerator/main.cpp
Spheya/WordGenerator
92d992d3f1dbb230e609ce67b534aa71728c8227
[ "MIT" ]
3
2019-06-19T16:19:28.000Z
2021-04-14T19:35:23.000Z
#include <string> #include <vector> #include <fstream> #include <iostream> #include "Generator.h" #include <iterator> #include <ctime> int main(int argc, char **argv) { Generator gen(7); std::ifstream myfile("trainingData.txt"); std::vector<std::string> names; std::copy(std::istream_iterator<std::string>(myfile), std::istream_iterator<std::string>(), std::back_inserter(names)); srand(long(time(nullptr))); for (std::string& name : names) std::transform(name.begin(), name.end(), name.begin(), ::tolower); gen.train(names); int word_count = (argc == 0) ? 29 : std::atoi(argv[1]); if (word_count < 1) word_count = 29; for (int i = 0; i < word_count; i++) std::cout << gen.nextNew() << std::endl; }
23
69
0.629776
Spheya
0925bf782849b0b04ec19881148dc3901763df6f
2,672
cpp
C++
src/libs/qlib/qdlgprog.cpp
3dhater/Racer
d7fe4014b1efefe981528547649dc397da7fa780
[ "Unlicense" ]
null
null
null
src/libs/qlib/qdlgprog.cpp
3dhater/Racer
d7fe4014b1efefe981528547649dc397da7fa780
[ "Unlicense" ]
null
null
null
src/libs/qlib/qdlgprog.cpp
3dhater/Racer
d7fe4014b1efefe981528547649dc397da7fa780
[ "Unlicense" ]
1
2021-01-03T16:16:47.000Z
2021-01-03T16:16:47.000Z
/* * QProgressDialog - useful during lengthy operations * 07-01-01: Created! (based on qstrdlg.cpp) * BUGS: * (C) MarketGraph/RvG */ #include <qlib/dialog.h> #include <qlib/app.h> #include <qlib/button.h> #include <qlib/keys.h> #pragma hdrstop #include <qlib/debug.h> DEBUG_ENABLE #define BUTTON_WID 100 // Cancel button #define BUTTON_HGT 40 #undef DBG_CLASS #define DBG_CLASS "QProgressDialog" /********* * C/DTOR * *********/ QProgressDialog::QProgressDialog(QWindow *parent,QRect *r,cstring ititle, cstring itext,int iflags) : QDialog(parent,r,ititle) { DBG_C("ctor") QRect rr; int y=38; pdlgFlags=iflags; //qdbg("pdlgFlags=%d, NO_CANCEL=%d\n",pdlgFlags,NO_CANCEL); // Make sure runtime flags are off pdlgFlags&=~(CANCEL_PRESSED); rr.SetXY(r->wid/2-BUTTON_WID/2,r->hgt-50); rr.SetSize(BUTTON_WID,BUTTON_HGT); if(!(pdlgFlags&NO_CANCEL)) { bCancel=new QButton(this,&rr,"Cancel"); bCancel->ShortCut(QK_ESC); bCancel->SetKeyPropagation(TRUE); } else bCancel=0; // Explanatory text inside dialog rr.SetXY(10,y); lText=new QLabel(this,&rr,itext); // Progress bar rr.SetXY(10,y+30); rr.SetSize(r->wid-2*10,25); prg=new QProgress(this,&rr); } QProgressDialog::~QProgressDialog() { DBG_C("dtor") if(bCancel)delete bCancel; if(lText)delete lText; if(prg)delete prg; } /********* * Events * *********/ bool QProgressDialog::Event(QEvent *e) { //qdbg("QPrgDlg: Event %d\n",e->type); if(e->type==QEVENT_CLICK) { if(e->win==bCancel) { // User wants to cancel pdlgFlags|=CANCEL_PRESSED; return TRUE; } } else if(e->type==QEvent::KEYPRESS) { if(e->n==QK_ESC) { // User wants to cancel pdlgFlags|=CANCEL_PRESSED; return TRUE; } } return QDialog::Event(e); } /********* * Create * *********/ bool QProgressDialog::Create() // Returns FALSE if dialog couldn't created. { QWM->SetKeyboardFocus(bCancel); // Get it up visually app->RunPoll(); return TRUE; } /********************************************* * Handling events while the progress is busy * *********************************************/ bool QProgressDialog::Poll() // Returns TRUE if polling was normal (can continue). // Returns FALSE if 'Cancel' was pressed (a request to abort) { app->RunPoll(); // Signal caller if Cancel was pressed if(pdlgFlags&CANCEL_PRESSED)return FALSE; return TRUE; } void QProgressDialog::SetProgress(int cur,int total) // Update the progress bar { if(prg) prg->SetProgress(cur,total,TRUE); } void QProgressDialog::SetProgressText(cstring text) // Update the progress bar text { if(prg) prg->SetText(text); }
20.875
73
0.636976
3dhater
0925dfad211ec13d7fa9a69669e13fbb332daca6
12,300
cc
C++
psdaq/psdaq/hsd/PVCtrls.cc
AntoineDujardin/lcls2
8b9d2815497fbbabb4d37800fd86a7be1728b552
[ "BSD-3-Clause-LBNL" ]
null
null
null
psdaq/psdaq/hsd/PVCtrls.cc
AntoineDujardin/lcls2
8b9d2815497fbbabb4d37800fd86a7be1728b552
[ "BSD-3-Clause-LBNL" ]
null
null
null
psdaq/psdaq/hsd/PVCtrls.cc
AntoineDujardin/lcls2
8b9d2815497fbbabb4d37800fd86a7be1728b552
[ "BSD-3-Clause-LBNL" ]
null
null
null
#include "psdaq/hsd/PVCtrls.hh" #include "psdaq/hsd/Module.hh" #include "psdaq/hsd/FexCfg.hh" #include "psdaq/hsd/QABase.hh" #include "psdaq/hsd/Pgp.hh" #include "psdaq/epicstools/EpicsPVA.hh" #include "psdaq/epicstools/PvServer.hh" #include "psdaq/service/Task.hh" #include "psdaq/service/Routine.hh" #include <algorithm> #include <sstream> #include <cctype> #include <stdio.h> #include <unistd.h> using Pds_Epics::EpicsPVA; using Pds_Epics::PvServer; using Pds_Epics::PVMonitorCb; using Pds::Routine; static std::string STOU(std::string s) { std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c){ return std::toupper(c); } ); return s; } static bool _interleave = false; namespace Pds { namespace HSD { class PVC_Routine : public Routine { public: PVC_Routine(PVCtrls& pvc, Action a) : _pvc(pvc), _a(a) {} void routine() { switch(_a) { case Configure : _pvc.configure (); break; case Unconfigure : _pvc.unconfigure(); break; case Reset : _pvc.reset (); break; default: break; } } private: PVCtrls& _pvc; Action _a; }; #define Q(a,b) a ## b #define PV(name) Q(name, PV) #define CPV(name, updatedBody, connectedBody) \ \ class PV(name) : public EpicsPVA, \ public PVMonitorCb \ { \ public: \ PV(name)(PVCtrls& ctrl, const char* pvName) : \ EpicsPVA(pvName, this), \ _ctrl(ctrl) {} \ virtual ~PV(name)() {} \ public: \ virtual void updated(); \ virtual void onConnect(); \ public: \ void put() { if (this->EpicsPVA::connected()) _channel.put(); } \ private: \ PVCtrls& _ctrl; \ }; \ void PV(name)::updated() \ { \ updatedBody \ } \ void PV(name)::onConnect() \ { \ connectedBody \ } CPV(ApplyConfig ,{if (getScalarAs<unsigned>()) _ctrl.call(Configure );}, {}) CPV(ApplyUnconfig ,{if (getScalarAs<unsigned>()) _ctrl.call(Unconfigure);}, {}) CPV(State ,{}, {}) CPV(Reset ,{if (getScalarAs<unsigned>()) _ctrl.call(Reset );}, {}) CPV(PgpLoopback ,{_ctrl.loopback (getScalarAs<unsigned>()!=0); }, {}) PVCtrls::PVCtrls(Module& m, Pds::Task& t) : _pv(0), _m(m), _task(t) {} PVCtrls::~PVCtrls() {} void PVCtrls::call(Action a) { _task.call(new PVC_Routine(*this, a)); } void PVCtrls::allocate(const std::string& title) { if (_state_pv) delete _state_pv; std::ostringstream o; o << title << ":"; std::string pvbase = o.str(); _state_pv = new EpicsPVA((pvbase+"BASE:READY").c_str()); _setState(InTransition); _m.stop(); for(unsigned i=0; i<4; i++) { FexCfg& fex = _m.fex()[i]; fex._streams= 0; } for(unsigned i=0; i<_pv.size(); i++) delete _pv[i]; _pv.resize(0); #define NPV(name,pv) _pv.push_back( new PV(name)(*this, (pvbase+pv).c_str()) ) #define NPV1(name) _pv.push_back( new PvServer(STOU(pvbase+#name).c_str()) ) NPV1(Enable); NPV1(Raw_Start); NPV1(Raw_Gate); NPV1(Raw_PS); NPV1(Fex_Start); NPV1(Fex_Gate); NPV1(Fex_PS); NPV1(Fex_Ymin); NPV1(Fex_Ymax); NPV1(Fex_Xpre); NPV1(Fex_Xpost); NPV1(FullEvt); NPV1(FullSize); NPV1(TestPattern); NPV1(SyncELo); NPV1(SyncEHi); NPV1(SyncOLo); NPV1(SyncOHi); NPV1(TrigShift); NPV1(PgpSkpIntvl); _pv.push_back(new PvServer((pvbase+"BASE:INTTRIGVAL" ).c_str())); _pv.push_back(new PvServer((pvbase+"BASE:INTAFULLVAL").c_str())); _pv.push_back(new PvServer((pvbase+"BASE:PARTITION" ).c_str())); NPV(ApplyConfig ,"BASE:APPLYCONFIG"); NPV(ApplyUnconfig,"BASE:APPLYUNCONFIG"); NPV(Reset ,"RESET"); NPV(PgpLoopback,"PGPLOOPBACK"); _setState(Unconfigured); } // enumeration of PV insert order above enum PvIndex { Enable, Raw_Start, Raw_Gate, Raw_PS, Fex_Start, Fex_Gate, Fex_PS, Fex_Ymin, Fex_Ymax, Fex_Xpre, Fex_Xpost, FullEvt, FullSize, TestPattern, SyncELo, SyncEHi, SyncOLo, SyncOHi, TrigShift, PgpSkpIntvl, IntTrigVal, IntAFullVal, Partition, LastPv }; Module& PVCtrls::module() { return _m; } void PVCtrls::configure() { _setState(InTransition); _m.stop(); // Update all necessary PVs for(unsigned i=0; i<LastPv; i++) { PvServer* pv = static_cast<PvServer*>(_pv[i]); while (!pv->EpicsPVA::connected()) { printf("pv[%u] not connected\n",i); usleep(100000); } pv->update(); } { unsigned i=0; while(i<FullEvt) { printf("pv[%u] :",i); pvd::shared_vector<const unsigned> vec; _pv[i]->getVectorAs<unsigned>(vec); for(unsigned j=0; j<vec.size(); j++ ) printf(" %u", vec[j]); printf("\n"); i++; } while(i<LastPv) { printf("pv[%u] : %u\n",i,_pv[i]->getScalarAs<unsigned>()); i++; } } { unsigned v = _pv[PgpSkpIntvl]->getScalarAs<unsigned>(); std::vector<Pgp*> pgp = _m.pgp(); for(unsigned i=0; i<4; i++) pgp[i]->skip_interval(v); } _m.dumpPgp(); // set trigger shift int shift = _pv[TrigShift]->getScalarAs<int>(); _m.trig_shift(shift); // don't know how often this is necessary _m.train_io(0); unsigned channelMask = 0; for(unsigned i=0; i<4; i++) { if (_pv[Enable]->getVectorElemAt<unsigned>(i)) { channelMask |= (1<<i); if (_interleave) break; } } printf("channelMask 0x%x: ilv %c\n", channelMask, _interleave?'T':'F'); _m.setAdcMux( _interleave, channelMask ); // set testpattern int pattern = _pv[TestPattern]->getScalarAs<int>(); printf("Pattern: %d\n",pattern); _m.disable_test_pattern(); if (pattern>=0) _m.enable_test_pattern((Module::TestPattern)pattern); int ephlo = _pv[SyncELo]->getScalarAs<int>(); int ephhi = _pv[SyncEHi]->getScalarAs<int>(); int ophlo = _pv[SyncOLo]->getScalarAs<int>(); int ophhi = _pv[SyncOHi]->getScalarAs<int>(); while(1) { int eph = _m.trgPhase()[0]; int oph = _m.trgPhase()[1]; printf("trig phase %05d [%05d/%05d] %05d [%05d/%05d]\n", eph,ephlo,ephhi, oph,ophlo,ophhi); if (eph > ephlo && eph < ephhi && oph > ophlo && oph < ophhi) break; _m.sync(); usleep(100000); // Wait for relock } // zero the testpattern error counts _m.clear_test_pattern_errors(); // _m.sample_init(32+48*length, 0, 0); QABase& base = *reinterpret_cast<QABase*>((char*)_m.reg()+0x80000); base.init(); base.resetCounts(); { std::vector<Pgp*> pgp = _m.pgp(); for(unsigned i=0; i<pgp.size(); i++) pgp[i]->resetCounts(); } // These aren't used... // base.samples = ; // base.prescale = ; unsigned partition = _pv[Partition]->getScalarAs<unsigned>(); _m.trig_daq(partition); // configure fex's for each channel unsigned fullEvt = _pv[FullEvt ]->getScalarAs<unsigned>(); unsigned fullSize = _pv[FullSize]->getScalarAs<unsigned>(); for(unsigned i=0; i<4; i++) { FexCfg& fex = _m.fex()[i]; if ((1<<i)&channelMask) { unsigned streamMask=0; if (_pv[Raw_PS]->getVectorElemAt<unsigned>(i)) { streamMask |= (1<<0); fex._base[0].setGate(_pv[Raw_Start]->getVectorElemAt<unsigned>(i), _pv[Raw_Gate ]->getVectorElemAt<unsigned>(i)); fex._base[0].setFull(fullSize,fullEvt); fex._base[0]._prescale=_pv[Raw_PS]->getVectorElemAt<unsigned>(i)-1; } if (_pv[Fex_PS]->getVectorElemAt<unsigned>(i)) { streamMask |= (1<<1); fex._base[1].setGate(_pv[Fex_Start]->getVectorElemAt<unsigned>(i), _pv[Fex_Gate ]->getVectorElemAt<unsigned>(i)); fex._base[1].setFull(fullSize,fullEvt); fex._base[1]._prescale=_pv[Fex_PS]->getVectorElemAt<unsigned>(i)-1; fex._stream[1].parms[0].v=_pv[Fex_Ymin]->getVectorElemAt<unsigned>(i); fex._stream[1].parms[1].v=_pv[Fex_Ymax]->getVectorElemAt<unsigned>(i); fex._stream[1].parms[2].v=_pv[Fex_Xpre]->getVectorElemAt<unsigned>(i); fex._stream[1].parms[3].v=_pv[Fex_Xpost]->getVectorElemAt<unsigned>(i); } fex._streams= streamMask; } else fex._streams= 0; } #define PRINT_FEX_FIELD(title,arg,op) { \ printf("%12.12s:",title); \ for(unsigned i=0; i<4; i++) { \ if (((1<<i)&channelMask)==0) continue; \ printf(" %u/%u/%u", \ fex[i]._base[0].arg op, \ fex[i]._base[1].arg op, \ fex[i]._base[2].arg op); \ } \ printf("\n"); } FexCfg* fex = _m.fex(); PRINT_FEX_FIELD("GateBeg", _gate, &0x3fff); PRINT_FEX_FIELD("GateLen", _gate, >>16&0x3fff); PRINT_FEX_FIELD("FullRow", _full, &0xffff); PRINT_FEX_FIELD("FullEvt", _full, >>16&0x1f); PRINT_FEX_FIELD("Prescal", _prescale, &0x3ff); printf("streams:"); for(unsigned i=0; i<4; i++) { if (((1<<i)&channelMask)==0) continue; printf(" %2u", fex[i]._streams &0xf); } printf("\n"); #undef PRINT_FEX_FIELD base.dump(); printf("Configure done\n"); _m.start(); _setState(Configured); } void PVCtrls::unconfigure() { _setState(InTransition); _m.stop(); for(unsigned i=0; i<4; i++) { FexCfg& fex = _m.fex()[i]; fex._streams= 0; } _setState(Unconfigured); } void PVCtrls::reset() { QABase& base = *reinterpret_cast<QABase*>((char*)_m.reg()+0x80000); base.resetFbPLL(); usleep(1000000); base.resetFb (); base.resetDma(); usleep(1000000); } void PVCtrls::loopback(bool v) { std::vector<Pgp*> pgp = _m.pgp(); for(unsigned i=0; i<4; i++) pgp[i]->loopback(v); // for(unsigned i=0; i<4; i++) // pgp[i]._rxReset = 1; // usleep(10); // for(unsigned i=0; i<4; i++) // pgp[i]._rxReset = 0; // usleep(100); } void PVCtrls::interleave(bool v) { _interleave = v; } void PVCtrls::_setState(State a) { unsigned v(a); _state_pv->putFrom(v); } }; };
33.333333
83
0.480894
AntoineDujardin
092a46829cd8d4514e055e391b3239c407c6f278
1,405
cpp
C++
HackerRankEulerProblems/20/P014_LongestCollatzSequence.cpp
wingkinl/HackerRankEulerProblems
3b5cf8945dc1d4f0a2214103f2e0414caf07a18a
[ "Apache-2.0" ]
null
null
null
HackerRankEulerProblems/20/P014_LongestCollatzSequence.cpp
wingkinl/HackerRankEulerProblems
3b5cf8945dc1d4f0a2214103f2e0414caf07a18a
[ "Apache-2.0" ]
null
null
null
HackerRankEulerProblems/20/P014_LongestCollatzSequence.cpp
wingkinl/HackerRankEulerProblems
3b5cf8945dc1d4f0a2214103f2e0414caf07a18a
[ "Apache-2.0" ]
null
null
null
#include "P014_LongestCollatzSequence.h" #include <iostream> uint64_t P014_LongestCollatzSequence::GetTermStep(uint64_t term) { if (term == 1) return 0; if (term_steps[term]) return term_steps[term]; uint64_t step = 0; uint64_t next_term = term; do { if (next_term & 1) next_term = next_term * 3 + 1; else next_term = next_term >> 1; ++step; } while (next_term > kMaximum); return step + GetTermStep(next_term); } uint64_t P014_LongestCollatzSequence::Solve(uint64_t n) { if (max_step_nums.empty()) { term_steps.resize(kMaximum + 1); term_steps[0] = 1; term_steps[1] = 1; uint64_t step = 0; // even term for (uint64_t ii = 2; ii <= kMaximum; ii <<= 1) { ++step; term_steps[ii] = step; } for (uint64_t ii = 3; ii <= kMaximum; ++ii) { term_steps[ii] = GetTermStep(ii); } max_step_nums.resize(kMaximum + 1); max_step_nums[1] = 1; for (uint64_t ii = 2; ii <= kMaximum; ++ii) { auto prev_max_step_num = max_step_nums[ii - 1]; if (term_steps[ii] >= term_steps[prev_max_step_num]) max_step_nums[ii] = ii; else max_step_nums[ii] = prev_max_step_num; } } return max_step_nums[n]; } void P014_LongestCollatzSequence::main() { std::ios_base::sync_with_stdio(false); int T; std::cin >> T; P014_LongestCollatzSequence p; for (int t = 0; t < T; ++t) { uint64_t n; std::cin >> n; std::cout << p.Solve(n) << "\n"; } }
20.362319
64
0.646975
wingkinl
092d671615dcfd45c8f15ad401beff88fe6e6332
4,868
cpp
C++
mge_v18_student_version/src/mge/scenes/TristanScene.cpp
TristanSmeets/Agent-OwO
9ee94c8fd605cdf2b2274624ef55f83e527ee472
[ "MIT" ]
null
null
null
mge_v18_student_version/src/mge/scenes/TristanScene.cpp
TristanSmeets/Agent-OwO
9ee94c8fd605cdf2b2274624ef55f83e527ee472
[ "MIT" ]
null
null
null
mge_v18_student_version/src/mge/scenes/TristanScene.cpp
TristanSmeets/Agent-OwO
9ee94c8fd605cdf2b2274624ef55f83e527ee472
[ "MIT" ]
null
null
null
#include <string> #include "glm.hpp" //Core #include "mge/core/Renderer.hpp" #include "mge/core/Mesh.hpp" #include "mge/core/World.hpp" #include "mge/core/Texture.hpp" #include "mge/core/Light.hpp" #include "mge/core/Camera.hpp" #include "mge/core/GameObject.hpp" #include "mge/core/Light.hpp" //Materials #include "mge/materials/AbstractMaterial.hpp" #include "mge/materials/ColorMaterial.hpp" #include "mge/materials/TextureMaterial.hpp" #include "mge/materials/LitMaterial.hpp" //Behaviours #include "mge/behaviours/KeysBehaviour.hpp" #include "mge/behaviours/RotatingBehaviour.hpp" #include "mge/behaviours/CameraOrbitBehaviour.hpp" #include "TristanScene.h" #include "mge/config.hpp" TristanScene::TristanScene():AbstractGame() { } TristanScene::~TristanScene() { } void TristanScene::initialize() { AbstractGame::initialize(); } void TristanScene::_initializeScene() { //Meshes Mesh* planeMeshDefault = Mesh::load(config::MGE_MODEL_PATH + "plane.obj"); Mesh* cubeMeshF = Mesh::load(config::MGE_MODEL_PATH + "cube_flat.obj"); Mesh* sphereMeshS = Mesh::load(config::MGE_MODEL_PATH + "sphere_smooth.obj"); Mesh* coneMeshS = Mesh::load(config::MGE_MODEL_PATH + "cone_smooth.obj"); Mesh* suzannaMeshS = Mesh::load(config::MGE_MODEL_PATH + "suzanna_smooth.obj"); //Materials //Create some materials to display the cube, the plane and the light AbstractMaterial* lightMaterial = new ColorMaterial(glm::vec3(1, 1, 0)); AbstractMaterial* colourMaterial = new ColorMaterial(glm::vec3(0, 1, 0.9903f)); AbstractMaterial* runicStoneMaterial = new TextureMaterial(Texture::load(config::MGE_TEXTURE_PATH + "runicfloor.png")); AbstractMaterial* bricksMaterial = new TextureMaterial(Texture::load(config::MGE_TEXTURE_PATH + "bricks.jpg")); AbstractMaterial* landMaterial = new TextureMaterial(Texture::load(config::MGE_TEXTURE_PATH + "land.jpg")); //Creating a Material for the litmaterial Material* material = new Material(); material->DiffuseTexture = Texture::load(config::MGE_TEXTURE_PATH + "container2.png"); material->SpecularTexture = Texture::load(config::MGE_TEXTURE_PATH + "container2_specular.png"); material->ShininessFactor = 32; //Creating LightingData for the light LightingData* data = new LightingData(); data->Type = LightType::SPOTLIGHT; data->Ambient = glm::vec3(1, 1, 1); data->Diffuse = glm::vec3(1, 1, 1); data->Specular = glm::vec3(1, 1, 1); data->Constant = 1.0f; data->Linear = 0.14f; data->Quadratic = 0.07f; data->CutOff = 12.5f; data->OuterCutOff = 15.5f; AbstractMaterial* litMaterial = new LitMaterial(material); //Scene setup //Add camera first(it will be updated last) std::cout << "Creating Camera" << std::endl; Camera* camera = new Camera("camera", glm::vec3(0, 5, 5)); camera->rotate(glm::radians(-45.0f), glm::vec3(1, 0, 0)); _world->add(camera); _world->setMainCamera(camera); //Add the floor with a landMaterial std::cout << "Creating Plane" << std::endl; GameObject* plane = new GameObject("plane", glm::vec3(0, 0, 0)); plane->scale(glm::vec3(5, 5, 5)); plane->setMesh(planeMeshDefault); plane->setMaterial(runicStoneMaterial); _world->add(plane); //Add a monkey head with the runicStone Material std::cout << "Creating Suzanna" << std::endl; GameObject* suzanna = new GameObject("suzanna", glm::vec3(2, 2, 0)); suzanna->scale(glm::vec3(1, 1, 1)); suzanna->setMesh(suzannaMeshS); suzanna->setMaterial(litMaterial); //suzanna->setBehaviour(new RotatingBehaviour()); _world->add(suzanna); std::cout << "Creating 2nd Suzanna" << std::endl; GameObject* suzanna2 = new GameObject("suzanna", glm::vec3(-2, 2, 0)); suzanna2->setMesh(cubeMeshF); suzanna2->setMaterial(litMaterial); //suzanna2->setBehaviour(new RotatingBehaviour()); _world->add(suzanna2); Light* light = new Light("light", //Name glm::vec3(0, 2, 0), //Position data); //Lighting variables light->setMesh(cubeMeshF); light->scale(glm::vec3(0.1f, 0.1f, 0.1f)); light->setMaterial(lightMaterial); light->setBehaviour(new KeysBehaviour(40,100)); //light->setBehaviour(new CameraOrbitBehaviour(5, 45, 1, suzanna, _window)); _world->add(light); //////Add a rotating brick sphere. //std::cout << "Creating Sphere" << std::endl; //GameObject* sphere = new GameObject("sphere", glm::vec3(0, 0, 0)); //sphere->setMesh(sphereMeshS); //sphere->setMaterial(bricksMaterial); //sphere->setBehaviour(new RotatingBehaviour()); //_world->add(sphere); ////Add a yellow cone //std::cout << "Creating Cone" << std::endl; //GameObject* cone = new GameObject("Cone", glm::vec3(-5, -5, 0)); //cone->scale(glm::vec3(2.5f, 2.5f, 2.5f)); //cone->setMesh(coneMeshS); //cone->setMaterial(lightMaterial); //_world->add(cone); //camera->setBehaviour(new CameraOrbitBehaviour(5, 45.0f, 1.0f, suzanna, _window)); } void TristanScene::_render() { AbstractGame::_render(); }
32.891892
120
0.713846
TristanSmeets
09300d293fec7813e5eee7e55f9e9e4fccadfb7e
6,319
cc
C++
src/trace_processor/storage_table.cc
zakerinasab/perfetto
7f86589d1522ce8bfc59f6b569ca52496a53eb79
[ "Apache-2.0" ]
null
null
null
src/trace_processor/storage_table.cc
zakerinasab/perfetto
7f86589d1522ce8bfc59f6b569ca52496a53eb79
[ "Apache-2.0" ]
null
null
null
src/trace_processor/storage_table.cc
zakerinasab/perfetto
7f86589d1522ce8bfc59f6b569ca52496a53eb79
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "src/trace_processor/storage_table.h" namespace perfetto { namespace trace_processor { StorageTable::StorageTable() = default; StorageTable::~StorageTable() = default; util::Status StorageTable::Init(int, const char* const*, Schema* schema) { schema_ = CreateStorageSchema(); *schema = schema_.ToTableSchema(); return util::OkStatus(); } std::unique_ptr<SqliteTable::Cursor> StorageTable::CreateCursor() { return std::unique_ptr<Cursor>(new Cursor(this)); } std::unique_ptr<RowIterator> StorageTable::CreateBestRowIterator( const QueryConstraints& qc, sqlite3_value** argv) { const auto& cs = qc.constraints(); auto obs = RemoveRedundantOrderBy(cs, qc.order_by()); // Figure out whether the data is already ordered and which order we should // traverse the data. bool is_ordered, is_desc = false; std::tie(is_ordered, is_desc) = IsOrdered(obs); // Create the range iterator and if we are sorted, just return it. auto index = CreateRangeIterator(cs, argv); if (!index.error().empty()) { SetErrorMessage(sqlite3_mprintf(index.error().c_str())); return nullptr; } if (is_ordered) return index.ToRowIterator(is_desc); // Otherwise, create the sorted vector of indices and create the vector // iterator. return std::unique_ptr<VectorRowIterator>( new VectorRowIterator(CreateSortedIndexVector(std::move(index), obs))); } FilteredRowIndex StorageTable::CreateRangeIterator( const std::vector<QueryConstraints::Constraint>& cs, sqlite3_value** argv) { // Try and bound the search space to the smallest possible index region and // store any leftover constraints to filter using bitvector. uint32_t min_idx = 0; uint32_t max_idx = RowCount(); std::vector<size_t> bitvector_cs; for (size_t i = 0; i < cs.size(); i++) { const auto& c = cs[i]; size_t column = static_cast<size_t>(c.column); auto bounds = schema_.GetColumn(column).BoundFilter(c.op, argv[i]); min_idx = std::max(min_idx, bounds.min_idx); max_idx = std::min(max_idx, bounds.max_idx); // If the lower bound is higher than the upper bound, return a zero-sized // range iterator. if (min_idx >= max_idx) return FilteredRowIndex(min_idx, min_idx); if (!bounds.consumed) bitvector_cs.emplace_back(i); } // Create an filter index and allow each of the columns filter on it. FilteredRowIndex index(min_idx, max_idx); for (const auto& c_idx : bitvector_cs) { const auto& c = cs[c_idx]; auto* value = argv[c_idx]; const auto& schema_col = schema_.GetColumn(static_cast<size_t>(c.column)); schema_col.Filter(c.op, value, &index); if (!index.error().empty()) break; } return index; } std::pair<bool, bool> StorageTable::IsOrdered( const std::vector<QueryConstraints::OrderBy>& obs) { if (obs.size() == 0) return std::make_pair(true, false); if (obs.size() != 1) return std::make_pair(false, false); const auto& ob = obs[0]; auto col = static_cast<size_t>(ob.iColumn); return std::make_pair(schema_.GetColumn(col).HasOrdering(), ob.desc); } std::vector<QueryConstraints::OrderBy> StorageTable::RemoveRedundantOrderBy( const std::vector<QueryConstraints::Constraint>& cs, const std::vector<QueryConstraints::OrderBy>& obs) { std::vector<QueryConstraints::OrderBy> filtered; std::set<int> equality_cols; for (const auto& c : cs) { if (sqlite_utils::IsOpEq(c.op)) equality_cols.emplace(c.column); } for (const auto& o : obs) { if (equality_cols.count(o.iColumn) > 0) continue; filtered.emplace_back(o); } return filtered; } std::vector<uint32_t> StorageTable::CreateSortedIndexVector( FilteredRowIndex index, const std::vector<QueryConstraints::OrderBy>& obs) { PERFETTO_DCHECK(obs.size() > 0); // Retrieve the index created above from the index. std::vector<uint32_t> sorted_rows = index.ToRowVector(); std::vector<StorageColumn::Comparator> comparators; for (const auto& ob : obs) { auto col = static_cast<size_t>(ob.iColumn); comparators.emplace_back(schema_.GetColumn(col).Sort(ob)); } auto comparator = [&comparators](uint32_t f, uint32_t s) { for (const auto& comp : comparators) { int c = comp(f, s); if (c != 0) return c < 0; } return false; }; std::sort(sorted_rows.begin(), sorted_rows.end(), comparator); return sorted_rows; } bool StorageTable::HasEqConstraint(const QueryConstraints& qc, const std::string& col_name) { size_t c_idx = schema().ColumnIndexFromName(col_name); auto fn = [c_idx](const QueryConstraints::Constraint& c) { return c.column == static_cast<int>(c_idx) && sqlite_utils::IsOpEq(c.op); }; const auto& cs = qc.constraints(); return std::find_if(cs.begin(), cs.end(), fn) != cs.end(); } StorageTable::Cursor::Cursor(StorageTable* table) : SqliteTable::Cursor(table), table_(table) {} int StorageTable::Cursor::Filter(const QueryConstraints& qc, sqlite3_value** argv, FilterHistory) { iterator_ = table_->CreateBestRowIterator(qc, argv); if (!iterator_) return SQLITE_ERROR; columns_ = table_->schema_.mutable_columns(); return SQLITE_OK; } int StorageTable::Cursor::Next() { iterator_->NextRow(); return SQLITE_OK; } int StorageTable::Cursor::Eof() { return iterator_->IsEnd(); } int StorageTable::Cursor::Column(sqlite3_context* context, int raw_col) { size_t column = static_cast<size_t>(raw_col); (*columns_)[column]->ReportResult(context, iterator_->Row()); return SQLITE_OK; } } // namespace trace_processor } // namespace perfetto
31.753769
78
0.69109
zakerinasab
093171954b1a43d655f4c9fb1aacc32cdacae34b
1,073
cpp
C++
Source/Core/AS_SFML/Font.cpp
ace13/LD34
82ecda6bdd69208be1ec6d03c3eb250313c4b7d1
[ "MIT" ]
1
2017-01-05T01:55:16.000Z
2017-01-05T01:55:16.000Z
Source/Core/AS_SFML/Font.cpp
ace13/AngelscriptMP
583d481fdbef75e4d96a45eb2942a21189087c77
[ "MIT" ]
null
null
null
Source/Core/AS_SFML/Font.cpp
ace13/AngelscriptMP
583d481fdbef75e4d96a45eb2942a21189087c77
[ "MIT" ]
null
null
null
#include "Shared.hpp" #include <SFML/Graphics/Font.hpp> #if SFML_VERSION_MINOR > 1 namespace { void getFamily(asIScriptGeneric* gen) { sf::Font* font = (sf::Font*)gen->GetObject(); new (gen->GetAddressOfReturnLocation()) std::string(font->getInfo().family); } } #endif void as::priv::RegFont(asIScriptEngine* eng) { AS_ASSERT(eng->SetDefaultNamespace("sf")); AS_ASSERT(eng->RegisterObjectType("Font", 0, asOBJ_REF | asOBJ_NOCOUNT)); #if SFML_VERSION_MINOR > 1 AS_ASSERT(eng->RegisterObjectMethod("Font", "string get_Family() const", asFUNCTION(getFamily), asCALL_GENERIC)); AS_ASSERT(eng->RegisterObjectMethod("Font", "uint GetLineSpacing(uint) const", asMETHOD(sf::Font, getLineSpacing), asCALL_THISCALL)); AS_ASSERT(eng->RegisterObjectMethod("Font", "uint GetUnderlinePosition(uint) const", asMETHOD(sf::Font, getUnderlinePosition), asCALL_THISCALL)); AS_ASSERT(eng->RegisterObjectMethod("Font", "uint GetUnderlineThickness(uint) const", asMETHOD(sf::Font, getUnderlineThickness), asCALL_THISCALL)); #endif AS_ASSERT(eng->SetDefaultNamespace("")); }
33.53125
148
0.755825
ace13
0931eaca86882560b2c9af9b38227cd11a9e52ff
1,008
cpp
C++
Fields (0432).cpp
michaelarakel/acmp-solutions
56b853805854d0f0c0131c59c7a48e207c35b15f
[ "Unlicense" ]
1
2021-09-22T12:14:59.000Z
2021-09-22T12:14:59.000Z
Fields (0432).cpp
michaelarakel/acmp-solutions
56b853805854d0f0c0131c59c7a48e207c35b15f
[ "Unlicense" ]
null
null
null
Fields (0432).cpp
michaelarakel/acmp-solutions
56b853805854d0f0c0131c59c7a48e207c35b15f
[ "Unlicense" ]
null
null
null
#include <fstream> #include <deque> #include <vector> using namespace std; void bfs (vector <vector <char> >& v, int row, int col) { deque <pair <int, int> > d; d.push_back(make_pair(row, col)); while (!d.empty()) { pair <int, int> node = d[0]; d.pop_front(); const int a[] = {1, -1, 0, 0}, b[] = {0, 0, 1, -1}; for (int i = 0; i < 4; ++i) { int x = node.first + a[i], y = node.second + b[i]; if (x >=0 && x < v.size() && y >= 0 && y < v[0].size() && v[x][y] == '#') { d.push_back(make_pair(x, y)); v[x][y] = '.'; } } } } int main () { ifstream cin ("INPUT.TXT"); ofstream cout ("OUTPUT.TXT"); int n, m, count = 0; cin >> n >> m; vector <vector <char> > v(n, vector <char>(m)); for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) cin >> v[i][j]; for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) if (v[i][j] == '#') { bfs(v, i, j); count++; } cout << count; }
20.16
56
0.436508
michaelarakel
09324ac0f058f1d213b1bd73a06074821bdc7495
390
cpp
C++
src/cpp_tester.cpp
kyoustat/SHT
0858531ab8b9a7a2faf5b581919a3fa38afd33af
[ "MIT" ]
3
2020-09-30T23:17:33.000Z
2021-06-06T16:19:32.000Z
src/cpp_tester.cpp
vishalbelsare/SHT
0858531ab8b9a7a2faf5b581919a3fa38afd33af
[ "MIT" ]
null
null
null
src/cpp_tester.cpp
vishalbelsare/SHT
0858531ab8b9a7a2faf5b581919a3fa38afd33af
[ "MIT" ]
2
2019-03-06T12:03:56.000Z
2021-08-11T14:45:18.000Z
#include "RcppArmadillo.h" // [[Rcpp::depends(RcppArmadillo)]] using namespace Rcpp; using namespace arma; //////////////////////////////////////// test 1. lgamma of arma : works fine // [[Rcpp::export]] arma::vec testcpp_lgamma(arma::vec x){ int n = x.n_elem; arma::vec output(n, fill::zeros); for (int i=0;i<n;i++){ output(i) = Rf_lgammafn(x(i)); } return(output); }
19.5
76
0.571795
kyoustat
09337a1660e953aa597aa1d29d05cbb9cbc864d8
1,182
hpp
C++
ultra/not_released/dark/cfgparser.hpp
badryasuo/UltraDark
c9f60e3a754b051db33c29129f943807c6010b9e
[ "MIT" ]
null
null
null
ultra/not_released/dark/cfgparser.hpp
badryasuo/UltraDark
c9f60e3a754b051db33c29129f943807c6010b9e
[ "MIT" ]
null
null
null
ultra/not_released/dark/cfgparser.hpp
badryasuo/UltraDark
c9f60e3a754b051db33c29129f943807c6010b9e
[ "MIT" ]
null
null
null
#ifndef DARK_PARSER #define DARK_PARSER #include "std.hpp" #include <stdlib.h> #include <fstream> #include <sstream> namespace dark { class cfgparser { private: std::ifstream file; const wchar_t * path; std::stringstream datastream; dark::str data; protected: public: cfgparser(const wchar_t * name) : path(name) { file.open(name); datastream << file.rdbuf(); std::string s = datastream.str(); data = datastream.str().c_str(); } ~cfgparser() { file.close(); } char_ptr valueof(const char * key, size_t length) { char_ptr value = dark::cstr::allocate(length+1); dark::index pos = 0; size_t newline = 0; /*if ((pos = data.indexof(key)) != -1) { while (data[pos]) { if (data[pos] == '=') { while (dark::c::isalpha(data[pos]) || dark::c::isdigit(data[pos])) { //dark::cstr::append(value, data[pos]); pos++; } } pos++; } std::cout << "pos=" << pos << std::endl; if ((newline = dark::cstr::find(data, "\n")) != -1) { std::cout << "newline=" << newline << std::endl; //val = data.substr(pos, newline); } }*/ return 0; } }; } #endif
20.033898
72
0.558376
badryasuo
093418209c98da3ac71566c02d72d267b745b077
16,379
cc
C++
ORC_app/jni-build/jni/include/google/protobuf/src/google/protobuf/compiler/objectivec/objectivec_field.cc
luoabd/EMNIST-ORC
8c2d633a9b4d5214e908550812f6a2489ba9eb72
[ "MIT" ]
42
2016-08-22T03:49:32.000Z
2020-06-29T14:00:27.000Z
ORC_app/jni-build/jni/include/google/protobuf/src/google/protobuf/compiler/objectivec/objectivec_field.cc
luoabd/EMNIST-ORC
8c2d633a9b4d5214e908550812f6a2489ba9eb72
[ "MIT" ]
6
2016-09-02T03:44:35.000Z
2018-11-27T13:20:36.000Z
ORC_app/jni-build/jni/include/google/protobuf/src/google/protobuf/compiler/objectivec/objectivec_field.cc
luoabd/EMNIST-ORC
8c2d633a9b4d5214e908550812f6a2489ba9eb72
[ "MIT" ]
12
2017-03-18T22:22:28.000Z
2020-06-19T20:54:53.000Z
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <google/protobuf/compiler/objectivec/objectivec_field.h> #include <google/protobuf/compiler/objectivec/objectivec_helpers.h> #include <google/protobuf/compiler/objectivec/objectivec_enum_field.h> #include <google/protobuf/compiler/objectivec/objectivec_map_field.h> #include <google/protobuf/compiler/objectivec/objectivec_message_field.h> #include <google/protobuf/compiler/objectivec/objectivec_primitive_field.h> #include <google/protobuf/io/printer.h> #include <google/protobuf/wire_format.h> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/strutil.h> namespace google { namespace protobuf { namespace compiler { namespace objectivec { namespace { void SetCommonFieldVariables(const FieldDescriptor* descriptor, map<string, string>* variables) { string camel_case_name = FieldName(descriptor); string raw_field_name; if (descriptor->type() == FieldDescriptor::TYPE_GROUP) { raw_field_name = descriptor->message_type()->name(); } else { raw_field_name = descriptor->name(); } // The logic here has to match -[GGPBFieldDescriptor textFormatName]. const string un_camel_case_name( UnCamelCaseFieldName(camel_case_name, descriptor)); const bool needs_custom_name = (raw_field_name != un_camel_case_name); SourceLocation location; if (descriptor->GetSourceLocation(&location)) { (*variables)["comments"] = BuildCommentsString(location); } else { (*variables)["comments"] = "\n"; } const string& classname = ClassName(descriptor->containing_type()); (*variables)["classname"] = classname; (*variables)["name"] = camel_case_name; const string& capitalized_name = FieldNameCapitalized(descriptor); (*variables)["capitalized_name"] = capitalized_name; (*variables)["raw_field_name"] = raw_field_name; (*variables)["field_number_name"] = classname + "_FieldNumber_" + capitalized_name; (*variables)["field_number"] = SimpleItoa(descriptor->number()); (*variables)["has_index"] = SimpleItoa(descriptor->index()); (*variables)["field_type"] = GetCapitalizedType(descriptor); std::vector<string> field_flags; if (descriptor->is_repeated()) field_flags.push_back("GPBFieldRepeated"); if (descriptor->is_required()) field_flags.push_back("GPBFieldRequired"); if (descriptor->is_optional()) field_flags.push_back("GPBFieldOptional"); if (descriptor->is_packed()) field_flags.push_back("GPBFieldPacked"); // ObjC custom flags. if (descriptor->has_default_value()) field_flags.push_back("GPBFieldHasDefaultValue"); if (needs_custom_name) field_flags.push_back("GPBFieldTextFormatNameCustom"); if (descriptor->type() == FieldDescriptor::TYPE_ENUM) { field_flags.push_back("GPBFieldHasEnumDescriptor"); } (*variables)["fieldflags"] = BuildFlagsString(field_flags); (*variables)["default"] = DefaultValue(descriptor); (*variables)["default_name"] = GPBGenericValueFieldName(descriptor); (*variables)["dataTypeSpecific_name"] = "className"; (*variables)["dataTypeSpecific_value"] = "NULL"; string field_options = descriptor->options().SerializeAsString(); // Must convert to a standard byte order for packing length into // a cstring. uint32 length = ghtonl(field_options.length()); if (length > 0) { string bytes((const char*)&length, sizeof(length)); bytes.append(field_options); string options_str = "\"" + CEscape(bytes) + "\""; (*variables)["fieldoptions"] = "\"" + CEscape(bytes) + "\""; } else { (*variables)["fieldoptions"] = ""; } // Clear some common things so they can be set just when needed. (*variables)["storage_attribute"] = ""; } } // namespace FieldGenerator* FieldGenerator::Make(const FieldDescriptor* field, const Options& options) { FieldGenerator* result = NULL; if (field->is_repeated()) { switch (GetObjectiveCType(field)) { case OBJECTIVECTYPE_MESSAGE: { if (field->is_map()) { result = new MapFieldGenerator(field, options); } else { result = new RepeatedMessageFieldGenerator(field, options); } break; } case OBJECTIVECTYPE_ENUM: result = new RepeatedEnumFieldGenerator(field, options); break; default: result = new RepeatedPrimitiveFieldGenerator(field, options); break; } } else { switch (GetObjectiveCType(field)) { case OBJECTIVECTYPE_MESSAGE: { result = new MessageFieldGenerator(field, options); break; } case OBJECTIVECTYPE_ENUM: result = new EnumFieldGenerator(field, options); break; default: if (IsReferenceType(field)) { result = new PrimitiveObjFieldGenerator(field, options); } else { result = new PrimitiveFieldGenerator(field, options); } break; } } result->FinishInitialization(); return result; } FieldGenerator::FieldGenerator(const FieldDescriptor* descriptor, const Options& options) : descriptor_(descriptor) { SetCommonFieldVariables(descriptor, &variables_); } FieldGenerator::~FieldGenerator() {} void FieldGenerator::GenerateFieldNumberConstant(io::Printer* printer) const { printer->Print( variables_, "$field_number_name$ = $field_number$,\n"); } void FieldGenerator::GenerateCFunctionDeclarations( io::Printer* printer) const { // Nothing } void FieldGenerator::GenerateCFunctionImplementations( io::Printer* printer) const { // Nothing } void FieldGenerator::DetermineForwardDeclarations( set<string>* fwd_decls) const { // Nothing } void FieldGenerator::GenerateFieldDescription( io::Printer* printer) const { printer->Print( variables_, "{\n" " .name = \"$name$\",\n" " .number = $field_number_name$,\n" " .hasIndex = $has_index$,\n" " .flags = $fieldflags$,\n" " .dataType = GPBDataType$field_type$,\n" " .offset = offsetof($classname$__storage_, $name$),\n" " .defaultValue.$default_name$ = $default$,\n"); // TODO(thomasvl): It might be useful to add a CPP wrapper to support // compiling away the EnumDescriptors. To do that, we'd need a #if here // to control setting the descriptor vs. the validator, and above in // SetCommonFieldVariables() we'd want to wrap how we add // GPBFieldHasDefaultValue to the flags. // " .dataTypeSpecific.value* = [something]," GenerateFieldDescriptionTypeSpecific(printer); const string& field_options(variables_.find("fieldoptions")->second); if (field_options.empty()) { printer->Print(" .fieldOptions = NULL,\n"); } else { // Can't use PrintRaw() here to get the #if/#else/#endif lines completely // outdented because the need for indent captured on the previous // printing of a \n and there is no way to get the current indent level // to call the right number of Outdent()/Indents() to maintain state. printer->Print( variables_, "#if GPBOBJC_INCLUDE_FIELD_OPTIONS\n" " .fieldOptions = $fieldoptions$,\n" "#else\n" " .fieldOptions = NULL,\n" "#endif // GPBOBJC_INCLUDE_FIELD_OPTIONS\n"); } printer->Print("},\n"); } void FieldGenerator::GenerateFieldDescriptionTypeSpecific( io::Printer* printer) const { printer->Print( variables_, " .dataTypeSpecific.$dataTypeSpecific_name$ = $dataTypeSpecific_value$,\n"); } void FieldGenerator::SetOneofIndexBase(int index_base) { if (descriptor_->containing_oneof() != NULL) { int index = descriptor_->containing_oneof()->index() + index_base; // Flip the sign to mark it as a oneof. variables_["has_index"] = SimpleItoa(-index); } } void FieldGenerator::FinishInitialization(void) { // If "property_type" wasn't set, make it "storage_type". if ((variables_.find("property_type") == variables_.end()) && (variables_.find("storage_type") != variables_.end())) { variables_["property_type"] = variable("storage_type"); } } SingleFieldGenerator::SingleFieldGenerator(const FieldDescriptor* descriptor, const Options& options) : FieldGenerator(descriptor, options) { // Nothing } SingleFieldGenerator::~SingleFieldGenerator() {} void SingleFieldGenerator::GenerateFieldStorageDeclaration( io::Printer* printer) const { printer->Print(variables_, "$storage_type$ $name$;\n"); } void SingleFieldGenerator::GeneratePropertyDeclaration( io::Printer* printer) const { printer->Print(variables_, "$comments$"); if (WantsHasProperty()) { printer->Print( variables_, "@property(nonatomic, readwrite) BOOL has$capitalized_name$;\n"); } printer->Print( variables_, "@property(nonatomic, readwrite) $property_type$ $name$;\n" "\n"); } void SingleFieldGenerator::GeneratePropertyImplementation( io::Printer* printer) const { if (WantsHasProperty()) { printer->Print(variables_, "@dynamic has$capitalized_name$, $name$;\n"); } else { printer->Print(variables_, "@dynamic $name$;\n"); } } bool SingleFieldGenerator::WantsHasProperty(void) const { if (descriptor_->containing_oneof() != NULL) { // If in a oneof, it uses the oneofcase instead of a has bit. return false; } if (HasFieldPresence(descriptor_->file())) { // In proto1/proto2, every field has a has_$name$() method. return true; } return false; } ObjCObjFieldGenerator::ObjCObjFieldGenerator(const FieldDescriptor* descriptor, const Options& options) : SingleFieldGenerator(descriptor, options) { variables_["property_storage_attribute"] = "strong"; if (IsRetainedName(variables_["name"])) { variables_["storage_attribute"] = " NS_RETURNS_NOT_RETAINED"; } } ObjCObjFieldGenerator::~ObjCObjFieldGenerator() {} void ObjCObjFieldGenerator::GenerateFieldStorageDeclaration( io::Printer* printer) const { printer->Print(variables_, "$storage_type$ *$name$;\n"); } void ObjCObjFieldGenerator::GeneratePropertyDeclaration( io::Printer* printer) const { // Differs from SingleFieldGenerator::GeneratePropertyDeclaration() in that // it uses pointers and deals with Objective C's rules around storage name // conventions (init*, new*, etc.) printer->Print(variables_, "$comments$"); if (WantsHasProperty()) { printer->Print( variables_, "@property(nonatomic, readwrite) BOOL has$capitalized_name$;\n"); } printer->Print( variables_, "@property(nonatomic, readwrite, $property_storage_attribute$, null_resettable) $property_type$ *$name$$storage_attribute$;\n"); if (IsInitName(variables_.find("name")->second)) { // If property name starts with init we need to annotate it to get past ARC. // http://stackoverflow.com/questions/18723226/how-do-i-annotate-an-objective-c-property-with-an-objc-method-family/18723227#18723227 printer->Print(variables_, "- ($property_type$ *)$name$ GPB_METHOD_FAMILY_NONE;\n"); } printer->Print("\n"); } RepeatedFieldGenerator::RepeatedFieldGenerator( const FieldDescriptor* descriptor, const Options& options) : ObjCObjFieldGenerator(descriptor, options) { // Repeated fields don't use the has index. variables_["has_index"] = "GPBNoHasBit"; // Default to no comment and let the cases needing it fill it in. variables_["array_comment"] = ""; } RepeatedFieldGenerator::~RepeatedFieldGenerator() {} void RepeatedFieldGenerator::FinishInitialization(void) { FieldGenerator::FinishInitialization(); if (variables_.find("array_property_type") == variables_.end()) { variables_["array_property_type"] = variable("array_storage_type"); } } void RepeatedFieldGenerator::GenerateFieldStorageDeclaration( io::Printer* printer) const { printer->Print(variables_, "$array_storage_type$ *$name$;\n"); } void RepeatedFieldGenerator::GeneratePropertyImplementation( io::Printer* printer) const { printer->Print(variables_, "@dynamic $name$, $name$_Count;\n"); } void RepeatedFieldGenerator::GeneratePropertyDeclaration( io::Printer* printer) const { // Repeated fields don't need the has* properties, but they do expose a // *Count (to check without autocreation). So for the field property we need // the same logic as ObjCObjFieldGenerator::GeneratePropertyDeclaration() for // dealing with needing Objective C's rules around storage name conventions // (init*, new*, etc.) printer->Print( variables_, "$comments$" "$array_comment$" "@property(nonatomic, readwrite, strong, null_resettable) $array_property_type$ *$name$$storage_attribute$;\n" "@property(nonatomic, readonly) NSUInteger $name$_Count;\n"); if (IsInitName(variables_.find("name")->second)) { // If property name starts with init we need to annotate it to get past ARC. // http://stackoverflow.com/questions/18723226/how-do-i-annotate-an-objective-c-property-with-an-objc-method-family/18723227#18723227 printer->Print(variables_, "- ($array_property_type$ *)$name$ GPB_METHOD_FAMILY_NONE;\n"); } printer->Print("\n"); } bool RepeatedFieldGenerator::WantsHasProperty(void) const { // Consumer check the array size/existance rather than a has bit. return false; } FieldGeneratorMap::FieldGeneratorMap(const Descriptor* descriptor, const Options& options) : descriptor_(descriptor), field_generators_( new scoped_ptr<FieldGenerator>[descriptor->field_count()]), extension_generators_( new scoped_ptr<FieldGenerator>[descriptor->extension_count()]) { // Construct all the FieldGenerators. for (int i = 0; i < descriptor->field_count(); i++) { field_generators_[i].reset( FieldGenerator::Make(descriptor->field(i), options)); } for (int i = 0; i < descriptor->extension_count(); i++) { extension_generators_[i].reset( FieldGenerator::Make(descriptor->extension(i), options)); } } FieldGeneratorMap::~FieldGeneratorMap() {} const FieldGenerator& FieldGeneratorMap::get( const FieldDescriptor* field) const { GOOGLE_CHECK_EQ(field->containing_type(), descriptor_); return *field_generators_[field->index()]; } const FieldGenerator& FieldGeneratorMap::get_extension(int index) const { return *extension_generators_[index]; } void FieldGeneratorMap::SetOneofIndexBase(int index_base) { for (int i = 0; i < descriptor_->field_count(); i++) { field_generators_[i]->SetOneofIndexBase(index_base); } } } // namespace objectivec } // namespace compiler } // namespace protobuf } // namespace google
36.972912
137
0.702546
luoabd
093474972d62594d339a7d76b21f7c90757ac57f
33,150
cpp
C++
daemon/SecretsImpl/metadatadb.cpp
mkenttala/sailfish-secrets
600ca62f76a0d537e4fefa80b6e69b77f0b3dac5
[ "BSD-3-Clause" ]
27
2017-11-02T11:18:47.000Z
2021-06-29T10:40:34.000Z
daemon/SecretsImpl/metadatadb.cpp
mkenttala/sailfish-secrets
600ca62f76a0d537e4fefa80b6e69b77f0b3dac5
[ "BSD-3-Clause" ]
149
2017-11-09T09:31:52.000Z
2021-12-24T09:27:19.000Z
daemon/SecretsImpl/metadatadb.cpp
mkenttala/sailfish-secrets
600ca62f76a0d537e4fefa80b6e69b77f0b3dac5
[ "BSD-3-Clause" ]
16
2017-11-09T08:23:22.000Z
2021-06-18T06:15:48.000Z
/* * Copyright (C) 2018 Jolla Ltd. * Contact: Chris Adams <chris.adams@jollamobile.com> * All rights reserved. * BSD 3-Clause License, see LICENSE. */ #include "metadatadb_p.h" #include "controller_p.h" using namespace Sailfish::Secrets; // arg %1 must be a 64-character hex string = 32 byte key. static const char *setupEncryptionKey = "\n PRAGMA key = \"x\'%1\'\";"; // arg %1 must be a 64-character hex string = 32 byte key. static const char *setupReEncryptionKey = "\n PRAGMA rekey = \"x\'%1\'\";"; static const char *setupEnforceForeignKeys = "\n PRAGMA foreign_keys = ON;"; static const char *setupEncoding = "\n PRAGMA encoding = \"UTF-16\";"; static const char *setupTempStore = "\n PRAGMA temp_store = MEMORY;"; static const char *setupJournal = "\n PRAGMA journal_mode = WAL;"; static const char *setupSynchronous = "\n PRAGMA synchronous = FULL;"; static const char *createCollectionsTable = "\n CREATE TABLE Collections (" " CollectionId INTEGER PRIMARY KEY AUTOINCREMENT," " CollectionName TEXT NOT NULL," " ApplicationId TEXT NOT NULL," " UsesDeviceLockKey INTEGER NOT NULL," " EncryptionPluginName TEXT NOT NULL," " AuthenticationPluginName TEXT NOT NULL," " UnlockSemantic INTEGER NOT NULL," " AccessControlMode INTEGER NOT NULL," " CONSTRAINT collectionNameUnique UNIQUE (CollectionName));"; static const char *createSecretsTable = "\n CREATE TABLE Secrets (" " SecretId INTEGER PRIMARY KEY AUTOINCREMENT," " CollectionName TEXT NOT NULL," " SecretName TEXT NOT NULL," " ApplicationId TEXT NOT NULL," " UsesDeviceLockKey INTEGER NOT NULL," " EncryptionPluginName TEXT NOT NULL," " AuthenticationPluginName TEXT NOT NULL," " UnlockSemantic INTEGER NOT NULL," " AccessControlMode INTEGER NOT NULL," " Type Text," " CryptoPluginName TEXT," " FOREIGN KEY (CollectionName) REFERENCES Collections(CollectionName) ON DELETE CASCADE," " CONSTRAINT collectionSecretNameUnique UNIQUE (CollectionName, SecretName));"; static const char *createStatements[] = { createCollectionsTable, createSecretsTable, NULL }; static Daemon::Sqlite::UpgradeOperation upgradeVersions[] = { { 0, 0 }, }; static const int currentSchemaVersion = 1; Daemon::ApiImpl::MetadataDatabase::MetadataDatabase( const QString &defaultEncryptionPluginName, const QString &defaultAuthenticationPluginName, const QString &storagePluginName, bool pluginIsEncryptedStorage, bool autotestMode) : m_defaultEncryptionPluginName(defaultEncryptionPluginName) , m_defaultAuthenticationPluginName(defaultAuthenticationPluginName) , m_storagePluginName(storagePluginName) , m_pluginIsEncryptedStorage(pluginIsEncryptedStorage) , m_autotestMode(autotestMode) { } Daemon::ApiImpl::MetadataDatabase::~MetadataDatabase() { } QString Daemon::ApiImpl::MetadataDatabase::databaseConnectionName() const { return QStringLiteral("%1-metadata").arg(m_storagePluginName); } QString Daemon::ApiImpl::MetadataDatabase::databaseFileName() const { return QStringLiteral("metadata.db"); } bool Daemon::ApiImpl::MetadataDatabase::openDatabase(const QByteArray &hexKey) { const QByteArray setupKeyStatement = QString::fromLatin1(setupEncryptionKey).arg(QString::fromLatin1(hexKey)).toLatin1(); const char *setupKeyStatementData = setupKeyStatement.constData(); const char *setupStatements[] = { setupKeyStatementData, setupEnforceForeignKeys, setupEncoding, setupTempStore, setupJournal, setupSynchronous, NULL }; bool success = m_db.open(QStringLiteral("QSQLCIPHER"), m_storagePluginName, databaseFileName(), setupStatements, createStatements, upgradeVersions, currentSchemaVersion, databaseConnectionName(), m_autotestMode); if (success) { QStringList cnames; Result result = collectionNames(&cnames, false); if (!cnames.contains(QStringLiteral("standalone"))) { CollectionMetadata metadata; metadata.collectionName = QStringLiteral("standalone"); metadata.ownerApplicationId = QStringLiteral("standalone"); metadata.usesDeviceLockKey = false; metadata.encryptionPluginName = QStringLiteral("standalone"); metadata.authenticationPluginName = QStringLiteral("standalone"); metadata.unlockSemantic = 0; metadata.accessControlMode = SecretManager::NoAccessControlMode; result = insertCollectionMetadata(metadata); if (result.code() != Result::Succeeded) { qWarning() << "Failed to insert the notional standalone collection in plugin" << m_storagePluginName << result.errorMessage(); success = false; } } } return success; } QString Daemon::ApiImpl::MetadataDatabase::errorMessage() const { return m_db.lastError().text(); } bool Daemon::ApiImpl::MetadataDatabase::isOpen() const { return m_db.isOpen(); } bool Daemon::ApiImpl::MetadataDatabase::beginTransaction() { return m_db.beginTransaction(); } bool Daemon::ApiImpl::MetadataDatabase::commitTransaction() { return m_db.commitTransaction(); } bool Daemon::ApiImpl::MetadataDatabase::rollbackTransaction() { return m_db.rollbackTransaction(); } bool Daemon::ApiImpl::MetadataDatabase::withinTransaction() { return m_db.withinTransaction(); } Result Daemon::ApiImpl::MetadataDatabase::isLocked( bool *locked) const { Result retn(Result::Succeeded); if (!m_db.isOpen()) { *locked = true; } else { const QString lockedQuery = QStringLiteral("SELECT Count(*) FROM sqlite_master;"); QString errorText; Daemon::Sqlite::Database::Query lq = m_db.prepare(lockedQuery, &errorText); if (!errorText.isEmpty()) { retn = Result(Result::DatabaseQueryError, QString::fromUtf8("Unable to prepare is locked query: %1") .arg(errorText)); } else if (!m_db.execute(lq, &errorText)) { // unable to execute - the encryption key must be wrong (locked) *locked = true; } else { // able to execute - the encryption key is correct (unlocked) *locked = false; } } return retn; } Result Daemon::ApiImpl::MetadataDatabase::lock() { m_db.close(); QSqlDatabase::removeDatabase(databaseConnectionName()); return Result(Result::Succeeded); } Result Daemon::ApiImpl::MetadataDatabase::unlock( const QByteArray &hexKey) { Result retn(Result::Succeeded); if (hexKey.length() != 64) { retn = Result(Result::IncorrectAuthenticationCodeError, QLatin1String("The bookkeeping database key is not a 256 bit key")); } else { if (!m_db.isOpen()) { if (!openDatabase(hexKey)) { retn = Result(Result::DatabaseError, QStringLiteral("Unable to initialize the bookkeeping database with the given key")); } } else { const QString setupKeyStatement = QString::fromLatin1(setupEncryptionKey).arg(QString::fromLatin1(hexKey)); QString errorText; Daemon::Sqlite::Database::Query kq = m_db.prepare(setupKeyStatement, &errorText); if (!errorText.isEmpty()) { retn = Result(Result::DatabaseQueryError, QString::fromUtf8("Unable to prepare setup key query: %1").arg(errorText)); } else if (!m_db.beginTransaction()) { retn = Result(Result::DatabaseTransactionError, QString::fromUtf8("Unable to begin setup key transaction")); } else if (!m_db.execute(kq, &errorText)) { m_db.rollbackTransaction(); retn = Result(Result::DatabaseQueryError, QString::fromUtf8("Unable to execute setup key query: %1").arg(errorText)); } else if (!m_db.commitTransaction()) { m_db.rollbackTransaction(); retn = Result(Result::DatabaseTransactionError, QString::fromUtf8("Unable to commit setup key transaction")); } } } return retn; } Result Daemon::ApiImpl::MetadataDatabase::reencrypt( const QByteArray &oldHexKey, const QByteArray &newHexKey) { Result retn = unlock(oldHexKey); if (retn.code() != Result::Succeeded) { return retn; } bool locked = false; retn = isLocked(&locked); if (retn.code() != Result::Succeeded) { return retn; } if (locked) { return Result(Result::CollectionIsLockedError, QString::fromUtf8("The old bookkeeping key was not correct")); } if (newHexKey.length() != 64) { return Result(Result::IncorrectAuthenticationCodeError, QLatin1String("The new bookkeeping key is not a 256 bit key")); } const QString setupReKeyStatement = QString::fromLatin1(setupReEncryptionKey).arg(QString::fromLatin1(newHexKey)); QString errorText; Daemon::Sqlite::Database::Query kq = m_db.prepare(setupReKeyStatement, &errorText); if (!errorText.isEmpty()) { retn = Result(Result::DatabaseQueryError, QString::fromUtf8("Unable to prepare setup rekey query: %1").arg(errorText)); } else if (!m_db.beginTransaction()) { retn = Result(Result::DatabaseTransactionError, QString::fromUtf8("Unable to begin setup rekey transaction")); } else if (!m_db.execute(kq, &errorText)) { m_db.rollbackTransaction(); retn = Result(Result::DatabaseQueryError, QString::fromUtf8("Unable to execute setup rekey query: %1").arg(errorText)); } else if (!m_db.commitTransaction()) { m_db.rollbackTransaction(); retn = Result(Result::DatabaseTransactionError, QString::fromUtf8("Unable to commit setup rekey transaction")); } return retn; } //------------------------------------------------------------------- Result Daemon::ApiImpl::MetadataDatabase::insertCollectionMetadata( const CollectionMetadata &metadata) { const QString insertCollectionQuery = QStringLiteral( "INSERT INTO Collections (" "CollectionName," "ApplicationId," "UsesDeviceLockKey," "EncryptionPluginName," "AuthenticationPluginName," "UnlockSemantic," "AccessControlMode" ")" " VALUES (" "?,?,?,?,?,?,?" ");"); QString errorText; Daemon::Sqlite::Database::Query iq = m_db.prepare(insertCollectionQuery, &errorText); if (!errorText.isEmpty()) { return Result(Result::DatabaseQueryError, QString::fromLatin1("Unable to prepare insert collection query: %1").arg(errorText)); } QVariantList ivalues; ivalues << metadata.collectionName << metadata.ownerApplicationId << QVariant::fromValue<int>(metadata.usesDeviceLockKey ? 1 : 0) << metadata.encryptionPluginName << metadata.authenticationPluginName << metadata.unlockSemantic << static_cast<int>(metadata.accessControlMode); iq.bindValues(ivalues); if (!m_db.execute(iq, &errorText)) { return Result(Result::DatabaseQueryError, QString::fromLatin1("Unable to execute insert collection query: %1").arg(errorText)); } return Result(Result::Succeeded); } Result Daemon::ApiImpl::MetadataDatabase::collectionNames( QStringList *names, bool removeStandalone) { const QString selectCollectionNamesQuery = QStringLiteral( "SELECT CollectionName" " FROM Collections;" ); QString errorText; Daemon::Sqlite::Database::Query sq = m_db.prepare(selectCollectionNamesQuery, &errorText); if (!errorText.isEmpty()) { return Result(Result::DatabaseQueryError, QString::fromLatin1("Unable to prepare select collection names query: %1").arg(errorText)); } if (!m_db.execute(sq, &errorText)) { return Result(Result::DatabaseQueryError, QString::fromLatin1("Unable to execute select collection names query: %1").arg(errorText)); } while (sq.next()) { const QString cname = sq.value(0).value<QString>(); if (!cname.isEmpty()) { if (!removeStandalone || cname.compare(QStringLiteral("standalone"), Qt::CaseInsensitive) != 0) { names->append(cname); } } } return Result(Result::Succeeded); } Result Daemon::ApiImpl::MetadataDatabase::collectionAlreadyExists( const QString &collectionName, bool *exists) { const QString selectCollectionsCountQuery = QStringLiteral( "SELECT" " Count(*)" " FROM Collections" " WHERE CollectionName = ?;" ); QString errorText; Daemon::Sqlite::Database::Query sq = m_db.prepare(selectCollectionsCountQuery, &errorText); if (!errorText.isEmpty()) { return Result(Result::DatabaseQueryError, QString::fromLatin1("Unable to prepare select collections query: %1").arg(errorText)); } QVariantList values; values << QVariant::fromValue<QString>(collectionName); sq.bindValues(values); if (!m_db.execute(sq, &errorText)) { return Result(Result::DatabaseQueryError, QString::fromLatin1("Unable to execute select collections query: %1").arg(errorText)); } if (sq.next() && sq.value(0).value<int>() > 0) { *exists = true; } else { *exists = false; } return Result(Result::Succeeded); } Result Daemon::ApiImpl::MetadataDatabase::collectionMetadata( const QString &collectionName, CollectionMetadata *metadata, bool *exists) { const QString selectCollectionQuery = QStringLiteral( "SELECT" " ApplicationId," " UsesDeviceLockKey," " EncryptionPluginName," " AuthenticationPluginName," " UnlockSemantic," " AccessControlMode" " FROM Collections" " WHERE CollectionName = ?;" ); QString errorText; Daemon::Sqlite::Database::Query sq = m_db.prepare(selectCollectionQuery, &errorText); if (!errorText.isEmpty()) { return Result(Result::DatabaseQueryError, QString::fromLatin1("Unable to prepare select collection query: %1").arg(errorText)); } QVariantList values; values << QVariant::fromValue<QString>(collectionName); sq.bindValues(values); if (!m_db.execute(sq, &errorText)) { return Result(Result::DatabaseQueryError, QString::fromLatin1("Unable to execute select collection query: %1").arg(errorText)); } if (exists) *exists = false; if (sq.next()) { if (exists) *exists = true; metadata->ownerApplicationId = sq.value(0).value<QString>(); metadata->usesDeviceLockKey = sq.value(1).value<int>() > 0; metadata->encryptionPluginName = sq.value(2).value<QString>(); metadata->authenticationPluginName = sq.value(3).value<QString>(); metadata->unlockSemantic = sq.value(4).value<int>(); metadata->accessControlMode = static_cast<SecretManager::AccessControlMode>(sq.value(5).value<int>()); } return Result(Result::Succeeded); } Result Daemon::ApiImpl::MetadataDatabase::deleteCollectionMetadata( const QString &collectionName) { const QString deleteCollectionQuery = QStringLiteral( "DELETE FROM Collections" " WHERE CollectionName = ?;"); QString errorText; Daemon::Sqlite::Database::Query dq = m_db.prepare(deleteCollectionQuery, &errorText); if (!errorText.isEmpty()) { return Result(Result::DatabaseQueryError, QString::fromLatin1("Unable to prepare delete collection query: %1").arg(errorText)); } QVariantList values; values << QVariant::fromValue<QString>(collectionName); dq.bindValues(values); if (!m_db.execute(dq, &errorText)) { return Result(Result::DatabaseQueryError, QString::fromLatin1("Unable to execute delete collection query: %1").arg(errorText)); } return Result(Result::Succeeded); } Result Daemon::ApiImpl::MetadataDatabase::secretAlreadyExists( const QString &collectionName, const QString &secretName, bool *exists) { const QString selectSecretsCountQuery = QStringLiteral( "SELECT" " Count(*)" " FROM Secrets" " WHERE CollectionName = ?" " AND SecretName = ?;" ); QString errorText; Daemon::Sqlite::Database::Query ssq = m_db.prepare(selectSecretsCountQuery, &errorText); if (!errorText.isEmpty()) { return Result(Result::DatabaseQueryError, QString::fromLatin1("Unable to prepare select secrets query: %1").arg(errorText)); } QVariantList values; values << QVariant::fromValue<QString>(collectionName); values << QVariant::fromValue<QString>(secretName); ssq.bindValues(values); if (!m_db.execute(ssq, &errorText)) { return Result(Result::DatabaseQueryError, QString::fromLatin1("Unable to execute select secrets query: %1").arg(errorText)); } if (ssq.next()) { *exists = ssq.value(0).value<int>() > 0; } return Result(Result::Succeeded); } Result Daemon::ApiImpl::MetadataDatabase::insertSecretMetadata( const SecretMetadata &metadata) { const QString insertSecretQuery = QStringLiteral( "INSERT INTO Secrets (" "CollectionName," "SecretName," "ApplicationId," "UsesDeviceLockKey," "EncryptionPluginName," "AuthenticationPluginName," "UnlockSemantic," "AccessControlMode," "Type," "CryptoPluginName" ")" " VALUES (" "?,?,?,?,?,?,?,?,?,?" ");"); QString errorText; Daemon::Sqlite::Database::Query iq = m_db.prepare(insertSecretQuery, &errorText); if (!errorText.isEmpty()) { return Result(Result::DatabaseQueryError, QString::fromLatin1("Unable to prepare insert secret query: %1").arg(errorText)); } QVariantList ivalues; ivalues << QVariant::fromValue<QString>(metadata.collectionName); ivalues << QVariant::fromValue<QString>(metadata.secretName); ivalues << QVariant::fromValue<QString>(metadata.ownerApplicationId); ivalues << QVariant::fromValue<int>(metadata.usesDeviceLockKey ? 1 : 0); ivalues << QVariant::fromValue<QString>(metadata.encryptionPluginName); ivalues << QVariant::fromValue<QString>(metadata.authenticationPluginName); ivalues << QVariant::fromValue<int>(metadata.unlockSemantic); ivalues << QVariant::fromValue<int>(static_cast<int>(metadata.accessControlMode)); ivalues << QVariant::fromValue<QString>(metadata.secretType); ivalues << QVariant::fromValue<QString>(metadata.cryptoPluginName); iq.bindValues(ivalues); if (!m_db.execute(iq, &errorText)) { return Result(Result::DatabaseQueryError, QString::fromLatin1("Unable to execute insert secret query: %1").arg(errorText)); } return Result(Result::Succeeded); } Result Daemon::ApiImpl::MetadataDatabase::updateSecretMetadata( const SecretMetadata &metadata) { const QString updateSecretQuery = QStringLiteral( "UPDATE Secrets" " SET ApplicationId = ?," " UsesDeviceLockKey = ?," " EncryptionPluginName = ?," " AuthenticationPluginName = ?," " UnlockSemantic = ?," " AccessControlMode = ?," " Type = ?," " CryptoPluginName = ?" " WHERE CollectionName = ?" " AND SecretName = ?;" ); QString errorText; Daemon::Sqlite::Database::Query iq = m_db.prepare(updateSecretQuery, &errorText); if (!errorText.isEmpty()) { return Result(Result::DatabaseQueryError, QString::fromLatin1("Unable to prepare update secret query: %1").arg(errorText)); } QVariantList ivalues; ivalues << QVariant::fromValue<QString>(metadata.ownerApplicationId); ivalues << QVariant::fromValue<int>(metadata.usesDeviceLockKey ? 1 : 0); ivalues << QVariant::fromValue<QString>(metadata.encryptionPluginName); ivalues << QVariant::fromValue<QString>(metadata.authenticationPluginName); ivalues << QVariant::fromValue<int>(metadata.unlockSemantic); ivalues << QVariant::fromValue<int>(static_cast<int>(metadata.accessControlMode)); ivalues << QVariant::fromValue<QString>(metadata.secretType); ivalues << QVariant::fromValue<QString>(metadata.cryptoPluginName); ivalues << QVariant::fromValue<QString>(metadata.collectionName); ivalues << QVariant::fromValue<QString>(metadata.secretName); iq.bindValues(ivalues); if (!m_db.execute(iq, &errorText)) { return Result(Result::DatabaseQueryError, QString::fromLatin1("Unable to execute update secret query: %1").arg(errorText)); } return Result(Result::Succeeded); } Result Daemon::ApiImpl::MetadataDatabase::deleteSecretMetadata( const QString &collectionName, const QString &secretName) { const QString deleteSecretQuery = QStringLiteral( "DELETE FROM Secrets" " WHERE CollectionName = ?" " AND SecretName = ?;"); QString errorText; Daemon::Sqlite::Database::Query dq = m_db.prepare(deleteSecretQuery, &errorText); if (!errorText.isEmpty()) { return Result(Result::DatabaseQueryError, QString::fromLatin1("Unable to prepare delete secret query: %1").arg(errorText)); } QVariantList values; values << QVariant::fromValue<QString>(collectionName); values << QVariant::fromValue<QString>(secretName); dq.bindValues(values); if (!m_db.execute(dq, &errorText)) { return Result(Result::DatabaseQueryError, QString::fromLatin1("Unable to execute delete secret query: %1").arg(errorText)); } return Result(Result::Succeeded); } Result Daemon::ApiImpl::MetadataDatabase::secretMetadata( const QString &collectionName, const QString &secretName, SecretMetadata *metadata, bool *exists) { const QString selectSecretsQuery = QStringLiteral( "SELECT" " ApplicationId," " UsesDeviceLockKey," " EncryptionPluginName," " AuthenticationPluginName," " UnlockSemantic," " AccessControlMode" " FROM Secrets" " WHERE CollectionName = ?" " AND SecretName = ?;" ); QString errorText; Daemon::Sqlite::Database::Query sq = m_db.prepare(selectSecretsQuery, &errorText); if (!errorText.isEmpty()) { return Result(Result::DatabaseQueryError, QString::fromLatin1("Unable to prepare select secrets query: %1").arg(errorText)); } QVariantList values; values << QVariant::fromValue<QString>(collectionName); values << QVariant::fromValue<QString>(secretName); sq.bindValues(values); if (!m_db.execute(sq, &errorText)) { return Result(Result::DatabaseQueryError, QString::fromLatin1("Unable to execute select secrets query: %1").arg(errorText)); } if (exists) *exists = false; if (sq.next()) { if (exists) *exists = true; metadata->ownerApplicationId = sq.value(0).value<QString>(); metadata->usesDeviceLockKey = sq.value(1).value<int>() > 0; metadata->encryptionPluginName = sq.value(2).value<QString>(); metadata->authenticationPluginName = sq.value(3).value<QString>(); metadata->unlockSemantic = sq.value(4).value<int>(); metadata->accessControlMode = static_cast<SecretManager::AccessControlMode>(sq.value(5).value<int>()); } return Result(Result::Succeeded); } Result Daemon::ApiImpl::MetadataDatabase::secretNames( const QString &collectionName, QStringList *names) { const QString selectSecretNamesQuery = QStringLiteral( "SELECT SecretName" " FROM Secrets" " WHERE CollectionName = ?;" ); QString errorText; Daemon::Sqlite::Database::Query sq = m_db.prepare(selectSecretNamesQuery, &errorText); if (!errorText.isEmpty()) { return Result(Result::DatabaseQueryError, QString::fromLatin1("Unable to prepare select secret names query: %1").arg(errorText)); } QVariantList values; values << collectionName; sq.bindValues(values); if (!m_db.execute(sq, &errorText)) { return Result(Result::DatabaseQueryError, QString::fromLatin1("Unable to execute select secret names query: %1").arg(errorText)); } while (sq.next()) { const QString sname = sq.value(0).value<QString>(); names->append(sname); } return Result(Result::Succeeded); } Result Daemon::ApiImpl::MetadataDatabase::keyNames( const QString &collectionName, QStringList *names) { const QString selectKeyNamesQuery = QStringLiteral( "SELECT SecretName" " FROM Secrets" " WHERE CollectionName = ?" " AND Type = 'CryptoKey';" ); QString errorText; Daemon::Sqlite::Database::Query sq = m_db.prepare(selectKeyNamesQuery, &errorText); if (!errorText.isEmpty()) { return Result(Result::DatabaseQueryError, QString::fromLatin1("Unable to prepare select key names query: %1").arg(errorText)); } QVariantList values; values << collectionName; sq.bindValues(values); if (!m_db.execute(sq, &errorText)) { return Result(Result::DatabaseQueryError, QString::fromLatin1("Unable to execute select key names query: %1").arg(errorText)); } while (sq.next()) { const QString sname = sq.value(0).value<QString>(); names->append(sname); } return Result(Result::Succeeded); } bool Daemon::ApiImpl::MetadataDatabase::initializeCollectionsFromPluginData( const QStringList &existingCollectionNames) { // retrieve the cnames from the metadata db QStringList cnames; Result result = collectionNames(&cnames); if (result.code() != Result::Succeeded) { return false; } bool modificationsSucceeded = true; // delete any collection in metadata db which is not in plugin for (const QString &cname : cnames) { if (!existingCollectionNames.contains(cname)) { if (deleteCollectionMetadata(cname).code() != Result::Succeeded) { modificationsSucceeded = false; } } } // add any collection which is not in metadata db to it. // TODO: this is imprecise, as we've "lost" information. // we just assume "default" values but it may be incorrect. // FIXME: how should we fix this issue? for (const QString &cname : existingCollectionNames) { if (!cnames.contains(cname)) { CollectionMetadata defaultMetadata; defaultMetadata.collectionName = cname; defaultMetadata.ownerApplicationId = QStringLiteral("imported"); defaultMetadata.usesDeviceLockKey = false; defaultMetadata.encryptionPluginName = m_pluginIsEncryptedStorage ? m_storagePluginName : m_defaultEncryptionPluginName; defaultMetadata.authenticationPluginName = m_defaultAuthenticationPluginName; defaultMetadata.unlockSemantic = SecretManager::CustomLockKeepUnlocked; defaultMetadata.accessControlMode = SecretManager::NoAccessControlMode; if (insertCollectionMetadata(defaultMetadata).code() != Result::Succeeded) { modificationsSucceeded = false; } } } return modificationsSucceeded; } bool Daemon::ApiImpl::MetadataDatabase::initializeSecretsFromPluginData( const QVector<Secret::Identifier> &identifiers, const QStringList &lockedCollectionNames) { // build up map of metadata identifiers, sorted by collection name QMap<QString, QStringList> metadataCNameToSNames; QStringList cnames; Result result = collectionNames(&cnames); if (result.code() != Result::Succeeded) { return false; } for (const QString &cname : cnames) { QStringList snames; result = secretNames(cname, &snames); if (result.code() != Result::Succeeded) { return false; } metadataCNameToSNames.insert(cname, snames); } // build up map of plugin data identifiers, sorted by collection name QMap<QString, QStringList> pluginCNameToSNames; for (const Secret::Identifier &ident : identifiers) { pluginCNameToSNames[ident.collectionName()].append(ident.name()); } bool modificationsSucceeded = true; // delete any secret in metadata db which is not in plugin for (const QString &cname : metadataCNameToSNames.keys()) { const QStringList &snames(metadataCNameToSNames[cname]); // don't delete secrets in locked collections, as we won't // know which ones still exist or not. if (!lockedCollectionNames.contains(cname)) { for (const QString &sname : snames) { if (!pluginCNameToSNames.contains(cname) || !pluginCNameToSNames[cname].contains(sname)) { // delete this secret, it must have been removed from the plugin. if (deleteSecretMetadata(cname, sname).code() != Result::Succeeded) { modificationsSucceeded = false; } } } } } // add any secret which is not in metadata db to it. // TODO: this is imprecise, as we've "lost" information. // we just assume "default" values but it may be incorrect. // FIXME: how should we fix this issue? for (const QString &cname : pluginCNameToSNames.keys()) { const QStringList &snames(pluginCNameToSNames[cname]); for (const QString &sname : snames) { if (!metadataCNameToSNames.contains(cname) || !metadataCNameToSNames[cname].contains(sname)) { // add this secret, it must have been added to the plugin. SecretMetadata defaultMetadata; defaultMetadata.collectionName = cname; defaultMetadata.secretName = sname; defaultMetadata.ownerApplicationId = QStringLiteral("imported"); defaultMetadata.usesDeviceLockKey = false; defaultMetadata.encryptionPluginName = m_pluginIsEncryptedStorage ? m_storagePluginName : m_defaultEncryptionPluginName; defaultMetadata.authenticationPluginName = m_defaultAuthenticationPluginName; defaultMetadata.unlockSemantic = SecretManager::CustomLockKeepUnlocked; defaultMetadata.accessControlMode = SecretManager::NoAccessControlMode; if (insertSecretMetadata(defaultMetadata).code() != Result::Succeeded) { modificationsSucceeded = false; } } } } return modificationsSucceeded; }
36.792453
125
0.615445
mkenttala
0936fbf8756708dd76c6540036e7e3e99a495e70
3,044
cpp
C++
src/game/client/hud_vguiscreencursor.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/game/client/hud_vguiscreencursor.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/game/client/hud_vguiscreencursor.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "hud.h" #include "iclientmode.h" #include "hudelement.h" //#include "view.h" //#include "vgui_controls/Controls.h" #include "vgui/ISurface.h" #include "vgui/IInput.h" #include <vgui_controls/Panel.h> // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" using namespace vgui; //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- class CHudVguiScreenCursor : public CHudElement, public vgui::Panel { DECLARE_CLASS_SIMPLE(CHudVguiScreenCursor, vgui::Panel); public: CHudVguiScreenCursor(const char *pElementName); virtual bool ShouldDraw(); protected: virtual void ApplySchemeSettings(vgui::IScheme *scheme); virtual void Paint(); private: // Cursor sprite and color CHudTexture *m_pCursor; Color m_clrCrosshair; }; DECLARE_HUDELEMENT(CHudVguiScreenCursor); CHudVguiScreenCursor::CHudVguiScreenCursor(const char *pElementName) : CHudElement(pElementName), BaseClass(NULL, "VguiScreenCursor") { vgui::Panel * pParent = g_pClientMode->GetViewport(); SetParent(pParent); m_pCursor = 0; m_clrCrosshair = Color(0, 0, 0, 0); SetHiddenBits(HIDEHUD_PLAYERDEAD); } void CHudVguiScreenCursor::ApplySchemeSettings(IScheme *scheme) { BaseClass::ApplySchemeSettings(scheme); m_clrCrosshair = scheme->GetColor("VguiScreenCursor", Color(255, 255, 255, 255)); m_pCursor = gHUD.GetIcon("arrow"); SetPaintBackgroundEnabled(false); SetSize(ScreenWidth(), ScreenHeight()); } //----------------------------------------------------------------------------- // Purpose: Save CPU cycles by letting the HUD system early cull // costly traversal. Called per frame, return true if thinking and // painting need to occur. //----------------------------------------------------------------------------- bool CHudVguiScreenCursor::ShouldDraw(void) { C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer(); if (!pPlayer) return false; if (pPlayer->IsInViewModelVGuiInputMode()) { return false; } if (!pPlayer->IsInVGuiInputMode()) { return false; } return CHudElement::ShouldDraw(); } void CHudVguiScreenCursor::Paint(void) { if (!m_pCursor) return; float x, y; x = ScreenWidth() / 2; y = ScreenHeight() / 2; C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer(); if (!pPlayer) return; if (pPlayer->IsInViewModelVGuiInputMode()) { int iX, iY; vgui::input()->GetCursorPos(iX, iY); x = (float) iX; y = (float) iY; } m_pCursor->DrawSelf( x - 0.5f * m_pCursor->Width(), y - 0.5f * m_pCursor->Height(), m_clrCrosshair); }
26.701754
85
0.578515
cstom4994