hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
80414079621538b5fd8948bf0a13bfa4c5831ccc
3,705
cpp
C++
fastflow/tests/test_ofarm.cpp
robzan8/prefixsum
5be9ae17473a3dd06406f614e6515c31ac68a219
[ "MIT" ]
2
2017-11-09T11:32:14.000Z
2021-09-12T20:26:36.000Z
fastflow/tests/test_ofarm.cpp
robzan8/prefixsum
5be9ae17473a3dd06406f614e6515c31ac68a219
[ "MIT" ]
null
null
null
fastflow/tests/test_ofarm.cpp
robzan8/prefixsum
5be9ae17473a3dd06406f614e6515c31ac68a219
[ "MIT" ]
null
null
null
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* *************************************************************************** * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * As a special exception, you may use this file as part of a free software * library without restriction. Specifically, if other files instantiate * templates or use macros or inline functions from this file, or you compile * this file and link it with other files to produce an executable, this * file does not by itself cause the resulting executable to be covered by * the GNU General Public License. This exception does not however * invalidate any other reasons why the executable file might be covered by * the GNU General Public License. * **************************************************************************** */ /* * 3-stages pipeline * * --> Worker1 --> * | | * Start ----> --> Worker1 --> -----> Stop * | | * --> Worker1 --> * * farm * * This test shows how to implement an ordered farm. In this case * the farm respects the FIFO ordering of tasks..... * * */ #include <vector> #include <iostream> #include <ff/farm.hpp> #include <ff/pipeline.hpp> #include <ff/node.hpp> using namespace ff; class Start: public ff_node { public: Start(int streamlen):streamlen(streamlen) {} void* svc(void*) { for (int j=0;j<streamlen;j++) { ff_send_out(new long(j)); } return NULL; } private: int streamlen; }; class Worker1: public ff_node { public: void * svc(void * task) { usleep(random() % 20000); return task; } }; class Stop: public ff_node { public: Stop():expected(0) {} void* svc(void* task) { long t = *(long*)task; if (t != expected) printf("ERROR: task received out of order, received %ld expected %ld\n", t, expected); expected++; return GO_ON; } private: long expected; }; int main(int argc, char * argv[]) { int nworkers = 3; int streamlen = 1000; if (argc>1) { if (argc<3) { std::cerr << "use: " << argv[0] << " nworkers streamlen\n"; return -1; } nworkers=atoi(argv[1]); streamlen=atoi(argv[2]); } if (nworkers<=0 || streamlen<=0) { std::cerr << "Wrong parameters values\n"; return -1; } srandom(131071); ff_pipeline pipe; Start start(streamlen); pipe.add_stage(&start); ff_ofarm ofarm; std::vector<ff_node *> w; for(int i=0;i<nworkers;++i) w.push_back(new Worker1); ofarm.add_workers(w); pipe.add_stage(&ofarm); Stop stop; pipe.add_stage(&stop); pipe.run_and_wait_end(); std::cerr << "DONE\n"; return 0; }
27.043796
98
0.546289
robzan8
804365d54585c9a92d463429a3c62c48c159a0bd
119
cpp
C++
src/csapex_core/src/core/bootstrap_plugin.cpp
ICRA-2018/csapex
8ee83b9166d0281a4923184cce67b4a55f273ea2
[ "BSD-3-Clause" ]
21
2016-09-02T15:33:25.000Z
2021-06-10T06:34:39.000Z
src/csapex_core/src/core/bootstrap_plugin.cpp
ICRA-2018/csapex
8ee83b9166d0281a4923184cce67b4a55f273ea2
[ "BSD-3-Clause" ]
null
null
null
src/csapex_core/src/core/bootstrap_plugin.cpp
ICRA-2018/csapex
8ee83b9166d0281a4923184cce67b4a55f273ea2
[ "BSD-3-Clause" ]
10
2016-10-12T00:55:17.000Z
2020-04-24T19:59:02.000Z
/// HEADER #include <csapex/core/bootstrap_plugin.h> using namespace csapex; BootstrapPlugin::~BootstrapPlugin() { }
13.222222
41
0.756303
ICRA-2018
8046d814225032655eff98b65bd7c499539e10af
2,290
hh
C++
src/device/timer.hh
othieno/invaders
89cb19d8d305943897530e636e0ba69b8c2ad8d6
[ "MIT" ]
null
null
null
src/device/timer.hh
othieno/invaders
89cb19d8d305943897530e636e0ba69b8c2ad8d6
[ "MIT" ]
null
null
null
src/device/timer.hh
othieno/invaders
89cb19d8d305943897530e636e0ba69b8c2ad8d6
[ "MIT" ]
null
null
null
/* * This file is part of the Space Invaders clone project. * https://github.com/othieno/invaders * * Copyright (c) 2016 Jeremy Othieno. * * The MIT License (MIT) * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef DEVICE_TIMER_HH #define DEVICE_TIMER_HH namespace device { #define TIMERFREQ_SYS 0x0000 #define TIMERFREQ_64 0x0001 #define TIMERFREQ_256 0x0002 #define TIMERFREQ_1024 0x0003 #define TIMER_CASCADE 0x0004 #define TIMER_IRQ 0x0040 #define ENABLE_TIMER 0x0080 #ifdef COMMENT // Store the address of the interrupt handler. //REG_INTERRUPT = (unsigned int) interruptHandler; // Initialize TIMER0. Steps to take to calculate the number of ticks: // 1. How many microseconds or nanoseconds make one second? // 2. Substract this value from 2^16 and voila, your initial value. // Suppose we are using a 256 frequency (each clock cycle takes 15.256 microseconds), then this // would give (10^6/61.05 = 16380.xyz). Our initial value would then be: //REG_TM0D = 65536 - 16380; //REG_TM0CNT = ENABLE_TIMER | ENABLE_TIMER_IRQ | FREQ_1024; // Activate TIMER0 interrupt in REG_IE. //REG_IE |= IRQ_TIMER0; #endif } // namespace device #endif // DEVICE_TIMER_HH
32.253521
98
0.734934
othieno
804b121ad12829fbba57c3e308e56c1521d1276b
39,649
cc
C++
centreon-engine/modules/external_commands/src/processing.cc
centreon/centreon-collect
e63fc4d888a120d588a93169e7d36b360616bdee
[ "Unlicense" ]
8
2020-07-26T09:12:02.000Z
2022-03-30T17:24:29.000Z
centreon-engine/modules/external_commands/src/processing.cc
centreon/centreon-collect
e63fc4d888a120d588a93169e7d36b360616bdee
[ "Unlicense" ]
47
2020-06-18T12:11:37.000Z
2022-03-16T10:28:56.000Z
centreon-engine/modules/external_commands/src/processing.cc
centreon/centreon-collect
e63fc4d888a120d588a93169e7d36b360616bdee
[ "Unlicense" ]
5
2020-06-29T14:22:02.000Z
2022-03-17T10:34:10.000Z
/* ** Copyright 2011-2013,2015-2016 Centreon ** ** This file is part of Centreon Engine. ** ** Centreon Engine is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Engine is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with Centreon Engine. If not, see ** <http://www.gnu.org/licenses/>. */ #include "com/centreon/engine/modules/external_commands/processing.hh" #include <cstdlib> #include "com/centreon/engine/broker.hh" #include "com/centreon/engine/flapping.hh" #include "com/centreon/engine/globals.hh" #include "com/centreon/engine/logging/logger.hh" #include "com/centreon/engine/modules/external_commands/commands.hh" #include "com/centreon/engine/retention/applier/state.hh" #include "com/centreon/engine/retention/dump.hh" #include "com/centreon/engine/retention/parser.hh" #include "com/centreon/engine/retention/state.hh" using namespace com::centreon; using namespace com::centreon::engine; using namespace com::centreon::engine::logging; using namespace com::centreon::engine::modules::external_commands; // Dummy command. void dummy_command() {} processing::processing() : _lst_command{ {"ENTER_STANDBY_MODE", command_info(CMD_DISABLE_NOTIFICATIONS, &_redirector<&disable_all_notifications>)}, {"DISABLE_NOTIFICATIONS", command_info(CMD_DISABLE_NOTIFICATIONS, &_redirector<&disable_all_notifications>)}, // process commands. {"ENTER_ACTIVE_MODE", command_info(CMD_ENABLE_NOTIFICATIONS, &_redirector<&enable_all_notifications>)}, {"ENABLE_NOTIFICATIONS", command_info(CMD_ENABLE_NOTIFICATIONS, &_redirector<&enable_all_notifications>)}, {"SHUTDOWN_PROGRAM", command_info(CMD_SHUTDOWN_PROCESS, &_redirector<&cmd_signal_process>)}, {"SHUTDOWN_PROCESS", command_info(CMD_SHUTDOWN_PROCESS, &_redirector<&cmd_signal_process>)}, {"RESTART_PROGRAM", command_info(CMD_RESTART_PROCESS, &_redirector<&cmd_signal_process>)}, {"RESTART_PROCESS", command_info(CMD_RESTART_PROCESS, &_redirector<&cmd_signal_process>)}, {"SAVE_STATE_INFORMATION", command_info(CMD_SAVE_STATE_INFORMATION, &_redirector<&_wrapper_save_state_information>)}, {"READ_STATE_INFORMATION", command_info(CMD_READ_STATE_INFORMATION, &_redirector<&_wrapper_read_state_information>)}, {"ENABLE_EVENT_HANDLERS", command_info(CMD_ENABLE_EVENT_HANDLERS, &_redirector<&start_using_event_handlers>)}, {"DISABLE_EVENT_HANDLERS", command_info(CMD_DISABLE_EVENT_HANDLERS, &_redirector<&stop_using_event_handlers>)}, // _lst_command["FLUSH_PENDING_COMMANDS"] = // command_info(CMD_FLUSH_PENDING_COMMANDS, // &_redirector<&>); {"ENABLE_FAILURE_PREDICTION", command_info(CMD_ENABLE_FAILURE_PREDICTION, &_redirector<&dummy_command>)}, {"DISABLE_FAILURE_PREDICTION", command_info(CMD_DISABLE_FAILURE_PREDICTION, &_redirector<&dummy_command>)}, {"ENABLE_PERFORMANCE_DATA", command_info(CMD_ENABLE_PERFORMANCE_DATA, &_redirector<&enable_performance_data>)}, {"DISABLE_PERFORMANCE_DATA", command_info(CMD_DISABLE_PERFORMANCE_DATA, &_redirector<&disable_performance_data>)}, {"START_EXECUTING_HOST_CHECKS", command_info(CMD_START_EXECUTING_HOST_CHECKS, &_redirector<&start_executing_host_checks>)}, {"STOP_EXECUTING_HOST_CHECKS", command_info(CMD_STOP_EXECUTING_HOST_CHECKS, &_redirector<&stop_executing_host_checks>)}, {"START_EXECUTING_SVC_CHECKS", command_info(CMD_START_EXECUTING_SVC_CHECKS, &_redirector<&start_executing_service_checks>)}, {"STOP_EXECUTING_SVC_CHECKS", command_info(CMD_STOP_EXECUTING_SVC_CHECKS, &_redirector<&stop_executing_service_checks>)}, {"START_ACCEPTING_PASSIVE_HOST_CHECKS", command_info(CMD_START_ACCEPTING_PASSIVE_HOST_CHECKS, &_redirector<&start_accepting_passive_host_checks>)}, {"STOP_ACCEPTING_PASSIVE_HOST_CHECKS", command_info(CMD_STOP_ACCEPTING_PASSIVE_HOST_CHECKS, &_redirector<&stop_accepting_passive_host_checks>)}, {"START_ACCEPTING_PASSIVE_SVC_CHECKS", command_info(CMD_START_ACCEPTING_PASSIVE_SVC_CHECKS, &_redirector<&start_accepting_passive_service_checks>)}, {"STOP_ACCEPTING_PASSIVE_SVC_CHECKS", command_info(CMD_STOP_ACCEPTING_PASSIVE_SVC_CHECKS, &_redirector<&stop_accepting_passive_service_checks>)}, {"START_OBSESSING_OVER_HOST_CHECKS", command_info(CMD_START_OBSESSING_OVER_HOST_CHECKS, &_redirector<&start_obsessing_over_host_checks>)}, {"STOP_OBSESSING_OVER_HOST_CHECKS", command_info(CMD_STOP_OBSESSING_OVER_HOST_CHECKS, &_redirector<&stop_obsessing_over_host_checks>)}, {"START_OBSESSING_OVER_SVC_CHECKS", command_info(CMD_START_OBSESSING_OVER_SVC_CHECKS, &_redirector<&start_obsessing_over_service_checks>)}, {"STOP_OBSESSING_OVER_SVC_CHECKS", command_info(CMD_STOP_OBSESSING_OVER_SVC_CHECKS, &_redirector<&stop_obsessing_over_service_checks>)}, {"ENABLE_FLAP_DETECTION", command_info(CMD_ENABLE_FLAP_DETECTION, &_redirector<&enable_flap_detection_routines>)}, {"DISABLE_FLAP_DETECTION", command_info(CMD_DISABLE_FLAP_DETECTION, &_redirector<&disable_flap_detection_routines>)}, {"CHANGE_GLOBAL_HOST_EVENT_HANDLER", command_info(CMD_CHANGE_GLOBAL_HOST_EVENT_HANDLER, &_redirector<&cmd_change_object_char_var>)}, {"CHANGE_GLOBAL_SVC_EVENT_HANDLER", command_info(CMD_CHANGE_GLOBAL_SVC_EVENT_HANDLER, &_redirector<&cmd_change_object_char_var>)}, {"ENABLE_SERVICE_FRESHNESS_CHECKS", command_info(CMD_ENABLE_SERVICE_FRESHNESS_CHECKS, &_redirector<&enable_service_freshness_checks>)}, {"DISABLE_SERVICE_FRESHNESS_CHECKS", command_info(CMD_DISABLE_SERVICE_FRESHNESS_CHECKS, &_redirector<&disable_service_freshness_checks>)}, {"ENABLE_HOST_FRESHNESS_CHECKS", command_info(CMD_ENABLE_HOST_FRESHNESS_CHECKS, &_redirector<&enable_host_freshness_checks>)}, {"DISABLE_HOST_FRESHNESS_CHECKS", command_info(CMD_DISABLE_HOST_FRESHNESS_CHECKS, &_redirector<&disable_host_freshness_checks>)}, // host-related commands. {"ADD_HOST_COMMENT", command_info(CMD_ADD_HOST_COMMENT, &_redirector<&cmd_add_comment>)}, {"DEL_HOST_COMMENT", command_info(CMD_DEL_HOST_COMMENT, &_redirector<&cmd_delete_comment>)}, {"DEL_ALL_HOST_COMMENTS", command_info(CMD_DEL_ALL_HOST_COMMENTS, &_redirector<&cmd_delete_all_comments>)}, {"DELAY_HOST_NOTIFICATION", command_info(CMD_DELAY_HOST_NOTIFICATION, &_redirector<&cmd_delay_notification>)}, {"ENABLE_HOST_NOTIFICATIONS", command_info(CMD_ENABLE_HOST_NOTIFICATIONS, &_redirector_host<&enable_host_notifications>)}, {"DISABLE_HOST_NOTIFICATIONS", command_info(CMD_DISABLE_HOST_NOTIFICATIONS, &_redirector_host<&disable_host_notifications>)}, {"ENABLE_ALL_NOTIFICATIONS_BEYOND_HOST", command_info(CMD_ENABLE_ALL_NOTIFICATIONS_BEYOND_HOST, &_redirector_host< &_wrapper_enable_all_notifications_beyond_host>)}, {"DISABLE_ALL_NOTIFICATIONS_BEYOND_HOST", command_info(CMD_DISABLE_ALL_NOTIFICATIONS_BEYOND_HOST, &_redirector_host< &_wrapper_disable_all_notifications_beyond_host>)}, {"ENABLE_HOST_AND_CHILD_NOTIFICATIONS", command_info(CMD_ENABLE_HOST_AND_CHILD_NOTIFICATIONS, &_redirector_host< &_wrapper_enable_host_and_child_notifications>)}, {"DISABLE_HOST_AND_CHILD_NOTIFICATIONS", command_info(CMD_DISABLE_HOST_AND_CHILD_NOTIFICATIONS, &_redirector_host< &_wrapper_disable_host_and_child_notifications>)}, {"ENABLE_HOST_SVC_NOTIFICATIONS", command_info( CMD_ENABLE_HOST_SVC_NOTIFICATIONS, &_redirector_host<&_wrapper_enable_host_svc_notifications>)}, {"DISABLE_HOST_SVC_NOTIFICATIONS", command_info( CMD_DISABLE_HOST_SVC_NOTIFICATIONS, &_redirector_host<&_wrapper_disable_host_svc_notifications>)}, {"ENABLE_HOST_SVC_CHECKS", command_info(CMD_ENABLE_HOST_SVC_CHECKS, &_redirector_host<&_wrapper_enable_host_svc_checks>)}, {"DISABLE_HOST_SVC_CHECKS", command_info(CMD_DISABLE_HOST_SVC_CHECKS, &_redirector_host<&_wrapper_disable_host_svc_checks>)}, {"ENABLE_PASSIVE_HOST_CHECKS", command_info(CMD_ENABLE_PASSIVE_HOST_CHECKS, &_redirector_host<&enable_passive_host_checks>)}, {"DISABLE_PASSIVE_HOST_CHECKS", command_info(CMD_DISABLE_PASSIVE_HOST_CHECKS, &_redirector_host<&disable_passive_host_checks>)}, {"SCHEDULE_HOST_SVC_CHECKS", command_info(CMD_SCHEDULE_HOST_SVC_CHECKS, &_redirector<&cmd_schedule_check>)}, {"SCHEDULE_FORCED_HOST_SVC_CHECKS", command_info(CMD_SCHEDULE_FORCED_HOST_SVC_CHECKS, &_redirector<&cmd_schedule_check>)}, {"ACKNOWLEDGE_HOST_PROBLEM", command_info(CMD_ACKNOWLEDGE_HOST_PROBLEM, &_redirector<&cmd_acknowledge_problem>)}, {"REMOVE_HOST_ACKNOWLEDGEMENT", command_info(CMD_REMOVE_HOST_ACKNOWLEDGEMENT, &_redirector<&cmd_remove_acknowledgement>)}, {"ENABLE_HOST_EVENT_HANDLER", command_info(CMD_ENABLE_HOST_EVENT_HANDLER, &_redirector_host<&enable_host_event_handler>)}, {"DISABLE_HOST_EVENT_HANDLER", command_info(CMD_DISABLE_HOST_EVENT_HANDLER, &_redirector_host<&disable_host_event_handler>)}, {"ENABLE_HOST_CHECK", command_info(CMD_ENABLE_HOST_CHECK, &_redirector_host<&enable_host_checks>)}, {"DISABLE_HOST_CHECK", command_info(CMD_DISABLE_HOST_CHECK, &_redirector_host<&disable_host_checks>)}, {"SCHEDULE_HOST_CHECK", command_info(CMD_SCHEDULE_HOST_CHECK, &_redirector<&cmd_schedule_check>)}, {"SCHEDULE_FORCED_HOST_CHECK", command_info(CMD_SCHEDULE_FORCED_HOST_CHECK, &_redirector<&cmd_schedule_check>)}, {"SCHEDULE_HOST_DOWNTIME", command_info(CMD_SCHEDULE_HOST_DOWNTIME, &_redirector<&cmd_schedule_downtime>)}, {"SCHEDULE_HOST_SVC_DOWNTIME", command_info(CMD_SCHEDULE_HOST_SVC_DOWNTIME, &_redirector<&cmd_schedule_downtime>)}, {"DEL_HOST_DOWNTIME", command_info(CMD_DEL_HOST_DOWNTIME, &_redirector<&cmd_delete_downtime>)}, {"DEL_HOST_DOWNTIME_FULL", command_info(CMD_DEL_HOST_DOWNTIME_FULL, &_redirector<&cmd_delete_downtime_full>)}, {"DEL_DOWNTIME_BY_HOST_NAME", command_info(CMD_DEL_DOWNTIME_BY_HOST_NAME, &_redirector<&cmd_delete_downtime_by_host_name>)}, {"DEL_DOWNTIME_BY_HOSTGROUP_NAME", command_info(CMD_DEL_DOWNTIME_BY_HOSTGROUP_NAME, &_redirector<&cmd_delete_downtime_by_hostgroup_name>)}, {"DEL_DOWNTIME_BY_START_TIME_COMMENT", command_info( CMD_DEL_DOWNTIME_BY_START_TIME_COMMENT, &_redirector<&cmd_delete_downtime_by_start_time_comment>)}, {"ENABLE_HOST_FLAP_DETECTION", command_info(CMD_ENABLE_HOST_FLAP_DETECTION, &_redirector_host<&enable_host_flap_detection>)}, {"DISABLE_HOST_FLAP_DETECTION", command_info(CMD_DISABLE_HOST_FLAP_DETECTION, &_redirector_host<&disable_host_flap_detection>)}, {"START_OBSESSING_OVER_HOST", command_info(CMD_START_OBSESSING_OVER_HOST, &_redirector_host<&start_obsessing_over_host>)}, {"STOP_OBSESSING_OVER_HOST", command_info(CMD_STOP_OBSESSING_OVER_HOST, &_redirector_host<&stop_obsessing_over_host>)}, {"CHANGE_HOST_EVENT_HANDLER", command_info(CMD_CHANGE_HOST_EVENT_HANDLER, &_redirector<&cmd_change_object_char_var>)}, {"CHANGE_HOST_CHECK_COMMAND", command_info(CMD_CHANGE_HOST_CHECK_COMMAND, &_redirector<&cmd_change_object_char_var>)}, {"CHANGE_NORMAL_HOST_CHECK_INTERVAL", command_info(CMD_CHANGE_NORMAL_HOST_CHECK_INTERVAL, &_redirector<&cmd_change_object_int_var>)}, {"CHANGE_RETRY_HOST_CHECK_INTERVAL", command_info(CMD_CHANGE_RETRY_HOST_CHECK_INTERVAL, &_redirector<&cmd_change_object_int_var>)}, {"CHANGE_MAX_HOST_CHECK_ATTEMPTS", command_info(CMD_CHANGE_MAX_HOST_CHECK_ATTEMPTS, &_redirector<&cmd_change_object_int_var>)}, {"SCHEDULE_AND_PROPAGATE_TRIGGERED_HOST_DOWNTIME", command_info(CMD_SCHEDULE_AND_PROPAGATE_TRIGGERED_HOST_DOWNTIME, &_redirector<&cmd_schedule_downtime>)}, {"SCHEDULE_AND_PROPAGATE_HOST_DOWNTIME", command_info(CMD_SCHEDULE_AND_PROPAGATE_HOST_DOWNTIME, &_redirector<&cmd_schedule_downtime>)}, {"SET_HOST_NOTIFICATION_NUMBER", command_info( CMD_SET_HOST_NOTIFICATION_NUMBER, &_redirector_host<&_wrapper_set_host_notification_number>)}, {"CHANGE_HOST_CHECK_TIMEPERIOD", command_info(CMD_CHANGE_HOST_CHECK_TIMEPERIOD, &_redirector<&cmd_change_object_char_var>)}, {"CHANGE_CUSTOM_HOST_VAR", command_info(CMD_CHANGE_CUSTOM_HOST_VAR, &_redirector<&cmd_change_object_custom_var>)}, {"SEND_CUSTOM_HOST_NOTIFICATION", command_info( CMD_SEND_CUSTOM_HOST_NOTIFICATION, &_redirector_host<&_wrapper_send_custom_host_notification>)}, {"CHANGE_HOST_NOTIFICATION_TIMEPERIOD", command_info(CMD_CHANGE_HOST_NOTIFICATION_TIMEPERIOD, &_redirector<&cmd_change_object_char_var>)}, {"CHANGE_HOST_MODATTR", command_info(CMD_CHANGE_HOST_MODATTR, &_redirector<&cmd_change_object_int_var>)}, // hostgroup-related commands. {"ENABLE_HOSTGROUP_HOST_NOTIFICATIONS", command_info(CMD_ENABLE_HOSTGROUP_HOST_NOTIFICATIONS, &_redirector_hostgroup<&enable_host_notifications>)}, {"DISABLE_HOSTGROUP_HOST_NOTIFICATIONS", command_info(CMD_DISABLE_HOSTGROUP_HOST_NOTIFICATIONS, &_redirector_hostgroup<&disable_host_notifications>)}, {"ENABLE_HOSTGROUP_SVC_NOTIFICATIONS", command_info( CMD_ENABLE_HOSTGROUP_SVC_NOTIFICATIONS, &_redirector_hostgroup<&_wrapper_enable_service_notifications>)}, {"DISABLE_HOSTGROUP_SVC_NOTIFICATIONS", command_info(CMD_DISABLE_HOSTGROUP_SVC_NOTIFICATIONS, &_redirector_hostgroup< &_wrapper_disable_service_notifications>)}, {"ENABLE_HOSTGROUP_HOST_CHECKS", command_info(CMD_ENABLE_HOSTGROUP_HOST_CHECKS, &_redirector_hostgroup<&enable_host_checks>)}, {"DISABLE_HOSTGROUP_HOST_CHECKS", command_info(CMD_DISABLE_HOSTGROUP_HOST_CHECKS, &_redirector_hostgroup<&disable_host_checks>)}, {"ENABLE_HOSTGROUP_PASSIVE_HOST_CHECKS", command_info(CMD_ENABLE_HOSTGROUP_PASSIVE_HOST_CHECKS, &_redirector_hostgroup<&enable_passive_host_checks>)}, {"DISABLE_HOSTGROUP_PASSIVE_HOST_CHECKS", command_info(CMD_DISABLE_HOSTGROUP_PASSIVE_HOST_CHECKS, &_redirector_hostgroup<&disable_passive_host_checks>)}, {"ENABLE_HOSTGROUP_SVC_CHECKS", command_info( CMD_ENABLE_HOSTGROUP_SVC_CHECKS, &_redirector_hostgroup<&_wrapper_enable_service_checks>)}, {"DISABLE_HOSTGROUP_SVC_CHECKS", command_info( CMD_DISABLE_HOSTGROUP_SVC_CHECKS, &_redirector_hostgroup<&_wrapper_disable_service_checks>)}, {"ENABLE_HOSTGROUP_PASSIVE_SVC_CHECKS", command_info(CMD_ENABLE_HOSTGROUP_PASSIVE_SVC_CHECKS, &_redirector_hostgroup< &_wrapper_enable_passive_service_checks>)}, {"DISABLE_HOSTGROUP_PASSIVE_SVC_CHECKS", command_info(CMD_DISABLE_HOSTGROUP_PASSIVE_SVC_CHECKS, &_redirector_hostgroup< &_wrapper_disable_passive_service_checks>)}, {"SCHEDULE_HOSTGROUP_HOST_DOWNTIME", command_info(CMD_SCHEDULE_HOSTGROUP_HOST_DOWNTIME, &_redirector<&cmd_schedule_downtime>)}, {"SCHEDULE_HOSTGROUP_SVC_DOWNTIME", command_info(CMD_SCHEDULE_HOSTGROUP_SVC_DOWNTIME, &_redirector<&cmd_schedule_downtime>)}, // service-related commands. {"ADD_SVC_COMMENT", command_info(CMD_ADD_SVC_COMMENT, &_redirector<&cmd_add_comment>)}, {"DEL_SVC_COMMENT", command_info(CMD_DEL_SVC_COMMENT, &_redirector<&cmd_delete_comment>)}, {"DEL_ALL_SVC_COMMENTS", command_info(CMD_DEL_ALL_SVC_COMMENTS, &_redirector<&cmd_delete_all_comments>)}, {"SCHEDULE_SVC_CHECK", command_info(CMD_SCHEDULE_SVC_CHECK, &_redirector<&cmd_schedule_check>)}, {"SCHEDULE_FORCED_SVC_CHECK", command_info(CMD_SCHEDULE_FORCED_SVC_CHECK, &_redirector<&cmd_schedule_check>)}, {"ENABLE_SVC_CHECK", command_info(CMD_ENABLE_SVC_CHECK, &_redirector_service<&enable_service_checks>)}, {"DISABLE_SVC_CHECK", command_info(CMD_DISABLE_SVC_CHECK, &_redirector_service<&disable_service_checks>)}, {"ENABLE_PASSIVE_SVC_CHECKS", command_info(CMD_ENABLE_PASSIVE_SVC_CHECKS, &_redirector_service<&enable_passive_service_checks>)}, {"DISABLE_PASSIVE_SVC_CHECKS", command_info(CMD_DISABLE_PASSIVE_SVC_CHECKS, &_redirector_service<&disable_passive_service_checks>)}, {"DELAY_SVC_NOTIFICATION", command_info(CMD_DELAY_SVC_NOTIFICATION, &_redirector<&cmd_delay_notification>)}, {"ENABLE_SVC_NOTIFICATIONS", command_info(CMD_ENABLE_SVC_NOTIFICATIONS, &_redirector_service<&enable_service_notifications>)}, {"DISABLE_SVC_NOTIFICATIONS", command_info(CMD_DISABLE_SVC_NOTIFICATIONS, &_redirector_service<&disable_service_notifications>)}, {"PROCESS_SERVICE_CHECK_RESULT", command_info(CMD_PROCESS_SERVICE_CHECK_RESULT, &_redirector<&cmd_process_service_check_result>, true)}, {"PROCESS_HOST_CHECK_RESULT", command_info(CMD_PROCESS_HOST_CHECK_RESULT, &_redirector<&cmd_process_host_check_result>, true)}, {"ENABLE_SVC_EVENT_HANDLER", command_info(CMD_ENABLE_SVC_EVENT_HANDLER, &_redirector_service<&enable_service_event_handler>)}, {"DISABLE_SVC_EVENT_HANDLER", command_info(CMD_DISABLE_SVC_EVENT_HANDLER, &_redirector_service<&disable_service_event_handler>)}, {"ENABLE_SVC_FLAP_DETECTION", command_info(CMD_ENABLE_SVC_FLAP_DETECTION, &_redirector_service<&enable_service_flap_detection>)}, {"DISABLE_SVC_FLAP_DETECTION", command_info(CMD_DISABLE_SVC_FLAP_DETECTION, &_redirector_service<&disable_service_flap_detection>)}, {"SCHEDULE_SVC_DOWNTIME", command_info(CMD_SCHEDULE_SVC_DOWNTIME, &_redirector<&cmd_schedule_downtime>)}, {"DEL_SVC_DOWNTIME", command_info(CMD_DEL_SVC_DOWNTIME, &_redirector<&cmd_delete_downtime>)}, {"DEL_SVC_DOWNTIME_FULL", command_info(CMD_DEL_SVC_DOWNTIME_FULL, &_redirector<&cmd_delete_downtime_full>)}, {"ACKNOWLEDGE_SVC_PROBLEM", command_info(CMD_ACKNOWLEDGE_SVC_PROBLEM, &_redirector<&cmd_acknowledge_problem>)}, {"REMOVE_SVC_ACKNOWLEDGEMENT", command_info(CMD_REMOVE_SVC_ACKNOWLEDGEMENT, &_redirector<&cmd_remove_acknowledgement>)}, {"START_OBSESSING_OVER_SVC", command_info(CMD_START_OBSESSING_OVER_SVC, &_redirector_service<&start_obsessing_over_service>)}, {"STOP_OBSESSING_OVER_SVC", command_info(CMD_STOP_OBSESSING_OVER_SVC, &_redirector_service<&stop_obsessing_over_service>)}, {"CHANGE_SVC_EVENT_HANDLER", command_info(CMD_CHANGE_SVC_EVENT_HANDLER, &_redirector<&cmd_change_object_char_var>)}, {"CHANGE_SVC_CHECK_COMMAND", command_info(CMD_CHANGE_SVC_CHECK_COMMAND, &_redirector<&cmd_change_object_char_var>)}, {"CHANGE_NORMAL_SVC_CHECK_INTERVAL", command_info(CMD_CHANGE_NORMAL_SVC_CHECK_INTERVAL, &_redirector<&cmd_change_object_int_var>)}, {"CHANGE_RETRY_SVC_CHECK_INTERVAL", command_info(CMD_CHANGE_RETRY_SVC_CHECK_INTERVAL, &_redirector<&cmd_change_object_int_var>)}, {"CHANGE_MAX_SVC_CHECK_ATTEMPTS", command_info(CMD_CHANGE_MAX_SVC_CHECK_ATTEMPTS, &_redirector<&cmd_change_object_int_var>)}, {"SET_SVC_NOTIFICATION_NUMBER", command_info(CMD_SET_SVC_NOTIFICATION_NUMBER, &_redirector_service< &_wrapper_set_service_notification_number>)}, {"CHANGE_SVC_CHECK_TIMEPERIOD", command_info(CMD_CHANGE_SVC_CHECK_TIMEPERIOD, &_redirector<&cmd_change_object_char_var>)}, {"CHANGE_CUSTOM_SVC_VAR", command_info(CMD_CHANGE_CUSTOM_SVC_VAR, &_redirector<&cmd_change_object_custom_var>)}, {"CHANGE_CUSTOM_CONTACT_VAR", command_info(CMD_CHANGE_CUSTOM_CONTACT_VAR, &_redirector<&cmd_change_object_custom_var>)}, {"SEND_CUSTOM_SVC_NOTIFICATION", command_info(CMD_SEND_CUSTOM_SVC_NOTIFICATION, &_redirector_service< &_wrapper_send_custom_service_notification>)}, {"CHANGE_SVC_NOTIFICATION_TIMEPERIOD", command_info(CMD_CHANGE_SVC_NOTIFICATION_TIMEPERIOD, &_redirector<&cmd_change_object_char_var>)}, {"CHANGE_SVC_MODATTR", command_info(CMD_CHANGE_SVC_MODATTR, &_redirector<&cmd_change_object_int_var>)}, // servicegroup-related commands. {"ENABLE_SERVICEGROUP_HOST_NOTIFICATIONS", command_info(CMD_ENABLE_SERVICEGROUP_HOST_NOTIFICATIONS, &_redirector_servicegroup<&enable_host_notifications>)}, {"DISABLE_SERVICEGROUP_HOST_NOTIFICATIONS", command_info( CMD_DISABLE_SERVICEGROUP_HOST_NOTIFICATIONS, &_redirector_servicegroup<&disable_host_notifications>)}, {"ENABLE_SERVICEGROUP_SVC_NOTIFICATIONS", command_info( CMD_ENABLE_SERVICEGROUP_SVC_NOTIFICATIONS, &_redirector_servicegroup<&enable_service_notifications>)}, {"DISABLE_SERVICEGROUP_SVC_NOTIFICATIONS", command_info( CMD_DISABLE_SERVICEGROUP_SVC_NOTIFICATIONS, &_redirector_servicegroup<&disable_service_notifications>)}, {"ENABLE_SERVICEGROUP_HOST_CHECKS", command_info(CMD_ENABLE_SERVICEGROUP_HOST_CHECKS, &_redirector_servicegroup<&enable_host_checks>)}, {"DISABLE_SERVICEGROUP_HOST_CHECKS", command_info(CMD_DISABLE_SERVICEGROUP_HOST_CHECKS, &_redirector_servicegroup<&disable_host_checks>)}, {"ENABLE_SERVICEGROUP_PASSIVE_HOST_CHECKS", command_info( CMD_ENABLE_SERVICEGROUP_PASSIVE_HOST_CHECKS, &_redirector_servicegroup<&enable_passive_host_checks>)}, {"DISABLE_SERVICEGROUP_PASSIVE_HOST_CHECKS", command_info( CMD_DISABLE_SERVICEGROUP_PASSIVE_HOST_CHECKS, &_redirector_servicegroup<&disable_passive_host_checks>)}, {"ENABLE_SERVICEGROUP_SVC_CHECKS", command_info(CMD_ENABLE_SERVICEGROUP_SVC_CHECKS, &_redirector_servicegroup<&enable_service_checks>)}, {"DISABLE_SERVICEGROUP_SVC_CHECKS", command_info(CMD_DISABLE_SERVICEGROUP_SVC_CHECKS, &_redirector_servicegroup<&disable_service_checks>)}, {"ENABLE_SERVICEGROUP_PASSIVE_SVC_CHECKS", command_info( CMD_ENABLE_SERVICEGROUP_PASSIVE_SVC_CHECKS, &_redirector_servicegroup<&enable_passive_service_checks>)}, {"DISABLE_SERVICEGROUP_PASSIVE_SVC_CHECKS", command_info( CMD_DISABLE_SERVICEGROUP_PASSIVE_SVC_CHECKS, &_redirector_servicegroup<&disable_passive_service_checks>)}, {"SCHEDULE_SERVICEGROUP_HOST_DOWNTIME", command_info(CMD_SCHEDULE_SERVICEGROUP_HOST_DOWNTIME, &_redirector<&cmd_schedule_downtime>)}, {"SCHEDULE_SERVICEGROUP_SVC_DOWNTIME", command_info(CMD_SCHEDULE_SERVICEGROUP_SVC_DOWNTIME, &_redirector<&cmd_schedule_downtime>)}, // contact-related commands. {"ENABLE_CONTACT_HOST_NOTIFICATIONS", command_info( CMD_ENABLE_CONTACT_HOST_NOTIFICATIONS, &_redirector_contact<&enable_contact_host_notifications>)}, {"DISABLE_CONTACT_HOST_NOTIFICATIONS", command_info( CMD_DISABLE_CONTACT_HOST_NOTIFICATIONS, &_redirector_contact<&disable_contact_host_notifications>)}, {"ENABLE_CONTACT_SVC_NOTIFICATIONS", command_info( CMD_ENABLE_CONTACT_SVC_NOTIFICATIONS, &_redirector_contact<&enable_contact_service_notifications>)}, {"DISABLE_CONTACT_SVC_NOTIFICATIONS", command_info( CMD_DISABLE_CONTACT_SVC_NOTIFICATIONS, &_redirector_contact<&disable_contact_service_notifications>)}, {"CHANGE_CONTACT_HOST_NOTIFICATION_TIMEPERIOD", command_info(CMD_CHANGE_CONTACT_HOST_NOTIFICATION_TIMEPERIOD, &_redirector<&cmd_change_object_char_var>)}, {"CHANGE_CONTACT_SVC_NOTIFICATION_TIMEPERIOD", command_info(CMD_CHANGE_CONTACT_SVC_NOTIFICATION_TIMEPERIOD, &_redirector<&cmd_change_object_char_var>)}, {"CHANGE_CONTACT_MODATTR", command_info(CMD_CHANGE_CONTACT_MODATTR, &_redirector<&cmd_change_object_int_var>)}, {"CHANGE_CONTACT_MODHATTR", command_info(CMD_CHANGE_CONTACT_MODHATTR, &_redirector<&cmd_change_object_int_var>)}, {"CHANGE_CONTACT_MODSATTR", command_info(CMD_CHANGE_CONTACT_MODSATTR, &_redirector<&cmd_change_object_int_var>)}, // contactgroup-related commands. {"ENABLE_CONTACTGROUP_HOST_NOTIFICATIONS", command_info( CMD_ENABLE_CONTACTGROUP_HOST_NOTIFICATIONS, &_redirector_contactgroup<&enable_contact_host_notifications>)}, {"DISABLE_CONTACTGROUP_HOST_NOTIFICATIONS", command_info( CMD_DISABLE_CONTACTGROUP_HOST_NOTIFICATIONS, &_redirector_contactgroup<&disable_contact_host_notifications>)}, {"ENABLE_CONTACTGROUP_SVC_NOTIFICATIONS", command_info(CMD_ENABLE_CONTACTGROUP_SVC_NOTIFICATIONS, &_redirector_contactgroup< &enable_contact_service_notifications>)}, {"DISABLE_CONTACTGROUP_SVC_NOTIFICATIONS", command_info(CMD_DISABLE_CONTACTGROUP_SVC_NOTIFICATIONS, &_redirector_contactgroup< &disable_contact_service_notifications>)}, {"NEW_THRESHOLDS_FILE", command_info(CMD_NEW_THRESHOLDS_FILE, &_redirector_file<&new_thresholds_file>)}, } { // misc commands. _lst_command["PROCESS_FILE"] = command_info( CMD_PROCESS_FILE, &_redirector<&cmd_process_external_commands_from_file>); } processing::~processing() noexcept {} bool processing::execute(const std::string& cmdstr) const { logger(dbg_functions, basic) << "processing external command"; char const* cmd{cmdstr.c_str()}; size_t len{cmdstr.size()}; // Left trim command while (*cmd && isspace(*cmd)) ++cmd; if (*cmd != '[') return false; // Right trim just by recomputing the optimal length value. char const* end{cmd + len - 1}; while (end != cmd && isspace(*end)) --end; cmd++; char* tmp; time_t entry_time{static_cast<time_t>(strtoul(cmd, &tmp, 10))}; while (*tmp && isspace(*tmp)) ++tmp; if (*tmp != ']' || tmp[1] != ' ') return false; cmd = tmp + 2; char const* a; for (a = cmd; *a && *a != ';'; ++a) ; std::string command_name(cmd, a - cmd); std::string args; if (*a == ';') { a++; args = std::string(a, end - a + 1); } int command_id(CMD_CUSTOM_COMMAND); std::unordered_map<std::string, command_info>::const_iterator it; { std::unique_lock<std::mutex> lock(_mutex); it = _lst_command.find(command_name); if (it != _lst_command.end()) command_id = it->second.id; else if (command_name[0] != '_') { lock.unlock(); logger(log_external_command | log_runtime_warning, basic) << "Warning: Unrecognized external command -> " << command_name; return false; } // Update statistics for external commands. update_check_stats(EXTERNAL_COMMAND_STATS, std::time(nullptr)); } // Log the external command. if (command_id == CMD_PROCESS_SERVICE_CHECK_RESULT || command_id == CMD_PROCESS_HOST_CHECK_RESULT) { // Passive checks are logged in checks.c. if (config->log_passive_checks()) logger(log_passive_check, basic) << "EXTERNAL COMMAND: " << command_name << ';' << args; } else if (config->log_external_commands()) logger(log_external_command, basic) << "EXTERNAL COMMAND: " << command_name << ';' << args; logger(dbg_external_command, more) << "External command id: " << command_id << "\nCommand entry time: " << entry_time << "\nCommand arguments: " << args; // Send data to event broker. broker_external_command(NEBTYPE_EXTERNALCOMMAND_START, NEBFLAG_NONE, NEBATTR_NONE, command_id, entry_time, const_cast<char*>(command_name.c_str()), const_cast<char*>(args.c_str()), nullptr); { std::lock_guard<std::mutex> lock(_mutex); if (it != _lst_command.end()) (*it->second.func)(command_id, entry_time, const_cast<char*>(args.c_str())); } // Send data to event broker. broker_external_command(NEBTYPE_EXTERNALCOMMAND_END, NEBFLAG_NONE, NEBATTR_NONE, command_id, entry_time, const_cast<char*>(command_name.c_str()), const_cast<char*>(args.c_str()), nullptr); return true; } /** * Check if a command is thread-safe. * * @param[in] cmd Command to check. * * @return True if command is thread-safe. */ bool processing::is_thread_safe(char const* cmd) const { char const* ptr = cmd + strspn(cmd, "[]0123456789 "); std::string short_cmd(ptr, strcspn(ptr, ";")); std::lock_guard<std::mutex> lock(_mutex); std::unordered_map<std::string, command_info>::const_iterator it = _lst_command.find(short_cmd); return it != _lst_command.end() && it->second.thread_safe; } void processing::_wrapper_read_state_information() { try { retention::state state; retention::parser p; p.parse(config->state_retention_file(), state); retention::applier::state app_state; app_state.apply(*config, state); } catch (std::exception const& e) { logger(log_runtime_error, basic) << "Error: could not load retention file: " << e.what(); } return; } void processing::_wrapper_save_state_information() { retention::dump::save(config->state_retention_file()); } void processing::_wrapper_enable_host_and_child_notifications(host* hst) { enable_and_propagate_notifications(hst, 0, true, true, false); } void processing::_wrapper_disable_host_and_child_notifications(host* hst) { disable_and_propagate_notifications(hst, 0, true, true, false); } void processing::_wrapper_enable_all_notifications_beyond_host(host* hst) { enable_and_propagate_notifications(hst, 0, false, true, true); } void processing::_wrapper_disable_all_notifications_beyond_host(host* hst) { disable_and_propagate_notifications(hst, 0, false, true, true); } void processing::_wrapper_enable_host_svc_notifications(host* hst) { for (service_map_unsafe::iterator it(hst->services.begin()), end(hst->services.end()); it != end; ++it) if (it->second) enable_service_notifications(it->second); } void processing::_wrapper_disable_host_svc_notifications(host* hst) { for (service_map_unsafe::iterator it(hst->services.begin()), end(hst->services.end()); it != end; ++it) if (it->second) disable_service_notifications(it->second); } void processing::_wrapper_disable_host_svc_checks(host* hst) { for (service_map_unsafe::iterator it(hst->services.begin()), end(hst->services.end()); it != end; ++it) if (it->second) disable_service_checks(it->second); } void processing::_wrapper_enable_host_svc_checks(host* hst) { for (service_map_unsafe::iterator it(hst->services.begin()), end(hst->services.end()); it != end; ++it) if (it->second) enable_service_checks(it->second); } void processing::_wrapper_set_host_notification_number(host* hst, char* args) { if (args) set_host_notification_number(hst, atoi(args)); } void processing::_wrapper_send_custom_host_notification(host* hst, char* args) { char* buf[3] = {NULL, NULL, NULL}; if ((buf[0] = my_strtok(args, ";")) && (buf[1] = my_strtok(NULL, ";")) && (buf[2] = my_strtok(NULL, ";"))) { hst->notify(notifier::reason_custom, buf[1], buf[2], static_cast<notifier::notification_option>(atoi(buf[0]))); } } void processing::_wrapper_enable_service_notifications(host* hst) { for (service_map_unsafe::iterator it(hst->services.begin()), end(hst->services.end()); it != end; ++it) if (it->second) enable_service_notifications(it->second); } void processing::_wrapper_disable_service_notifications(host* hst) { for (service_map_unsafe::iterator it(hst->services.begin()), end(hst->services.end()); it != end; ++it) if (it->second) disable_service_notifications(it->second); } void processing::_wrapper_enable_service_checks(host* hst) { for (service_map_unsafe::iterator it(hst->services.begin()), end(hst->services.end()); it != end; ++it) if (it->second) enable_service_checks(it->second); } void processing::_wrapper_disable_service_checks(host* hst) { for (service_map_unsafe::iterator it(hst->services.begin()), end(hst->services.end()); it != end; ++it) if (it->second) disable_service_checks(it->second); } void processing::_wrapper_enable_passive_service_checks(host* hst) { for (service_map_unsafe::iterator it(hst->services.begin()), end(hst->services.end()); it != end; ++it) if (it->second) enable_passive_service_checks(it->second); } void processing::_wrapper_disable_passive_service_checks(host* hst) { for (service_map_unsafe::iterator it(hst->services.begin()), end(hst->services.end()); it != end; ++it) if (it->second) disable_passive_service_checks(it->second); } void processing::_wrapper_set_service_notification_number(service* svc, char* args) { char* str(my_strtok(args, ";")); if (str) set_service_notification_number(svc, atoi(str)); } void processing::_wrapper_send_custom_service_notification(service* svc, char* args) { char* buf[3] = {NULL, NULL, NULL}; if ((buf[0] = my_strtok(args, ";")) && (buf[1] = my_strtok(NULL, ";")) && (buf[2] = my_strtok(NULL, ";"))) { svc->notify(notifier::reason_custom, buf[1], buf[2], static_cast<notifier::notification_option>(atoi(buf[0]))); } }
47.540767
80
0.642488
centreon
804d793560b541fcb2452448b6cd1e33c00042f5
6,032
cc
C++
iree/base/dynamic_library_win32.cc
3alireza32109/iree
fd32e47b1695f105d20c06b8b20a29ef65c5e54c
[ "Apache-2.0" ]
2
2021-10-03T15:58:09.000Z
2021-11-17T10:34:35.000Z
iree/base/dynamic_library_win32.cc
3alireza32109/iree
fd32e47b1695f105d20c06b8b20a29ef65c5e54c
[ "Apache-2.0" ]
null
null
null
iree/base/dynamic_library_win32.cc
3alireza32109/iree
fd32e47b1695f105d20c06b8b20a29ef65c5e54c
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 Google LLC // // 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 // // https://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 "absl/memory/memory.h" #include "absl/strings/str_replace.h" #include "iree/base/dynamic_library.h" #include "iree/base/internal/file_path.h" #include "iree/base/target_platform.h" #include "iree/base/tracing.h" #if defined(IREE_PLATFORM_WINDOWS) // TODO(benvanik): support PDB overlays when tracy is not enabled too; we'll // need to rearrange how the dbghelp lock is handled for that (probably moving // it here and having the tracy code redirect to this). #if defined(TRACY_ENABLE) #define IREE_HAVE_DYNAMIC_LIBRARY_PDB_SUPPORT 1 #pragma warning(disable : 4091) #include <dbghelp.h> extern "C" void IREEDbgHelpLock(); extern "C" void IREEDbgHelpUnlock(); #endif // TRACY_ENABLE namespace iree { // We need to match the expected paths from dbghelp exactly or else we'll get // spurious warnings during module resolution. AFAICT our approach here with // loading the PDBs directly with a module base/size of the loaded module will // work regardless but calls like SymRefreshModuleList will still attempt to // load from system symbol search paths if things don't line up. static void CanonicalizePath(std::string* path) { absl::StrReplaceAll({{"/", "\\"}}, path); absl::StrReplaceAll({{"\\\\", "\\"}}, path); } class DynamicLibraryWin : public DynamicLibrary { public: ~DynamicLibraryWin() override { IREE_TRACE_SCOPE(); // TODO(benvanik): disable if we want to get profiling results. // Sometimes closing the library can prevent proper symbolization on // crashes or in sampling profilers. ::FreeLibrary(library_); } static Status Load(absl::Span<const char* const> search_file_names, std::unique_ptr<DynamicLibrary>* out_library) { IREE_TRACE_SCOPE(); out_library->reset(); for (int i = 0; i < search_file_names.size(); ++i) { HMODULE library = ::LoadLibraryA(search_file_names[i]); if (library) { out_library->reset( new DynamicLibraryWin(search_file_names[i], library)); return OkStatus(); } } return iree_make_status( IREE_STATUS_UNAVAILABLE, "unable to open dynamic library, not found on search paths"); } #if defined(IREE_HAVE_DYNAMIC_LIBRARY_PDB_SUPPORT) void AttachDebugDatabase(const char* database_file_name) override { IREE_TRACE_SCOPE(); // Derive the base module name (path stem) for the loaded module. // For example, the name of 'C:\Dev\foo.dll' would be 'foo'. // This name is used by dbghelp for listing loaded modules and we want to // ensure we match the name of the PDB module with the library module. std::string module_name = file_name_; size_t last_slash = module_name.find_last_of('\\'); if (last_slash != std::string::npos) { module_name = module_name.substr(last_slash + 1); } size_t dot = module_name.find_last_of('.'); if (dot != std::string::npos) { module_name = module_name.substr(0, dot); } IREEDbgHelpLock(); // Useful for debugging; will print search paths and results: // SymSetOptions(SYMOPT_LOAD_LINES | SYMOPT_DEBUG); // Enumerates all loaded modules in the process to extract the module // base/size parameters we need to overlay the PDB. There's other ways to // get this (such as registering a LdrDllNotification callback and snooping // the values during LoadLibrary or using CreateToolhelp32Snapshot), however // EnumerateLoadedModules is in dbghelp which we are using anyway. ModuleEnumCallbackState state; state.module_file_path = file_name_.c_str(); EnumerateLoadedModules64(GetCurrentProcess(), EnumLoadedModulesCallback, &state); // Load the PDB file and overlay it onto the already-loaded module at the // address range it got loaded into. if (state.module_base != 0) { SymLoadModuleEx(GetCurrentProcess(), NULL, database_file_name, module_name.c_str(), state.module_base, state.module_size, NULL, 0); } IREEDbgHelpUnlock(); } #endif // IREE_HAVE_DYNAMIC_LIBRARY_PDB_SUPPORT void* GetSymbol(const char* symbol_name) const override { return reinterpret_cast<void*>(::GetProcAddress(library_, symbol_name)); } private: DynamicLibraryWin(std::string file_name, HMODULE library) : DynamicLibrary(std::move(file_name)), library_(library) { CanonicalizePath(&file_name_); } #if defined(IREE_HAVE_DYNAMIC_LIBRARY_PDB_SUPPORT) struct ModuleEnumCallbackState { const char* module_file_path = NULL; DWORD64 module_base = 0; ULONG module_size = 0; }; static BOOL EnumLoadedModulesCallback(PCSTR ModuleName, DWORD64 ModuleBase, ULONG ModuleSize, PVOID UserContext) { auto* state = reinterpret_cast<ModuleEnumCallbackState*>(UserContext); if (strcmp(ModuleName, state->module_file_path) != 0) { return TRUE; // not a match; continue } state->module_base = ModuleBase; state->module_size = ModuleSize; return FALSE; // match found; stop enumeration } #endif // IREE_HAVE_DYNAMIC_LIBRARY_PDB_SUPPORT HMODULE library_ = NULL; }; // static Status DynamicLibrary::Load(absl::Span<const char* const> search_file_names, std::unique_ptr<DynamicLibrary>* out_library) { return DynamicLibraryWin::Load(search_file_names, out_library); } } // namespace iree #endif // IREE_PLATFORM_*
37.465839
80
0.706233
3alireza32109
804e1d28dc4634b129850c1120594c76640aa6f9
770
hpp
C++
Deitel/Chapter13/exercises/13.16/SavingsAccount.hpp
SebastianTirado/Cpp-Learning-Archive
fb83379d0cc3f9b2390cef00119464ec946753f4
[ "MIT" ]
19
2019-09-15T12:23:51.000Z
2020-06-18T08:31:26.000Z
Deitel/Chapter13/exercises/13.16/SavingsAccount.hpp
eirichan/CppLearingArchive
07a4baf63f0765d41eb0cc6d32a4c9d2ae1d5bac
[ "MIT" ]
15
2021-12-07T06:46:03.000Z
2022-01-31T07:55:32.000Z
Deitel/Chapter13/exercises/13.16/SavingsAccount.hpp
eirichan/CppLearingArchive
07a4baf63f0765d41eb0cc6d32a4c9d2ae1d5bac
[ "MIT" ]
13
2019-06-29T02:58:27.000Z
2020-05-07T08:52:22.000Z
/* * ===================================================================================== * * Filename: SavingsAccount.hpp * * Description: Exercise 12.10 - Account Inheritance Hierarchy * * Version: 1.0 * Created: 24/07/16 20:27:54 * Revision: none * Compiler: gcc * * Author: Siidney Watson - siidney.watson.work@gmail.com * Organization: LolaDog Studio * * ===================================================================================== */ #pragma once #include "Account.hpp" class SavingsAccount : public Account { public: SavingsAccount(double, double); double calculateInterest() const; void credit(double); bool debit(double); private: double interestRate; };
22.647059
88
0.480519
SebastianTirado
804f874a6c67bc61047e95b341f9589d0da4ff42
5,699
cpp
C++
framework/src/minko/component/Camera.cpp
aerys/minko
edc3806a4e01570c5cb21f3402223ca695d08d22
[ "BSD-3-Clause" ]
478
2015-01-04T16:59:53.000Z
2022-03-07T20:28:07.000Z
framework/src/minko/component/Camera.cpp
aerys/minko
edc3806a4e01570c5cb21f3402223ca695d08d22
[ "BSD-3-Clause" ]
83
2015-01-15T21:45:06.000Z
2021-11-08T11:01:48.000Z
framework/src/minko/component/Camera.cpp
aerys/minko
edc3806a4e01570c5cb21f3402223ca695d08d22
[ "BSD-3-Clause" ]
175
2015-01-04T03:30:39.000Z
2020-01-27T17:08:14.000Z
/* Copyright (c) 2014 Aerys Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "minko/component/Camera.hpp" #include "minko/scene/Node.hpp" #include "minko/data/Provider.hpp" #include "minko/math/Ray.hpp" #include "minko/component/Transform.hpp" #include "minko/scene/Node.hpp" #include "minko/component/SceneManager.hpp" #include "minko/file/AssetLibrary.hpp" #include "minko/render/AbstractContext.hpp" using namespace minko; using namespace minko::component; Camera::Camera(const math::mat4& projection, const math::mat4& postProjection) : _data(data::Provider::create()), _view(math::mat4(1.f)), _position(), _direction(0.f, 0.f, 1.f), _postProjection(postProjection), _projectionMatrixChanged(Signal<>::create()) { _data ->set("eyeDirection", _direction) ->set("eyePosition", _position) ->set("viewMatrix", _view) ->set("projectionMatrix", _projection); projectionMatrix(projection); } // TODO #Clone /* Camera::Camera(const Camera& camera, const CloneOption& option) : _data(camera._data->clone()), _fov(camera._fov), _aspectRatio(camera._aspectRatio), _zNear(camera._zNear), _zFar(camera._zFar), _view(Matrix4x4::create()), _projection(Matrix4x4::create()->perspective(camera._fov, camera._aspectRatio, camera._zNear, camera._zFar)), _viewProjection(Matrix4x4::create()->copyFrom(_projection)), _position(Vector3::create()), _postProjection(camera._postProjection) { } AbstractComponent::Ptr Camera::clone(const CloneOption& option) { auto ctrl = std::shared_ptr<Camera>(new Camera(*this, option)); return ctrl; } */ void Camera::targetAdded(NodePtr target) { target->data().addProvider(_data); _modelToWorldChangedSlot = target->data().propertyChanged("modelToWorldMatrix").connect( [&](data::Store& data, data::Provider::Ptr, const data::Provider::PropertyName&) { localToWorldChangedHandler(data); }); if (target->data().hasProperty("modelToWorldMatrix")) updateMatrices(target->data().get<math::mat4>("modelToWorldMatrix")); } void Camera::targetRemoved(NodePtr target) { target->data().removeProvider(_data); } void Camera::localToWorldChangedHandler(data::Store& data) { updateMatrices(data.get<math::mat4>("modelToWorldMatrix")); } void Camera::updateMatrices(const math::mat4& modelToWorldMatrix) { _position = (modelToWorldMatrix * math::vec4(0.f, 0.f, 0.f, 1.f)).xyz(); _direction = math::normalize(math::mat3(modelToWorldMatrix) * math::vec3(0.f, 0.f, 1.f)); _view = math::inverse(modelToWorldMatrix); _data ->set("eyeDirection", _direction) ->set("eyePosition", _position) ->set("viewMatrix", _view); updateWorldToScreenMatrix(); } void Camera::updateWorldToScreenMatrix() { _projection = _postProjection * _projection; _viewProjection = _projection * _view; _data ->set("projectionMatrix", _projection) ->set("worldToScreenMatrix", _viewProjection); } std::shared_ptr<math::Ray> Camera::unproject(float x, float y) { // Should take normalized X and Y coordinates (between -1 and 1) const auto viewport = math::vec4(-1.f, -1.f, 2.f, 2.f); // GLM unProject function expect coordinates with the origin at the lower left corner const auto rayWorldOrigin = math::unProject( math::vec3(x, -y, 0.f), _view, _projection, viewport ); const auto unprojectedWorldPosition = math::unProject( math::vec3(x, -y, 1.f), _view, _projection, viewport ); const auto rayWorldDirection = math::normalize(unprojectedWorldPosition - rayWorldOrigin); return math::Ray::create(rayWorldOrigin, rayWorldDirection); } math::vec3 Camera::project(const math::vec3& worldPosition) const { auto context = target()->root()->component<SceneManager>()->assets()->context(); return project( worldPosition, context->viewportWidth(), context->viewportHeight(), _view, _viewProjection ); } math::vec3 Camera::project(const math::vec3& worldPosition, unsigned int viewportWidth, unsigned int viewportHeight, const math::mat4& viewMatrix, const math::mat4& viewProjectionMatrix) { const auto width = viewportWidth; const auto height = viewportHeight; const auto pos = math::vec4(worldPosition, 1.f); auto vector = viewProjectionMatrix * pos; vector /= vector.w; return math::vec3( width * ((vector.x + 1.0f) * .5f), height * ((1.0f - ((vector.y + 1.0f) * .5f))), -(viewMatrix * pos).z ); }
29.994737
111
0.689244
aerys
8052e1cb116b2c86e01367c2ead20ace8cb3dd5e
1,057
cpp
C++
lintcode/165_merge_two_sorted_lists.cpp
code-master5/CP-Personal
2f40cc6c0f7fcee47085959dac8f37ad66318aaa
[ "MIT" ]
null
null
null
lintcode/165_merge_two_sorted_lists.cpp
code-master5/CP-Personal
2f40cc6c0f7fcee47085959dac8f37ad66318aaa
[ "MIT" ]
null
null
null
lintcode/165_merge_two_sorted_lists.cpp
code-master5/CP-Personal
2f40cc6c0f7fcee47085959dac8f37ad66318aaa
[ "MIT" ]
null
null
null
/** * Definition of singly-linked-list: * class ListNode { * public: * int val; * ListNode *next; * ListNode(int val) { * this->val = val; * this->next = NULL; * } * } */ class Solution { public: /** * @param l1: ListNode l1 is the head of the linked list * @param l2: ListNode l2 is the head of the linked list * @return: ListNode head of linked list */ ListNode * mergeTwoLists(ListNode * l1, ListNode * l2) { ListNode *dummyNode = new ListNode(0); ListNode *lastNode = dummyNode; while (l1 != NULL && l2 != NULL) { if (l1->val <= l2->val) { lastNode->next = l1; l1 = l1->next; } else { lastNode->next = l2; l2 = l2->next; } lastNode = lastNode->next; } if (l1 != NULL) { lastNode->next = l1; } else { lastNode->next = l2; } return dummyNode->next; } };
23.488889
60
0.456954
code-master5
805515743fe5be5e0f0d06a47b0c056c0c6e7e1f
1,483
cpp
C++
src/Dimmer.cpp
foxostro/CheeseTesseract
737ebbd19cee8f5a196bf39a11ca793c561e56cb
[ "MIT" ]
1
2016-05-17T03:36:52.000Z
2016-05-17T03:36:52.000Z
src/Dimmer.cpp
foxostro/CheeseTesseract
737ebbd19cee8f5a196bf39a11ca793c561e56cb
[ "MIT" ]
null
null
null
src/Dimmer.cpp
foxostro/CheeseTesseract
737ebbd19cee8f5a196bf39a11ca793c561e56cb
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "color.h" #include "Dimmer.h" float Dimmer::alphaBlur = 1.0f; Dimmer::Dimmer() {} void Dimmer::draw() const { if (alphaBlur < FLT_EPSILON) { alphaBlur = 0.0f; return; } glPushAttrib(GL_ALL_ATTRIB_BITS); glColor4f(0, 0, 0, alphaBlur); glDisable(GL_LIGHTING); glDisable(GL_COLOR_MATERIAL); glDisable(GL_FOG); glDisable(GL_DEPTH_TEST); glDisable(GL_TEXTURE_2D); glDisable(GL_ALPHA_TEST); glDisable(GL_CULL_FACE); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); /*glBlendFunc(GL_SRC_ALPHA, GL_ONE);*/ // Save the projection matrix glMatrixMode(GL_PROJECTION); glPushMatrix(); // Set up the projection matrix for 2D glLoadIdentity(); glOrtho(0.0f, 1024.0f, 0.0f, 768.0f, -1.0f, 1.0f); // Save the model view matrix glMatrixMode(GL_MODELVIEW); glPushMatrix(); // Set up the model view matrix glLoadIdentity(); glTranslatef(0.0f, 0.0f, -0.2f); // Render a quad over the screen glBegin(GL_QUADS); glTexCoord2f(1.0f, 0.0f); glVertex3f(1024.0f, 0.0f, 0.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f(1024.0f, 768.0f, 0.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f( 0.0f, 768.0f, 0.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f( 0.0f, 0.0f, 0.0f); glEnd(); // Restore the model view matrix glPopMatrix(); // Restore the projection matrix glMatrixMode(GL_PROJECTION); glPopMatrix(); // Use modelview mode glMatrixMode(GL_MODELVIEW); // Restore settings glPopAttrib(); }
20.887324
51
0.700607
foxostro
8056f7a227e5adb5c357004ba1b2c4bc92866c89
1,025
cpp
C++
leetcode.com/0393 UTF-8 Validation/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2020-08-20T11:02:49.000Z
2020-08-20T11:02:49.000Z
leetcode.com/0393 UTF-8 Validation/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
null
null
null
leetcode.com/0393 UTF-8 Validation/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2022-01-01T23:23:13.000Z
2022-01-01T23:23:13.000Z
#include <iostream> #include <vector> using namespace std; class Solution { private: int count_bytes(int first_byte) { int mask = 1 << 7; int res = 0; for (int i = 0; i < 4; ++i) { if (first_byte & mask) { ++res; } else { break; } mask >>= 1; } // res could only be 0, 2, 3, 4 if ((first_byte & mask) || res == 1) return 0; return res ? res : 1; } public: bool validUtf8(vector<int>& data) { int n = data.size(); for (int i = 0; i < n;) { int bytes_cnt = count_bytes(data[i]); if (bytes_cnt == 0 || i + bytes_cnt > n) return false; i += bytes_cnt; for (int j = i - bytes_cnt + 1; j < i; ++j) { if ((data[j] & 0xC0) != 0x80) return false; } } return true; } }; int main(int argc, char const* argv[]) { Solution sol; vector<int> data = {197, 130, 1}; // true cout << sol.validUtf8(data) << endl; data = {235, 140, 4}; // false cout << sol.validUtf8(data) << endl; return 0; }
21.354167
60
0.513171
sky-bro
8059f8cdd9388e4674d4c42704c862bf4f3528aa
46,477
cc
C++
test_atp.cc
wwmfdb/ATP-Engine
00eaf0f551907c9d6e2db446d5e78364364531d4
[ "BSD-3-Clause-Clear" ]
16
2020-05-19T16:13:10.000Z
2022-02-05T19:22:37.000Z
test_atp.cc
wwmfdb/ATP-Engine
00eaf0f551907c9d6e2db446d5e78364364531d4
[ "BSD-3-Clause-Clear" ]
6
2020-07-16T14:30:02.000Z
2021-11-08T22:10:18.000Z
test_atp.cc
wwmfdb/ATP-Engine
00eaf0f551907c9d6e2db446d5e78364364531d4
[ "BSD-3-Clause-Clear" ]
12
2020-05-21T17:56:34.000Z
2022-01-19T02:07:15.000Z
/* * SPDX-License-Identifier: BSD-3-Clause-Clear * * Copyright (c) 2015, 2017 ARM Limited * All rights reserved * Created on: Oct 19, 2015 * Author: Matteo Andreozzi * Riken Gohil */ #include "test_atp.hh" #include "event.hh" #include "stats.hh" #include "fifo.hh" #include "packet_desc.hh" #include <vector> #include <sstream> #include <algorithm> #include <cassert> #include "traffic_profile_desc.hh" #include "utilities.hh" #include "kronos.hh" #ifndef CPPUNIT_ASSERT #define CPPUNIT_ASSERT(x) #endif using namespace std; namespace TrafficProfiles { TestAtp::TestAtp(): tpm(nullptr), configuration(nullptr) { } TestAtp::~TestAtp() { tearDown(); } // test helper functions PatternConfiguration* TestAtp::makePatternConfiguration(PatternConfiguration* t, const Command cmd, const Command wait) { t->set_cmd(cmd); t->set_wait_for(wait); return t; } FifoConfiguration* TestAtp::makeFifoConfiguration(FifoConfiguration* t, const uint64_t fullLevel, const FifoConfiguration::StartupLevel level,const uint64_t ot, const uint64_t total, const uint64_t rate) { t->set_full_level(fullLevel); t->set_start_fifo_level(level); t->set_ot_limit(ot); t->set_total_txn(total); t->set_rate(std::to_string(rate)); return t; } void TestAtp::makeProfile(Profile *p, const ProfileDescription &desc) const { p->set_name(desc.name); p->set_type(desc.type); if (desc.master) { p->set_master_id(*desc.master); } else { p->set_master_id(desc.name); } if (desc.waitFor) { for (const auto& a: *desc.waitFor) { p->add_wait_for(a); } } } // test specific functions void TestAtp::setUp() { // create new TPM tpm = new TrafficProfileManager(); // load the Configuration into the TPM if (configuration) { tpm->configure(*configuration); // Dump the TPM configuration string out; if (!tpm->print(out)) { ERROR("unable to dump TPM"); } // display the TPM LOG(out); } } void TestAtp::tearDown() { if (tpm) { delete tpm; tpm = nullptr; } if (configuration) { delete configuration; configuration = nullptr; } } bool TestAtp::buildManager_fromFile(const string& fileName) { // create new TPM if not created yet if (nullptr == tpm) { tpm = new TrafficProfileManager(); } // load the Configuration into the TPM return (tpm->load(fileName)); } void TestAtp::dumpStats() { if (tpm) { LOG ("TestAtp::dumpStats dumping TPM stats"); PRINT("Global TPM Stats:", tpm->getStats().dump()); for (auto&m: tpm->getMasters()) { PRINT(m,"Stats:",tpm->getMasterStats(m).dump()); } } } void TestAtp::testAgainstInternalSlave(const string& rate, const string& latency) { PRINT("ATP Engine running in standalone execution mode. " "Internal slave configuration:",rate,latency); // the TPM should already be created and loaded with masters // query the TPM for masters and assign all unassigned masters to // an internal slave Profile slave; // fill the configuration makeProfile(&slave, ProfileDescription { "TestAtp::InternalSlave::", Profile::READ }); // fill in the slave field SlaveConfiguration* slave_cfg = slave.mutable_slave(); slave_cfg->set_latency(latency); slave_cfg->set_rate(rate); slave_cfg->set_granularity(64); slave_cfg->set_ot_limit(0); // request list of all masters and add unassigned ones to internal slave auto& masters = tpm->getMasters(); auto& masterSlaves = tpm->getMasterSlaves(); for (auto&m : masters) { if (masterSlaves.find(m)==masterSlaves.end()) { slave_cfg->add_master(m); } } // register (overwrite) slave with TPM tpm->configureProfile(slave, make_pair(1,1), true); // request packets to masters and route to the internal slave tpm->loop(); dumpStats(); } // unit tests void TestAtp::testAtp_fifo() { Fifo fifo; // start with an empty FIFO, which fills every time by 1000 fifo.init(nullptr, Profile::READ,1000,1,0,2000,true); uint64_t next = 0; uint64_t request_time=0; bool underrun=false, overrun=false; uint64_t i = 0; for (; i< 2; ++i){ // read 1000 every time fifo.send(underrun, overrun, next, request_time, i, 1000); CPPUNIT_ASSERT(fifo.getOt() == 1); fifo.receive(underrun, overrun, i, 1000); CPPUNIT_ASSERT(fifo.getOt() == 0); } // checks to see if send allocation was successful CPPUNIT_ASSERT(fifo.getLevel() == 1000); // consume last data fifo.send(underrun, overrun, next, request_time, i, 0); CPPUNIT_ASSERT(fifo.getOt() == 0); fifo.receive(underrun, overrun, i,0); CPPUNIT_ASSERT(fifo.getOt() == 0); // we should have an empty FIFO here CPPUNIT_ASSERT(fifo.getLevel() == 0); CPPUNIT_ASSERT(!underrun); CPPUNIT_ASSERT(!overrun); // checks for having multiple outstanding transactions fifo.send(underrun, overrun, next, request_time, i, 1000); fifo.send(underrun, overrun, next, request_time, ++i, 1000); CPPUNIT_ASSERT(fifo.getOt() == 2); fifo.receive(underrun, overrun, i, 1000); fifo.receive(underrun, overrun, ++i, 1000); CPPUNIT_ASSERT(fifo.getOt() == 0); // we should underrun now fifo.send(underrun, overrun, next, request_time, ++i, 0); CPPUNIT_ASSERT(fifo.getOt() == 0); fifo.receive(underrun, overrun, i,0); CPPUNIT_ASSERT(fifo.getOt() == 0); CPPUNIT_ASSERT(underrun); CPPUNIT_ASSERT(!overrun); // clear flags underrun=overrun=false; // start with a full WRITE FIFO, which fills every time by 1000 fifo.init(nullptr, Profile::WRITE,1000,1,2000,2000,true); i=0; for (;i< 2; ++i){ // read 1000 every time, receive partial 500 twice fifo.send(underrun, overrun, next, request_time, i, 1000); CPPUNIT_ASSERT(fifo.getOt() == 1); fifo.receive(underrun, overrun, i, 500); fifo.receive(underrun, overrun, i, 500); CPPUNIT_ASSERT(fifo.getOt() == 0); } // checks to see if send removal was successful CPPUNIT_ASSERT(fifo.getLevel() == 1000); // cause FIFO update fifo.send(underrun, overrun, next, request_time, i, 0); CPPUNIT_ASSERT(fifo.getOt() == 0); fifo.receive(underrun, overrun, i,0); CPPUNIT_ASSERT(fifo.getOt() == 0); // we should have a full FIFO here CPPUNIT_ASSERT(fifo.getLevel() == 2000); CPPUNIT_ASSERT(!underrun); CPPUNIT_ASSERT(!overrun); // we should overrun now fifo.send(underrun, overrun, next, request_time, ++i, 0); CPPUNIT_ASSERT(fifo.getOt() == 0); fifo.receive(underrun, overrun, i,0); CPPUNIT_ASSERT(fifo.getOt() == 0); CPPUNIT_ASSERT(!underrun); CPPUNIT_ASSERT(overrun); CPPUNIT_ASSERT(fifo.getLevel() == 2000); // consume 1000 fifo.send(underrun, overrun, next, request_time, i, 1000); CPPUNIT_ASSERT(fifo.getOt() == 1); CPPUNIT_ASSERT(fifo.getLevel() == 2000); fifo.receive(underrun, overrun, i,1000); CPPUNIT_ASSERT(fifo.getLevel() == 1000); // reset the FIFO fifo.reset(); // verify that the FIFO is back to startup values CPPUNIT_ASSERT(fifo.getOt() == 0); CPPUNIT_ASSERT(fifo.getLevel() == 2000); for (;i< 2; ++i){ // read 1000 every time, receive partial 500 twice fifo.send(underrun, overrun, next, request_time, i, 1000); CPPUNIT_ASSERT(fifo.getOt() == 1); fifo.receive(underrun, overrun, i, 500); fifo.receive(underrun, overrun, i, 500); CPPUNIT_ASSERT(fifo.getOt() == 0); } // test mid-update cycle activation // start with a full READ FIFO, which depletes every 10 units by 1000 fifo.init(nullptr, Profile::READ,1000,10,2000,2000,true); // send request at time 3 bool ok = fifo.send(underrun, overrun, next, request_time, 13, 1000); // verify that we get next time 23 and not 10 CPPUNIT_ASSERT(!ok); CPPUNIT_ASSERT(next == 23); ok = fifo.send(underrun, overrun, next, request_time, 21, 1000); // verify that we get next time 23 and not 10 CPPUNIT_ASSERT(!ok); CPPUNIT_ASSERT(next == 23); // verify that the next send time is correct and that the FIFO transmits ok = fifo.send(underrun, overrun, next, request_time, next, 1000); CPPUNIT_ASSERT(ok); // note : as the FIFO is now at level 1000 with 1000 in-flight, next is 0 CPPUNIT_ASSERT(next==0); // set the time to 33 and see if we get another transaction fifo.receive(underrun, overrun, 33, 1000); // verify that the 2nd next send time is correct ok = fifo.send(underrun, overrun, next, request_time, 33, 1000); CPPUNIT_ASSERT(ok); } void TestAtp::testAtp_event() { Event ev1(Event::NONE,Event::AWAITED,0,0), ev2(Event::NONE,Event::AWAITED,0,0), ev3(Event::NONE,Event::TRIGGERED,0,0), ev4(Event::TERMINATION,Event::AWAITED,0,0), ev5(Event::NONE,Event::TRIGGERED,1,0); // test comparison of event objects CPPUNIT_ASSERT(ev1==ev2); // a triggered and awaited event compare equal CPPUNIT_ASSERT(ev1==ev3); CPPUNIT_ASSERT(ev1!=ev4); CPPUNIT_ASSERT(ev1!=ev5); // test parsing event objects from string string event = "testAtp_event TERMINATION"; string name =""; Event::Type type = Event::NONE; CPPUNIT_ASSERT(Event::parse(type, name, event)); CPPUNIT_ASSERT(type == Event::TERMINATION); CPPUNIT_ASSERT(name == "testAtp_event"); event = "ERROR ERROR"; CPPUNIT_ASSERT(!Event::parse(type, name, event)); } void TestAtp::testAtp_packetDesc() { Profile config; // fill the configuration makeProfile(&config, ProfileDescription { "testAtp_packetDesc_profile", Profile::READ }); // fill the FIFO configuration - pointer, maxLevel, // startup level, OT, transactions, rate makeFifoConfiguration(config.mutable_fifo(), 0, FifoConfiguration::EMPTY, 0, 0, 0); // ATP Packet descriptor PacketDesc pd; // fill the Google Protocol Buffer configuration object makePatternConfiguration(config.mutable_pattern(), Command::READ_REQ, Command::READ_RESP); // configure the packet address and size generation policies auto* pk = config.mutable_pattern(); pk->set_size(64); PatternConfiguration::Address* address = pk->mutable_address(); address->set_base(0); // set increment address->set_increment(0x1FBE); // set local id limits pk->set_lowid(10); pk->set_highid(11); // initialize the Packet Descriptor and checks if initialized correctly pd.init(0, *config.mutable_pattern()); CPPUNIT_ASSERT(pd.isInitialized()); CPPUNIT_ASSERT(pd.waitingFor() == Command::READ_RESP); // register profile tpm->configureProfile(config); // request a packet three times for (uint64_t i=0; i< 3 ; ++i) { Packet * p(nullptr); bool ok = pd.send(p,0); CPPUNIT_ASSERT(ok); // test local id generation CPPUNIT_ASSERT(p->id()== (10+i>11?10:10+i)); // set correct type of packet and receive p->set_cmd(Command::READ_RESP); ok = pd.receive(0, p); CPPUNIT_ASSERT(ok); // delete packet delete p; } // descriptor re-initialisation to test range reset pd.addressReconfigure(0xBEEF, 0x3F7C); for (uint64_t i=0; i< 3 ; ++i) { Packet * p(nullptr); bool ok = pd.send(p,0); CPPUNIT_ASSERT(ok); // test address reconfiguration CPPUNIT_ASSERT(p->addr() == (i == 0 || i == 2 ? 0xBEEF: 0xDEAD)); // set correct type of packet and receive p->set_cmd(Command::READ_RESP); ok = pd.receive(0, p); CPPUNIT_ASSERT(ok); // delete packet delete p; } /* * test autoRange - first call fails as autoRange * cannot extend an existing range * so we still get the old range returned */ CPPUNIT_ASSERT(pd.autoRange(1023) == 0x3F7C); // force the packet descriptor autoRange CPPUNIT_ASSERT(pd.autoRange(1023, true) == 0x7ED842); // test new range applies for (uint64_t i=0; i< 3 ; ++i) { Packet * p(nullptr); // reset before the third packet is sent if (i==2) pd.reset(); bool ok = pd.send(p,0); CPPUNIT_ASSERT(ok); // test address reconfiguration // second packet shouldn't wrap around anymore // third packet should now have the base address due to reset if (i==0) { CPPUNIT_ASSERT(p->addr() == 0xDEAD); } else if (i==1) { CPPUNIT_ASSERT(p->addr() == 0xfe6b); } else { CPPUNIT_ASSERT(p->addr() == 0xBEEF); } // set correct type of packet and receive p->set_cmd(Command::READ_RESP); ok = pd.receive(0, p); CPPUNIT_ASSERT(ok); // delete packet delete p; } // test striding autorange - re-init the pd auto* stride = pk->mutable_stride(); pk->mutable_address()->set_increment(10); stride->set_increment(64); stride->set_range("640"); pd.init(0, *pk); // test that the range is 640 times the strides (10) times the increment CPPUNIT_ASSERT(pd.autoRange(100)==6400); // reduce the increment to and test the autoRange again address->set_increment(640); pd.init(0, *pk); pd.autoRange(100); Packet * p(nullptr); // TEMP test packet generation doesn't wrap for (uint64_t i=0; i< 100 ; ++i) { bool ok = pd.send(p,0); // verify that no wrap-around has occurred CPPUNIT_ASSERT(p->addr() == i*64); delete p; } } void TestAtp::testAtp_stats() { Stats s1, s2, s3, s4; // record sending 1000 bytes every 2 ticks for (uint64_t i=0; i <= 10; i+=2) { s1.send(i, 1000); } // data transferred should be 6KB and rate should be // 600 B/tick CPPUNIT_ASSERT(s1.dataSent == 6000); CPPUNIT_ASSERT(s1.sendRate() == 600); CPPUNIT_ASSERT(s1.sent == 6); CPPUNIT_ASSERT(s1.received == 0); CPPUNIT_ASSERT(s1.dataReceived == 0); s1.reset(); // data should now be back to 0 CPPUNIT_ASSERT(s1.dataSent == 0); // test reception s1.receive(0, 0, 0.0); s1.receive(10, 1000, 0.0); CPPUNIT_ASSERT(s1.dataReceived == 1000); CPPUNIT_ASSERT(s1.receiveRate() == 100); CPPUNIT_ASSERT(s1.sent == 0); CPPUNIT_ASSERT(s1.received == 2); // tests to make sure add and sum operator are working correctly s1.reset(); for (uint64_t i=0; i <= 10; i+=2) { s1.send(i, 1000); s2.send(i+12, 1000); } for (uint64_t i=0; i <= 22; i+=2) { s3.send(i, 1000); } s4 = s1 + s2; CPPUNIT_ASSERT(s4.dump() == s3.dump()); s2 += s1; CPPUNIT_ASSERT(s2.dump() == s3.dump()); } void TestAtp::testAtp_trafficProfile() { // configuration object Profile config; // fill the configuration makeProfile(&config, ProfileDescription { "testAtp_trafficProfile", Profile::READ }); CPPUNIT_ASSERT(!config.has_pattern()); CPPUNIT_ASSERT(!config.wait_for_size()); CPPUNIT_ASSERT(!config.has_fifo()); // fill the FIFO configuration - pointer, // maxLevel, startup level, OT, transactions, rate makeFifoConfiguration(config.mutable_fifo(), 1000, FifoConfiguration::EMPTY, 1, 1, 10); // fill the Packet Descriptor configuration PatternConfiguration* pk = makePatternConfiguration(config.mutable_pattern(), Command::READ_REQ, Command::READ_RESP); // configure the packet address and size generation policies pk->set_size(64); PatternConfiguration::Address* address = pk->mutable_address(); address->set_base(0); address->set_increment(0); // register this profile in the TPM tpm->configureProfile(config); // add a wait on a PLAY event and register as new profile config.add_wait_for("testAtp_trafficProfile_to_play ACTIVATION"); config.set_name("testAtp_trafficProfile_to_play"); // register this profile in the TPM tpm->configureProfile(config); // remove the wait for field from the config object config.clear_wait_for(); // delete the packet configuration from the config object config.release_pattern(); // change name config.set_name("testAtp_trafficProfile_checker"); // set the checker to monitor test_profile config.add_check("testAtp_trafficProfile"); // register this profile in the TPM tpm->configureProfile(config); // get the ATP Profile Descriptors TrafficProfileDescriptor* pd = tpm->profiles.at(0); TrafficProfileDescriptor* wait = tpm->profiles.at(1); TrafficProfileDescriptor* checker = tpm->profiles.at(2); // test packet send and receive bool locked = false; Packet* p(nullptr),*empty(nullptr); uint64_t next=0; CPPUNIT_ASSERT(pd->send(locked, p, next)); CPPUNIT_ASSERT(checker->send(locked, p, next)); p->set_cmd(Command::READ_RESP); // profile should be locked, not active CPPUNIT_ASSERT(!pd->active(locked)); CPPUNIT_ASSERT(locked); // profile should not accept a send request at this time CPPUNIT_ASSERT(!pd->send(locked, empty, next)); // receive two partial responses p->set_size(32); CPPUNIT_ASSERT(pd->receive(next, p, .0)); CPPUNIT_ASSERT(pd->receive(next, p, .0)); // update checker checker->receive(next, p, .0); // profile should now terminate - not active, not locked CPPUNIT_ASSERT(!pd->active(locked)); CPPUNIT_ASSERT(!locked); // checker should have terminated CPPUNIT_ASSERT(!checker->active(locked)); CPPUNIT_ASSERT(!locked); // reset the checker checker->reset(); // checker is active again CPPUNIT_ASSERT(checker->active(locked)); // test locked profile CPPUNIT_ASSERT(!wait->send(locked, p, next)); CPPUNIT_ASSERT(locked); // issue PLAY event CPPUNIT_ASSERT(wait->receiveEvent(Event(Event::ACTIVATION, Event::TRIGGERED,wait->getId(),0))); // test packet is now sent CPPUNIT_ASSERT(wait->send(locked, p, next)); CPPUNIT_ASSERT(!locked); } void TestAtp::testAtp_tpm() { const string profile_0 = "testAtp_tpm_profile_0"; const string profile_1 = "testAtp_tpm_profile_1"; const unordered_set<string> profiles = {profile_0, profile_1}; // profile configuration object Profile config_0, config_1; // fill the configuration makeProfile(&config_0, ProfileDescription { profile_0, Profile::READ }); // fill the FIFO configuration - pointer, maxLevel, // startup level, OT, transactions, rate makeFifoConfiguration(config_0.mutable_fifo(), 1000, FifoConfiguration::EMPTY, 1, 4, 10); // fill the Packet Descriptor configuration PatternConfiguration* pk = makePatternConfiguration(config_0.mutable_pattern(), Command::READ_REQ, Command::READ_RESP); // configure the packet address and size generation policies pk->set_size(32); PatternConfiguration::Address* address = pk->mutable_address(); address->set_base(0); address->set_increment(64); PatternConfiguration::Stride* stride = pk->mutable_stride(); stride->set_increment(1); stride->set_range("3B"); // register 1st profile tpm->configureProfile(config_0); // change fields for 2nd profile // 2nd profile waits on 1st to complete config_1 = config_0; config_1.set_name(profile_1); config_1.set_master_id(profile_1); config_1.add_wait_for(profile_0); // register 2nd profile tpm->configureProfile(config_1); // checks to see if list of masters was set correctly CPPUNIT_ASSERT(tpm->getMasters() == profiles); // checks to see if the number of slaves is 0 CPPUNIT_ASSERT(tpm->getMasterSlaves().empty()); // request packets to TPM bool locked = false; uint64_t next = 0, time = 0; // every time a packet is generated, send a response // to terminate test_profile and unlock test_profile2 // reuse request as response, so that it gets deallocated by ATP // each profile sends 3 packets , then terminates for (uint64_t i = 0; i < 4 ; ++i) { auto packets = tpm->send(locked, next, time); // only one masters sent packets CPPUNIT_ASSERT(packets.size() == 1); // test_profile sent a packet CPPUNIT_ASSERT(packets.find(profile_0) != packets.end()); // one master is locked, so flag on CPPUNIT_ASSERT(locked); Packet* p = (packets.find(profile_0)->second); CPPUNIT_ASSERT(p->addr()==(i<3?i:64)); p->set_cmd(Command::READ_RESP); tpm->receive(0, p); } for (uint64_t i = 0; i < 4 ; ++i) { // "test_profile2" is now unlocked auto packets = tpm->send(locked, next, time); // test_profile2 sent a packet CPPUNIT_ASSERT(packets.find(profile_1) != packets.end()); // test_profile2 is locked, waiting for response CPPUNIT_ASSERT(locked); // TPM is waiting for responses CPPUNIT_ASSERT(tpm->waiting()); // send the response Packet* p = (packets.find(profile_1)->second); CPPUNIT_ASSERT(p->addr()==(i<3?i:64)); p->set_cmd(Command::READ_RESP); tpm->receive(0, p); } CPPUNIT_ASSERT(!tpm->waiting()); // no packets left to send auto packets = tpm->send(locked, next, time); CPPUNIT_ASSERT(packets.empty()); // check that the stream composed by profile 0 and 1 is completed const uint64_t pId = tpm->profileId("testAtp_tpm_profile_0"); CPPUNIT_ASSERT(tpm->streamTerminated(pId)); // reset the stream from profile 0 tpm->streamReset(pId); CPPUNIT_ASSERT(!tpm->streamTerminated(pId)); // play profile 0 again. for (uint64_t i = 0; i < 4 ; ++i) { auto packets = tpm->send(locked, next, time); // only one masters sent packets CPPUNIT_ASSERT(packets.size() == 1); // test_profile sent a packet CPPUNIT_ASSERT(packets.find(profile_0) != packets.end()); // one master is locked, so flag on CPPUNIT_ASSERT(locked); Packet* p = (packets.find(profile_0)->second); CPPUNIT_ASSERT(p->addr()==(i<3?i:64)); p->set_cmd(Command::READ_RESP); tpm->receive(0, p); } for (uint64_t i = 0; i < 4 ; ++i) { // "test_profile2" is now unlocked auto packets = tpm->send(locked, next, time); // test_profile2 sent a packet CPPUNIT_ASSERT(packets.find(profile_1) != packets.end()); // test_profile2 is locked, waiting for response CPPUNIT_ASSERT(locked); // TPM is waiting for responses CPPUNIT_ASSERT(tpm->waiting()); // send the response Packet* p = (packets.find(profile_1)->second); CPPUNIT_ASSERT(p->addr()==(i<3?i:64)); p->set_cmd(Command::READ_RESP); tpm->receive(0, p); } CPPUNIT_ASSERT(tpm->streamTerminated(pId)); // reset the TPM - this causes profiles to be reloaded tpm->reset(); // register 1st profile tpm->configureProfile(config_0); // register 2nd profile tpm->configureProfile(config_1); // define a new profile, which also waits on profile 0 const string profile_2 = "testAtp_tpm_profile_2"; Profile config_2(config_1); config_2.set_name(profile_2); config_2.set_master_id(profile_2); // change type to WRITE config_2.set_type(Profile::WRITE); // register 3nd profile tpm->configureProfile(config_2); // define a new profile, which waits on profile 1 and 2 const string profile_3 = "testAtp_tpm_profile_3"; Profile config_3(config_0); config_3.set_name(profile_3); config_3.set_master_id(profile_3); config_3.add_wait_for(profile_1); config_3.add_wait_for(profile_2); // register 3nd profile tpm->configureProfile(config_3); /* * profile 1 and profile 2 wait on profile 0 - all READ profiles, * whilst profile 3 is of type WRITE and waits on 1 and 2. * They all are configured with 4 transactions of 64 bytes each. * They form a diamond-shaped stream. * Each of them streams 3 packets with a stride of 1 byte distance, * then jumps with an increment of 64 to issue the fourth. * We therefore reconfigure the stream to constrain it to * 64 (first increment) + 1 (left over packet) = 65 bytes per profile * with a starting address base of 0x00FF */ const uint64_t rootId = tpm->profileId("testAtp_tpm_profile_0"); const uint64_t newRange = tpm->addressStreamReconfigure(rootId, 0x00FF, 388); // verify that the new range has been applied CPPUNIT_ASSERT(newRange == 260); // send all packets for (uint64_t i = 0; i < 16 ; ++i) { auto packets = tpm->send(locked, next, time); if (!locked) time = next; for (auto p: packets) { p.second->set_cmd(Command::READ_RESP); tpm->receive(time, p.second); } } /* uniqueStream */ config_0.add_wait_for(profile_0 + " ACTIVATION"); auto reset { [this, &config_0, &config_1]() { tpm->reset(); tpm->configureProfile(config_0); tpm->configureProfile(config_1); } }; /* 1. First usage should return Root Profile ID of Original */ reset(); tpm->streamCacheUpdate(); uint64_t orig_id { tpm->profileId(profile_0) }; TrafficProfileDescriptor *orig { tpm->getProfile(orig_id) }; uint64_t clone0_id { tpm->uniqueStream(orig_id) }; TrafficProfileDescriptor *clone0 { tpm->getProfile(clone0_id) }; CPPUNIT_ASSERT(tpm->getStreamCache().size() == 1); CPPUNIT_ASSERT(tpm->getProfileMap().size() == 2); CPPUNIT_ASSERT(orig_id == clone0_id); CPPUNIT_ASSERT(orig == clone0); /* 2. Non-first usage should create Clone and return its Root Profile ID Clone name should be different from Original */ clone0_id = tpm->uniqueStream(orig_id); clone0 = tpm->getProfile(clone0_id); CPPUNIT_ASSERT(tpm->getStreamCache().size() == 2); CPPUNIT_ASSERT(tpm->getProfileMap().size() == 4); CPPUNIT_ASSERT(orig_id != clone0_id); CPPUNIT_ASSERT(orig != clone0); uint64_t clone1_id = tpm->uniqueStream(orig_id); TrafficProfileDescriptor *clone1 { tpm->getProfile(clone1_id) }; CPPUNIT_ASSERT(tpm->getStreamCache().size() == 3); CPPUNIT_ASSERT(tpm->getProfileMap().size() == 6); CPPUNIT_ASSERT(orig_id != clone1_id); CPPUNIT_ASSERT(orig != clone1); CPPUNIT_ASSERT(clone0_id != clone1_id); CPPUNIT_ASSERT(clone0 != clone1); /* 3. Clone state should be independent */ auto diff_conf { [this](const uint64_t id0, const uint64_t id1) { tpm->addressStreamReconfigure(id0, 0x11, 0x123, Profile::READ); tpm->addressStreamReconfigure(id1, 0xFF, 0x321, Profile::READ); } }; /* 3.1 Original activated, one Packet per send, Original terminated, Clones not terminated */ diff_conf(orig_id, clone0_id); orig->activate(); locked = false ; next = time = 0; for (uint64_t txn { 0 }; txn < config_0.fifo().total_txn(); ++txn) { auto packets { tpm->send(locked, next, time) }; CPPUNIT_ASSERT(packets.size() == 1); for (auto &packet : packets) { Packet *p { packet.second }; p->set_cmd(Command::READ_RESP); tpm->receive(0, p); } } // Handle remaining transactions for (uint64_t txn { 0 }; txn < config_1.fifo().total_txn(); ++txn) { for (auto &packet : tpm->send(locked, next, time)) { Packet *p { packet.second }; p->set_cmd(Command::READ_RESP); tpm->receive(0, p); } } CPPUNIT_ASSERT(tpm->streamTerminated(orig_id)); CPPUNIT_ASSERT(!tpm->streamTerminated(clone0_id)); CPPUNIT_ASSERT(!tpm->streamTerminated(clone1_id)); // 3.2 Original and Clone activated, two Packets per Send, different // addresses as configured, reset of Original does not reset Clone reset(); tpm->streamCacheUpdate(); orig_id = tpm->profileId(profile_0); tpm->uniqueStream(orig_id); clone0_id = tpm->uniqueStream(orig_id); orig = tpm->getProfile(orig_id); clone0 = tpm->getProfile(clone0_id); diff_conf(orig_id, clone0_id); orig->activate(); clone0->activate(); locked = false ; next = time = 0; for (uint64_t txn { 0 }; txn < config_0.fifo().total_txn(); ++txn) { auto packets { tpm->send(locked, next, time) }; CPPUNIT_ASSERT(packets.size() == 2); Packet *p0 { packets.begin()->second }, *p1 { (++packets.begin())->second }; CPPUNIT_ASSERT(p0->addr() != p1->addr()); if (txn < 3) { CPPUNIT_ASSERT( (p0->addr() == 0x11 + txn && p1->addr() == 0xFF + txn) || (p0->addr() == 0xFF + txn && p1->addr() == 0x11 + txn) ); } for (auto &packet : packets) { Packet *p { packet.second }; p->set_cmd(Command::READ_RESP); tpm->receive(time, p); } } // Handle remaining transactions for (uint64_t txn { 0 }; txn < config_1.fifo().total_txn(); ++txn) { auto packets { tpm->send(locked, next, time) }; CPPUNIT_ASSERT(packets.size() == 2); for (auto &packet : packets) { Packet *p { packet.second }; p->set_cmd(Command::READ_RESP); tpm->receive(0, p); } } CPPUNIT_ASSERT(tpm->streamTerminated(orig_id)); CPPUNIT_ASSERT(tpm->streamTerminated(clone0_id)); tpm->streamReset(orig_id); CPPUNIT_ASSERT(!tpm->streamTerminated(orig_id)); CPPUNIT_ASSERT(tpm->streamTerminated(clone0_id)); /* 4. Diamond-shaped Stream Clones */ reset(); tpm->configureProfile(config_2); tpm->configureProfile(config_3); tpm->streamCacheUpdate(); orig_id = tpm->profileId(profile_0); tpm->uniqueStream(orig_id); clone0_id = tpm->uniqueStream(orig_id); CPPUNIT_ASSERT(tpm->getStreamCache().size() == 2); CPPUNIT_ASSERT(tpm->getProfileMap().size() == 8); orig = tpm->getProfile(orig_id); clone0 = tpm->getProfile(clone0_id); orig->activate(); clone0->activate(); locked = false ; next = time = 0; for (uint64_t txn { 0 }; txn < 16; ++txn) { auto packets { tpm->send(locked, next, time) }; for (auto &packet : packets) { Packet *p { packet.second }; p->set_cmd(Command::READ_RESP); tpm->receive(time, p); } if (next) time = next; } CPPUNIT_ASSERT(tpm->streamTerminated(orig_id)); CPPUNIT_ASSERT(tpm->streamTerminated(clone0_id)); tpm->streamReset(clone0_id); CPPUNIT_ASSERT(tpm->streamTerminated(orig_id)); CPPUNIT_ASSERT(!tpm->streamTerminated(clone0_id)); /* 5. Stream Clones in different Masters */ reset(); orig_id = tpm->profileId(profile_0); clone0_id = tpm->uniqueStream(orig_id, tpm->masterId(profile_1)); CPPUNIT_ASSERT(tpm->getStreamCache().size() == 2); CPPUNIT_ASSERT(tpm->getProfileMap().size() == 4); clone0 = tpm->getProfile(clone0_id); clone0->activate(); locked = false ; next = time = 0; for (uint64_t txn { 0 }; txn < config_0.fifo().total_txn(); ++txn) { for (auto &packet : tpm->send(locked, next, time)) { Packet *p { packet.second }; CPPUNIT_ASSERT(p->master_id() == profile_1); p->set_cmd(Command::READ_RESP); tpm->receive(0, p); } } } void TestAtp::testAtp_trafficProfileDelay() { // profile configuration object Profile config; // fill the configuration makeProfile(&config, ProfileDescription { "testAtp_trafficProfileDelay_pause", Profile::READ }); // fill in the delay field DelayConfiguration* delay = config.mutable_delay(); delay->set_time("2s"); // register delay profile tpm->configureProfile(config); // delay will return next == 2s in ATP time units bool locked = false; uint64_t next = 0, time = 0; auto packets = tpm->send(locked, next, time); // we should now find that delay is active CPPUNIT_ASSERT(!tpm->isTerminated("testAtp_trafficProfileDelay_pause")); // no transmission CPPUNIT_ASSERT(packets.size() == 0); // next is 2s in picoseconds (default ATP time resolution) CPPUNIT_ASSERT(next==2*(1e+12)); // we should now find that delay is terminated time = next; packets = tpm->send(locked, next, time); CPPUNIT_ASSERT(packets.size() == 0); CPPUNIT_ASSERT(tpm->isTerminated("testAtp_trafficProfileDelay_pause")); // register another profile delay->set_time("3.7ns"); config.set_name("testAtp_trafficProfileDelay_pause_2"); config.set_master_id("testAtp_trafficProfileDelay_pause_2"); // register delay profile 2 tpm->configureProfile(config); // call send packets = tpm->send(locked, next, time); // we should now find that delay is active CPPUNIT_ASSERT(!tpm->isTerminated("testAtp_trafficProfileDelay_pause_2")); // no transmission CPPUNIT_ASSERT(packets.size() == 0); // next is 3.7ns + 2s in picoseconds (default ATP time resolution) CPPUNIT_ASSERT(next==(2*(1e+12) + 3700)); // we should now find that delay is terminated time = next; packets = tpm->send(locked, next, time); CPPUNIT_ASSERT(packets.size() == 0); CPPUNIT_ASSERT(tpm->isTerminated("testAtp_trafficProfileDelay_pause_2")); // reset the profile const uint64_t delayId = tpm->profileId("testAtp_trafficProfileDelay_pause_2"); tpm->getProfile(delayId)->reset(); // the profile should now be active again and have a next time equal to its delay packets = tpm->send(locked, next, time); // we should now find that delay is active CPPUNIT_ASSERT(!tpm->isTerminated("testAtp_trafficProfileDelay_pause_2")); // no transmission CPPUNIT_ASSERT(packets.size() == 0); // next is NOW (time) + 3.7ns in picoseconds (default ATP time resolution) CPPUNIT_ASSERT(next==time+3700); // allow for the delay to expire time = next; packets = tpm->send(locked, next, time); // register another profile - white-spaces in delay specifier delay->set_time("0.191 us"); config.set_name("testAtp_trafficProfileDelay_pause_3"); config.set_master_id("testAtp_trafficProfileDelay_pause_3"); // register delay profile 2 tpm->configureProfile(config); // call send packets = tpm->send(locked, next, time); // we should now find that delay is active CPPUNIT_ASSERT(!tpm->isTerminated("testAtp_trafficProfileDelay_pause_3")); // no transmission CPPUNIT_ASSERT(packets.size() == 0); // next is 3.7ns + 2s + 0.191 us in picoseconds (default ATP time resolution) CPPUNIT_ASSERT(next==(2*(1e+12) + 2*3700 + 191000)); // we should now find that delay is terminated time = next; packets = tpm->send(locked, next, time); CPPUNIT_ASSERT(packets.size() == 0); CPPUNIT_ASSERT(tpm->isTerminated("testAtp_trafficProfileDelay_pause_3")); } void TestAtp::testAtp_unitConversion() { pair<uint64_t, uint64_t> result(0, 0); // tests converting string to lowercase CPPUNIT_ASSERT(Utilities::toLower("aBcDEFg")=="abcdefg"); // test reducing a fraction auto h = Utilities::reduce<uint64_t>; result = h(30,6); CPPUNIT_ASSERT(result.first==5); CPPUNIT_ASSERT(result.second==1); // test number in string detection CPPUNIT_ASSERT(Utilities::isNumber("10")); CPPUNIT_ASSERT(!Utilities::isNumber("a")); // test trimming of string CPPUNIT_ASSERT(Utilities::trim(" t e s t ")=="test"); // test floating point string conversion to pair number, scale auto g = Utilities::toUnsignedWithScale<uint64_t>; result = g("1.34"); CPPUNIT_ASSERT(result.first==134); CPPUNIT_ASSERT(result.second==100); // test byte conversion from string CPPUNIT_ASSERT(Utilities::toBytes<int>("512 Bytes")==512); // test power of two rate detection auto f = Utilities::toRate<uint64_t>; result = f("3 TiB@s"); CPPUNIT_ASSERT(result.first==3); CPPUNIT_ASSERT(result.second==1099511627776); // test power of two rate, bits detection result = f( " 5 Kibit/s"); CPPUNIT_ASSERT(result.first==5); CPPUNIT_ASSERT(result.second==128); // test rate in Gbytes detection result = f( " 12.3 GBps"); // test rate in bits detection CPPUNIT_ASSERT(result.first==123); CPPUNIT_ASSERT(result.second==1e8); // test rate in bytes detection result = f( " 4.23 Bpus"); CPPUNIT_ASSERT(result.first==423); CPPUNIT_ASSERT(result.second==1e4); // test separator detection result = f( "44 Bpps"); CPPUNIT_ASSERT(result.first==44); CPPUNIT_ASSERT(result.second==1e12); result = f("16 Tbit ps"); CPPUNIT_ASSERT(result.first==16); CPPUNIT_ASSERT(result.second==(1e12)/8); // tests hex conversion from int CPPUNIT_ASSERT(Utilities::toHex(167489)=="0x28e41"); // tests next power of two calculation CPPUNIT_ASSERT(Utilities::nextPowerTwo(27004)==16384); } void TestAtp::testAtp_kronos() { // set Kronos bucket width and calendar size tpm->setKronosConfiguration("3ps","15ps"); // create a Kronos system Kronos k (tpm); // initialize Kronos and checks for no schedules events CPPUNIT_ASSERT(!k.isInitialized()); k.init(); CPPUNIT_ASSERT(k.isInitialized()); CPPUNIT_ASSERT(!k.next()); // generate events and register to Kronos for (uint64_t i=0; i < 30; i+=3) { Event ev(Event::TICK,Event::TRIGGERED,i,i); k.schedule(ev); CPPUNIT_ASSERT(k.getCounter()==(i+3)/3); } // get events while advancing TPM time for (uint64_t i=3; i < 30; i+=6) { tpm->setTime(i); list<Event> q; k.get(q); CPPUNIT_ASSERT(!q.empty() && (q.size()==2)); for (auto& ev:q){ CPPUNIT_ASSERT(ev.action==Event::TRIGGERED); CPPUNIT_ASSERT((ev.time==i) || (ev.time==(i-3))); CPPUNIT_ASSERT((ev.id==i) || (ev.id==(i-3))); } CPPUNIT_ASSERT((k.getCounter()==0) || k.next()==(i+3)); } // should be no scheduled events CPPUNIT_ASSERT(!k.next()); } void TestAtp::testAtp_trafficProfileSlave() { // profile configuration object Profile config; bool locked = false; // fill the configuration for testing the buffer makeProfile(&config, ProfileDescription { "testAtp_testAtp_trafficProfileSlave", Profile::READ }); // fill in the slave field SlaveConfiguration* slave_cfg = config.mutable_slave(); slave_cfg->set_latency("80ns"); slave_cfg->set_rate("32GBps"); slave_cfg->set_granularity(16); slave_cfg->set_ot_limit(6); // register slave profile tpm->configureProfile(config); // get pointer to slave auto slave = tpm->getProfile(0); Packet* req = nullptr; uint64_t next = 0; bool ok = false; /* * Here the first 2 packets will be sent, but no further. * This is because of the size 33 and granularity 16. So * each packet will actually take up 3 slots. So after 2 * packets have been sent, no more packets can be be in * transit as the buffer is full. So here we will test * to make sure this happens. */ for (uint64_t i=0; i<slave_cfg->ot_limit(); i++) { req = new Packet; req->set_cmd(READ_REQ); req->set_addr(0); req->set_size(33); ok = slave->receive(next,req,0); CPPUNIT_ASSERT(i>1?!ok:ok); } // fill the configuration for testing the OT limit makeProfile(&config, ProfileDescription { "testAtp_testAtp_trafficProfileSlave_2", Profile::READ }); // fill in the slave field SlaveConfiguration* slave_cfg_2 = config.mutable_slave(); slave_cfg_2->set_latency("80ns"); slave_cfg_2->set_rate("32GBps"); slave_cfg_2->set_granularity(16); slave_cfg_2->set_ot_limit(6); // register slave profile tpm->configureProfile(config); // get pointer to slave auto slave_2 = tpm->getProfile(1); req = nullptr; next = 0; /* * Here we see that the size of the packets fit * perfectly into the buffer, so 6 packets can be * in transit. We will test to make sure that once * the limit has been reached that the slave then * becomes locked * attempt another send after reset, * which should succeed * only one response should then be available for transmission */ for (uint64_t i=0; i<slave_cfg_2->ot_limit()+2; i++) { req = new Packet; req->set_cmd(READ_REQ); req->set_addr(0); req->set_size(16); if (i>slave_cfg_2->ot_limit()) { // resets the slave for the last request slave_2->reset(); } bool ok = slave_2->receive(next,req,0); if (i<slave_cfg_2->ot_limit()) { // requests within the OT limit are accepted CPPUNIT_ASSERT(ok); } else if (i==slave_cfg_2->ot_limit()) { // request is rejected due to OT limit reached CPPUNIT_ASSERT(!ok); } else if (i>slave_cfg_2->ot_limit()) { // last request is accepted after reset CPPUNIT_ASSERT(ok); } } // get responses - advance TPM time to memory latency tpm->setTime(80000); locked = false; Packet* res = nullptr; next = 0; for (uint64_t i=0; i<slave_cfg_2->ot_limit(); i++) { ok = slave_2->send(locked,res,next); if (ok) { delete res; } // only one response is available (one request after reset) CPPUNIT_ASSERT(i==0||!ok); } } void TestAtp::testAtp_trafficProfileManagerRouting() { // number of master/slave pairs to test const uint8_t nPairs = 10; // fill the configurations const string master = "testAtp_trafficProfileManagerRouting_master"; const string slave = "testAtp_trafficProfileManagerRouting_slave"; // profile configuration objects Profile masters[nPairs]; Profile slaves[nPairs]; std::set<pair<string,string>> slaveToMasterMap; for (uint8_t i = 0; i < nPairs; ++i) { const string num = to_string(i); string mName = master + num; string sName = slave + num; slaveToMasterMap.insert(pair <string,string> (mName,sName)); makeProfile(&masters[i], ProfileDescription { mName, Profile::READ, &mName }); makeProfile(&slaves[i], ProfileDescription { sName, Profile::READ, &sName }); // fill in the master field // fill the FIFO configuration - pointer, maxLevel, // startup level, OT, transactions, rate makeFifoConfiguration(masters[i].mutable_fifo(), 1000, FifoConfiguration::EMPTY, 2, 10, 2); // fill the Packet Descriptor configuration PatternConfiguration* pk = makePatternConfiguration(masters[i].mutable_pattern(), Command::READ_REQ, Command::READ_RESP); // configure the packet address and size generation policies pk->set_size(64); PatternConfiguration::Address* address = pk->mutable_address(); address->set_base(0); address->set_increment(64); // fill in the slave field SlaveConfiguration* slave_cfg = slaves[i].mutable_slave(); slave_cfg->set_latency("80ns"); slave_cfg->set_rate("32GBps"); slave_cfg->set_granularity(16); slave_cfg->set_ot_limit(6); slave_cfg->add_master(mName); tpm->configureProfile(masters[i]); tpm->configureProfile(slaves[i]); } // Checks to make sure each master and slave pair were added correctly, and // then removes it. for (const auto& pair: tpm->getMasterSlaves()) { CPPUNIT_ASSERT(slaveToMasterMap.find(pair) != slaveToMasterMap.end()); slaveToMasterMap.erase(pair); } // Checks to make sure that the mapping is now empty CPPUNIT_ASSERT(slaveToMasterMap.empty()); // start TPM internal routing tpm->loop(); } CppUnit::TestSuite* TestAtp::suite() { CppUnit::TestSuite* suiteOfTests = new CppUnit::TestSuite("TestAtp"); suiteOfTests->addTest(new CppUnit::TestCaller<TestAtp>( "Test0 - Tests the ATP FIFO", &TestAtp::testAtp_fifo )); suiteOfTests->addTest(new CppUnit::TestCaller<TestAtp>( "Test1 - Tests the ATP Event", &TestAtp::testAtp_event )); suiteOfTests->addTest(new CppUnit::TestCaller<TestAtp>( "Test2 - Tests the ATP Packet Descriptor", &TestAtp::testAtp_packetDesc )); suiteOfTests->addTest(new CppUnit::TestCaller<TestAtp>( "Test3 - Tests the ATP Stats object", &TestAtp::testAtp_stats )); suiteOfTests->addTest(new CppUnit::TestCaller<TestAtp>( "Test4 - Tests the ATP Traffic Profile", &TestAtp::testAtp_trafficProfile )); suiteOfTests->addTest(new CppUnit::TestCaller<TestAtp>( "Test5 - Tests the ATP Traffic Profile Manager", &TestAtp::testAtp_tpm )); suiteOfTests->addTest(new CppUnit::TestCaller<TestAtp>( "Test6 - Tests the ATP Traffic Profile Delay", &TestAtp::testAtp_trafficProfileDelay )); suiteOfTests->addTest(new CppUnit::TestCaller<TestAtp>( "Test 7 - Tests the ATP Unit Conversion Utilities", &TestAtp::testAtp_unitConversion)); suiteOfTests->addTest(new CppUnit::TestCaller<TestAtp>( "Test 8 - Tests the Kronos engine", &TestAtp::testAtp_kronos)); suiteOfTests->addTest(new CppUnit::TestCaller<TestAtp>( "Test 9 - Tests the ATP Traffic Profile Slave", &TestAtp::testAtp_trafficProfileSlave)); suiteOfTests->addTest(new CppUnit::TestCaller<TestAtp>( "Test 10 - Tests the ATP Traffic Profile Manager routing", &TestAtp::testAtp_trafficProfileManagerRouting)); return suiteOfTests; } } // end of namespace
34.892643
121
0.63823
wwmfdb
805e6bc7723f90f790ec29fb614e1b636c31e5f5
2,365
cpp
C++
Receiver/src/main.cpp
rhymu8354/SocketTutorial
9f6b6c243da6ac0b7e6754d5b2edc8f803d8c1ef
[ "MIT" ]
28
2020-06-25T03:19:26.000Z
2021-12-08T04:27:09.000Z
Receiver/src/main.cpp
rhymu8354/SocketTutorial
9f6b6c243da6ac0b7e6754d5b2edc8f803d8c1ef
[ "MIT" ]
1
2021-09-21T06:32:29.000Z
2021-09-21T06:32:29.000Z
Receiver/src/main.cpp
rhymu8354/SocketTutorial
9f6b6c243da6ac0b7e6754d5b2edc8f803d8c1ef
[ "MIT" ]
5
2020-11-26T23:38:52.000Z
2022-01-13T13:02:20.000Z
#include <inttypes.h> #include <signal.h> #include <Sockets/DatagramSocket.hpp> #include <stdio.h> #include <stdlib.h> #include <thread> namespace { // This is the UDP port number at which we will receive messages. constexpr uint16_t port = 8000; // This flag is set by our SIGINT signal handler in order to cause the main // program's polling loop to exit and let the program clean up and // terminate. bool shutDown = false; // This function is provided to the event loop to be called whenever a // message is received at our socket. // // When this happens, simply print the message to standard output. void OnReceiveMessage(const std::string& message) { printf("Received message: %s\n", message.c_str()); } // This function is set up to be called whenever the SIGINT signal // (interrupt signal, typically sent when the user presses <Ctrl>+<C> on // the terminal) is sent to the program. We just set a flag which is // checked in the program's polling loop to control when the loop is // exited. void OnSigInt(int) { shutDown = true; } // This is the function called from the main program in order to operate // the socket while a SIGINT handler is set up to control when the program // should terminate. int InterruptableMain() { // Make a socket and assign an address to it. Sockets::DatagramSocket receiver; if (!receiver.Bind(port)) { return EXIT_FAILURE; } // Start the event loop to process the sending and receiving of // datagrams. receiver.Start(OnReceiveMessage); printf("Now listening for messages on port %" PRIu16 "...\n", port); // Poll the flag set by our SIGINT handler, until it is set. while (!shutDown) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } printf("Program exiting.\n"); return EXIT_SUCCESS; } } int main(int argc, char* argv[]) { // Catch SIGINT (interrupt signal, typically sent when the user presses // <Ctrl>+<C> on the terminal) during program execution. const auto previousInterruptHandler = signal(SIGINT, OnSigInt); const auto returnValue = InterruptableMain(); (void)signal(SIGINT, previousInterruptHandler); return returnValue; }
34.779412
79
0.660888
rhymu8354
805f1f34a091be632afc6ce698d2a72ea9be4b6d
1,691
cpp
C++
p3.cpp
mihaimusat/PA-Tema1-2019
60b959ca1665db8614be54ef1ca71849aeeee4ba
[ "MIT" ]
null
null
null
p3.cpp
mihaimusat/PA-Tema1-2019
60b959ca1665db8614be54ef1ca71849aeeee4ba
[ "MIT" ]
null
null
null
p3.cpp
mihaimusat/PA-Tema1-2019
60b959ca1665db8614be54ef1ca71849aeeee4ba
[ "MIT" ]
null
null
null
/*Musat Mihai-Robert *Grupa 323CB */ #include <bits/stdc++.h> const int NMAX = 1e3 + 5, TUZGU = 0, RITZA = 1; using namespace std; int main() { ifstream fin("p3.in"); ofstream fout("p3.out"); int n, v[NMAX]; long long dp[NMAX][NMAX]; //citire date de intrare fin >> n; for(int i = 1; i <= n; ++i) { fin >> v[i]; } //dp[i][j] = diferenta maxima pe care o poate obtine Tuzgu pe fiecare interval [i..j] //fixez lungimea intervalului 1, 2, ... for(int lg = 1; lg <= n; ++lg) { //imi fixez capetele intervalului //si stiu ca initial Tuzgu este la mutare int lin = 1, col = lg, turn = TUZGU; //daca ma aflu la pozitie impara, Ritza e la mutare if((n - lg) % 2 != 0) { turn = RITZA; } //cat timp pot sa mai marginesc superior intervalul while(col <= n) { if(turn == TUZGU) { //daca iau din stanga, vad cat ar fi facut Tuzgu pe [i+1..j] si adun elementul curent //daca iau din dreapta, vad cat ar fi facut Tuzgu pe [i..j-1] si adun elementul curent //scorul maxim obtinut de Tuzgu va fi maximul dintre cele 2 cazuri dp[lin][col] = max(dp[lin + 1][col] + v[lin], dp[lin][col - 1] + v[col]); } else { //analog situatiei anterioare, doar ca vreau sa maximizez acum scorul Ritzei //deci va trebui sa calculez scorul minim dintre cele doua cazuri si sa scad elementul curent dp[lin][col] = min(dp[lin + 1][col] - v[lin], dp[lin][col - 1] - v[col]); } ++lin;//actualizez si capatul inferior ++col; } } //afisez rezultatul fout << dp[1][n] << endl; return 0; }
29.155172
109
0.564755
mihaimusat
8067fbf9ccdc6bffb693b8ea482f3205352d6a6c
3,101
tpp
C++
code/source/ui/hid/actionlistener.tpp
crafn/clover
586acdbcdb34c3550858af125e9bb4a6300343fe
[ "MIT" ]
12
2015-01-12T00:19:20.000Z
2021-08-05T10:47:20.000Z
code/source/ui/hid/actionlistener.tpp
crafn/clover
586acdbcdb34c3550858af125e9bb4a6300343fe
[ "MIT" ]
null
null
null
code/source/ui/hid/actionlistener.tpp
crafn/clover
586acdbcdb34c3550858af125e9bb4a6300343fe
[ "MIT" ]
null
null
null
template <nodes::SignalType S> ActionListener<S>::ActionListener( const ContextChannel::Name& channel_name, const Context::Tag& context_tag, const Action::Name& action_name, Callback on_action){ startListening(channel_name, context_tag, action_name, createTypeSafeCallback(on_action)); } template <nodes::SignalType S> ActionListener<S>::ActionListener( const ContextChannel::Name& channel_name, const Context::Tag& context_tag, const Action::Name& action_name, GenericCb on_action){ startListening(channel_name, context_tag, action_name, on_action); } template <nodes::SignalType S> ActionListener<S>::ActionListener(const ActionListener& other){ startListening(other); } template <nodes::SignalType S> ActionListener<S>::ActionListener(ActionListener&& other){ other.stopListening(); startListening(other); } template <nodes::SignalType S> ActionListener<S>::~ActionListener(){ stopListening(); } template <nodes::SignalType S> ActionListener<S>& ActionListener<S>::operator=(const ActionListener& other){ stopListening(); startListening(other); return *this; } template <nodes::SignalType S> ActionListener<S>& ActionListener<S>::operator=(ActionListener&& other){ other.stopListening(); stopListening(); startListening(other); return *this; } template <nodes::SignalType S> template <int Dummy> typename ActionListener<S>::GenericCb ActionListener<S>::createTypeSafeCallbackWithValue(Callback on_action) const { return [on_action, this] (nodes::SignalValue sig_value){ Value value; try { value= sig_value.get<S>(); } catch (...){ print(debug::Ch::General, debug::Vb::Critical, "ui::hid::ActionListener::onAction(..): Invalid type for action %s: %s for %s (fix control mappings)", getActionName().cStr(), nodes::RuntimeSignalTypeTraits::enumString(S).cStr(), nodes::RuntimeSignalTypeTraits::enumString(sig_value.getType()).cStr()); return; } on_action(value); }; } template <nodes::SignalType S> template <int Dummy> typename ActionListener<S>::GenericCb ActionListener<S>::createTypeSafeCallbackWithoutValue(Callback on_action) const { return [on_action] (nodes::SignalValue){ on_action(); }; } template <nodes::SignalType S> void ActionListener<S>::triggerCallback(const Action& action) const { ensure(isListening()); ensure(onActionCallback); onActionCallback(action.getValue()); } template <nodes::SignalType S> void ActionListener<S>::startListening(const ContextChannel::Name& channel_name, const Context::Tag& context_tag, const Action::Name& action_name, GenericCb on_action){ channelName= channel_name; contextTag= context_tag; actionName= action_name; onActionCallback= on_action; Base::onActionListeningStart(*this); } template <nodes::SignalType S> void ActionListener<S>::startListening(const ActionListener& other){ startListening(other.channelName, other.contextTag, other.actionName, other.onActionCallback); } template <nodes::SignalType S> void ActionListener<S>::stopListening(){ if (isListening()){ Base::onActionListeningStop(*this); } }
29.254717
168
0.750726
crafn
80754a668bb28675bc4251228b13ef9225016b78
1,170
cc
C++
config/tests/iconv.cc
henkdemarie/dicom-dimse-native
a2a5042de8c5de04831baf3de7182ea2eb7b78f8
[ "MIT" ]
29
2020-02-13T17:40:16.000Z
2022-03-12T14:58:22.000Z
config/tests/iconv.cc
henkdemarie/dicom-dimse-native
a2a5042de8c5de04831baf3de7182ea2eb7b78f8
[ "MIT" ]
20
2020-03-20T18:06:31.000Z
2022-02-25T08:38:08.000Z
config/tests/iconv.cc
henkdemarie/dicom-dimse-native
a2a5042de8c5de04831baf3de7182ea2eb7b78f8
[ "MIT" ]
9
2020-03-20T17:29:55.000Z
2022-02-14T10:15:33.000Z
/* * Copyright (C) 2018, OFFIS e.V. * All rights reserved. See COPYRIGHT file for details. * * This software and supporting documentation were developed by * * OFFIS e.V. * R&D Division Health * Escherweg 2 * D-26121 Oldenburg, Germany * * * Module: config * * Author: Jan Schlamelcher * * Purpose: Analyze behavior of an iconv implementation. */ #include <iconv.h> #include <stdio.h> int main() { char input[2] = { '\366', '\0' }; char output[8]; iconv_t i = iconv_open( "ASCII", "ISO-8859-1" ); if( (iconv_t)-1 != i ) { iconv( i, 0, 0, 0, 0 ); #ifdef LIBICONV_SECOND_ARGUMENT_CONST const #endif char* in = input; char* out = output; size_t ins = 1; size_t outs = 8; const size_t result = iconv( i, &in, &ins, &out, &outs ); iconv_close( i ); if( ~(size_t)0 == result ) { printf( "AbortTranscodingOnIllegalSequence" ); return 0; } if( 8 == outs ) // output buffer not touched { printf( "DiscardIllegalSequences" ); return 0; } } return 1; }
22.075472
65
0.538462
henkdemarie
807a53f7c05dbaaf2ba29c8924fd6bf94ef1a31e
850
cpp
C++
docs/examples/stroke_closed_degenerate_path.cpp
mohad12211/skia
042a53aa094715e031ebad4da072524ace316744
[ "BSD-3-Clause" ]
6,304
2015-01-05T23:45:12.000Z
2022-03-31T09:48:13.000Z
docs/examples/stroke_closed_degenerate_path.cpp
mohad12211/skia
042a53aa094715e031ebad4da072524ace316744
[ "BSD-3-Clause" ]
67
2016-04-18T13:30:02.000Z
2022-03-31T23:06:55.000Z
docs/examples/stroke_closed_degenerate_path.cpp
mohad12211/skia
042a53aa094715e031ebad4da072524ace316744
[ "BSD-3-Clause" ]
1,231
2015-01-05T03:17:39.000Z
2022-03-31T22:54:58.000Z
// Copyright 2020 Google LLC. // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. #include "tools/fiddle/examples.h" REG_FIDDLE(stroke_closed_degenerate_path, 256, 256, false, 0) { void draw(SkCanvas* canvas) { SkPath path; path.addRect({50.f, 50.f, 50.f, 50.f}); SkPaint joinStroke; joinStroke.setColor(SK_ColorGREEN); joinStroke.setStrokeWidth(10.f); joinStroke.setStyle(SkPaint::kStroke_Style); joinStroke.setStrokeJoin(SkPaint::kRound_Join); canvas->drawPath(path, joinStroke); canvas->translate(100.f, 0); SkPaint capStroke; capStroke.setColor(SK_ColorRED); capStroke.setStrokeWidth(10.f); capStroke.setStyle(SkPaint::kStroke_Style); capStroke.setStrokeCap(SkPaint::kRound_Cap); canvas->drawPath(path, capStroke); } } // END FIDDLE
32.692308
100
0.723529
mohad12211
807e6fab3e5a7a819f3ad2a1877cb1240b1a4b1d
818
cpp
C++
examples/example_as_list.cpp
alipha/streamer
5ce6e19ea517dd201a946bd83ba1732b769c84d3
[ "MIT" ]
null
null
null
examples/example_as_list.cpp
alipha/streamer
5ce6e19ea517dd201a946bd83ba1732b769c84d3
[ "MIT" ]
null
null
null
examples/example_as_list.cpp
alipha/streamer
5ce6e19ea517dd201a946bd83ba1732b769c84d3
[ "MIT" ]
null
null
null
#include "../streamer/generate.hpp" #include "../streamer/list.hpp" #include <array> #include <cassert> /* * as_list and as_list() move the elements in the stream into a std::list and returns the std::list. * as_list and as_list() force the steps of the stream to be executed. * as_list and as_list() cannot be used with an infinite stream. */ void example_as_list() { using namespace streamer; std::array<int, 5> input = {56, 3, 23, 100, 42}; std::list<int> result = input | as_list; std::list<int> result2 = input | as_list(); try { generator([]() { return 1; }) | as_list; assert(false); } catch(const unbounded_stream &) {} std::list<int> expected = {56, 3, 23, 100, 42}; assert(result == expected); assert(result2 == expected); }
25.5625
100
0.621027
alipha
8081e2164b2e6afc7d999f573f34ec1a4131ccef
910
cpp
C++
Number of Coins - GFG/number-of-coins.cpp
Jatin-Shihora/LeetCode-Solutions
8e6fc84971ec96ec1263ba5ba2a8ae09e6404398
[ "MIT" ]
1
2022-01-02T10:29:32.000Z
2022-01-02T10:29:32.000Z
Number of Coins - GFG/number-of-coins.cpp
Jatin-Shihora/LeetCode-Solutions
8e6fc84971ec96ec1263ba5ba2a8ae09e6404398
[ "MIT" ]
null
null
null
Number of Coins - GFG/number-of-coins.cpp
Jatin-Shihora/LeetCode-Solutions
8e6fc84971ec96ec1263ba5ba2a8ae09e6404398
[ "MIT" ]
1
2022-03-04T12:44:14.000Z
2022-03-04T12:44:14.000Z
// { Driver Code Starts #include <bits/stdc++.h> using namespace std; // } Driver Code Ends class Solution{ public: int minCoins(int coins[], int M, int V) { // Your code goes here int dp[V+1]; dp[0] = 0 ; for(int i=1;i<=V;i++) dp[i] = INT_MAX; for(int i=1;i<=V;i++){ for(int j=0;j<M;j++){ if(coins[j]<=i){ int res = dp[i-coins[j]]; if(res!=INT_MAX) dp[i] = min(dp[i],res+1); } } } return dp[V]==INT_MAX?-1:dp[V]; } }; // { Driver Code Starts. int main() { int t; cin >> t; while (t--) { int v, m; cin >> v >> m; int coins[m]; for(int i = 0; i < m; i++) cin >> coins[i]; Solution ob; cout << ob.minCoins(coins, m, v) << "\n"; } return 0; } // } Driver Code Ends
17.169811
46
0.414286
Jatin-Shihora
8081f77ad22462c18d1483e12413ea11fff88d8a
46
cpp
C++
src/libs/ocMath/Point2d.cpp
TO85/OttoCODE
48f0ea1be3c55cf63f508db93a2794b10bc346c8
[ "MIT" ]
2
2021-08-15T17:21:27.000Z
2021-08-20T21:41:16.000Z
src/libs/ocMath/Point2d.cpp
TO85/OttoCODE
48f0ea1be3c55cf63f508db93a2794b10bc346c8
[ "MIT" ]
8
2022-01-19T08:18:51.000Z
2022-03-13T14:45:03.000Z
src/libs/ocMath/Point2d.cpp
TO85/torc
fb21aa272192023fec9d5e1018c291e26462fd36
[ "MIT" ]
null
null
null
#include "Point2d.h" Point2d::Point2d() { }
6.571429
20
0.630435
TO85
8092684d8aeb7d29e32f21e1371ca51c03fba9b8
1,417
hpp
C++
cpp/godot-cpp/include/gen/Shader.hpp
GDNative-Gradle/proof-of-concept
162f467430760cf959f68f1638adc663fd05c5fd
[ "MIT" ]
1
2021-03-16T09:51:00.000Z
2021-03-16T09:51:00.000Z
cpp/godot-cpp/include/gen/Shader.hpp
GDNative-Gradle/proof-of-concept
162f467430760cf959f68f1638adc663fd05c5fd
[ "MIT" ]
null
null
null
cpp/godot-cpp/include/gen/Shader.hpp
GDNative-Gradle/proof-of-concept
162f467430760cf959f68f1638adc663fd05c5fd
[ "MIT" ]
null
null
null
#ifndef GODOT_CPP_SHADER_HPP #define GODOT_CPP_SHADER_HPP #include <gdnative_api_struct.gen.h> #include <stdint.h> #include <core/CoreTypes.hpp> #include <core/Ref.hpp> #include "Shader.hpp" #include "Resource.hpp" namespace godot { class Texture; class Shader : public Resource { struct ___method_bindings { godot_method_bind *mb_get_code; godot_method_bind *mb_get_default_texture_param; godot_method_bind *mb_get_mode; godot_method_bind *mb_has_param; godot_method_bind *mb_set_code; godot_method_bind *mb_set_default_texture_param; }; static ___method_bindings ___mb; public: static void ___init_method_bindings(); static inline const char *___get_class_name() { return (const char *) "Shader"; } static inline Object *___get_from_variant(Variant a) { godot_object *o = (godot_object*) a; return (o) ? (Object *) godot::nativescript_1_1_api->godot_nativescript_get_instance_binding_data(godot::_RegisterState::language_index, o) : nullptr; } // enums enum Mode { MODE_SPATIAL = 0, MODE_CANVAS_ITEM = 1, MODE_PARTICLES = 2, }; // constants static Shader *_new(); // methods String get_code() const; Ref<Texture> get_default_texture_param(const String param) const; Shader::Mode get_mode() const; bool has_param(const String name) const; void set_code(const String code); void set_default_texture_param(const String param, const Ref<Texture> texture); }; } #endif
24.431034
245
0.768525
GDNative-Gradle
80937a3344b282b72997fbe04f38d7d1554b3e03
1,303
hpp
C++
third_party/boost/simd/function/refine_rsqrt.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
6
2018-02-25T22:23:33.000Z
2021-01-15T15:13:12.000Z
third_party/boost/simd/function/refine_rsqrt.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
null
null
null
third_party/boost/simd/function/refine_rsqrt.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
7
2017-12-12T12:36:31.000Z
2020-02-10T14:27:07.000Z
//================================================================================================== /*! @file @copyright 2016 NumScale SAS Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ //================================================================================================== #ifndef BOOST_SIMD_FUNCTION_REFINE_RSQRT_HPP_INCLUDED #define BOOST_SIMD_FUNCTION_REFINE_RSQRT_HPP_INCLUDED #if defined(DOXYGEN_ONLY) namespace boost { namespace simd { /*! @ingroup group-arithmetic This function object performs a Newton-Raphson step to improve precision of rsqrt estimate. This function can be used in conjunction with raw_(rsqrt) to add more precision to the estimates if their default precision is not enough. @par Header <boost/simd/function/refine_rsqrt.hpp> @par semantic: @code auto r = refine_rsqrt(x, est); @endcode is similar to @code auto r = fma( fnms(x, sqr(est), 1), est/2, est); @endcode @see rec **/ IEEEValue refine_rsqrt(IEEEValue const& x, IEEEValue const& est); } } #endif #include <boost/simd/function/scalar/refine_rsqrt.hpp> #include <boost/simd/function/simd/refine_rsqrt.hpp> #endif
24.584906
100
0.606293
SylvainCorlay
8093b98e1aadbae41453d92eb6af47bcff31e12b
4,704
cpp
C++
test/src/tc/es/gtest/src/helper/enrollee/ESEnrolleeHelper.cpp
jonghenhan/iotivity
7dfc2bc6a5c0506cf88bc23e88e38fe1b795da31
[ "Apache-2.0" ]
301
2015-01-20T16:11:32.000Z
2021-11-25T04:29:36.000Z
test/src/tc/es/gtest/src/helper/enrollee/ESEnrolleeHelper.cpp
jonghenhan/iotivity
7dfc2bc6a5c0506cf88bc23e88e38fe1b795da31
[ "Apache-2.0" ]
13
2015-06-04T09:55:15.000Z
2020-09-23T00:38:07.000Z
test/src/tc/es/gtest/src/helper/enrollee/ESEnrolleeHelper.cpp
jonghenhan/iotivity
7dfc2bc6a5c0506cf88bc23e88e38fe1b795da31
[ "Apache-2.0" ]
233
2015-01-26T03:41:59.000Z
2022-03-18T23:54:04.000Z
/****************************************************************** * * Copyright 2016 Samsung Electronics All Rights Reserved. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ******************************************************************/ #include "ESEnrolleeHelper.h" #include <iostream> #ifdef HAVE_PTHREAD_H #include <pthread.h> #endif #include <stdio.h> #include <stdlib.h> bool ESEnrolleeHelper::isCallbackInvoked = false; const int g_timeout = 30; ESEnrolleeHelper m_esEnrolleeHelper; ESEnrolleeHelper::ESEnrolleeHelper() { } void ESEnrolleeHelper::waitForResponse() { void* ret = NULL; pthread_t callbackListiningThread; pthread_create(&callbackListiningThread, NULL, listeningFunc, NULL); pthread_join(callbackListiningThread, &ret); } void* ESEnrolleeHelper::listeningFunc(void *arg) { int second = 0; OCStackResult result = OC_STACK_ERROR; IOTIVITYTEST_LOG(INFO,"\nWaiting For the Response...........................\n"); while (!ESEnrolleeHelper::isCallbackInvoked) { result = OCProcess(); if (result != OC_STACK_OK) { IOTIVITYTEST_LOG(INFO,"OCStack stop error\n"); } CommonUtil::waitInSecond(1); if (++second == g_timeout) { second = 0; IOTIVITYTEST_LOG(INFO,"\nTimeout For Response!Please Try Again\n\n"); break; } } IOTIVITYTEST_LOG(INFO,"Callback is successfully called\n"); pthread_exit (NULL); } void ESEnrolleeHelper::wiFiProvCbInApp(ESWiFiConfData *eventData) { IOTIVITYTEST_LOG(INFO,"wiFiProvCbInApp IN\n"); ESEnrolleeHelper::isCallbackInvoked = true; if (eventData->ssid != NULL) { IOTIVITYTEST_LOG(INFO,"SSID : %s\n", eventData->ssid); } else { IOTIVITYTEST_LOG(INFO,"ERROR! SSID IS NULL\n"); } if (eventData->pwd != NULL) { IOTIVITYTEST_LOG(INFO,"Password : %s\n", eventData->pwd); } else { IOTIVITYTEST_LOG(INFO,"ERROR! Password IS NULL\n"); } if (eventData->authtype == NONE_AUTH || eventData->authtype == WEP || eventData->authtype == WPA_PSK || eventData->authtype == WPA2_PSK) { IOTIVITYTEST_LOG(INFO,"AuthType : %d\n", eventData->authtype); } else { IOTIVITYTEST_LOG(INFO,"ERROR! AuthType IS NULL\n"); } if (eventData->enctype == NONE_ENC || eventData->enctype == WEP_64 || eventData->enctype == WEP_128 || eventData->enctype == TKIP || eventData->enctype == AES || eventData->enctype == TKIP_AES) { IOTIVITYTEST_LOG(INFO,"EncType : %d\n", eventData->enctype); } else { IOTIVITYTEST_LOG(INFO,"ERROR! EncType IS NULL\n"); } if (eventData->userdata != NULL) { } IOTIVITYTEST_LOG(INFO,"enven data User", eventData->userdata); IOTIVITYTEST_LOG(INFO,"wiFiProvCbInApp OUT\n"); } void ESEnrolleeHelper::devConfProvCbInApp(ESDevConfData *eventData) { IOTIVITYTEST_LOG(INFO,"devConfProvCbInApp IN\n"); ESEnrolleeHelper::isCallbackInvoked = true; IOTIVITYTEST_LOG(INFO,"enven data User", eventData->userdata); IOTIVITYTEST_LOG(INFO,"devConfProvCbInApp OUT\n"); } void ESEnrolleeHelper::cloudDataProvCbInApp(ESCoapCloudConfData *eventData) { IOTIVITYTEST_LOG(INFO,"cloudDataProvCbInApp IN\n"); ESEnrolleeHelper::isCallbackInvoked = true; if (eventData->authProvider != NULL) { IOTIVITYTEST_LOG(INFO,"AuthProvider : %s\n", eventData->authProvider); } else { IOTIVITYTEST_LOG(INFO,"ERROR! AuthProvider IS NULL\n"); } if (eventData->ciServer != NULL) { IOTIVITYTEST_LOG(INFO,"CI Server : %s\n", eventData->ciServer); } else { IOTIVITYTEST_LOG(INFO,"ERROR! CI Server IS NULL\n"); } IOTIVITYTEST_LOG(INFO,"cloudDataProvCbInApp OUT\n"); } ESResult ESEnrolleeHelper::setDeviceProperty() { ESDeviceProperty deviceProperty = { { { WIFI_11G, WIFI_11N, WIFI_11AC }, 3, { WIFI_24G, WIFI_5G }, 2, { WPA_PSK, WPA2_PSK }, 2, { AES, TKIP_AES }, 2 }, { "Test Device" } }; return ESSetDeviceProperty(&deviceProperty); }
27.348837
85
0.635629
jonghenhan
809777ad73d752c8f0b59c3145993b57bebcfe5d
4,963
cxx
C++
ds/security/protocols/kerberos/parser/asn1base.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
ds/security/protocols/kerberos/parser/asn1base.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
ds/security/protocols/kerberos/parser/asn1base.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//============================================================================= // // MODULE: ASN1Base.cxx // // Description: // // Implementation of the ASN1ParserBase class // // Modification History // // Mark Pustilnik Date: 06/09/02 - created // //============================================================================= #include "ASN1Parser.hxx" // // For a frame which starts with 6a 82 01 30 ... (long form) // // 82 (*(Frame+1)) indicates "long form" where Size is 2 (0x82 & 0x7F) // and the return value is ( 0x01 << 8 ) | 0x30 = 0x130 // // For a frame which starts with 6a 30 ... (short form) // // the return value is simply 0x30 // DWORD ASN1ParserBase::DataLength( IN ASN1FRAME * Frame ) { LPBYTE LengthPortion = Frame->Address + 1; if ( *LengthPortion & 0x80 ) // long form { USHORT i; DWORD Sum = 0; BYTE Size = *LengthPortion & 0x7F; for ( i = 1; i <= Size; i++ ) { Sum <<= 8; Sum |= *(LengthPortion + i); } return Sum; } else // short form { return *LengthPortion; } } // // Calculates the length of the length header in either short or long form // Returns '3' for "82 01 30" // Returns '1' for "30" // ULONG ASN1ParserBase::HeaderLength( IN ULPBYTE Address ) { if ( *Address & 0x80 ) { // // If long form, assign size to value of bits 7-1 // return ( 1 + *Address & 0x7F); } else { // // Short form only takes one octet // return 1; } } // // Verifies that the frame is pointing at the type of item we expect by // performing a descriptor comparison, then moves past the descriptor and // the length header. The caller uses this to point the frame at the next // item to be parsed. // DWORD ASN1ParserBase::VerifyAndSkipHeader( IN OUT ASN1FRAME * Frame ) { DWORD dw; // // Check both optional descriptors associated with this frame // BYTE Descriptors[2] = { m_Descriptor, m_AppDescriptor }; for ( ULONG i = 0; i < ARRAY_COUNT( Descriptors ); i++ ) { if ( Descriptors[i] != 0 ) { // // Verify the descriptor and bail on mismatch // if ( *Frame->Address != Descriptors[i] ) { dw = ERROR_INVALID_USER_BUFFER; goto Cleanup; } // // Skip over the descriptor // Frame->Address++; // // Skip over the length header // Frame->Address += HeaderLength( Frame->Address ); } } dw = ERROR_SUCCESS; Cleanup: return dw; } // // Displays the value of the unit, mapping between the ASN.1 encoding and the // actual parsed-out value as necessary // DWORD ASN1ParserBase::Display( IN ASN1FRAME * Frame, IN ASN1VALUE * Value, IN HPROPERTY hProperty, IN DWORD IFlags ) { DWORD dw = ERROR_SUCCESS; DWORD Length; ULPVOID Address; switch( Value->ut ) { case utGeneralizedTime: Length = sizeof( Value->st ); Address = &Value->st; break; case utBoolean: Length = sizeof( Value->b ); Address = &Value->b; break; case utInteger: case utBitString: // // ASN.1 integers are optimally encoded using the fewest number of bytes // This does not bode well with Netmon which insists on knowing how long // a value is before displaying it. The mapping below will show both // the raw buffer and the corresponding value properly // Length = sizeof( Value->dw ); Address = &Value->dw; break; case utGeneralString: case utOctetString: if ( Value->string.l == 0 ) { Address = "<empty string>"; Length = strlen(( const char * )Address ); } else { Address = Value->string.s; Length = Value->string.l; } break; default: // // By default, display unadulterated raw data pointed to by 'Value' // Length = Value->Length; Address = Value->Address; } if ( FALSE == AttachPropertyInstanceEx( Frame->hFrame, hProperty, Value->Length, Value->Address, Length, Address, 0, Frame->Level, IFlags )) { dw = ERROR_CAN_NOT_COMPLETE; } return dw; }
22.057778
81
0.480959
npocmaka
8098e862feb929b40a73d442ae17e8e9596eeccb
478
cpp
C++
src/snap/undirected.cpp
jrbn/trident
e56a4977054eea01cb3f716db92bde5d6a49bfb7
[ "Apache-2.0" ]
null
null
null
src/snap/undirected.cpp
jrbn/trident
e56a4977054eea01cb3f716db92bde5d6a49bfb7
[ "Apache-2.0" ]
null
null
null
src/snap/undirected.cpp
jrbn/trident
e56a4977054eea01cb3f716db92bde5d6a49bfb7
[ "Apache-2.0" ]
null
null
null
#include <snap/directed.h> #include <snap/undirected.h> Trident_UTNGraph::Trident_UTNGraph(KB *kb) { this->kb = kb; this->q = kb->query(); SnapReaders::loadAllFiles(kb); string path = kb->getPath() + string("/tree/flat"); mapping = bip::file_mapping(path.c_str(), bip::read_only); mapped_rgn = bip::mapped_region(mapping, bip::read_only); rawnodes = static_cast<char*>(mapped_rgn.get_address()); nnodes = (uint64_t)mapped_rgn.get_size() / 18; }
34.142857
62
0.67364
jrbn
809ebd14915c0890cc407b1c94923460312d5c72
115
cpp
C++
examples/implementation/greeter.cpp
dwd31415/emscripten-build-tool
0e8d1ec10f0fc899d07873ee1bed8e61b48d31c0
[ "MIT" ]
null
null
null
examples/implementation/greeter.cpp
dwd31415/emscripten-build-tool
0e8d1ec10f0fc899d07873ee1bed8e61b48d31c0
[ "MIT" ]
null
null
null
examples/implementation/greeter.cpp
dwd31415/emscripten-build-tool
0e8d1ec10f0fc899d07873ee1bed8e61b48d31c0
[ "MIT" ]
null
null
null
#include "greeter.h" void Greeter::greet(std::string name) { std::cout << this->greeting << name << std::endl; }
16.428571
50
0.643478
dwd31415
80a082797bce020722e5a80eef379cc17550980b
3,423
cpp
C++
Chaos-Engine/Material.cpp
MrAbnox/Chaos-Engine
cad124526f416d661f110ac1fcc7070f4ae9fedf
[ "MIT" ]
1
2020-02-10T13:30:44.000Z
2020-02-10T13:30:44.000Z
Chaos-Engine/Material.cpp
MrAbnox/Chaos-Engine
cad124526f416d661f110ac1fcc7070f4ae9fedf
[ "MIT" ]
null
null
null
Chaos-Engine/Material.cpp
MrAbnox/Chaos-Engine
cad124526f416d661f110ac1fcc7070f4ae9fedf
[ "MIT" ]
null
null
null
#include "Material.h" #include "TheShader.h" #include "TheDebug.h" //------------------------------------------------------------------------------- //Constructor //------------------------------------------------------------------------------- Material::Material() { name = "Material"; shininess = 0; ambient = glm::vec3(1.0f); diffuse = glm::vec3(1.0f); specular = glm::vec3(1.0f); } //------------------------------------------------------------------------------- //Destructor //------------------------------------------------------------------------------- Material::~Material() { } //------------------------------------------------------------------------------- //Send Data //------------------------------------------------------------------------------- void Material::SendData(Materials m, std::string shader) { std::string tempString; switch (m) { case Materials::M_AMBIENT: tempString = shader + "_material.ambient"; TheShader::Instance()->SendUniformData(tempString.c_str(), ambient); break; case Materials::M_SPECULAR: tempString = shader + "_material.diffuse"; TheShader::Instance()->SendUniformData(tempString.c_str(), diffuse); break; case Materials::M_DIFFUSE: tempString = shader + "_material.specular"; TheShader::Instance()->SendUniformData(tempString.c_str(), specular); break; case Materials::M_SHINE: tempString = shader + "_material.shininess"; TheShader::Instance()->SendUniformData(tempString.c_str(), shininess); break; default: break; } } //------------------------------------------------------------------------------- //Get Ambient //------------------------------------------------------------------------------- glm::vec3 Material::GetAmbient() const { return ambient; } //------------------------------------------------------------------------------- //Get Diffuse //------------------------------------------------------------------------------- glm::vec3 Material::GetDiffuse() const { return diffuse; } //------------------------------------------------------------------------------- //Get Specular //------------------------------------------------------------------------------- glm::vec3 Material::GetSpecular() const { return specular; } //------------------------------------------------------------------------------- //Set Ambient //------------------------------------------------------------------------------- void Material::SetAmbient(glm::vec3 v3) { ambient = v3; } //------------------------------------------------------------------------------- //Set Diffuse //------------------------------------------------------------------------------- void Material::SetDiffuse(glm::vec3 v3) { diffuse = v3; } //------------------------------------------------------------------------------- //Set Specular //------------------------------------------------------------------------------- void Material::SetSpecular(glm::vec3 v3) { specular = v3; } //------------------------------------------------------------------------------- //Set Shine //------------------------------------------------------------------------------- void Material::SetShine(float m_shininess) { shininess = m_shininess; }
28.057377
82
0.322232
MrAbnox
80a1accc0ac9c2b7d6fbcf56cf38871659f33407
2,193
cpp
C++
13.cpp
malkiewiczm/adventofcode2020
8491a5a0be11fa8cfa61d67c97401797c0e7cf6b
[ "Apache-2.0" ]
null
null
null
13.cpp
malkiewiczm/adventofcode2020
8491a5a0be11fa8cfa61d67c97401797c0e7cf6b
[ "Apache-2.0" ]
null
null
null
13.cpp
malkiewiczm/adventofcode2020
8491a5a0be11fa8cfa61d67c97401797c0e7cf6b
[ "Apache-2.0" ]
null
null
null
//#define PARTONE #include "template.hpp" #define INF(T) std::numeric_limits<T>::max() #ifndef PARTONE struct BusPair { I64 line; I64 order; }; static inline std::ostream &operator<< (std::ostream &o, const BusPair &pair) { o << "{ line: " << pair.line << ", order: " << pair.order << " }"; return o; } #endif int main(int argc, char **argv) { const char *const fname = (argc >= 2) ? argv[1] : "in.txt"; std::ifstream f(fname); if (! f.good()) { TRACE << "file cannot be opened" << std::endl; die(); } int start_time; f >> start_time; #ifdef PARTONE std::vector<int> bus_lines; { std::string line; std::getline(f, line); std::getline(f, line); size_t start = 0; size_t end; for (end = 0; (end = line.find(',', end)) != std::string::npos; ++end) { const std::string token = line.substr(start, end - start); start = end + 1; if (token[0] == 'x') continue; bus_lines.push_back(atoi(token.c_str())); } { const std::string token = line.substr(start, end - start); bus_lines.push_back(atoi(token.c_str())); } } int smallest = INF(int); int which_line = 0; for (auto bus : bus_lines) { const int amt = bus - (start_time % bus); if (amt < smallest) { smallest = amt; which_line = bus; } } trace(smallest * which_line); #else std::vector<BusPair> bus_lines; { std::string line; std::getline(f, line); std::getline(f, line); size_t start = 0; size_t end; int i = -1; for (end = 0; (end = line.find(',', end)) != std::string::npos; ++end) { const std::string token = line.substr(start, end - start); start = end + 1; ++i; if (token[0] == 'x') continue; bus_lines.push_back({ atoi(token.c_str()), i}); } { const std::string token = line.substr(start, end - start); ++i; bus_lines.push_back({ atoi(token.c_str()), i}); } } I64 t = 0; int solved = 0; I64 step = 1; for ( ; ; ) { const BusPair &bus = bus_lines[solved]; const I64 level = (t + bus.order) % bus.line; if (level == 0) { // we have solved this line ++solved; if (solved == static_cast<int>(bus_lines.size())) break; step = std::lcm(step, bus.line); } t += step; } trace(t); #endif }
21.712871
77
0.588235
malkiewiczm
80a1d9ad5e474a1350b805d04546a7092717587d
227
cpp
C++
NgineApp/src/NgineApplication.cpp
nak1411/Ngine
1f8d0784c43780f8a53149dc176f877aa12e6d7d
[ "Apache-2.0" ]
1
2022-02-26T08:43:14.000Z
2022-02-26T08:43:14.000Z
NgineApp/src/NgineApplication.cpp
nak1411/Ngine
1f8d0784c43780f8a53149dc176f877aa12e6d7d
[ "Apache-2.0" ]
null
null
null
NgineApp/src/NgineApplication.cpp
nak1411/Ngine
1f8d0784c43780f8a53149dc176f877aa12e6d7d
[ "Apache-2.0" ]
null
null
null
#include <Ngine.h> #include"Ngine/Core/EntryPoint.h" class NgineApp : public Ngine::Application { public: NgineApp() { } ~NgineApp() { } }; Ngine::Application* Ngine::CreateApplication() { return new NgineApp(); }
9.869565
46
0.669604
nak1411
80a1f117850185069dcd0ec18217efebeae81d40
905
cpp
C++
119. Pascal's Triangle II.cpp
NeoYY/Leetcode-Solution
0f067973d3c296ac7f2fa85a89dbdd5295b0b037
[ "MIT" ]
null
null
null
119. Pascal's Triangle II.cpp
NeoYY/Leetcode-Solution
0f067973d3c296ac7f2fa85a89dbdd5295b0b037
[ "MIT" ]
null
null
null
119. Pascal's Triangle II.cpp
NeoYY/Leetcode-Solution
0f067973d3c296ac7f2fa85a89dbdd5295b0b037
[ "MIT" ]
null
null
null
/* Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle. Note that the row index starts from 0. In Pascal's triangle, each number is the sum of the two numbers directly above it. Example: Input: 3 Output: [1,3,3,1] Follow up: Could you optimize your algorithm to use only O(k) extra space? This solution is already optimized, using dynamic allocation, only need one previous vector, reduce space usage */ class Solution { public: vector<int> getRow(int rowIndex) { vector<int> temp; vector<int> curr; temp.push_back( 1 ); curr.push_back( 1 ); for ( int i = 1; i <= rowIndex; i++ ) { curr.resize( i + 1, 1 ); for ( int j = 1; j < i; j++ ) { curr[j] = temp[j - 1] + temp[j]; } temp = curr; } return curr; } };
22.625
111
0.569061
NeoYY
80a444cc11798aac7491f9109473930eb6c479d5
72,268
cxx
C++
windows/core/ntgdi/gre/rle4blt.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
windows/core/ntgdi/gre/rle4blt.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
windows/core/ntgdi/gre/rle4blt.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/******************************Module*Header*******************************\ * Module Name: rleblt4.cxx * * This contains the bitmap simulation functions that blt from a 4 bit * Run-Length Encoded (RLE) source to a DIB surface. The DIB surface can be * 1, 4, 8, 16, 24, or 32 bits/pel. * * The code is based on functions found in 'rleblt8.cxx', version 2. * * Added RLE Encoding functions: 10 Oct 92 @ 10:18 * Gerrit van Wingerden [gerritv] * * Created: 03 Feb 92 @ 21:00 * * Author: Andrew Milton (w-andym) * * Notes: * * 1) These functions return a BOOL value. This value is TRUE if the * function ends before running out of data in the source RLE or before * hitting an End-of-Bitmap code. Otherwise, we return FALSE. This return * value is used by <EngCopyajBits> in the complex clipping case to decide * if the blt is complete. * * 2) Before exiting a function with a TRUE value, position information is * saved by the macro <RLE_SavePosition>. This is used by <EngCopyajBits> * to speed up the complex clipping case. * * 3) The below functions use about twenty different macros. This is * because they are all using the same basic algorithm to play an RLE * compression. The macros allow us to focus in on the nifty stuff of writing * the bytes out to the DIB. Routine administrivia is handled by the macros. * * The macros themselves are used to manage * * - Source Access and data alignment * - Visability Checking * - Output position changes with Newline & Delta codes * * The macro <RLE_InitVars> is used to define the varibles that relate to * the above information, and to define variables common to all RLE 4 * blt functions. Note that actual names of the common variables are passed * in as parameters to the macro. Why? Two reasons. Firstly, they are * initialized by values taken of the BLTINFO structure passed into the blt * function. Secondly, showing the variable names in the macro 'call' means * they don't just appear from nowhere into the function. RLE_InitVars * is the one macro that you should think three times about before modifying. * * One further note. The variables 'ulDstLeft' and 'ulDstRight' appear to * come from nowhere. This is not true. They are in fact declared by the * macro <RLE_GetVisibleRect>. However, showing these names in the macro * 'call' tended to obscure the code. Pretend you can see the declaration. * * Where can I find a macro definition? * * Good question, glad you asked. Look at the prefix: * * RLE_<stuff> - lives in RLEBLT.H * RLE4_<blah> - lives in RLE4BLT.H * * Anything else in here that looks like function call is not. It's a macro. * Probably for bitwise manipulations. Look for it in BITMANIP.H or in * the Miscellaneous section of RLEBLT.H * * 4) The 8 and 16 ajBits/Pel cases can be optimized by packing the source * colours into a word / dword. However, to actually see some net gain in * run time, it will take some tricky-dicky-doo pointer alignment checking. * This sort of thing may break on MIPS. * * * Copyright (c) 1990-1999 Microsoft Corporation * \**************************************************************************/ #include "precomp.hxx" /*******************************Public*Routine*****************************\ * bSrcCopySRLE4D8 * * Secure RLE blting that does clipping and won't die or write somewhere * it shouldn't if given bad data. * * History: * 3 Feb 1992 - Andrew Milton (w-andym): Creation. * \**************************************************************************/ BOOL bSrcCopySRLE4D8( PBLTINFO psb) { // Common RLE Initialization RLE_InitVars(psb, pjSrc, pjDst, PBYTE, ulCount, ulNext, lOutCol, pulXlate); RLE_AssertValid(psb); RLE_FetchVisibleRect(psb); RLE_SetStartPos(psb, lOutCol); // Outta here if we start past the top edge. Don't need to save our position. if (RLE_PastTopEdge) return(TRUE); // Must have bits left in the bitmap since we haven't // consumed any. // Extra Variables BYTE jSource; // Packed RLE 4 colour code BYTE ajColours[2]; // Destination for unpacking an RLE 4 code BOOL bExtraByte; // TRUE when an absolute run ends with a partial byte ULONG ulClipMargin; // Number of bytes clipped in an Encoded run // Main process loop LOOP_FOREVER { // Outta here if we can't get two more bytes if (RLE_SourceExhausted(2)) return(FALSE); RLE_GetNextCode(pjSrc, ulCount, ulNext); if (ulCount == 0) { // Absolute or Escape Mode. switch (ulNext) { case 0: // New Line RLE_NextLine(PBYTE, pjDst, lOutCol); if (RLE_PastTopEdge) { RLE_SavePosition(psb, pjSrc, pjDst, lOutCol); return(TRUE); } break; case 1: // End of the bitmap return(FALSE); case 2: /* Positional Delta. * The delta values live in the next two source bytes */ // Outta here if we can't get two more bytes if (RLE_SourceExhausted(2)) return(FALSE); RLE_GetNextCode(pjSrc, ulCount, ulNext); RLE_PosDelta(pjDst, lOutCol, ulCount, ulNext); if (RLE_PastTopEdge) { RLE_SavePosition(psb, pjSrc, pjDst, lOutCol); return(TRUE); } break; default: /* Absolute Mode. * The run length is stored in <ulNext>, <ulCount> is used to * hold left and right clip amounts. */ // Outta here if the bytes aren't in the source if (RLE_SourceExhausted(RLE4_ByteLength(ulNext))) return(FALSE); RLE4_AlignToWord(pjSrc, ulNext); if (RLE_InVisibleRect(ulNext, lOutCol)) { // Left Side Clipping if (lOutCol < (LONG)ulDstLeft) { ulCount = ulDstLeft - lOutCol; ulNext -= ulCount; lOutCol += ulCount; pjSrc += (ulCount >> 1); // Force the Source Run to a byte boundary if (bIsOdd(ulCount)) { jSource = *pjSrc++; pjDst[lOutCol] = (BYTE) pulXlate[GetLowNybble(jSource)]; lOutCol++; ulNext--; } } // Right Side Clipping. if ((lOutCol + (LONG) ulNext) > (LONG)ulDstRight) { ulCount = (lOutCol + ulNext) - ulDstRight; ulNext -= ulCount; } else ulCount = 0; // Slap the bits on. -- this is the funky-doodle stuff. bExtraByte = (BOOL) bIsOdd(ulNext); ulNext >>= 1; // Write complete bytes from the source while (ulNext) { jSource = *pjSrc++; RLE4_MakeColourBlock(jSource, ajColours, BYTE, pulXlate); pjDst[lOutCol] = ajColours[0]; pjDst[lOutCol+1] = ajColours[1]; lOutCol += 2; ulNext--; } // Account for a partial source byte in the run if (bExtraByte) { jSource = *pjSrc++; pjDst[lOutCol] = (BYTE) pulXlate[GetHighNybble(jSource)]; lOutCol++; pjSrc += (ulCount >> 1); // Clip Adjustment } else pjSrc += ((ulCount + 1) >> 1); // Clip Adjustment // Adjust the column for the right side clipping. lOutCol += ulCount; } else { /* Not on a visible scanline. * Adjust our x output position and source pointer. */ lOutCol += ulNext; pjSrc += (ulNext + 1) >> 1; } /* if */ // Pad so the run ends on a WORD boundary RLE4_FixAlignment(pjSrc) } /* switch */ } else { /* Encoded Mode * The run length is stored in <ulCount>, <ulClipMargin> is used * to hold left and right clip amounts. */ if (RLE_InVisibleRect(ulCount, lOutCol)) { // Left Side Clipping if (lOutCol < (LONG)ulDstLeft) { ulClipMargin = ulDstLeft - lOutCol; ulCount -= ulClipMargin; lOutCol += ulClipMargin; } // Right Side Clipping if ((lOutCol + (LONG) ulCount) > (LONG)ulDstRight) { ulClipMargin = (lOutCol + ulCount) - ulDstRight; ulCount -= ulClipMargin; } else ulClipMargin = 0; // Setup for the run bExtraByte = (BOOL) bIsOdd(ulCount); ulCount >>= 1; RLE4_MakeColourBlock(ulNext, ajColours, BYTE, pulXlate); // Write it while (ulCount) { pjDst[lOutCol] = ajColours[0]; pjDst[lOutCol+1] = ajColours[1]; lOutCol += 2; ulCount--; } /* Write the extra byte from an odd run length */ if (bExtraByte) { pjDst[lOutCol] = ajColours[0]; lOutCol++; } // Adjust for the right side clipping. lOutCol += ulClipMargin; } else { /* Not on a visible scanline. Adjust our x output position */ lOutCol += ulCount; } /* if */ } /* if */ } /* LOOP_FOREVER */ } /* bSrcCopySRLE4D8 */ /********************************Public*Routine****************************\ * bSrcCopySRLE4D1 * * Secure RLE blting to a 1 BPP DIB that does clipping and won't die or * write somewhere it shouldn't if given bad data. * * History: * 5 Feb 1992 - Andrew Milton (w-andym): * Added clip support. * 22 Jan 1992 - Andrew Milton (w-andym): Creation. * \**************************************************************************/ /* Local Macros ***********************************************************/ /* NOTE: In the Escape Modes, the current working byte must be * written to destination before the escape is executed. * These writes look unpleasant because we have to mask * current destination contents onto the working byte when * it is written. To such an end, the below macro... */ #define RLE4to1_WritePartial(DstPtr, OutByte, OutColumn, WritePos) \ if (RLE_RowVisible && (jBitPos = (BYTE) (OutColumn) & 7)) \ { \ if (RLE_ColVisible(OutColumn)) \ DstPtr[WritePos] = OutByte | \ ((~ajBits[jBitPos]) & DstPtr[WritePos]); \ else \ if (RLE_PastRightEdge(OutColumn)) \ DstPtr[ulRightWritePos] = OutByte | \ (DstPtr[ulRightWritePos] & jRightMask); \ } \ /* Converts an output column to a bitnumber in the working byte */ #define ColToBitPos(col) (7 - (BYTE)((col) & 7)) /* Lookup tables for bit patterns *****************************************/ static BYTE ajPosMask[] = // The i'th entry contains a byte with the i'th bit set { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x00 }; static BYTE ajBits[] = // The i'th entry contains a byte with the high i bits set { 0x00, 0x80, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC, 0xFE, 0xFF }; static BYTE ajBitPatterns[] = // The four possible full byte bit patterns of a packed colour { 0x00, 0x55, 0xAA, 0xFF }; /* And now the function ***************************************************/ BOOL bSrcCopySRLE4D1( PBLTINFO psb) { // Common RLE Initialization RLE_InitVars(psb, pjSrc, pjDst, PBYTE, ulCount, ulNext, lOutCol, pulXlate); RLE_AssertValid(psb); RLE_FetchVisibleRect(psb); RLE_SetStartPos(psb, lOutCol); // Outta here if we start past the top edge. Don't need to save our position. if (RLE_PastTopEdge) return(TRUE); // Must have bits left in the bitmap since we haven't // consumed any. // Extra Variables BYTE jWorking; // Hold area to build a byte for output ULONG ulWritePos; // Write position off <pjDst> into the destination ULONG ulLeftWritePos; // Leftmost write position BYTE jLeftMask; // Bitmask for taking bytes off the left edge ULONG ulRightWritePos; // Rightmost write position BYTE jRightMask; // Bitmask for taking bytes off the right edge BYTE jBitPos; // Bit number of the next write into <jWorking> BYTE jBitPosMask; // Bitmask with the <jBitPos>th bit set. ULONG ulCompBytes; // Number of full bytes in an Encoded run. ULONG ulClipMargin; // Number of bytes clipped off the right side of a run BYTE jSource; // Packed RLE 4 colour code BYTE ajColours[2]; // Destination for unpacking an RLE 4 code BOOL bExtraByte; // TRUE when an absolute run ends with a partial byte UINT i=0, j=0; // Our Initialization ulLeftWritePos = (ULONG)(ulDstLeft >> 3); jLeftMask = ajBits[ulDstLeft % 8]; ulRightWritePos = (ULONG) (ulDstRight >> 3); jRightMask = ~ajBits[(ulDstRight % 8)]; /* Fetch first working byte from the source. Yes, this is ugly. * We cannot assume we are at a left edge because the complex clipping * case could resume an RLE in the middle of its bitmap. We cannot do * a simple bounds check like RLE 8 to 4 because of bitmasking. Argh. */ ulWritePos = lOutCol >> 3; if (RLE_RowVisible) { if (RLE_ColVisible(lOutCol)) jWorking = pjDst[ulWritePos] & ajBits[lOutCol & 7]; else { if (RLE_PastRightEdge(lOutCol)) jWorking = pjDst[ulRightWritePos]; else jWorking = pjDst[ulLeftWritePos] & jLeftMask; } } // Diddle the translation table for (i = 1, j = 1; i < 16; i+=1, j ^= 1) pulXlate[i] = j; // Main Process loop LOOP_FOREVER { // Outta here if we can't get two more bytes if (RLE_SourceExhausted(2)) return(FALSE); RLE_GetNextCode(pjSrc, ulCount, ulNext); ulWritePos = lOutCol >> 3; if (ulCount == 0) { // Absolute or Escape Mode switch (ulNext) { case 0: // New Line. RLE4to1_WritePartial(pjDst, jWorking, lOutCol, ulWritePos); RLE_NextLine(PBYTE, pjDst, lOutCol); if (RLE_PastTopEdge) { RLE_SavePosition(psb, pjSrc, pjDst, lOutCol); return(TRUE); } if (RLE_RowVisible) jWorking = pjDst[ulLeftWritePos] & jLeftMask; break; case 1: // End of the bitmap. RLE4to1_WritePartial(pjDst, jWorking, lOutCol, ulWritePos); return(FALSE); case 2: // Positional Delta RLE4to1_WritePartial(pjDst, jWorking, lOutCol, ulWritePos); // Outta here if we can't get the delta values if (RLE_SourceExhausted(2)) return(FALSE); RLE_GetNextCode(pjSrc, ulCount, ulNext); RLE_PosDelta(pjDst, lOutCol, ulCount, ulNext); if (RLE_PastTopEdge) { RLE_SavePosition(psb, pjSrc, pjDst, lOutCol); return(TRUE); } // Fetch a new working byte off the destination ulWritePos = lOutCol >> 3; if (RLE_ColVisible(lOutCol)) jWorking = pjDst[ulWritePos] & ajBits[lOutCol & 7]; else if (RLE_PastRightEdge(lOutCol)) jWorking = pjDst[ulRightWritePos]; else jWorking = pjDst[ulLeftWritePos] & jLeftMask; break; default: /* Absolute Mode. * The run length is stored in <ulNext>, <ulCount> is used to * hold left and right clip amounts. */ // Outta here if the bytes aren't in the source if (RLE_SourceExhausted(RLE4_ByteLength(ulNext))) return(FALSE); RLE4_AlignToWord(pjSrc, ulNext); if (RLE_InVisibleRect(ulNext, lOutCol)) { // Left side clipping if (lOutCol < (LONG)ulDstLeft) { ulCount = ulDstLeft - lOutCol; ulNext -= ulCount; lOutCol += ulCount; ulWritePos = lOutCol >> 3; pjSrc += (ulCount >> 1); jBitPos = (BYTE) ColToBitPos(lOutCol); jBitPosMask = ajPosMask[jBitPos]; // Always non-zero. // Force the source to a byte boundary if (bIsOdd(ulCount)) { jSource = (BYTE) pulXlate[GetLowNybble(*pjSrc++)]; if (jSource) jWorking |= jBitPosMask; jBitPosMask >>= 1; lOutCol++; ulNext--; } } else { jBitPos = (BYTE) ColToBitPos(lOutCol); jBitPosMask = ajPosMask[jBitPos]; // Always non-zero. } // Right side clipping if ((lOutCol + (LONG) ulNext) > (LONG)ulDstRight) { ulCount = (lOutCol + ulNext) - ulDstRight; ulNext -= ulCount; } else ulCount = 0; // Run Initialization bExtraByte = (BOOL) bIsOdd(ulNext); lOutCol += ulNext; // Slap the bits on. -- this is the funky-doodle stuff. i = 0; // Source read toggle. do { // Fill the working byte while(jBitPosMask && ulNext) { if (!i) { jSource = *pjSrc++; RLE4_MakeColourBlock(jSource, ajColours, BYTE, pulXlate); } if (ajColours[i]) jWorking |= jBitPosMask; jBitPosMask >>= 1; ulNext--; i ^= 1; } // Write it if (!(jBitPosMask)) { pjDst[ulWritePos] = jWorking; ulWritePos++; jBitPosMask = 0x80; jWorking = 0; } } while (ulNext); // Adjust for the right side clipping. pjSrc += bExtraByte ? (ulCount >> 1) : ((ulCount + 1) >> 1); lOutCol += ulCount; } else { /* Not on a visible scanline. * Adjust our x output position and source pointer. */ lOutCol += ulNext; pjSrc += ((ulNext + 1) >> 1); } /* if */ // Fix up if this run was not WORD aligned. RLE4_FixAlignment(pjSrc); } /* switch */ } else { /* Encoded Mode * The run length is stored in <ulCount>, <ulClipMargin> is used * to hold left and right clip amounts. */ if (RLE_InVisibleRect(ulCount, lOutCol)) { // Left side clipping if (lOutCol < (LONG)ulDstLeft) { ulClipMargin = ulDstLeft - lOutCol; ulCount -= ulClipMargin; lOutCol += ulClipMargin; ulWritePos = lOutCol >> 3; } // Right side clipping if ((lOutCol + (LONG) ulCount) > (LONG)ulDstRight) { ulClipMargin = (lOutCol + ulCount) - ulDstRight; ulCount -= ulClipMargin; } else ulClipMargin = 0; // Initialize for the run RLE4_MakeColourBlock(ulNext, ajColours, BYTE, pulXlate); jSource = ajBitPatterns[2*ajColours[0] + ajColours[1]]; // jSource |= ((jSource << 2) | // (jSource << 4) | // (jSource << 6)); jBitPos = (BYTE) ColToBitPos(lOutCol); jBitPosMask = ajPosMask[jBitPos]; ulCompBytes = (ulCount < (ULONG)jBitPos + 1) ? 0 : ((BYTE)ulCount - jBitPos - 1) >> 3; lOutCol += ulCount; ulCount -= (ulCompBytes << 3); // Deal with a partial byte on the left if (jBitPos >= (LONG) ulCount) { // Will not fill the working byte jSource &= ajBits[ulCount]; jWorking |= (BYTE)(jSource >> (7-jBitPos)); jBitPos -= (BYTE)ulCount; ulCount = 0; } else { // Will fill the working byte jWorking |= (jSource & ajBits[jBitPos + 1]) >> (7-jBitPos); pjDst[ulWritePos] = jWorking; if (!bIsOdd(jBitPos)) jSource = RollLeft(jSource); ulWritePos++; jWorking = 0; ulCount -= (jBitPos + 1); jBitPos = 7; } // Deal with complete byte output if (ulCompBytes) { for (i = 0; i < ulCompBytes; i++) pjDst[ulWritePos + i] = jSource; ulWritePos += ulCompBytes; jBitPos = 7; jWorking = 0; } // Deal with the right side partial byte if (ulCount) jWorking |= (ajBits[ulCount] & jSource); // Adjust for the right side clipping. lOutCol += ulClipMargin; } else { /* Not on a visible scanline. * Adjust our x output position and source pointer. */ lOutCol += ulCount; } /* if */ } /* if */ } /* LOOP_FOREVER */ } /* bSrcCopySRLE4D1 */ /******************************Public*Routine***************************** ** bSrcCopySRLE4D4 * * Secure RLE blting to a 4 BPP DIB that does clipping and won't die or * write somewhere it shouldn't if given bad data. * * History: * 5 Feb 1992 - Andrew Milton (w-andym): * Added clip support. * * 24 Jan 1992 - Andrew Milton (w-andym): Creation. * \**************************************************************************/ /* NOTE: In the Escape Modes, the current working byte must be * written to destination before the escape is executed. * To this end, the below macro... */ #define RLE4to4_WritePartial(DstPtr, OutByte, OutColumn, WritePos) \ if (RLE_RowVisible) \ { \ if (RLE_ColVisible(OutColumn) && bIsOdd(OutColumn)) \ { \ SetLowNybble(OutByte, DstPtr[WritePos]); \ DstPtr[WritePos] = OutByte; \ } \ else \ { \ if (bRightPartial && RLE_PastRightEdge(OutColumn)) \ { \ SetLowNybble(OutByte, DstPtr[ulRightWritePos]); \ DstPtr[ulRightWritePos] = OutByte; \ } \ } \ } \ BOOL bSrcCopySRLE4D4( PBLTINFO psb) { // Common RLE Initialization RLE_InitVars(psb, pjSrc, pjDst, PBYTE, ulCount, ulNext, lOutCol, pulXlate); RLE_AssertValid(psb); RLE_FetchVisibleRect(psb); RLE_SetStartPos(psb, lOutCol); // Outta here if we start past the top edge. Don't need to save our position. if (RLE_PastTopEdge) return(TRUE); // Must have bits left in the bitmap since we haven't // consumed any. // Extra Variables BOOL bRightPartial; // TRUE when a visible row ends in a partial byte BYTE jWorking; // Hold area to build a byte for output ULONG ulWritePos; // Write position off <pjDst> into the destination ULONG ulLeftWritePos; // Leftmost write position ULONG ulRightWritePos; // Rightmost write position BYTE jSource; // Packed RLE 4 colour code BYTE ajColours[2]; // Destination for unpacking an RLE 4 code // Our Initialization ulLeftWritePos = ulDstLeft >> 1; ulRightWritePos = ulDstRight >> 1; bRightPartial = (BOOL) bIsOdd(ulDstRight); // Fetch our inital working byte ulWritePos = lOutCol >> 1; if (RLE_RowVisible) jWorking = pjDst[BoundsCheck(ulLeftWritePos, ulRightWritePos, ulWritePos)]; // Main processing loop LOOP_FOREVER { ulWritePos = lOutCol >> 1; // Outta here if we can't get two more bytes if (RLE_SourceExhausted(2)) return(FALSE); RLE_GetNextCode(pjSrc, ulCount, ulNext); if (ulCount == 0) { // Absolute or Escape Mode. switch (ulNext) { case 0: // New Line RLE4to4_WritePartial(pjDst, jWorking, lOutCol, ulWritePos); RLE_NextLine(PBYTE, pjDst, lOutCol); if (RLE_PastTopEdge) { RLE_SavePosition(psb, pjSrc, pjDst, lOutCol); return(TRUE); } if (RLE_RowVisible) jWorking = pjDst[ulLeftWritePos]; break; case 1: // End of bitmap RLE4to4_WritePartial(pjDst, jWorking, lOutCol, ulWritePos); return(FALSE); case 2: // Positional Delta RLE4to4_WritePartial(pjDst, jWorking, lOutCol, ulWritePos); // Outta here if we can't get the delta values if (RLE_SourceExhausted(2)) return(FALSE); RLE_GetNextCode(pjSrc, ulCount, ulNext); RLE_PosDelta(pjDst, lOutCol, ulCount, ulNext); if (RLE_PastTopEdge) { RLE_SavePosition(psb, pjSrc, pjDst, lOutCol); return(TRUE); } // Read initial working byte ulWritePos = lOutCol >> 1; jWorking = pjDst[BoundsCheck(ulLeftWritePos, ulRightWritePos, ulWritePos)]; break; default: // Absolute Mode // Outta here if the bytes aren't in the source if (RLE_SourceExhausted(RLE4_ByteLength(ulNext))) return(FALSE); RLE4_AlignToWord(pjSrc, ulNext); if (RLE_InVisibleRect(ulNext, lOutCol)) { // Left Side Clipping. Lots 'o stuff happenin' if (lOutCol < (LONG)ulDstLeft) { ulCount = ulDstLeft - lOutCol; lOutCol = ulDstLeft; ulWritePos = ulDstLeft >> 1; ulNext -= ulCount; pjSrc += (ulCount >> 1); // Align the source run to a byte boundary if (bIsOdd(ulCount)) { jSource = (BYTE) pulXlate[GetLowNybble(*pjSrc++)]; if (bIsOdd(lOutCol)) { SetLowNybble(jWorking, jSource); pjDst[ulWritePos] = jWorking; ulWritePos++; } else SetHighNybble(jWorking, jSource); lOutCol++; ulNext--; // Deal with the special case only one byte is visible if (!ulNext) { RLE4_FixAlignment(pjSrc); continue; } } } // Right Side Clipping if ((lOutCol + (LONG) ulNext) > (LONG)ulDstRight) { ulCount = (lOutCol + ulNext) - ulDstRight; ulNext = ulDstRight - lOutCol; } else ulCount = 0; // Write the Run ASSERTGDI(lOutCol < (LONG) ulDstRight, "No longer visible\n"); if (ulNext != 0) { if (bIsOdd(lOutCol)) { // Case 1: Source & Dest misaligned w.r.t. bytes lOutCol += ulNext; jSource = *pjSrc++; RLE4_MakeColourBlock(jSource, ajColours, BYTE, pulXlate); SetLowNybble(jWorking, ajColours[0]); pjDst[ulWritePos] = jWorking; ulWritePos++; ulNext--; ulNext >>= 1; while (ulNext) { SetHighNybble(jWorking, ajColours[1]); jSource = *pjSrc++; RLE4_MakeColourBlock(jSource, ajColours, BYTE, pulXlate); SetLowNybble(jWorking, ajColours[0]); pjDst[ulWritePos] = jWorking; ulWritePos++; ulNext--; } /* while */ /* Account for the right side partial byte * and do the right clip adjustment on the source */ if (bIsOdd(lOutCol)) { SetHighNybble(jWorking, ajColours[1]); pjSrc += ((ulCount + 1) >> 1); } else { pjSrc += (ulCount >> 1); } } else { // Case 2: Source & Dest aligned on byte boundaries lOutCol += ulNext; ulNext >>= 1; while (ulNext) { jSource = *pjSrc++; RLE4_MakeColourBlock(jSource, ajColours, BYTE, pulXlate); jWorking = BuildByte(ajColours[0], ajColours[1]); pjDst[ulWritePos] = jWorking; ulWritePos++; ulNext--; } /* while */ /* Account for the right side partial byte * and do the right clip adjustment on the source */ if (bIsOdd(lOutCol)) { jSource = GetHighNybble(*pjSrc++); SetHighNybble(jWorking, (BYTE)pulXlate[(ULONG)jSource]); pjSrc += (ulCount >> 1); } else { pjSrc += ((ulCount + 1) >> 1); } } } else { /* Do the right clip adjustment on the source */ pjSrc += ((ulCount + 1) >> 1); } lOutCol += ulCount; } else { /* Not on a visible scanline. * Adjust our x output position and source pointer. */ lOutCol += ulNext; pjSrc += ((ulNext + 1) >> 1); } /* if */ // Fix up if this run was not WORD aligned. RLE4_FixAlignment(pjSrc); } /* switch */ } else { // Encoded Mode if (RLE_InVisibleRect(ulCount, lOutCol)) { ULONG ulClipMargin = 0; // Left side clipping if (lOutCol < (LONG)ulDstLeft) { ulClipMargin = ulDstLeft - lOutCol; lOutCol = ulDstLeft; ulWritePos = ulDstLeft >> 1; ulCount -= ulClipMargin; } // Right side clipping if ((lOutCol + (LONG) ulCount) > (LONG)ulDstRight) { ulClipMargin = (lOutCol + ulCount) - ulDstRight; ulCount = ulDstRight - lOutCol; } else ulClipMargin = 0; RLE4_MakeColourBlock(ulNext, ajColours, BYTE, pulXlate); // Align the destination to a byte boundary if (bIsOdd(lOutCol)) { SetLowNybble(jWorking, ajColours[0]); pjDst[ulWritePos] = jWorking; ulWritePos++; lOutCol++; ulCount--; SwapValues(ajColours[0], ajColours[1]); } lOutCol += ulCount; // Run initialization ulCount >>= 1; jWorking = BuildByte(ajColours[0], ajColours[1]); // Write complete bytes while(ulCount) { pjDst[ulWritePos] = jWorking; ulWritePos++; ulCount--; } // Account for writing a partial byte on the right side if (bIsOdd(lOutCol)) SetHighNybble(jWorking, ajColours[0]); // Adjust for the right side clipping. lOutCol += ulClipMargin; } else { // Not on a visible scanline. Adjust our x output position lOutCol += ulCount; } /* if */ } /* if */ } /* LOOP_FOREVER */ } /* bSrcCopySRLE4D4 */ /******************************Public*Routine******************************\ * bSrcCopySRLE4D16 * * Secure RLE blting to a 16 BPP DIB that does clipping and won't die or * write somewhere it shouldn't if given bad data. * * History: * 28 Feb 1992 - Andrew Milton (w-andym): Creation. * \**************************************************************************/ BOOL bSrcCopySRLE4D16( PBLTINFO psb) { // Common RLE Initialization RLE_InitVars(psb, pjSrc, pwDst, PWORD, ulCount, ulNext, lOutCol, pulXlate); RLE_AssertValid(psb); RLE_FetchVisibleRect(psb); RLE_SetStartPos(psb, lOutCol); // Outta here if we start past the top edge. Don't need to save our position. if (RLE_PastTopEdge) return(TRUE); // Must have bits left in the bitmap since we haven't // consumed any. // Extra Variables BYTE jSource; // Packed RLE 4 colour code WORD awColours[2]; // Destination for unpacking an RLE 4 code BOOL bExtraByte; // TRUE when an absolute run ends with a partial byte // Main process loop LOOP_FOREVER { // Outta here if we can't get two more bytes if (RLE_SourceExhausted(2)) return(FALSE); RLE_GetNextCode(pjSrc, ulCount, ulNext); if (ulCount == 0) { // Absolute or Escape Mode switch (ulNext) { case 0: // New Line RLE_NextLine(PWORD, pwDst, lOutCol); if (RLE_PastTopEdge) { RLE_SavePosition(psb, pjSrc, pwDst, lOutCol); return(TRUE); } break; case 1: // End of the Bitmap. return(FALSE); case 2: /* Positional Delta. * The delta values live in the next two source bytes */ // Outta here if we can't get the delta values if (RLE_SourceExhausted(2)) return(FALSE); RLE_GetNextCode(pjSrc, ulCount, ulNext); RLE_PosDelta(pwDst, lOutCol, ulCount, ulNext); if (RLE_PastTopEdge) { RLE_SavePosition(psb, pjSrc, pwDst, lOutCol); return(TRUE); } break; default: /* Absolute Mode. * The run length is stored in <ulNext>, <ulCount> is used to * hold left and right clip amounts. */ // Outta here if the bytes aren't in the source if (RLE_SourceExhausted(RLE4_ByteLength(ulNext))) return(FALSE); RLE4_AlignToWord(pjSrc, ulNext); if (RLE_InVisibleRect(ulNext, lOutCol)) { // Left side clipping if (lOutCol < (LONG)ulDstLeft) { ulCount = ulDstLeft - lOutCol; lOutCol = ulDstLeft; ulNext -= ulCount; pjSrc += (ulCount >> 1); // Align the source run to a byte boundary if (bIsOdd(ulCount)) { jSource = (BYTE) *pjSrc++; pwDst[lOutCol] = (WORD) pulXlate[GetLowNybble(jSource)]; lOutCol++; ulNext--; } } // Right side clipping if ((lOutCol + (LONG) ulNext) > (LONG)ulDstRight) { ulCount = (lOutCol + ulNext) - ulDstRight; ulNext -= ulCount; } else ulCount = 0; // Slap the bits on. -- this is the funky-doodle stuff. bExtraByte = (BOOL) bIsOdd(ulNext); ulNext >>= 1; // Deal with complete source bytes while (ulNext) { jSource = *pjSrc++; RLE4_MakeColourBlock(jSource, awColours, WORD, pulXlate); pwDst[lOutCol] = awColours[0]; pwDst[lOutCol+1] = awColours[1]; lOutCol += 2; ulNext--; } // Account for right partial byte in the source */ if (bExtraByte) { jSource = *pjSrc++; RLE4_MakeColourBlock(jSource, awColours, WORD, pulXlate); pwDst[lOutCol] = awColours[0]; lOutCol++; pjSrc += (ulCount >> 1); // Clip Adjustment } else pjSrc += ((ulCount + 1) >> 1); // Clip Adjustment // Adjust the column for the right side clipping. lOutCol += ulCount; } else { /* Not on a visible scanline. * Adjust our x output position and source pointer. */ lOutCol += ulNext; pjSrc += (ulNext + 1) >> 1; } /* if */ // Fix up if this run was not WORD aligned. RLE4_FixAlignment(pjSrc) } /* switch */ } else { /* Encoded Mode * The run length is stored in <ulCount>, <ulClipMargin> is used * to hold left and right clip amounts. */ if (RLE_InVisibleRect(ulCount, lOutCol)) { ULONG ulClipMargin = 0; // Left side clipping if (lOutCol < (LONG)ulDstLeft) { ulClipMargin = ulDstLeft - lOutCol; lOutCol = ulDstLeft; ulCount -= ulClipMargin; } // Right side clipping if ((lOutCol + (LONG) ulCount) > (LONG)ulDstRight) { ulClipMargin = (lOutCol + ulCount) - ulDstRight; ulCount -= ulClipMargin; } else ulClipMargin = 0; // Run initialization bExtraByte = (BOOL) bIsOdd(ulCount); ulCount >>= 1; RLE4_MakeColourBlock(ulNext, awColours, WORD, pulXlate); // Write the run while (ulCount) { pwDst[lOutCol] = awColours[0]; pwDst[lOutCol+1] = awColours[1]; lOutCol += 2; ulCount --; } // ... and an extra byte for an odd run length if (bExtraByte) { pwDst[lOutCol] = awColours[0]; lOutCol++; } // Adjust for the right side clipping. lOutCol += ulClipMargin; } else { /* Not on a visible scanline. * Adjust our x output position */ lOutCol += ulCount; } /* if */ } /* if */ } /* LOOP_FOREVER */ } /* bSrcCopySRLE4D16 */ /******************************Public*Routine***************************** ** bSrcCopySRLE4D24 * * Secure RLE blting to a 24 BPP DIB that does clipping and won't die or * write somewhere it shouldn't if given bad data. * * History: * 28 Feb 1992 - Andrew Milton (w-andym): Creation. * \**************************************************************************/ #define RLE_24BitWrite(DstPtr, BytePos, Colour) \ DstPtr[BytePos] = (BYTE)Colour; \ DstPtr[BytePos+1] = (BYTE)(Colour >> 8); \ DstPtr[BytePos+2] = (BYTE)(Colour >> 16); \ BytePos += 3; \ BOOL bSrcCopySRLE4D24( PBLTINFO psb) { // Common RLE Initialization RLE_InitVars(psb, pjSrc, pjDst, PBYTE, ulCount, ulNext, lOutCol, pulXlate); RLE_AssertValid(psb); RLE_FetchVisibleRect(psb); RLE_SetStartPos(psb, lOutCol); // Outta here if we start past the top edge. Don't need to save our position. if (RLE_PastTopEdge) return(TRUE); // Must have bits left in the bitmap since we haven't // consumed any. // Extra Variables ULONG ulWritePos; // Write position off <pjDst> into the destination BYTE jSource; // Packed RLE 4 colour code DWORD adwColours[2]; // Destination for unpacking an RLE 4 code BOOL bExtraByte; // TRUE when an absolute run ends with a partial byte ULONG ulClipMargin; // Number of bytes clipped off an Encoded run // Main process loop LOOP_FOREVER { // Outta here if we can't get two more bytes if (RLE_SourceExhausted(2)) return(FALSE); RLE_GetNextCode(pjSrc, ulCount, ulNext); if (ulCount == 0) { // Absolute or Escape Mode switch (ulNext) { case 0: // New line RLE_NextLine(PBYTE, pjDst, lOutCol); if (RLE_PastTopEdge) { RLE_SavePosition(psb, pjSrc, pjDst, lOutCol); return(TRUE); } break; case 1: // End of the Bitmap return(FALSE); case 2: /* Positional Delta. * The delta values live in the next two source bytes */ // Outta here if we can't get two more bytes if (RLE_SourceExhausted(2)) return(FALSE); RLE_GetNextCode(pjSrc, ulCount, ulNext); RLE_PosDelta(pjDst, lOutCol, ulCount, ulNext); if (RLE_PastTopEdge) { RLE_SavePosition(psb, pjSrc, pjDst, lOutCol); return(TRUE); } break; default: /* Absolute Mode. * The run length is stored in <ulNext>, <ulCount> is used to * hold left and right clip amounts. */ // Outta here if the bytes aren't in the source if (RLE_SourceExhausted(RLE4_ByteLength(ulNext))) return(FALSE); RLE4_AlignToWord(pjSrc, ulNext); if (RLE_InVisibleRect(ulNext, lOutCol)) { // Left side clipping if (lOutCol < (LONG)ulDstLeft) { ulCount = ulDstLeft - lOutCol; lOutCol = ulDstLeft; ulNext -= ulCount; ulWritePos = 3*lOutCol; pjSrc += (ulCount >> 1); // Align the Source run to a byte boundary if (bIsOdd(ulCount)) { adwColours[0] = pulXlate[GetLowNybble(*pjSrc++)]; RLE_24BitWrite(pjDst, ulWritePos, adwColours[0]); lOutCol++; ulNext--; } } else ulWritePos = 3*lOutCol; // Right side clipping if ((lOutCol + (LONG) ulNext) > (LONG)ulDstRight) { ulCount = (lOutCol + ulNext) - ulDstRight; ulNext -= ulCount; } else ulCount = 0; // Run Initialization. bExtraByte = (BOOL) bIsOdd(ulNext); lOutCol += ulNext; ulNext >>= 1; // Write complete bytes from the source while (ulNext) { jSource = *pjSrc++; RLE4_MakeColourBlock(jSource, adwColours, DWORD, pulXlate); RLE_24BitWrite(pjDst, ulWritePos, adwColours[0]); RLE_24BitWrite(pjDst, ulWritePos, adwColours[1]); ulNext--; } // Account for a right partial byte in the source if (bExtraByte) { adwColours[0] = pulXlate[GetHighNybble(*pjSrc++)]; RLE_24BitWrite(pjDst, ulWritePos, adwColours[0]); pjSrc += (ulCount >> 1); // Clip Adjustment } else pjSrc += ((ulCount + 1) >> 1); // Clip Adjustment // Adjust the column for the right side clipping. lOutCol += ulCount; } else { /* Not on a visible scanline. * Adjust our x output position and source pointer. */ lOutCol += ulNext; pjSrc += (ulNext + 1) >> 1; } /* if */ // Fix up if this run was not WORD aligned. RLE4_FixAlignment(pjSrc) } /* switch */ } else { /* Encoded Mode * The run length is stored in <ulCount>, <ulClipMargin> is used * to hold left and right clip amounts. */ if (RLE_InVisibleRect(ulCount, lOutCol)) { // Left side clipping if (lOutCol < (LONG)ulDstLeft) { ulClipMargin = ulDstLeft - lOutCol; lOutCol = ulDstLeft; ulCount -= ulClipMargin; } // Right side clipping if ((lOutCol + (LONG) ulCount) > (LONG)ulDstRight) { ulClipMargin = (lOutCol + ulCount) - ulDstRight; ulCount -= ulClipMargin; } else ulClipMargin = 0; // Run initialization ulWritePos = 3*lOutCol; lOutCol += ulCount; bExtraByte = (BOOL) bIsOdd(ulCount); ulCount >>= 1; RLE4_MakeColourBlock(ulNext, adwColours, DWORD, pulXlate); // Write the run while (ulCount) { RLE_24BitWrite(pjDst, ulWritePos, adwColours[0]); RLE_24BitWrite(pjDst, ulWritePos, adwColours[1]); ulCount --; } // Write the extra byte from an odd run length if (bExtraByte) { RLE_24BitWrite(pjDst, ulWritePos, adwColours[0]); } // Adjust for the right side clipping. lOutCol += ulClipMargin; } else { /* Not on a visible scanline. * Adjust our x output position */ lOutCol += ulCount; } /* if */ } /* if */ } /* LOOP_FOREVER */ } /* bSrcCopySRLE4D24 */ /******************************Public*Routine***************************** ** bSrcCopySRLE4D32 * * Secure RLE blting to a 32 BPP DIB that does clipping and won't die or * write somewhere it shouldn't if given bad data. * * History: * 28 Feb 1992 - Andrew Milton (w-andym): Creation. * \**************************************************************************/ BOOL bSrcCopySRLE4D32( PBLTINFO psb) { // Common RLE Initialization RLE_InitVars(psb, pjSrc, pdwDst, PDWORD, ulCount, ulNext, lOutCol, pulXlate); RLE_AssertValid(psb); RLE_FetchVisibleRect(psb); RLE_SetStartPos(psb, lOutCol); // Outta here if we start past the top edge. Don't need to save our position. if (RLE_PastTopEdge) return(TRUE); // Must have bits left in the bitmap since we haven't // consumed any. // Extra Variables BYTE jSource; // Packed RLE 4 colour code DWORD adwColours[2]; // Destination for unpacking an RLE 4 code BOOL bExtraByte; // TRUE when an absolute run ends with a partial byte ULONG ulClipMargin; // Number of bytes clipped off an Encoded run // Main processing loop LOOP_FOREVER { // Outta here if we can't get two more bytes if (RLE_SourceExhausted(2)) return(FALSE); RLE_GetNextCode(pjSrc, ulCount, ulNext); if (ulCount == 0) { // Absolute or Escape Mode switch (ulNext) { case 0: // New line RLE_NextLine(PDWORD, pdwDst, lOutCol); if (RLE_PastTopEdge) { RLE_SavePosition(psb, pjSrc, pdwDst, lOutCol); return(TRUE); } break; case 1: // End of the Bitmap return(FALSE); case 2: /* Positional Delta. * The delta values live in the next two source bytes */ // Outta here if we can't get two more bytes if (RLE_SourceExhausted(2)) return(FALSE); RLE_GetNextCode(pjSrc, ulCount, ulNext); RLE_PosDelta(pdwDst, lOutCol, ulCount, ulNext); if (RLE_PastTopEdge) { RLE_SavePosition(psb, pjSrc, pdwDst, lOutCol); return(TRUE); } break; default: // Absolute Mode // Outta here if the bytes aren't in the source if (RLE_SourceExhausted(RLE4_ByteLength(ulNext))) return(FALSE); RLE4_AlignToWord(pjSrc, ulNext); if (RLE_InVisibleRect(ulNext, lOutCol)) { // Left side clipping if (lOutCol < (LONG)ulDstLeft) { ulCount = ulDstLeft - lOutCol; lOutCol = ulDstLeft; ulNext -= ulCount; pjSrc += (ulCount >> 1); // Align the source run to a byte boundary if (bIsOdd(ulCount)) { jSource = (BYTE) *pjSrc++; pdwDst[lOutCol] = (DWORD) pulXlate[GetLowNybble(jSource)]; lOutCol++; ulNext--; } } // Right side clipping if ((lOutCol + (LONG) ulNext) > (LONG)ulDstRight) { ulCount = (lOutCol + ulNext) - ulDstRight; ulNext -= ulCount; } else ulCount = 0; // Slap the bits on. -- this is the funky-doodle stuff. bExtraByte = (BOOL) bIsOdd(ulNext); ulNext >>= 1; // Write complete bytes from the source while (ulNext) { jSource = *pjSrc++; RLE4_MakeColourBlock(jSource, adwColours, DWORD, pulXlate); pdwDst[lOutCol] = adwColours[0]; pdwDst[lOutCol+1] = adwColours[1]; lOutCol += 2; ulNext--; } // Account for a right partial byte in the source if (bExtraByte) { jSource = *pjSrc++; RLE4_MakeColourBlock(jSource, adwColours, DWORD, pulXlate); pdwDst[lOutCol] = adwColours[0]; lOutCol++; pjSrc += (ulCount >> 1); // Clip Adjustment } else pjSrc += ((ulCount + 1) >> 1); // Clip Adjustment // Adjust the column for the right side clipping. lOutCol += ulCount; } else { /* Not on a visible scanline. * Adjust our x output position and source pointer. */ lOutCol += ulNext; pjSrc += (ulNext + 1) >> 1; } /* if */ // Fix up if this run was not WORD aligned. RLE4_FixAlignment(pjSrc); } /* switch */ } else { /* Encoded Mode * The run length is stored in <ulCount>, <ulClipMargin> is used * to hold left and right clip amounts. */ if (RLE_InVisibleRect(ulCount, lOutCol)) { // Left side clipping if (lOutCol < (LONG)ulDstLeft) { ulClipMargin = ulDstLeft - lOutCol; lOutCol = ulDstLeft; ulCount -= ulClipMargin; } // Right side clipping if ((lOutCol + (LONG) ulCount) > (LONG)ulDstRight) { ulClipMargin = (lOutCol + ulCount) - ulDstRight; ulCount -= ulClipMargin; } else ulClipMargin = 0; // Run Initialization. bExtraByte = (BOOL) bIsOdd(ulCount); ulCount >>= 1; RLE4_MakeColourBlock(ulNext, adwColours, DWORD, pulXlate); // Write the run while (ulCount) { pdwDst[lOutCol] = adwColours[0]; pdwDst[lOutCol+1] = adwColours[1]; lOutCol += 2; ulCount --; } // Write the extra byte from an odd run length if (bExtraByte) { pdwDst[lOutCol] = adwColours[0]; lOutCol++; } // Adjust for the right side clipping. lOutCol += ulClipMargin; } else { /* Not on a visible scanline. * Adjust our x output position */ lOutCol += ulCount; } /* if */ } /* if */ } /* LOOP_FOREVER */ } /* bSrcCopySRLE4D32 */ /*******************************Public*Routine*****************************\ * WriteEncoded4 * * A helper function for EncodeRLE4. Writes a run of bytes in encoded format. * * Created: 28 Oct 92 @ 14:00 * * Author: Gerrit van Wingerden [gerritv] * \**************************************************************************/ int WriteEncoded4( BYTE bValue, BYTE *pbTarget, UINT uiLength, BYTE *pbEndOfBuffer ) { if( pbTarget == NULL ) return(2); if( pbTarget + 2 > pbEndOfBuffer ) return(0); *pbTarget++ = (BYTE) uiLength; *pbTarget++ = bValue; return(2); } /*******************************Public*Routine*****************************\ * WriteAbsolute4 * * A helper function for EncodeRLE4. Writes a run of bytes in absolute format. * * Created: 28 Oct 92 @ 14:00 * * Author: Gerrit van Wingerden [gerritv] * \**************************************************************************/ int WriteAbsolute4( BYTE *pbRunStart, BYTE *pbTarget, int cRunLength, BYTE *pbEndOfBuffer ) { int iRet; if( cRunLength < 3 ) { iRet = 2; } else { if( ( cRunLength + 1 ) & 0x02 ) { iRet = (( cRunLength + 1 ) >> 1) + 3; } else { iRet = (( cRunLength + 1 ) >> 1) + 2; } } if( pbTarget == NULL ) return(iRet); if( pbTarget + iRet > pbEndOfBuffer ) return(0); if( cRunLength < 3 ) { *pbTarget++ = (BYTE) cRunLength; *pbTarget = *pbRunStart; return(2); } *pbTarget++ = 0; *pbTarget++ = (BYTE) cRunLength; RtlMoveMemory( pbTarget, pbRunStart, ( cRunLength + 1 ) >> 1 ); pbTarget += ( cRunLength + 1 ) >> 1; if( ( cRunLength + 1 ) & 0x02 ) { *pbTarget++ = 0; return( iRet ); } else return( iRet ); } /*******************************Public*Routine*****************************\ * EncodeRLE4 * * Encodes a bitmap into RLE4 format and returns the length of the of the * encoded format. If the source is NULL it just returns the length of * the format. If the encoded output turns out to be longer than cBufferSize * the functions stops encoding. * * History: * 28 Oct 1992 Gerrit van Wingerden [gerritv] : creation * 15 Mar 1993 Stephan J. Zachwieja [szach] : return 0 if buffer too small * \**************************************************************************/ int EncodeRLE4( BYTE *pbSource, BYTE *pbTarget, UINT uiWidth, UINT cNumLines, UINT cBufferSize ) { UINT cLineCount, uiLineWidth; BYTE bLastByte,bCurChar; BYTE *pbRunStart; BYTE *pbLineEnd; BYTE *pbEndOfBuffer; BYTE *pbCurPos; INT cCurrentRunLength; INT iMode, cTemp; UINT cTotal = 0; pbEndOfBuffer = pbTarget + cBufferSize; // Compute width of line in bytes rounded to a DWORD boundary uiLineWidth = ( ( uiWidth + 7 ) >> 3 ) << 2 ; for( cLineCount = 0; cLineCount < cNumLines; cLineCount ++ ) { pbRunStart = pbSource + uiLineWidth * cLineCount; bLastByte = *pbRunStart; pbLineEnd = pbRunStart + ( ( uiWidth + 1 ) >> 1 ); iMode = RLE_START; cCurrentRunLength = 2; for(pbCurPos = pbRunStart+1;pbCurPos <= pbLineEnd; pbCurPos += 1) { // We won't really encode the value at *pbLineEnd since it points // past the end of the scan so it doesn't matter what value we use. // However, it is important not to reference it since it may point // past the end of the buffer which can be uncommited memory. if( pbCurPos == pbLineEnd ) { bCurChar = 0xFF; } else { bCurChar = *pbCurPos; } switch( iMode ) { case RLE_START: iMode = ( bCurChar == bLastByte ) ? RLE_ENCODED : RLE_ABSOLUTE; bLastByte = bCurChar; break; case RLE_ABSOLUTE: // There are two ways that this run could be over. We could have exceeded the // maximum length 0xFE ( since this algorithm works with bytes ), or there // could be a switch into absolute mode. if( ( bCurChar == bLastByte ) || ( cCurrentRunLength == 0xFE ) ) { int iOffset; if( cCurrentRunLength == 0xFE ) { // If this is the end of the line and there is and odd line length, ignore the // last nibble of the the final byte. if( (pbCurPos == pbLineEnd ) && ( uiWidth & 0x01 )) iOffset = 1; else iOffset = 0; iMode = RLE_START; } else { iOffset = 2; iMode = RLE_ENCODED; } cTemp = WriteAbsolute4(pbRunStart, pbTarget, cCurrentRunLength - iOffset, pbEndOfBuffer); // if pbTarget is not NULL and cTemp is zero then // the buffer is too small to hold encoded data if(pbTarget != NULL) { if (cTemp == 0) return(0); pbTarget += cTemp; } cTotal += cTemp; pbRunStart = pbCurPos; cCurrentRunLength = iOffset; } bLastByte = bCurChar; break; case RLE_ENCODED: if( ( bCurChar != bLastByte ) || ( cCurrentRunLength == 0xFE ) ) { // Don't include last nibble if the width of the scan line is odd and this // this is the last byte. if( (pbCurPos == pbLineEnd ) && ( uiWidth & 0x01 )) cCurrentRunLength -= 1; cTemp = WriteEncoded4(bLastByte, pbTarget, cCurrentRunLength, pbEndOfBuffer); // if pbTarget is not NULL and cTemp is zero then // the buffer is too small to hold encoded data if(pbTarget != NULL) { if (cTemp == 0) return(0); pbTarget += cTemp; } cTotal += cTemp; bLastByte = bCurChar; pbRunStart = pbCurPos; cCurrentRunLength = 0; iMode = RLE_START ; } } cCurrentRunLength += 2; } if( cCurrentRunLength > 3 ) { // Don't include last nibble if the width of the scan line is odd and this // this is the last byte. if( uiWidth & 0x01 ) cCurrentRunLength -= 1; // if pbTarget is not NULL and cTemp is zero then // the buffer is too small to hold encoded data if(iMode == RLE_ABSOLUTE) cTemp = WriteAbsolute4(pbRunStart, pbTarget, cCurrentRunLength - 2, pbEndOfBuffer); else { cTemp = WriteEncoded4(bLastByte, pbTarget, cCurrentRunLength - 2, pbEndOfBuffer); } if (pbTarget != NULL) { if (cTemp == 0) return(0); pbTarget += cTemp; } cTotal += cTemp; } if( pbTarget <= pbEndOfBuffer ) cTotal += 2; if( pbTarget != NULL ) { *((WORD *) pbTarget) = 0; pbTarget += 2; } } // Write "End of bitmap" at the end so we're win31 compatible. if( pbTarget == NULL ) return(cTotal + 2); if( pbTarget + 2 > pbEndOfBuffer ) return(0); *pbTarget++ = 0; *pbTarget++ = 1; return(cTotal + 2); }
31.230769
93
0.418747
npocmaka
80a78fa4dec4e5bec73431063b8f66aa778de0c0
5,354
cpp
C++
src/Exciton/PaintingSecrets/PaintingSecretSurface.cpp
Vladimir-Lin/QtExciton
ac5bc82f22ac3cdcdccb90526f7dd79060535b5a
[ "MIT" ]
null
null
null
src/Exciton/PaintingSecrets/PaintingSecretSurface.cpp
Vladimir-Lin/QtExciton
ac5bc82f22ac3cdcdccb90526f7dd79060535b5a
[ "MIT" ]
null
null
null
src/Exciton/PaintingSecrets/PaintingSecretSurface.cpp
Vladimir-Lin/QtExciton
ac5bc82f22ac3cdcdccb90526f7dd79060535b5a
[ "MIT" ]
null
null
null
#include <exciton.h> N::PaintingSecretSurface:: PaintingSecretSurface (QWidget * parent) : QWidget ( parent) , progress (NULL ) , indicator (NULL ) { } N::PaintingSecretSurface::~PaintingSecretSurface (void) { } void N::PaintingSecretSurface::showEvent(QShowEvent * event) { QWidget :: showEvent ( event ) ; relocation ( ) ; } void N::PaintingSecretSurface::resizeEvent (QResizeEvent * event) { QWidget :: resizeEvent ( event ) ; relocation ( ) ; } void N::PaintingSecretSurface::paintEvent(QPaintEvent * event) { Q_UNUSED ( event ) ; QPainter p ( this ) ; p . drawImage ( 0 , 0 , Painting ) ; } QImage N::PaintingSecretSurface::Cut(void) { QImage I ; QImage S ; int x = 0 ; int y = 0 ; int w = 0 ; int h = 0 ; double wf = width ( ) ; double hf = height ( ) ; wf /= Background.width ( ) ; hf /= Background.height ( ) ; if (wf<hf) { y = 0 ; h = Background.height() ; wf = width ( ) ; wf /= height ( ) ; wf *= h ; w = wf ; x = Background.width () ; x -= w ; x /= 2 ; x += Background.width () * 3 / 16 ; if ((x+w)>Background.width()) { x = Background.width() - w ; } ; } else { x = 0 ; w = Background.width () ; hf = height ( ) ; hf /= width ( ) ; hf *= w ; h = hf ; y = Background.height() ; y -= h ; y /= 2 ; } ; S = Background.copy(x,y,w,h) ; I = S.scaled ( size() , Qt::KeepAspectRatio , Qt::SmoothTransformation ) ; return I ; } void N::PaintingSecretSurface::relocation (void) { QColor w = QColor ( 255 , 255 , 255 ) ; QSize s = size ( ) ; /////////////////////////////////////////////////// Mutex . lock ( ) ; Painting = QImage ( s , QImage::Format_ARGB32 ) ; Drawing = QImage ( s , QImage::Format_ARGB32 ) ; Painting . fill ( w ) ; Drawing . fill ( w ) ; /////////////////////////////////////////////////// Painting = Cut ( ) ; /////////////////////////////////////////////////// MoveIndicator ( ) ; Mutex . unlock ( ) ; } void N::PaintingSecretSurface::StartBusy(N::Plan * plan,int total) { if (IsNull(indicator)) { QColor green ( 0 , 255 , 0 ) ; indicator = new ProgressIndicator(this,plan) ; indicator -> setColor ( green ) ; indicator -> setAnimationDelay ( 100 ) ; indicator -> show ( ) ; } ; if (IsNull(progress)) { progress = new QProgressBar ( this ) ; progress -> setTextVisible ( false ) ; progress -> hide ( ) ; progress -> setRange ( 0 , total ) ; } ; MoveIndicator ( ) ; indicator->startAnimation() ; } void N::PaintingSecretSurface::StopBusy(void) { if (IsNull(indicator)) return ; int cnt = indicator->stopAnimation() ; if (cnt<=0) { indicator -> deleteLater ( ) ; indicator = NULL ; } ; if (IsNull(progress)) return ; progress -> deleteLater ( ) ; progress = NULL ; } void N::PaintingSecretSurface::setStep(int index) { if (IsNull(progress)) return ; if (index>0) { progress -> show ( ) ; } ; progress -> setValue ( index ) ; } void N::PaintingSecretSurface::MoveIndicator(void) { if (IsNull(indicator)) return ; int w = width () ; int h = height() ; int x = w / 2 ; int y = h / 2 ; indicator -> move ( x - 20 , y - 20 ) ; indicator -> resize ( 40 , 40 ) ; if (IsNull(progress)) return ; y = h - 12 ; progress -> move ( 0 , y ) ; progress -> resize ( w , 12 ) ; }
35.932886
67
0.341053
Vladimir-Lin
80aaba02c630ecb4f4a1ba82e2af72719c13d5ee
1,243
hpp
C++
src/org/apache/poi/ss/formula/ptg/BoolPtg.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/ss/formula/ptg/BoolPtg.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/ss/formula/ptg/BoolPtg.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /POI/java/org/apache/poi/ss/formula/ptg/BoolPtg.java #pragma once #include <fwd-POI.hpp> #include <java/lang/fwd-POI.hpp> #include <org/apache/poi/ss/formula/ptg/fwd-POI.hpp> #include <org/apache/poi/util/fwd-POI.hpp> #include <org/apache/poi/ss/formula/ptg/ScalarConstantPtg.hpp> struct default_init_tag; class poi::ss::formula::ptg::BoolPtg final : public ScalarConstantPtg { public: typedef ScalarConstantPtg super; static constexpr int32_t SIZE { int32_t(2) }; static constexpr int8_t sid { int8_t(29) }; private: static BoolPtg* FALSE_; static BoolPtg* TRUE_; bool _value { }; protected: void ctor(bool b); public: static BoolPtg* valueOf(bool b); static BoolPtg* read(::poi::util::LittleEndianInput* in); bool getValue(); void write(::poi::util::LittleEndianOutput* out) override; int32_t getSize() override; ::java::lang::String* toFormulaString() override; // Generated private: BoolPtg(bool b); protected: BoolPtg(const ::default_init_tag&); public: static ::java::lang::Class *class_(); static void clinit(); private: static BoolPtg*& FALSE(); static BoolPtg*& TRUE(); virtual ::java::lang::Class* getClass0(); };
23.018519
70
0.687852
pebble2015
80abe069b989bb06b09778fbbd321e50e8fe82ab
349
cpp
C++
RedProgramacionCompetitiva/Actividad 14-2018/M14-2018.cpp
raulcr98/ProgrammingTeamBookScoobyDoo
0fcb98e012e0f2db2dda68cbf01b96f567a12578
[ "MIT" ]
1
2020-03-17T01:44:09.000Z
2020-03-17T01:44:09.000Z
RedProgramacionCompetitiva/Actividad 14-2018/M14-2018.cpp
raulcr98/teambook-scooby-doo
0fcb98e012e0f2db2dda68cbf01b96f567a12578
[ "MIT" ]
null
null
null
RedProgramacionCompetitiva/Actividad 14-2018/M14-2018.cpp
raulcr98/teambook-scooby-doo
0fcb98e012e0f2db2dda68cbf01b96f567a12578
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int N, mx, f, l; bool ok(int a){ while(a > 0){ if(a % 10 == 0) return 0; a /= 10; } return 1; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> N; do{ N++; }while(!ok(N)); cout << N << '\n'; return 0; }
12.464286
33
0.444126
raulcr98
80ad77e44e131e11e30f500e0ef91e5fd717e4b3
26,894
cxx
C++
ds/adsi/winnt/cextmgr.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
ds/adsi/winnt/cextmgr.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
ds/adsi/winnt/cextmgr.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//--------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1992 - 1996 // // File: cextmgr.cxx // // Contents: LDAP ExtMgr Object // // // History: 06-15-96 yihsins Created. // //---------------------------------------------------------------------------- #include "winnt.hxx" #pragma hdrstop // Class CADsExtMgr CADsExtMgr::CADsExtMgr( IUnknown FAR * pUnkOuter ): _pUnkOuter(pUnkOuter), _pClassEntry(NULL), _pDispMgr(NULL), _fExtensionsLoaded(FALSE) { } HRESULT CADsExtMgr::CreateExtMgr( IUnknown FAR * pUnkOuter, CAggregatorDispMgr * pDispMgr, LPTSTR pszClassName, CWinNTCredentials& Credentials, CADsExtMgr ** ppExtMgr ) { PCLASS_ENTRY pClassEntry = NULL; CADsExtMgr FAR * pExtMgr = NULL; HRESULT hr = S_OK; pExtMgr = new CADsExtMgr(pUnkOuter); if (!pExtMgr) RRETURN(E_OUTOFMEMORY); // // Now store the DispatchMgr of the Aggregator // pExtMgr->_pDispMgr = pDispMgr; // // Read the list of extension object of the same class from registry // hr = ADSIGetExtensionList( pszClassName, &(pExtMgr->_pClassEntry) ); BAIL_ON_FAILURE(hr); pExtMgr->_Credentials = Credentials; *ppExtMgr = pExtMgr; RRETURN(hr); error: *ppExtMgr = NULL; delete pExtMgr; RRETURN(hr); } CADsExtMgr::~CADsExtMgr( ) { // // Free the ClassEntry // if (_pClassEntry) { FreeClassEntry(_pClassEntry); } // // And do nothing with the DispMgr - we just keep a pointer // } // // Instantiate extension objects listed in _pClassEntry as aggregates of // aggregator _pUnkOuter. Initialize extensions with <Credentials>. // // Max Load 127 extensions. // HRESULT CADsExtMgr::LoadExtensions( CWinNTCredentials &Credentials ) { HRESULT hr = S_OK; PEXTENSION_ENTRY pExtEntry = NULL; DWORD dwExtensionID = MIN_EXTENSION_ID; IPrivateDispatch * pPrivDisp = NULL; LPWSTR pszUserName = NULL; LPWSTR pszPassword = NULL; DWORD dwAuthFlags = 0; // dummy for winnt VARIANT varUserName; VARIANT varPassword; VARIANT varAuthFlags; PVARIANT pvarUserName = &varUserName; PVARIANT pvarPassword = &varPassword; PVARIANT pvarAuthFlags = &varAuthFlags; BOOL fReturnError = FALSE; // // Extensions (ext mgr) do(es) not exist on its own without an aggregator // ADsAssert(_pUnkOuter); // // If _pClassEntry!=NULL, pClassEntry->pExtensionHead should not // be NULL either. But just in case a user removes all extension entries // under a class key without removing the class key itself in the registry, // we will let it pass and just return S_OK here. // if (!_pClassEntry || !(pExtEntry=_pClassEntry->pExtensionHead) ) { RRETURN(S_OK); } VariantInit(pvarUserName); VariantInit(pvarPassword); VariantInit(pvarAuthFlags); hr = Credentials.GetUserName(&pszUserName); if (FAILED(hr)) { RRETURN(S_OK); } hr = Credentials.GetPassword(&pszPassword); if (FAILED(hr)) { RRETURN(S_OK); } while (pExtEntry) { // // Max # of extension have been loaded, cannot load more // if (dwExtensionID>MAX_EXTENSION_ID) { break; } // // create extension object (aggregatee) and ask for Non-delegating // IUnknown. Ref count on extension object = 1. // hr = CoCreateInstance( pExtEntry->ExtCLSID, _pUnkOuter, CLSCTX_INPROC_SERVER, IID_IUnknown, (void **)&(pExtEntry->pUnknown) ); // // if fail, go to next extesion entry s.t. bad individual extension // cannot block other extensions from loading (no clean up needed) // // no warning to user about failure // if (SUCCEEDED(hr)) { pExtEntry->dwExtensionID = dwExtensionID; hr = (pExtEntry->pUnknown)->QueryInterface( IID_IADsExtension, (void **) &(pExtEntry->pADsExt) ); if (FAILED(hr)) { // // extension does not support the optioanl IADsExtension -> OK. // (no clean up needed) // pExtEntry->pADsExt=NULL; pExtEntry->fDisp = FALSE; } else { // // Cache the interface ptr but call Release() immediately to // avoid aggregator having a ref count on itself // since IADsExtension inherits from delegating IUnknown. // // Note: codes still works if inherit from NonDelegatingIUknown // (pExtEntry->pADsExt)->Release() ; // // For efficiency, set this flag to FALSE on FIRST encounter of // pADsExt->PrivateGetIDsOfNames()/Invoke() returning E_NOTIMPL. // Set as TRUE now s.t. at least first encounter will happen. // pExtEntry->fDisp = TRUE; // // Pass its own credentials to extension. Ignore error if any. // hr = ADsAllocString( pszUserName, &(pvarUserName->bstrVal) ); if (FAILED(hr)) { fReturnError = TRUE; BAIL_ON_FAILURE(hr); } V_VT(pvarUserName) = VT_BSTR; hr = ADsAllocString( pszPassword, &(pvarPassword->bstrVal) ); if (FAILED(hr)) { fReturnError = TRUE; BAIL_ON_FAILURE(hr); } V_VT(pvarPassword) = VT_BSTR; V_I4(pvarAuthFlags) = dwAuthFlags; V_VT(pvarAuthFlags) = VT_I4; hr = (pExtEntry->pADsExt)->Operate( ADS_EXT_INITCREDENTIALS, varUserName, varPassword, varAuthFlags ); // // Zero out the memory that was used to store the password. // if (pvarPassword->bstrVal) { SecureZeroMemory ( pvarPassword->bstrVal, wcslen(pvarPassword->bstrVal) * sizeof(WCHAR) ); } // // Free them as they are reused // VariantClear(pvarUserName); VariantClear(pvarPassword); } } // end if CoCreateInstance() succeeded pExtEntry = pExtEntry->pNext; // // ++ extension ID even if creat'n of extension fails just to be safe // - chuck's stuff :) // dwExtensionID++; } // end while error: if (pszUserName) { FreeADsStr(pszUserName); } if (pszPassword) { // // Zero out the password before freeing so it doesn't remain // visible in memory. // SecureZeroMemory(pszPassword, wcslen(pszPassword) * sizeof(WCHAR)); FreeADsStr(pszPassword); } VariantClear(pvarUserName); VariantClear(pvarPassword); VariantClear(pvarAuthFlags); if (fReturnError) { RRETURN(hr); // fetal error, } else { RRETURN(S_OK); // "okay" error if any, optional support } } HRESULT CADsExtMgr::LoadExtensionsIfReqd(void) { HRESULT hr = S_OK; if(FALSE == _fExtensionsLoaded) { hr = LoadExtensions(_Credentials); BAIL_ON_FAILURE(hr); hr = FinalInitializeExtensions(); // this call never fails BAIL_ON_FAILURE(hr); _fExtensionsLoaded = TRUE; } RRETURN(S_OK); error: RRETURN(hr); } STDMETHODIMP CADsExtMgr::QueryInterface(REFIID iid, LPVOID FAR* ppv) { PCLASS_ENTRY pClassEntry = _pClassEntry; IUnknown * pUnknown = NULL; PINTERFACE_ENTRY pIID = NULL; PEXTENSION_ENTRY pExtensionEntry = NULL; HRESULT hr = S_OK; if (!pClassEntry) { RRETURN(E_NOINTERFACE); } pExtensionEntry = pClassEntry->pExtensionHead; while (pExtensionEntry) { pIID = pExtensionEntry->pIID; while (pIID) { if (IsEqualIID(pIID->iid, iid)) { hr = LoadExtensionsIfReqd(); if(FAILED(hr)) RRETURN(E_NOINTERFACE); pUnknown = pExtensionEntry->pUnknown; if (!pUnknown) { RRETURN(E_NOINTERFACE); } hr = pUnknown->QueryInterface( iid, ppv ); RRETURN(hr); } pIID = pIID->pNext; } pExtensionEntry = pExtensionEntry->pNext; } RRETURN(hr = E_NOINTERFACE); } HRESULT ADSILoadExtensionManager( LPWSTR pszClassName, IUnknown * pUnkOuter, CAggregatorDispMgr * pDispMgr, CWinNTCredentials& Credentials, CADsExtMgr ** ppExtMgr ) { HRESULT hr = S_OK; hr = CADsExtMgr::CreateExtMgr( pUnkOuter, pDispMgr, pszClassName, Credentials, ppExtMgr ); RRETURN(hr); } STDMETHODIMP CADsExtMgr::GetTypeInfoCount( unsigned int FAR* pctinfo ) { RRETURN(E_NOTIMPL); } STDMETHODIMP CADsExtMgr::GetTypeInfo( unsigned int itinfo, LCID lcid, ITypeInfo FAR* FAR* pptinfo ) { RRETURN(E_NOTIMPL); } STDMETHODIMP CADsExtMgr::GetIDsOfNames( REFIID iid, LPWSTR FAR* rgszNames, unsigned int cNames, LCID lcid, DISPID FAR* rgdispid ) { HRESULT hr = S_OK; PEXTENSION_ENTRY pExtension = NULL; IPrivateDispatch FAR * pPrivDisp = NULL; hr = _pDispMgr->GetIDsOfNames( iid, rgszNames, cNames, lcid, rgdispid ); if (FAILED(hr)) { if (!_pClassEntry) { RRETURN(DISP_E_UNKNOWNNAME); } hr = LoadExtensionsIfReqd(); if(FAILED(hr)) RRETURN(DISP_E_UNKNOWNNAME); pExtension = _pClassEntry->pExtensionHead; while (pExtension) { if (pExtension->fDisp) { // // fDisp = TRUE indicates // 1) extension supports pADsExt AND // 2) either // a) PrivateGetIDsOfNames() does Not return E_NOTIMPL // OR // b) we don't know if a) is true or not yet // ADsAssert(pExtension->pADsExt); hr = (pExtension->pADsExt)->PrivateGetIDsOfNames( iid, rgszNames, cNames, lcid, rgdispid ); if (SUCCEEDED(hr)) { // // check & prefix extension id to dispid(s) returned // by extension // hr = CheckAndPrefixExtIDArray( pExtension->dwExtensionID, cNames, rgdispid ); if (SUCCEEDED(hr) ) { RRETURN(hr); } // // if cannot prefix extension id because NOT ALL // dispids returned by PrivateGetIDsOfNames() are // valid, this extension does not support this property // or method -> try next extension // } else if (hr == E_NOTIMPL) { // // extension object does not support the optional // IADsExtension::PrivateGetIDsOfNames()/PrivateInvoke() // -> remember this in cache & try next extension object // pExtension->fDisp = FALSE; } else { // // extens'n object supports PrivateGetIDsOfNames()/Invoke() // but does not know about this property or method // -> try next extension object // } } // end "if (pExtension->pADs && pExtension->fDisp)" pExtension = pExtension->pNext; } // end while } // // Unify the final error code retuned to ADSI client to DISP_E_UNKNOWNNAME // if ( FAILED(hr) && hr!=E_OUTOFMEMORY) { hr = DISP_E_UNKNOWNNAME; } RRETURN(hr); } STDMETHODIMP CADsExtMgr::Invoke( DISPID dispidMember, REFIID iid, LCID lcid, unsigned short wFlags, DISPPARAMS FAR* pdispparams, VARIANT FAR* pvarResult, EXCEPINFO FAR* pexcepinfo, unsigned int FAR* puArgErr ) { DWORD dwExtensionId = 0; HRESULT hr = S_OK; PEXTENSION_ENTRY pExtension = NULL; IPrivateDispatch * pPrivDisp = NULL; DISPID rgExtDispid = DISPID_UNKNOWN; // // This could be a special dispatch id - pass it to // the aggregator // if (dispidMember <= 0) { hr = _pDispMgr->Invoke( dispidMember, iid, lcid, wFlags, pdispparams, pvarResult, pexcepinfo, puArgErr ); RRETURN(hr); } // // It is not a special dispatch id, so compute the extension // id and pass it to the appropriate dispatch manager // dwExtensionId = EXTRACT_EXTENSION_ID(dispidMember); if (!dwExtensionId) { hr = _pDispMgr->Invoke( dispidMember, iid, lcid, wFlags, pdispparams, pvarResult, pexcepinfo, puArgErr ); RRETURN(hr); } if (!_pClassEntry) { RRETURN(DISP_E_MEMBERNOTFOUND); } // Shouldn't really be required here, but just being paranoid. hr = LoadExtensionsIfReqd(); if(FAILED(hr)) RRETURN(DISP_E_MEMBERNOTFOUND); pExtension = _pClassEntry->pExtensionHead; rgExtDispid = REMOVE_EXTENSION_ID(dispidMember); while (pExtension) { if (dwExtensionId == pExtension->dwExtensionID) { if (pExtension->fDisp) { // // fDisp = TRUE indicates // 1) extension supports pADsExt AND // 2) either // a) PrivateGetIDsOfNames() does Not return E_NOTIMPL // OR // b) we don't know if a) is true or not yet // ADsAssert(pExtension->pADsExt); hr = (pExtension->pADsExt)->PrivateInvoke( rgExtDispid, iid, lcid, wFlags, pdispparams, pvarResult, pexcepinfo, puArgErr ); RRETURN(hr); } else { // // A dwExtensionId match indicates THIS extens'n has returned // a valid dispid to clients thru' pADs->PrivateGetIDsOfNames. // Thus, fDisp should be TURE. // // But since dispid goes thru' clients before passed back to // PrivateInovke(), don't ASSERT in case of clients errors. // RRETURN(DISP_E_MEMBERNOTFOUND); } } pExtension = pExtension->pNext; } // end while RRETURN(DISP_E_MEMBERNOTFOUND); } HRESULT CADsExtMgr::CheckAndPrefixExtIDArray( IN DWORD dwExtensionID, IN unsigned int cDispids, IN OUT DISPID * rgDispids ) { HRESULT hrEach = S_OK; HRESULT hrAll = S_OK; ASSERT_VALID_EXTENSION_ID(dwExtensionID); for (unsigned int i = 0; i<cDispids; i++) { hrEach = CheckAndPrefixExtID( dwExtensionID, rgDispids[i], rgDispids+i ); if (FAILED(hrEach)) { hrAll = E_FAIL; // // The entire operation is considered as failure as a whole. // But continue to get other dispid s.t. debugger or user knows // which dispid in the array is causing problem -> DISPID_UNKOWN // } } RRETURN(hrAll); } HRESULT CADsExtMgr::CheckAndPrefixExtID( IN DWORD dwExtensionID, IN DISPID dispid, IN OUT DISPID * pNewDispid ) { ADsAssert(pNewDispid); if ( (dispid>= ADS_EXT_MINEXTDISPID) && (dispid<= ADS_EXT_MAXEXTDISPID) ) { *pNewDispid = PREFIX_EXTENSION_ID(dwExtensionID, dispid) ; RRETURN(S_OK); } else { *pNewDispid = DISPID_UNKNOWN; RRETURN(E_FAIL); } } //+------------------------------------------------------------------------ // // Function: CADsExtMgr::FinalInitializeExtensions // // Synopsis: At this point we call Operate on all the extensions // so that they can do initialization stuff that // // // // Arguments: None // // AjayR - added on 1-28-99. //------------------------------------------------------------------------- HRESULT CADsExtMgr::FinalInitializeExtensions() { HRESULT hr = S_OK; PEXTENSION_ENTRY pExtEntry = NULL; VARIANT vDummy; VariantInit(&vDummy); // // Extensions (ext mgr) does not exist on its own without an aggregator // ADsAssert(_pUnkOuter); // // If _pClassEntry!=NULL, pClassEntry->pExtensionHead should not // be NULL either. But just in case a user removes all extension entries // under a class key without removing the class key itself in the registry, // we will let it pass and just return S_OK here. // if (!_pClassEntry || !(pExtEntry=_pClassEntry->pExtensionHead) ) { RRETURN(S_OK); } while (pExtEntry) { // // Call operate only if the extension supports the interface // if (pExtEntry->pADsExt) { hr = (pExtEntry->pADsExt)->Operate( ADS_EXT_INITIALIZE_COMPLETE, vDummy, vDummy, vDummy ); } // // we cannot really do much if there is a failure here // pExtEntry = pExtEntry->pNext; } // end while // // We need to return S_OK here as otherwise just because // the final initialization of one extension failed - we // will hold up the entire lot. // RRETURN(S_OK); } //---------------------------------------------------------------------------- // Function: GetCLSIDForIID // // Synopsis: Returns the CLSID corresponding to a given interface IID. // If the IID is one of the interfaces implemented by the // extension manager, then the extension's CLSID is returned. // // Arguments: // // riid Interface ID for which we want to find the CLSID // lFlags Reserved. Must be 0. // pCLSID Returns the CLSID corresponding to the IID. // // Returns: S_OK on success. Error code otherwise. // // Modifies: *pCLSID to return CLSID. // //---------------------------------------------------------------------------- STDMETHODIMP CADsExtMgr::GetCLSIDForIID( REFIID riid, long lFlags, CLSID *pCLSID ) { PCLASS_ENTRY pClassEntry = _pClassEntry; PEXTENSION_ENTRY pExtensionEntry = NULL; PINTERFACE_ENTRY pIID = NULL; HRESULT hr = S_OK; ADsAssert( (0 == lFlags) && (pCLSID != NULL) ); if (!pClassEntry) { RRETURN(UMI_E_NOT_FOUND); } pExtensionEntry = pClassEntry->pExtensionHead; while (pExtensionEntry) { pIID = pExtensionEntry->pIID; while (pIID) { if (IsEqualIID(pIID->iid, riid)) { *pCLSID = pExtensionEntry->ExtCLSID; RRETURN(S_OK); } pIID = pIID->pNext; } pExtensionEntry = pExtensionEntry->pNext; } RRETURN(hr = UMI_E_NOT_FOUND); } //---------------------------------------------------------------------------- // Function: GetObjectByCLSID // // Synopsis: Returns a pointer to a requested interface on the object // specified by a CLSID. The object specified by the CLSID is // aggregated by the specified outer unknown on return. The // interface returned is a non-delegating interface on the object. // // Arguments: // // clsid CLSID of object on which interface should be obtained // pUnkOuter Aggregating outer unknown // riid Interface requested // ppInterface Returns requested interface // // Returns: UMI_S_NO_ERROR on success. Error code otherwise. // // Modifies: *ppInterface to return requested interface // //---------------------------------------------------------------------------- STDMETHODIMP CADsExtMgr::GetObjectByCLSID( CLSID clsid, IUnknown *pUnkOuter, REFIID riid, void **ppInterface ) { PCLASS_ENTRY pClassEntry = _pClassEntry; PEXTENSION_ENTRY pExtensionEntry = NULL; HRESULT hr = S_OK; IUnknown *pPrevUnk = NULL, *pUnknown = NULL; ADsAssert( (ppInterface != NULL) && (pUnkOuter != NULL) ); if (!pClassEntry) { RRETURN(UMI_E_NOT_FOUND); } pExtensionEntry = pClassEntry->pExtensionHead; while (pExtensionEntry) { if (IsEqualCLSID(pExtensionEntry->ExtCLSID, clsid)) { pPrevUnk = _pUnkOuter; _pUnkOuter = pUnkOuter; hr = LoadExtensionsIfReqd(); if(FAILED(hr)) { _pUnkOuter = pPrevUnk; BAIL_ON_FAILURE(hr = UMI_E_FAIL); } pUnknown = pExtensionEntry->pUnknown; if (!pUnknown) { BAIL_ON_FAILURE(hr = UMI_E_FAIL); } *ppInterface = pUnknown; pUnknown->AddRef(); RRETURN(S_OK); } pExtensionEntry = pExtensionEntry->pNext; } RRETURN(UMI_E_NOT_FOUND); error: RRETURN(hr); } //---------------------------------------------------------------------------- // Function: GetCLSIDForNames // // Synopsis: Returns the CLSID of the object that supports a specified // method/property. Also returns DISPIDs for the property/method. // // Arguments: // // rgszNames Names to be mapped // cNames Number of names to be mapped // lcid Locale in which to interpret the names // rgDispId Returns DISPID // lFlags Reserved. Must be 0. // pCLSID Returns CLSID of object which supports this property/method. // // Returns: S_OK on success. Error code otherwise. // // Modifies: *pCLSID to return the CLSID. // *rgDispId to return the DISPIDs. // //---------------------------------------------------------------------------- STDMETHODIMP CADsExtMgr::GetCLSIDForNames( LPOLESTR *rgszNames, UINT cNames, LCID lcid, DISPID *rgDispId, long lFlags, CLSID *pCLSID ) { HRESULT hr = S_OK; PEXTENSION_ENTRY pExtension = NULL; ADsAssert( (pCLSID != NULL) && (0 == lFlags) && (rgszNames != NULL) && (rgDispId != NULL) ); if (!_pClassEntry) { RRETURN(DISP_E_UNKNOWNNAME); } hr = LoadExtensionsIfReqd(); if(FAILED(hr)) RRETURN(DISP_E_UNKNOWNNAME); pExtension = _pClassEntry->pExtensionHead; while(pExtension) { if (pExtension->fDisp) { // // fDisp = TRUE indicates // 1) extension supports pADsExt AND // 2) either // a) PrivateGetIDsOfNames() does Not return E_NOTIMPL // OR // b) we don't know if a) is true or not yet // ADsAssert(pExtension->pADsExt); hr = (pExtension->pADsExt)->PrivateGetIDsOfNames( IID_NULL, rgszNames, cNames, lcid, rgDispId ); if (SUCCEEDED(hr)) { *pCLSID = pExtension->ExtCLSID; RRETURN(S_OK); } else if (hr == E_NOTIMPL) { // // extension object does not support the optional // IADsExtension::PrivateGetIDsOfNames()/PrivateInvoke() // -> remember this in cache & try next extension object // pExtension->fDisp = FALSE; } } pExtension = pExtension->pNext; } // end while RRETURN(hr = DISP_E_UNKNOWNNAME); }
25.181648
81
0.487469
npocmaka
80ad8da62fd529299af03efce787f0cab86330a3
1,395
cpp
C++
contest/1406/c/c.cpp
GoatGirl98/cf
4077ca8e0fe29dc2bbb7b60166989857cc062e17
[ "MIT" ]
null
null
null
contest/1406/c/c.cpp
GoatGirl98/cf
4077ca8e0fe29dc2bbb7b60166989857cc062e17
[ "MIT" ]
null
null
null
contest/1406/c/c.cpp
GoatGirl98/cf
4077ca8e0fe29dc2bbb7b60166989857cc062e17
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define watch(x) std::cout << (#x) << " is " << (x) << std::endl #define print(x) std::cout << (x) << std::endl using LL = long long; int main() { //freopen("in", "r", stdin); std::cin.tie(nullptr)->sync_with_stdio(false); int cas; std::cin >> cas; while (cas--) { int n; std::cin >> n; std::vector<std::vector<int>> q(n); int d[n] = {}, w[n] = {}; for (int i = 1, x, y; i < n; ++i) { std::cin >> x >> y; --x; --y; q[x].emplace_back(y); q[y].emplace_back(x); } bool vis[n] = {}; std::function<int(int)> dfs = [&](int u) -> int { vis[u] = true; ++d[u]; for (auto v : q[u]) if (!vis[v]) { d[u] += dfs(v); w[u] = std::max(w[u], d[v]); } w[u] = std::max(w[u], n - d[u]); return d[u]; }; dfs(0); int mw = std::min_element(w, w + n) - w; std::memset(d, 0, sizeof(d)); std::memset(w, 0, sizeof(w)); std::memset(vis, 0, sizeof(vis)); dfs(mw); int id = 0, md = 0; for (auto x : q[mw]) if (d[x] > md) { id = x; md = d[x]; } std::memset(vis, 0, sizeof(vis)); std::memset(w, 0, sizeof(w)); std::memset(d, 0, sizeof(d)); vis[mw] = 1; dfs(id); int id2 = 0; for (int i = 0; i < n; ++i) if (i != mw) { if (d[i] == 1) { id2 = i; break; } } std::cout << id2 + 1 << " " << q[id2][0] + 1 << std::endl; std::cout << id2 + 1 << " " << mw + 1 << std::endl; } return 0; }
23.25
64
0.461649
GoatGirl98
80ade0f65db7d720e9f16b50b80455393a7e66ba
645
hpp
C++
source/symbol/h2_cxa.hpp
lingjf/h2unit
5a55c718bc22ba52bd4500997b2df18939996efa
[ "Apache-2.0" ]
5
2015-03-02T22:29:00.000Z
2020-06-28T08:52:00.000Z
source/symbol/h2_cxa.hpp
lingjf/h2unit
5a55c718bc22ba52bd4500997b2df18939996efa
[ "Apache-2.0" ]
5
2019-05-10T02:28:00.000Z
2021-07-17T00:53:18.000Z
source/symbol/h2_cxa.hpp
lingjf/h2unit
5a55c718bc22ba52bd4500997b2df18939996efa
[ "Apache-2.0" ]
5
2016-05-25T07:31:16.000Z
2021-08-29T04:25:18.000Z
struct h2_cxa { static char* demangle(const char* mangle_name, char* demangle_name = (char*)alloca(1024), size_t length = 1024); static void* follow_jmp(void* fp, int n = 32); template <typename T, typename U = typename std::remove_reference<T>::type> static const char* type_name(char* name = (char*)alloca(512), size_t size = 512) { strcpy(name, ""); if (std::is_const<U>::value) strcat(name, "const "); strcat(name, demangle(typeid(U).name())); if (std::is_lvalue_reference<T>::value) strcat(name, "&"); else if (std::is_rvalue_reference<T>::value) strcat(name, "&&"); return name; } };
40.3125
115
0.63876
lingjf
80ae4e6762d35c93cec69126f5d23ffe4cf5170a
1,653
cc
C++
src/package.cc
Kronuz/Xapiand
a71570859dcfc9f48090d845053f359b07f4f78c
[ "MIT" ]
370
2016-03-14T12:19:08.000Z
2022-03-25T02:07:29.000Z
src/package.cc
puer99miss/Xapiand
480f312709d40e2b1deb244ff0761b79846ed608
[ "MIT" ]
34
2015-11-30T19:06:40.000Z
2022-02-26T03:46:58.000Z
src/package.cc
puer99miss/Xapiand
480f312709d40e2b1deb244ff0761b79846ed608
[ "MIT" ]
31
2015-02-13T22:27:34.000Z
2022-03-25T02:07:34.000Z
/* * Copyright (c) 2015-2019 Dubalu LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "package.h" #include "package_config.h" #ifndef PACKAGE_REVISION #define PACKAGE_REVISION "" #endif #ifndef PACKAGE_HASH #define PACKAGE_HASH "" #endif std::string Package::STRING = PACKAGE_STRING; std::string Package::NAME = PACKAGE_NAME; std::string Package::VERSION = PACKAGE_VERSION; std::string Package::REVISION = PACKAGE_REVISION; std::string Package::HASH = PACKAGE_HASH; std::string Package::URL = PACKAGE_URL; std::string Package::BUGREPORT = PACKAGE_BUGREPORT; std::string Package::TARNAME = PACKAGE_TARNAME;
39.357143
80
0.76709
Kronuz
80b8ac5e22a102766b78ccf8658ea2edd8f09d70
369
cpp
C++
tools/pathanalyzer/tests/rv_same_var.cpp
tjschweizer/pharos
4c5cea68c4489d798e341319d1d5e0d2fee71422
[ "RSA-MD" ]
1,247
2015-06-15T17:51:31.000Z
2022-03-31T10:24:47.000Z
tools/pathanalyzer/tests/rv_same_var.cpp
tjschweizer/pharos
4c5cea68c4489d798e341319d1d5e0d2fee71422
[ "RSA-MD" ]
191
2017-07-05T19:06:28.000Z
2022-03-20T14:31:10.000Z
tools/pathanalyzer/tests/rv_same_var.cpp
tjschweizer/pharos
4c5cea68c4489d798e341319d1d5e0d2fee71422
[ "RSA-MD" ]
180
2015-06-25T21:34:54.000Z
2022-03-21T04:25:04.000Z
// Copyright 2019 Carnegie Mellon University. See LICENSE file for terms. #include "test.hpp" int func(int n) { return n + 1; } int main() { path_start(); int n = SMALL_POSITIVE_RAND; n = func(n + 3); volatile int t = n; // volatile to prevent optimization of nongoal if (func(n + 4) < t) { path_nongoal(); } if (n == 5) { path_goal(); } }
18.45
74
0.607046
tjschweizer
80b8fdde5e5fa6d1e9963a1efd0790a65a47d240
10,855
cc
C++
stimulus/EmotionalImages.cc
Bearzeng/x-amber
351e5e9b4f66d5d4099c7ad92072b3ceaf7b11a4
[ "Apache-2.0" ]
156
2020-11-02T06:18:55.000Z
2022-03-18T10:05:01.000Z
stimulus/EmotionalImages.cc
dryxia/x-amber
351e5e9b4f66d5d4099c7ad92072b3ceaf7b11a4
[ "Apache-2.0" ]
1
2021-08-23T05:38:56.000Z
2021-08-23T05:38:56.000Z
stimulus/EmotionalImages.cc
dryxia/x-amber
351e5e9b4f66d5d4099c7ad92072b3ceaf7b11a4
[ "Apache-2.0" ]
31
2020-11-03T02:05:25.000Z
2022-01-06T06:04:39.000Z
// Copyright 2020 Google LLC // // 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 <cmath> #include "CommonScreens.h" #include "EmotionalImages.h" #include "Image.h" #include "Mark.h" #include "Screen.h" #include "Shuffler.h" #include "Util.h" namespace stimulus { namespace { const int kImageWidthCm = 15; const int kDefaultImageDisplayTimeMs = 600; const int kMinPreimageFixationTimeMs = 1000; const int kMaxPreimageFixationTimeMs = 2000; const int kNumRatingDots = 5; const float kRatingCircleDiameterCm = 1.5; const float kRatingDotDiameterCm = 0.5; const int kRatingDelayMs = 150; const char *kImageDisplayTimeSetting = "image_display_time_ms"; const int kMaxRunLength = 3; // marks const int kMarkTaskStartStop = 999; const int kMarkStimulusOffset = 777; struct EmotionalImage { std::string path; int mark; }; struct EmotionalImagesState { std::string current_path; std::string image_folder; SDL_Texture *current_image = nullptr; SDL_Rect dest_rect; int current_mark; Shuffler<EmotionalImage> *shuffler = nullptr; }; void BuildImageList(Shuffler<EmotionalImage>*); // This is just a blank screen. It loads the image, then switches // to the fixation screen. This ensures there is no delay when // the image is displayed. class PreloaderScreen : public Screen { public: PreloaderScreen(EmotionalImagesState *state) : state_(state) { } void IsVisible() override { if (state_->shuffler == nullptr) { state_->shuffler = new Shuffler<EmotionalImage>(); BuildImageList(state_->shuffler); } if (state_->shuffler->IsDone()) { state_->current_image = nullptr; delete state_->shuffler; state_->shuffler = nullptr; SwitchToScreen(1); // Back to selection screen return; } EmotionalImage image = state_->shuffler->GetNextItem(); if (state_->current_image != nullptr) { SDL_DestroyTexture(state_->current_image); } state_->current_image = LoadImage(state_->image_folder + image.path); if (state_->current_image == nullptr) { // Exit SwitchToScreen(1); return; } state_->current_path = image.path; state_->current_mark = image.mark; state_->dest_rect = ComputeRectForPhysicalWidth(state_->current_image, kImageWidthCm); SwitchToScreen(0); } private: EmotionalImagesState *state_; }; class ImageScreen : public Screen { public: ImageScreen(EmotionalImagesState *state, int image_display_time_ms) : state_(state), image_display_time_ms_(image_display_time_ms) { } void IsInvisible() override { SendMark(kMarkStimulusOffset); } void Render() override { Blit(state_->current_image, state_->dest_rect); } SDL_Color GetBackgroundColor() override { return SDL_Color { 0x60, 0x60, 0x60, 0xff }; } void IsVisible() override { SendMark(state_->current_mark, state_->current_path); SwitchToScreen(0, image_display_time_ms_); } private: EmotionalImagesState *state_; int image_display_time_ms_; }; class RatingScreen : public Screen { public: RatingScreen(const std::string &instructions, const std::string &low_label, const std::string &high_label, int mark_base_id) : instructions_(instructions), low_label_(low_label), high_label_(high_label), mark_base_id_(mark_base_id) { SetCursorVisible(true); circle_width_px_ = HorzSizeToPixels(kRatingCircleDiameterCm); circle_height_px_ = VertSizeToPixels(kRatingCircleDiameterCm); dot_x_inset_px_ = circle_width_px_ - HorzSizeToPixels(kRatingDotDiameterCm); dot_y_inset_px_ = circle_height_px_ - VertSizeToPixels(kRatingDotDiameterCm); rating_circle_ = LoadImage(GetResourceDir() + "rating-circle.bmp"); rating_dot_ = LoadImage(GetResourceDir() + "rating-dot.bmp"); int bounding_box_inset = GetDisplayWidthPx() / 3; rating_bounding_box_.w = GetDisplayWidthPx() - bounding_box_inset * 2; rating_bounding_box_.x = bounding_box_inset; rating_bounding_box_.h = circle_height_px_; rating_bounding_box_.y = (GetDisplayHeightPx() - circle_height_px_) / 2; dot_spacing_ = (rating_bounding_box_.w - circle_width_px_) / (kNumRatingDots - 1); int connector_height = rating_bounding_box_.h / 4; connector_rect_.x = rating_bounding_box_.x + circle_width_px_ / 2; connector_rect_.y = rating_bounding_box_.y + (rating_bounding_box_.h - connector_height) / 2; connector_rect_.w = rating_bounding_box_.w - circle_width_px_; connector_rect_.h = connector_height; int instruction_width = GetStringWidth(instructions); instruction_location_.x = (GetDisplayWidthPx() - instruction_width) / 2; instruction_location_.y = (GetDisplayHeightPx() / 4) - (GetFontHeight() / 2); int low_label_width = GetStringWidth(low_label_); // Center label over dot low_label_location_.x = rating_bounding_box_.x + (circle_width_px_ - low_label_width) / 2; low_label_location_.y = rating_bounding_box_.y - GetFontHeight() * 2; int high_label_width = GetStringWidth(high_label_); high_label_location_.x = rating_bounding_box_.x + rating_bounding_box_.w - (circle_width_px_ + high_label_width) / 2; high_label_location_.y = rating_bounding_box_.y - GetFontHeight() * 2; } void IsActive() override { checked_item_ = -1; } void Render() override { DrawString(low_label_location_.x, low_label_location_.y, low_label_); DrawString(high_label_location_.x, high_label_location_.y, high_label_); DrawString(instruction_location_.x, instruction_location_.y, instructions_); SDL_SetRenderDrawColor(GetRenderer(), 255, 255, 255, 255); SDL_RenderFillRect(GetRenderer(), &connector_rect_); SDL_Rect rating_circle_rect { rating_bounding_box_.x, rating_bounding_box_.y, circle_width_px_, circle_height_px_ }; for (int i = 0; i < kNumRatingDots; i++) { Blit(rating_circle_, rating_circle_rect); if (checked_item_ == i) { // Fill in this dot SDL_Rect dot_rect = stimulus::InsetRect(rating_circle_rect, dot_x_inset_px_, dot_y_inset_px_); Blit(rating_dot_, dot_rect); } rating_circle_rect.x += dot_spacing_; } SDL_SetRenderDrawColor(GetRenderer(), 96, 96, 96, 255); } void MouseClicked(int button, int x, int y) override { int dot_y = rating_bounding_box_.y + rating_bounding_box_.h / 2; float circle_r2_px = pow(circle_width_px_ / 2, 2); for (int i = 0; i < kNumRatingDots; i++) { int dot_x = rating_bounding_box_.x + circle_width_px_ / 2 + dot_spacing_ * i; float distance2 = pow(x - dot_x, 2) + pow(y - dot_y, 2); if (distance2 <= circle_r2_px) { checked_item_ = i; SendMark(mark_base_id_ + i, "Response"); SwitchToScreen(0, kRatingDelayMs); break; } } } private: std::string instructions_; std::string low_label_; std::string high_label_; int dot_spacing_; SDL_Point low_label_location_; SDL_Point high_label_location_; int mark_base_id_; SDL_Texture *rating_dot_; SDL_Texture *rating_circle_; SDL_Rect rating_bounding_box_; int circle_width_px_; int circle_height_px_; SDL_Point instruction_location_; SDL_Rect connector_rect_; int checked_item_ = -1; int dot_x_inset_px_; int dot_y_inset_px_; }; void BuildImageList(std::vector<EmotionalImage> *out_vec, const std::string &folder_name, const std::string &suffix, int count, int mark_start_id) { for (int i = 0; i < count; i++) { std::string path = folder_name + "/" + std::to_string(i + 1) + "_" + suffix + ".jpg"; EmotionalImage image = { path, mark_start_id + i }; out_vec->push_back(image); } } void BuildImageList(Shuffler<EmotionalImage> *shuffler) { std::vector<EmotionalImage> pleasantImages; BuildImageList(&pleasantImages, "pleasant_families_groups", "posgrp", 20, 1); BuildImageList(&pleasantImages, "pleasant_babies", "posbaby", 20, 21); BuildImageList(&pleasantImages, "pleasant_animals", "posaml", 20, 41); shuffler->AddCategoryElements(pleasantImages, kMaxRunLength); std::vector<EmotionalImage> neutralImages; BuildImageList(&neutralImages, "neutral_people", "neutppl", 40, 61); BuildImageList(&neutralImages, "neutral_animals", "neutaml", 20, 101); shuffler->AddCategoryElements(neutralImages, kMaxRunLength); std::vector<EmotionalImage> unpleasantImages; BuildImageList(&unpleasantImages, "unpleasant_sadness", "negsad", 20, 121); BuildImageList(&unpleasantImages, "unpleasant_disgust", "negdis", 20, 141); BuildImageList(&unpleasantImages, "unpleasant_animals", "negaml", 20, 161); shuffler->AddCategoryElements(unpleasantImages, kMaxRunLength); shuffler->ShuffleElements(); } } // namespace Screen *InitEmotionalImages(Screen *main_screen, const Settings &settings) { EmotionalImagesState *state = new EmotionalImagesState(); state->image_folder = stimulus::GetResourceDir() + "/emotional_images/"; Screen *version = new VersionScreen(); Screen *start_screen = new InstructionScreen( "Click to begin."); Screen *start_mark_screen = new MarkScreen(kMarkTaskStartStop); Screen *preloader = new PreloaderScreen(state); Screen *fixation1 = new FixationScreen(kMinPreimageFixationTimeMs, kMaxPreimageFixationTimeMs); Screen *finish = new MarkScreen(kMarkTaskStartStop); int image_display_time_ms = kDefaultImageDisplayTimeMs; if (settings.HasKey(kImageDisplayTimeSetting)) { image_display_time_ms = settings.GetIntValue(kImageDisplayTimeSetting); } Screen *image = new ImageScreen(state, image_display_time_ms); #if ENABLE_RATINGS_SCREEN Screen *rating1 = new RatingScreen( "How excited did this image make you feel?", "Calm", "Tense", 181); Screen *rating2 = new RatingScreen( "What was your emotion when you saw this image", "Unhappy", "Happy",191); image->AddSuccessor(rating1); rating1->AddSuccessor(rating2); rating2->AddSuccessor(preloader); #endif image->AddSuccessor(preloader); version->AddSuccessor(start_screen); start_screen->AddSuccessor(start_mark_screen); start_mark_screen->AddSuccessor(preloader); preloader->AddSuccessor(fixation1); preloader->AddSuccessor(finish); fixation1->AddSuccessor(image); finish->AddSuccessor(main_screen); return version; } } // namespace stimulus
34.351266
120
0.727683
Bearzeng
01e93875b238b49b9f788cd0160ce72b73090d80
5,923
cpp
C++
Data Structures/Permutation Tree.cpp
bazzyadb/all-code
cf3039641b5aa84b1c5b184a95d69bd4091974c9
[ "MIT" ]
1,639
2021-09-15T09:12:06.000Z
2022-03-31T22:58:57.000Z
Data Structures/Permutation Tree.cpp
bazzyadb/all-code
cf3039641b5aa84b1c5b184a95d69bd4091974c9
[ "MIT" ]
16
2022-01-15T17:50:08.000Z
2022-01-28T12:55:21.000Z
Data Structures/Permutation Tree.cpp
bazzyadb/all-code
cf3039641b5aa84b1c5b184a95d69bd4091974c9
[ "MIT" ]
444
2021-09-15T09:17:41.000Z
2022-03-29T18:21:46.000Z
#include<bits/stdc++.h> using namespace std; const int N = 1e5 + 9, inf = 1e9 + 7, LG = 19; struct ST { #define lc (n << 1) #define rc ((n << 1) | 1) int t[4 * N], lazy[4 * N]; ST() {} inline void push(int n, int b, int e) { if (lazy[n] == 0) return; t[n] = t[n] + lazy[n]; if (b != e) { lazy[lc] = lazy[lc] + lazy[n]; lazy[rc] = lazy[rc] + lazy[n]; } lazy[n] = 0; } inline int combine(int a, int b) { return min(a, b); } inline void pull(int n) { t[n] = min(t[lc], t[rc]); } void build(int n, int b, int e) { lazy[n] = 0; if (b == e) { t[n] = 0; return; } int mid = (b + e) >> 1; build(lc, b, mid); build(rc, mid + 1, e); pull(n); } void upd(int n, int b, int e, int i, int j, int v) { push(n, b, e); if (j < b || e < i) return; if (i <= b && e <= j) { lazy[n] = v; push(n, b, e); return; } int mid = (b + e) >> 1; upd(lc, b, mid, i, j, v); upd(rc, mid + 1, e, i, j, v); pull(n); } int query(int n, int b, int e, int i, int j) { push(n, b, e); if (i > e || b > j) return inf; if (i <= b && e <= j) return t[n]; int mid = (b + e) >> 1; return combine(query(lc, b, mid, i, j), query(rc, mid + 1, e, i, j)); } } t; // id of span {i, i} is i int p[N]; pair<int, int> range[N * 2]; // range of permutation values pair<int, int> span[N * 2]; // range of permutation indices vector<int> pt[N * 2]; //directed permutation tree int par[N * 2]; int ty[N * 2]; // 0 if cut node and 1 if increasing join node, 2 if decreasing join node int id; //new index to assign to nodes pair<int, int> get_range(pair<int, int> x, pair<int, int> y) { return pair<int, int>(min(x.first, y.first), max(x.second, y.second)); } void add_edge(int u, int v) { //u is parent of v par[v] = u; pt[u].push_back(v); } bool adjacent(int i, int j) { return range[i].second == range[j].first - 1; } int length(int i) { return range[i].second - range[i].first + 1; } // leaf node is a cut node int build(int n) { //returns root of the tree for (int i = 1; i <= 2 * n; i++) { pt[i].clear(); ty[i] = 0; par[i] = -1; } id = n + 1; t.build(1, 1, n); vector<int> mx = {0}, mn = {0}; vector<int> nodes; //stack of cut and join nodes for (int i = 1; i <= n; i++) { while (mx.back() != 0 && p[mx.back()] < p[i]) { int r = mx.back(); mx.pop_back(); t.upd(1, 1, n, mx.back() + 1, r, p[i] - p[r]); } mx.push_back(i); while (mn.back() != 0 && p[mn.back()] > p[i]) { int r = mn.back(); mn.pop_back(); t.upd(1, 1, n, mn.back() + 1, r, p[r] - p[i]); } mn.push_back(i); // handle stack updates range[i] = {p[i], p[i]}; span[i] = {i, i}; int cur = i; while (true) { if (!nodes.empty() && (adjacent(nodes.back(), cur) || adjacent(cur, nodes.back()))) { if ((adjacent(nodes.back(), cur) && ty[nodes.back()] == 1) || (adjacent(cur, nodes.back()) && ty[nodes.back()] == 2)) { add_edge(nodes.back(), cur); range[nodes.back()] = get_range(range[nodes.back()], range[cur]); span[nodes.back()] = get_range(span[nodes.back()], span[cur]); cur = nodes.back(); nodes.pop_back(); } else { //make a new join node ty[id] = (adjacent(nodes.back(), cur) ? 1 : 2); add_edge(id, nodes.back()); add_edge(id, cur); range[id] = get_range(range[nodes.back()], range[cur]); span[id] = get_range(span[nodes.back()], span[cur]); nodes.pop_back(); cur = id++; } } else if (i - (length(cur) - 1) && t.query(1, 1, n, 1, i - length(cur)) == 0) { int len = length(cur); pair<int, int> r = range[cur]; pair<int, int> s = span[cur]; add_edge(id, cur); do { len += length(nodes.back()); r = get_range(r, range[nodes.back()]); s = get_range(s, span[nodes.back()]); add_edge(id, nodes.back()); nodes.pop_back(); } while (r.second - r.first + 1 != len); reverse(pt[id].begin(), pt[id].end()); range[id] = r; span[id] = s; cur = id++; } else { break; } } nodes.push_back(cur); t.upd(1, 1, n, 1, i, -1); } id--; assert(id <= 2 * n); int r = 0; for (int i = 1; i <= id; i++) { if (par[i] == -1) r = i; } assert(r); return r; } int P[N * 2][LG]; void dfs(int u, int p = 0) { P[u][0] = p; for (int k = 1; k < LG; k++) { P[u][k] = P[P[u][k - 1]][k - 1]; } for (auto v : pt[u]) { if (v == p) continue; dfs(v, u); } } int32_t main() { ios_base::sync_with_stdio(0); cin.tie(0); int n; cin >> n; for (int i = 1; i <= n; i++) cin >> p[i]; int r = build(n); dfs(r); int q; cin >> q; while (q--) { int l, r; cin >> l >> r; if (l == r) { cout << l << ' ' << r << '\n'; continue; } int u = l; for (int k = LG - 1; k >= 0; k--) { if (P[u][k] && span[P[u][k]].second < r) u = P[u][k]; } u = P[u][0]; if (ty[u] == 0) { cout << span[u].first << ' ' << span[u].second << '\n'; continue; } int curl = -1, curr = pt[u].size(); for (int k = LG - 1; k >= 0; k--) { if (curl + (1 << k) < pt[u].size() && span[pt[u][curl + (1 << k)]].second < l) curl += 1 << k; if (curr - (1 << k) >= 0 && r < span[pt[u][curr - (1 << k)]].first) curr -= 1 << k; } cout << span[pt[u][curl + 1]].first << ' ' << span[pt[u][curr - 1]].second << '\n'; } return 0; } // https://codeforces.com/gym/101620, Problem I // https://codeforces.com/blog/entry/78898
28.204762
101
0.449097
bazzyadb
01ea332bf6507cb176300a84298d943e3eff4bb8
4,300
cpp
C++
2D/src/Pyromania/Util.cpp
Squareys/pyromania
88cbc4f3474e8407c3be09df497dd4be47a587ba
[ "Unlicense", "MIT" ]
1
2018-06-19T10:19:23.000Z
2018-06-19T10:19:23.000Z
2D/src/Pyromania/Util.cpp
Squareys/pyromania
88cbc4f3474e8407c3be09df497dd4be47a587ba
[ "Unlicense", "MIT" ]
null
null
null
2D/src/Pyromania/Util.cpp
Squareys/pyromania
88cbc4f3474e8407c3be09df497dd4be47a587ba
[ "Unlicense", "MIT" ]
null
null
null
#include "util.h" #include <cstring> // Double Buffer BITMAP *screenAlias = NULL; BITMAP *doubleBuffer = NULL; // Die Timer Variablen und FUnktionen // ------------------------------------------------------- volatile int ticks = 0; volatile int gameTime = 0; static void tick() { ticks++; } END_OF_STATIC_FUNCTION(tick); static void gameTimer() { gameTime++; } END_OF_STATIC_FUNCTION(gameTimer); // ------------------------------------------------------- void fatalError(char *str) { allegro_message(str); exit(0); } // ------------------------------------------------------- int setGfxMode(int mode, int width, int height) { static int colorDepths[] = { 32, 16, 24, 15, 32}; int a; for (a=0; a < 4; a++) { set_color_depth(colorDepths[a]); if (set_gfx_mode(mode, width, height, 0, 0) >= 0) { return TRUE; } } return FALSE; } // ------------------------------------------------------- void playSound(SAMPLE *sample, int vol) { if (!sample) return; play_sample(sample, vol, 128, rnd(400) + 900, 0); } // ------------------------------------------------------- void secure_destroy_bitmap(BITMAP* BMP){ if (BMP != NULL){ destroy_bitmap(BMP); } } // ------------------------------------------------------- void show() { blit(doubleBuffer, screen, 0, 0, 0, 0, doubleBuffer->w, doubleBuffer->h); } // ------------------------------------------------------- int rnd( int n ){ return (int)( n * ( (double)rand() / (double)(RAND_MAX + 1.0 ) ) ); } // ------------------------------------------------------- void init(int w, int h, int fps, bool fullscreen) { srand(time(NULL)); // Allegro und Grafik, Timer, Sound und Eingabemedien // initilaisieren allegro_init(); if (!fullscreen || !setGfxMode(GFX_AUTODETECT_FULLSCREEN, w, h)) { if (!setGfxMode(GFX_AUTODETECT_WINDOWED, w, h)) { fatalError("Unable to set a graphics mode"); } set_display_switch_mode(SWITCH_BACKGROUND); } else { set_display_switch_mode(SWITCH_BACKAMNESIA); } install_timer(); /* Den DoubleBuffer erstellen */ screenAlias = create_video_bitmap(SCREEN_W, SCREEN_H); doubleBuffer = create_video_bitmap(SCREEN_W, SCREEN_H); if (!doubleBuffer) { if (screenAlias != NULL) { destroy_bitmap(screenAlias); } doubleBuffer = create_system_bitmap(SCREEN_W, SCREEN_H); if (!doubleBuffer) { fatalError("Unable to create double buffer"); } } vsync(); /* Timer Funktionen und Variablen locken */ LOCK_FUNCTION(tick); LOCK_VARIABLE(ticks); LOCK_FUNCTION(gameTimer); LOCK_VARIABLE(gameTime); /* Die logische Framerate setzen */ install_int_ex(tick, BPS_TO_TIMER(fps)); install_int(gameTimer, 10); DATAFILE* Logo_dat = load_datafile("Images\\Images00.dat"); BITMAP* Logo = (BITMAP*) Logo_dat[0].dat; BITMAP* Logo_glanz = (BITMAP*) Logo_dat[1].dat; BITMAP* allegro_logo = (BITMAP*) Logo_dat[2].dat; int x = 0; bool needsRefresh = false; while (x < Logo->w) { if (ticks) { do { x+= 6; --ticks; } while (ticks); needsRefresh = true; } if (needsRefresh) { blit(Logo,doubleBuffer, 0,0, 0,0,Logo->w, Logo->h); blit(Logo_glanz, doubleBuffer, x, 0, x, 0, 30, Logo->h); show(); needsRefresh = false; } } install_keyboard(); install_joystick(JOY_TYPE_AUTODETECT); install_mouse(); install_sound(DIGI_AUTODETECT, MIDI_AUTODETECT, NULL); // ASCII Zeichen benutzen set_uformat(U_ASCII); // Allegro Logo anzeigen if (allegro_logo) { blit(allegro_logo, screen, 0, 0, 0, 0, allegro_logo->w, allegro_logo->h); } unload_datafile(Logo_dat); } // ------------------------------------------------------- // Gibt die in init() angelegten Resourcen // wieder frei void done() { destroy_bitmap(doubleBuffer); secure_destroy_bitmap(screenAlias); } // ------------------------------------------------------- void syncTimer(volatile int * timer) { int value = *timer; while (*timer == value); }
27.564103
81
0.523721
Squareys
01edb7810392521a86c9c0676e0f0a0b77741cd9
837
cpp
C++
software/zynq/SoundComponents/src/mulsc/MultiplyControl.cpp
EPiCS/soundgates
a6014d6a68fa209703d749ffe21a1e58b9279d30
[ "MIT" ]
null
null
null
software/zynq/SoundComponents/src/mulsc/MultiplyControl.cpp
EPiCS/soundgates
a6014d6a68fa209703d749ffe21a1e58b9279d30
[ "MIT" ]
1
2017-04-10T10:57:53.000Z
2017-04-10T10:57:53.000Z
software/zynq/SoundComponents/src/mulsc/MultiplyControl.cpp
EPiCS/soundgates
a6014d6a68fa209703d749ffe21a1e58b9279d30
[ "MIT" ]
3
2016-09-12T14:08:20.000Z
2021-03-22T20:07:34.000Z
/* * MultiplyControl.cpp * * Created on: Jan 17, 2014 * Author: lukas */ #include "MultiplyControl.h" #include "impl/MultiplyControlSW.h" DEFINE_COMPONENTNAME(MultiplyControl, "mulsc") EXPORT_SOUNDCOMPONENT_SW_ONLY(MultiplyControl); MultiplyControl::MultiplyControl(std::vector<std::string> params) : SoundComponentImpl(params) { multValue = 0; CREATE_AND_REGISTER_PORT3(MultiplyControl, In, SoundPort, SoundIn, 1); CREATE_AND_REGISTER_PORT3(MultiplyControl, In, ControlPort, ValueIn, 2); CREATE_AND_REGISTER_PORT3(MultiplyControl, Out, SoundPort, SoundOut, 1); } MultiplyControl::~MultiplyControl() { } void MultiplyControl::init() { LOG_DEBUG("Init multiply control"); m_ValueIn_2_Port->registerCallback(ICallbackPtr(new OnValueChange<float, ControlPortPtr>(multValue, m_ValueIn_2_Port))); }
22.621622
121
0.761051
EPiCS
01ee616b752ac087d4a25ae15bf4812570950439
6,442
cpp
C++
forwarder/ci/src/route_table_test.cpp
kamaboko123/salacia-forwarder
756c504e49fce5b8ff35f6671f7d2117660ae10b
[ "MIT" ]
2
2019-09-10T12:35:27.000Z
2022-03-24T02:41:23.000Z
forwarder/ci/src/route_table_test.cpp
kamaboko123/salacia-forwarder
756c504e49fce5b8ff35f6671f7d2117660ae10b
[ "MIT" ]
8
2017-12-12T14:36:57.000Z
2018-11-06T15:10:05.000Z
forwarder/ci/src/route_table_test.cpp
kamaboko123/salacia-forwarder
756c504e49fce5b8ff35f6671f7d2117660ae10b
[ "MIT" ]
null
null
null
#include <cstring> #include <cppunit/extensions/HelperMacros.h> #include "RouteTable.hpp" #ifdef FIXTURE_NAME #undef FIXTURE_NAME #endif #define FIXTURE_NAME RouteTableTest class FIXTURE_NAME : public CPPUNIT_NS::TestFixture { CPPUNIT_TEST_SUITE(FIXTURE_NAME); CPPUNIT_TEST(test_route_constructor); CPPUNIT_TEST(test_route_core); CPPUNIT_TEST(test_route_invalid); CPPUNIT_TEST_SUITE_END(); private: void copy_constructor_test(Route target, Route *expect); public: void setUp(); void tearDown(); protected: void test_route_constructor(); void test_route_core(); void test_route_invalid(); void test_route_table_core(); }; void FIXTURE_NAME::copy_constructor_test(Route target, Route *expect){ //WIP } CPPUNIT_TEST_SUITE_REGISTRATION(FIXTURE_NAME); void FIXTURE_NAME::setUp() {} void FIXTURE_NAME::tearDown() {} void FIXTURE_NAME::test_route_constructor(){ Route r1("10.0.0.0/8"); //str Array<IPAddress> bests; Array<RouteType> route_types; CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)0, r1.getNexthops(RTYPE_LOCAL).getSize()); CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)0, r1.getBestNexthops(bests)); CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)0, bests.getSize()); CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)0, r1.getBestNexthops().getSize()); CPPUNIT_ASSERT_EQUAL(RTYPE_INVALID, r1.getBestRouteType()); CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)0, r1.getRouteTypes(route_types)); CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)0, route_types.getSize()); CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)0, r1.getRouteTypes().getSize()); CPPUNIT_ASSERT_EQUAL(0, strcmp("10.0.0.0/8", r1.getNetwork().toStr())); //IPNetwork IPNetwork nw("20.0.0.0/16"); Route r2(nw); CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)0, r2.getNexthops(RTYPE_LOCAL).getSize()); CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)0, r2.getNexthops(RTYPE_CONNECTED).getSize()); CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)0, r2.getNexthops(RTYPE_STATIC).getSize()); CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)0, r2.getNexthops(RTYPE_RIP).getSize()); CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)0, r2.getNexthops(RTYPE_INVALID).getSize()); CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)0, r2.getBestNexthops(bests)); CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)0, bests.getSize()); CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)0, r2.getBestNexthops().getSize()); CPPUNIT_ASSERT_EQUAL(RTYPE_INVALID, r2.getBestRouteType()); CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)0, r2.getRouteTypes(route_types)); CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)0, route_types.getSize()); CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)0, r2.getRouteTypes().getSize()); CPPUNIT_ASSERT_EQUAL(0, strcmp("20.0.0.0/16", r2.getNetwork().toStr())); //copy constructor } void FIXTURE_NAME::test_route_core(){ Route *r1; r1 = new Route("10.0.0.0/8"); r1->addNexthop(RTYPE_LOCAL, IPAddress("1.1.1.1")); Array<IPAddress> bests; Array<RouteType> route_types; CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)1, r1->getNexthops(RTYPE_LOCAL).getSize()); CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)0, r1->getNexthops(RTYPE_CONNECTED).getSize()); CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)0, r1->getNexthops(RTYPE_STATIC).getSize()); CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)0, r1->getNexthops(RTYPE_RIP).getSize()); CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)0, r1->getNexthops(RTYPE_INVALID).getSize()); CPPUNIT_ASSERT_EQUAL(IPAddress("1.1.1.1").touInt(), r1->getNexthops(RTYPE_LOCAL).get(0).touInt()); CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)1, r1->getBestNexthops(bests)); CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)1, bests.getSize()); CPPUNIT_ASSERT_EQUAL(IPAddress("1.1.1.1").touInt(), bests.get(0).touInt()); CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)1, r1->getBestNexthops().getSize()); CPPUNIT_ASSERT_EQUAL(RTYPE_LOCAL, r1->getBestRouteType()); CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)1, r1->getRouteTypes(route_types)); CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)1, route_types.getSize()); CPPUNIT_ASSERT_EQUAL(RTYPE_LOCAL, route_types.get(0)); CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)1, r1->getRouteTypes().getSize()); r1->addNexthop(RTYPE_CONNECTED, IPAddress("2.2.2.2")); r1->addNexthop(RTYPE_STATIC, IPAddress("3.3.3.3")); CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)1, r1->getNexthops(RTYPE_LOCAL).getSize()); CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)1, r1->getNexthops(RTYPE_CONNECTED).getSize()); CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)1, r1->getNexthops(RTYPE_STATIC).getSize()); CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)0, r1->getNexthops(RTYPE_RIP).getSize()); CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)0, r1->getNexthops(RTYPE_INVALID).getSize()); CPPUNIT_ASSERT_EQUAL(IPAddress("1.1.1.1").touInt(), r1->getNexthops(RTYPE_LOCAL).get(0).touInt()); CPPUNIT_ASSERT_EQUAL(IPAddress("2.2.2.2").touInt(), r1->getNexthops(RTYPE_CONNECTED).get(0).touInt()); CPPUNIT_ASSERT_EQUAL(IPAddress("3.3.3.3").touInt(), r1->getNexthops(RTYPE_STATIC).get(0).touInt()); CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)1, r1->getBestNexthops(bests)); CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)1, bests.getSize()); CPPUNIT_ASSERT_EQUAL(IPAddress("1.1.1.1").touInt(), bests.get(0).touInt()); CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)1, r1->getBestNexthops().getSize()); CPPUNIT_ASSERT_EQUAL(RTYPE_LOCAL, r1->getBestRouteType()); CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)3, r1->getRouteTypes(route_types)); CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)3, route_types.getSize()); CPPUNIT_ASSERT_EQUAL(RTYPE_LOCAL, route_types.get(0)); CPPUNIT_ASSERT_EQUAL(RTYPE_CONNECTED, route_types.get(1)); CPPUNIT_ASSERT_EQUAL(RTYPE_STATIC, route_types.get(2)); CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)3, r1->getRouteTypes().getSize()); r1->addNexthop(RTYPE_STATIC, IPAddress("4.4.4.4")); CPPUNIT_ASSERT_EQUAL((sfwdr::size_t)2, r1->getNexthops(RTYPE_STATIC).getSize()); CPPUNIT_ASSERT_EQUAL(IPAddress("3.3.3.3").touInt(), r1->getNexthops(RTYPE_STATIC).get(0).touInt()); CPPUNIT_ASSERT_EQUAL(IPAddress("4.4.4.4").touInt(), r1->getNexthops(RTYPE_STATIC).get(1).touInt()); delete r1; } void FIXTURE_NAME::test_route_invalid(){ Route *r1; CPPUNIT_ASSERT_THROW(r1 = new Route("a"), sfwdr::Exception::InvalidIPNetwork); } void test_route_table_core(){ //WIP }
38.57485
106
0.712512
kamaboko123
01ee629ad4389705dc86e11cf0843797e189b348
21,301
cpp
C++
emulator/src/devices/video/crtc_ega.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
1
2022-01-15T21:38:38.000Z
2022-01-15T21:38:38.000Z
emulator/src/devices/video/crtc_ega.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
emulator/src/devices/video/crtc_ega.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
// license:BSD-3-Clause // copyright-holders:Wilbert Pol /********************************************************************** IBM EGA CRT Controller emulation This controller is very loosely based on the mc6845. **********************************************************************/ #include "emu.h" #include "crtc_ega.h" #include "screen.h" #define VERBOSE 1 #include "logmacro.h" DEFINE_DEVICE_TYPE(CRTC_EGA, crtc_ega_device, "crtc_ega", "IBM EGA CRT Controller") crtc_ega_device::crtc_ega_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : device_t(mconfig, CRTC_EGA, tag, owner, clock), device_video_interface(mconfig, *this, false) , m_res_out_de_cb(*this), m_res_out_hsync_cb(*this), m_res_out_vsync_cb(*this), m_res_out_vblank_cb(*this) , m_horiz_char_total(0), m_horiz_disp(0), m_horiz_blank_start(0), m_horiz_blank_end(0) , m_ena_vert_access(0), m_de_skew(0) , m_horiz_retr_start(0), m_horiz_retr_end(0), m_horiz_retr_skew(0) , m_vert_total(0), m_preset_row_scan(0), m_byte_panning(0), m_max_ras_addr(0), m_scan_doubling(0) , m_cursor_start_ras(0), m_cursor_disable(0), m_cursor_end_ras(0), m_cursor_skew(0) , m_disp_start_addr(0), m_cursor_addr(0), m_light_pen_addr(0) , m_vert_retr_start(0), m_vert_retr_end(0) , m_protect(0), m_bandwidth(0), m_vert_disp_end(0), m_offset(0), m_underline_loc(0) , m_vert_blank_start(0), m_vert_blank_end(0) , m_mode_control(0), m_line_compare(0), m_register_address_latch(0) , m_cursor_state(false), m_cursor_blink_count(0) , m_hpixels_per_column(0), m_cur(0), m_hsync(0), m_vsync(0), m_vblank(0), m_de(0) , m_character_counter(0), m_hsync_width_counter(0), m_line_counter(0), m_raster_counter(0), m_vsync_width_counter(0) , m_line_enable_ff(false), m_vsync_ff(0), m_adjust_active(0), m_line_address(0), m_cursor_x(0) , m_line_timer(nullptr), m_de_off_timer(nullptr), m_cur_on_timer(nullptr), m_cur_off_timer(nullptr), m_hsync_on_timer(nullptr), m_hsync_off_timer(nullptr), m_light_pen_latch_timer(nullptr) , m_horiz_pix_total(0), m_vert_pix_total(0), m_max_visible_x(0), m_max_visible_y(0) , m_hsync_on_pos(0), m_hsync_off_pos(0), m_vsync_on_pos(0), m_vsync_off_pos(0) , m_current_disp_addr(0), m_light_pen_latched(0), m_has_valid_parameters(false) { } void crtc_ega_device::device_post_load() { recompute_parameters(true); } WRITE8_MEMBER( crtc_ega_device::address_w ) { m_register_address_latch = data & 0x1f; } READ8_MEMBER( crtc_ega_device::register_r ) { uint8_t ret = 0; switch (m_register_address_latch) { case 0x0c: ret = (m_disp_start_addr >> 8) & 0xff; break; case 0x0d: ret = (m_disp_start_addr >> 0) & 0xff; break; case 0x0e: ret = (m_cursor_addr >> 8) & 0xff; break; case 0x0f: ret = (m_cursor_addr >> 0) & 0xff; break; case 0x10: ret = (m_light_pen_addr >> 8) & 0xff; m_light_pen_latched = false; break; case 0x11: ret = (m_light_pen_addr >> 0) & 0xff; m_light_pen_latched = false; break; /* all other registers are write only and return 0 */ default: break; } return ret; } WRITE8_MEMBER( crtc_ega_device::register_w ) { LOG("%s CRTC_EGA: reg 0x%02x = 0x%02x\n", machine().describe_context(), m_register_address_latch, data); switch (m_register_address_latch) { case 0x00: m_horiz_char_total = data & 0xff; break; case 0x01: m_horiz_disp = data & 0xff; break; case 0x02: m_horiz_blank_start = data & 0xff; break; case 0x03: m_horiz_blank_end = ((data & 0x1f) << 0) | (m_horiz_blank_end & 0x20); m_de_skew = ((data & 0x60) >> 5); m_ena_vert_access = data & 0x80; break; case 0x04: m_horiz_retr_start = data & 0xff; break; case 0x05: m_horiz_retr_end = data & 0x1f; m_horiz_retr_skew = ((data & 0x60) >> 5); m_horiz_blank_end = ((data & 0x80) >> 2) | (m_horiz_blank_end & 0x1f); break; case 0x06: m_vert_total = ((data & 0xff) << 0) | (m_vert_total & 0x0300); break; case 0x07: m_vert_total = ((data & 0x01) << 8) | (m_vert_total & 0x02ff); m_vert_disp_end = ((data & 0x02) << 7) | (m_vert_disp_end & 0x02ff); m_vert_retr_start = ((data & 0x04) << 6) | (m_vert_retr_start & 0x02ff); m_vert_blank_start = ((data & 0x08) << 5) | (m_vert_blank_start & 0x02ff); m_line_compare = ((data & 0x10) << 4) | (m_line_compare & 0x02ff); m_vert_total = ((data & 0x20) << 4) | (m_vert_total & 0x01ff); m_vert_disp_end = ((data & 0x40) << 3) | (m_vert_disp_end & 0x1ff); m_vert_retr_start = ((data & 0x80) << 2) | (m_vert_retr_start & 0x01ff); break; case 0x08: m_preset_row_scan = data & 0x1f; m_byte_panning = ((data & 0x60) >> 5); break; case 0x09: m_max_ras_addr = data & 0x1f; m_vert_blank_start = ((data & 0x20) << 4) | (m_vert_blank_start & 0x01ff); m_line_compare = ((data & 0x40) << 3) | (m_line_compare & 0x01ff); m_scan_doubling = data & 0x80; break; case 0x0a: m_cursor_start_ras = data & 0x1f; m_cursor_disable = data & 0x20; break; case 0x0b: m_cursor_end_ras = data & 0x1f; m_cursor_skew = ((data & 0x60) >> 5); break; case 0x0c: m_disp_start_addr = ((data & 0xff) << 8) | (m_disp_start_addr & 0x00ff); break; case 0x0d: m_disp_start_addr = ((data & 0xff) << 0) | (m_disp_start_addr & 0xff00); break; case 0x0e: m_cursor_addr = ((data & 0xff) << 8) | (m_cursor_addr & 0x00ff); break; case 0x0f: m_cursor_addr = ((data & 0xff) << 0) | (m_cursor_addr & 0xff00); break; case 0x10: m_vert_retr_start = ((data & 0xff) << 0) | (m_vert_retr_start & 0x0300); break; case 0x11: m_vert_retr_end = data & 0x0f; m_bandwidth = data & 0x40; m_protect = data & 0x80; break; case 0x12: m_vert_disp_end = ((data & 0xff) << 0) | (m_vert_disp_end & 0x0300); break; case 0x13: m_offset = data & 0xff; break; case 0x14: m_underline_loc = data & 0x7f; break; case 0x15: m_vert_blank_start = ((data & 0xff) << 0) | (m_vert_blank_start & 0x0300); break; case 0x16: m_vert_blank_end = data & 0x7f; break; case 0x17: m_mode_control = data & 0xff; break; case 0x18: m_line_compare = ((data & 0xff) << 0) | (m_line_compare & 0x0300); break; default: break; } recompute_parameters(false); } void crtc_ega_device::recompute_parameters(bool postload) { uint16_t hsync_on_pos, hsync_off_pos, vsync_on_pos, vsync_off_pos; /* compute the screen sizes */ uint16_t horiz_pix_total = (m_horiz_char_total + 2) * m_hpixels_per_column; uint16_t vert_pix_total = m_vert_total + 1; /* determine the visible area, avoid division by 0 */ uint16_t max_visible_x = ( m_horiz_disp + 1 ) * m_hpixels_per_column - 1; uint16_t max_visible_y = m_vert_disp_end; /* determine the syncing positions */ int horiz_sync_char_width = ( m_horiz_retr_end + 1 ) - ( m_horiz_retr_start & 0x1f ); int vert_sync_pix_width = m_vert_retr_end - ( m_vert_retr_start & 0x0f ); if (horiz_sync_char_width <= 0) horiz_sync_char_width += 0x10; if (vert_sync_pix_width <= 0) vert_sync_pix_width += 0x10; hsync_on_pos = m_horiz_retr_start * m_hpixels_per_column; hsync_off_pos = hsync_on_pos + (horiz_sync_char_width * m_hpixels_per_column); vsync_on_pos = m_vert_retr_start; /* + 1 ?? */ vsync_off_pos = vsync_on_pos + vert_sync_pix_width; if (hsync_off_pos > horiz_pix_total) hsync_off_pos = horiz_pix_total; if (vsync_off_pos > vert_pix_total) vsync_off_pos = vert_pix_total; if ( vsync_on_pos >= vsync_off_pos ) { vsync_on_pos = vsync_off_pos - 2; } /* update only if screen parameters changed, unless we are coming here after loading the saved state */ if (postload || (horiz_pix_total != m_horiz_pix_total) || (vert_pix_total != m_vert_pix_total) || (max_visible_x != m_max_visible_x) || (max_visible_y != m_max_visible_y) || (hsync_on_pos != m_hsync_on_pos) || (vsync_on_pos != m_vsync_on_pos) || (hsync_off_pos != m_hsync_off_pos) || (vsync_off_pos != m_vsync_off_pos)) { /* update the screen if we have valid data */ if ((horiz_pix_total > 0) && (max_visible_x < horiz_pix_total) && (vert_pix_total > 0) && (max_visible_y < vert_pix_total) && (hsync_on_pos <= horiz_pix_total) && (vsync_on_pos <= vert_pix_total) && (hsync_on_pos != hsync_off_pos)) { attoseconds_t refresh = HZ_TO_ATTOSECONDS(m_clock) * (m_horiz_char_total + 2) * vert_pix_total; rectangle visarea(0, max_visible_x, 0, max_visible_y); LOG("CRTC_EGA config screen: HTOTAL: 0x%x VTOTAL: 0x%x MAX_X: 0x%x MAX_Y: 0x%x HSYNC: 0x%x-0x%x VSYNC: 0x%x-0x%x Freq: %ffps\n", horiz_pix_total, vert_pix_total, max_visible_x, max_visible_y, hsync_on_pos, hsync_off_pos - 1, vsync_on_pos, vsync_off_pos - 1, 1 / ATTOSECONDS_TO_DOUBLE(refresh)); if (has_screen()) screen().configure(horiz_pix_total, vert_pix_total, visarea, refresh); m_has_valid_parameters = true; } else { m_has_valid_parameters = false; LOG("CRTC_EGA bad config screen: HTOTAL: 0x%x VTOTAL: 0x%x MAX_X: 0x%x MAX_Y: 0x%x HSYNC: 0x%x-0x%x VSYNC: 0x%x-0x%x\n", horiz_pix_total, vert_pix_total, max_visible_x, max_visible_y, hsync_on_pos, hsync_off_pos - 1, vsync_on_pos, vsync_off_pos - 1); } m_horiz_pix_total = horiz_pix_total; m_vert_pix_total = vert_pix_total; m_max_visible_x = max_visible_x; m_max_visible_y = max_visible_y; m_hsync_on_pos = hsync_on_pos; m_hsync_off_pos = hsync_off_pos; m_vsync_on_pos = vsync_on_pos; m_vsync_off_pos = vsync_off_pos; } } void crtc_ega_device::update_counters() { m_character_counter = m_line_timer->elapsed().as_ticks( m_clock ); if ( m_hsync_off_timer->enabled() ) { m_hsync_width_counter = m_hsync_off_timer->elapsed().as_ticks( m_clock ); } } void crtc_ega_device::set_de(int state) { if (m_de != state) { m_de = state; if (!m_res_out_de_cb.isnull()) m_res_out_de_cb(m_de); } } void crtc_ega_device::set_hsync(int state) { if (m_hsync != state) { m_hsync = state; if (!m_res_out_hsync_cb.isnull()) m_res_out_hsync_cb(m_hsync); } } void crtc_ega_device::set_vsync(int state) { if (m_vsync != state) { m_vsync = state; if (!m_res_out_vsync_cb.isnull()) m_res_out_vsync_cb(m_vsync); } } void crtc_ega_device::set_vblank(int state) { if (m_vblank != state) { m_vblank = state; if (!m_res_out_vblank_cb.isnull()) m_res_out_vblank_cb(m_vblank); } } void crtc_ega_device::set_cur(int state) { if (m_cur != state) { m_cur = state; // if (!m_res_out_cur_cb.isnull()) // m_res_out_cur_cb(m_cur); } } void crtc_ega_device::handle_line_timer() { int new_vsync = m_vsync; m_character_counter = 0; m_cursor_x = -1; /* Check if VSYNC is active */ if ( m_vsync_ff ) { m_vsync_width_counter = ( m_vsync_width_counter + 1 ) & 0x0F; /* Check if we've reached end of VSYNC */ if ( m_vsync_width_counter == m_vert_retr_end ) { m_vsync_ff = 0; new_vsync = false; } } if ( m_raster_counter == m_max_ras_addr ) { m_raster_counter = 0; m_line_address = ( m_line_address + m_horiz_disp + 1 ) & 0xffff; } else { m_raster_counter = ( m_raster_counter + 1 ) & 0x1F; } m_line_counter = ( m_line_counter + 1 ) & 0x3ff; /* Check if we've reached the end of active display */ if ( m_line_counter == m_vert_disp_end ) { m_line_enable_ff = false; } /* Check if VSYNC should be enabled */ if ( m_line_counter == m_vert_retr_start ) { m_vsync_width_counter = 0; m_vsync_ff = 1; new_vsync = true; } /* Check if we have reached the end of the vertical area */ if ( m_line_counter == m_vert_total ) { m_line_counter = 0; m_line_address = m_disp_start_addr; m_line_enable_ff = true; set_vblank( false ); /* also update the cursor state now */ update_cursor_state(); if (has_screen()) screen().reset_origin(); } if ( m_line_enable_ff ) { /* Schedule DE off signal change */ m_de_off_timer->adjust(attotime::from_ticks( m_horiz_disp + 1, m_clock )); /* Is cursor visible on this line? */ if ( m_cursor_state && (m_raster_counter >= (m_cursor_start_ras & 0x1f)) && (m_raster_counter <= m_cursor_end_ras) && (m_cursor_addr >= m_line_address) && (m_cursor_addr < (m_line_address + m_horiz_disp + 1)) ) { m_cursor_x = m_cursor_addr - m_line_address; /* Schedule CURSOR ON signal */ m_cur_on_timer->adjust( attotime::from_ticks( m_cursor_x, m_clock ) ); } } /* Schedule HSYNC on signal */ m_hsync_on_timer->adjust( attotime::from_ticks( m_horiz_blank_start, m_clock ) ); /* Set VBlank signal */ if ( m_line_counter == m_vert_disp_end + 1 ) { set_vblank( true ); } /* Schedule our next callback */ m_line_timer->adjust( attotime::from_ticks( m_horiz_char_total + 2, m_clock ) ); /* Set VSYNC and DE signals */ set_vsync( new_vsync ); set_de( m_line_enable_ff ? true : false ); } void crtc_ega_device::device_timer(emu_timer &timer, device_timer_id id, int param, void *ptr) { switch (id) { case TIMER_LINE: handle_line_timer(); break; case TIMER_DE_OFF: set_de( false ); break; case TIMER_CUR_ON: set_cur( true ); /* Schedule CURSOR off signal */ m_cur_off_timer->adjust( attotime::from_ticks( 1, m_clock ) ); break; case TIMER_CUR_OFF: set_cur( false ); break; case TIMER_HSYNC_ON: { int8_t hsync_width = ( 0x20 | m_horiz_blank_end ) - ( m_horiz_blank_start & 0x1f ); if ( hsync_width <= 0 ) { hsync_width += 0x20; } m_hsync_width_counter = 0; set_hsync( true ); /* Schedule HSYNC off signal */ m_hsync_off_timer->adjust( attotime::from_ticks( hsync_width, m_clock ) ); } break; case TIMER_HSYNC_OFF: set_hsync( false ); break; case TIMER_LIGHT_PEN_LATCH: m_light_pen_addr = get_ma(); m_light_pen_latched = true; break; } } uint16_t crtc_ega_device::get_ma() { update_counters(); return m_line_address + m_character_counter; } uint8_t crtc_ega_device::get_ra() { return m_raster_counter; } void crtc_ega_device::assert_light_pen_input() { /* compute the pixel coordinate of the NEXT character -- this is when the light pen latches */ /* set the timer that will latch the display address into the light pen registers */ m_light_pen_latch_timer->adjust(attotime::from_ticks( 1, m_clock )); } void crtc_ega_device::set_clock(int clock) { /* validate arguments */ assert(clock > 0); if (clock != m_clock) { m_clock = clock; recompute_parameters(true); } } void crtc_ega_device::set_hpixels_per_column(int hpixels_per_column) { /* validate arguments */ assert(hpixels_per_column > 0); if (hpixels_per_column != m_hpixels_per_column) { m_hpixels_per_column = hpixels_per_column; recompute_parameters(true); } } void crtc_ega_device::update_cursor_state() { /* save and increment cursor counter */ uint8_t last_cursor_blink_count = m_cursor_blink_count; m_cursor_blink_count = m_cursor_blink_count + 1; /* switch on cursor blinking mode */ switch (m_cursor_start_ras & 0x60) { /* always on */ case 0x00: m_cursor_state = true; break; /* always off */ case 0x20: m_cursor_state = false; break; /* fast blink */ case 0x40: if ((last_cursor_blink_count & 0x10) != (m_cursor_blink_count & 0x10)) { m_cursor_state = !m_cursor_state; } break; /* slow blink */ case 0x60: if ((last_cursor_blink_count & 0x20) != (m_cursor_blink_count & 0x20)) { m_cursor_state = !m_cursor_state; } break; } } uint32_t crtc_ega_device::screen_update(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect) { assert(bitmap.valid()); if (m_has_valid_parameters) { uint16_t y; assert(!m_row_update_cb.isnull()); /* call the set up function if any */ if (!m_begin_update_cb.isnull()) m_begin_update_cb(bitmap, cliprect); if (cliprect.min_y == 0) { /* read the start address at the beginning of the frame */ m_current_disp_addr = m_disp_start_addr; } /* for each row in the visible region */ for (y = cliprect.min_y; y <= cliprect.max_y; y++) { /* compute the current raster line */ uint8_t ra = y % (m_max_ras_addr + 1); /* check if the cursor is visible and is on this scanline */ int cursor_visible = m_cursor_state && (ra >= (m_cursor_start_ras & 0x1f)) && ( (ra <= (m_cursor_end_ras & 0x1f)) || ((m_cursor_end_ras & 0x1f) == 0x00 )) && (m_cursor_addr >= m_current_disp_addr) && (m_cursor_addr < (m_current_disp_addr + ( m_horiz_disp + 1 ))); /* compute the cursor X position, or -1 if not visible */ int8_t cursor_x = cursor_visible ? (m_cursor_addr - m_current_disp_addr) : -1; /* call the external system to draw it */ m_row_update_cb(bitmap, cliprect, m_current_disp_addr, ra, y, m_horiz_disp + 1, cursor_x); /* update MA if the last raster address */ if (ra == m_max_ras_addr) m_current_disp_addr = (m_current_disp_addr + m_horiz_disp + 1) & 0xffff; } /* call the tear down function if any */ if (!m_end_update_cb.isnull()) m_end_update_cb(bitmap, cliprect); } else logerror("Invalid crtc_ega screen parameters - display disabled!!!\n"); return 0; } /* device interface */ void crtc_ega_device::device_start() { /* validate arguments */ assert(m_clock > 0); assert(m_hpixels_per_column > 0); /* resolve callbacks */ m_res_out_de_cb.resolve(); m_res_out_hsync_cb.resolve(); m_res_out_vsync_cb.resolve(); m_res_out_vblank_cb.resolve(); /* bind delegates */ m_begin_update_cb.bind_relative_to(*owner()); m_row_update_cb.bind_relative_to(*owner()); m_end_update_cb.bind_relative_to(*owner()); /* create the timers */ m_line_timer = timer_alloc(TIMER_LINE); m_de_off_timer = timer_alloc(TIMER_DE_OFF); m_cur_on_timer = timer_alloc(TIMER_CUR_ON); m_cur_off_timer = timer_alloc(TIMER_CUR_OFF); m_hsync_on_timer = timer_alloc(TIMER_HSYNC_ON); m_hsync_off_timer = timer_alloc(TIMER_HSYNC_OFF); m_light_pen_latch_timer = timer_alloc(TIMER_LIGHT_PEN_LATCH); /* Use some large startup values */ m_horiz_char_total = 0xff; m_max_ras_addr = 0x1f; m_vert_total = 0x3ff; m_ena_vert_access = 0; m_de_skew = 0; m_horiz_retr_start = 0; m_horiz_retr_end = 0; m_horiz_retr_skew = 0; m_preset_row_scan = 0; m_byte_panning = 0; m_scan_doubling = 0; m_cursor_start_ras = 0x20; m_cursor_disable = 0; m_cursor_end_ras = 0; m_cursor_skew = 0; m_disp_start_addr = 0; m_light_pen_addr = 0; m_vert_retr_end = 0; m_protect = 0; m_bandwidth = 0; m_offset = 0; m_underline_loc = 0; m_vert_blank_end = 0; m_mode_control = 0; m_line_compare = 0; m_register_address_latch = 0; m_cursor_state = false; m_cursor_blink_count = 0; m_cur = 0; m_hsync = 0; m_vsync = 0; m_vblank = 0; m_de = 0; m_character_counter = 0; m_hsync_width_counter = 0; m_vsync_width_counter = 0; m_line_enable_ff = false; m_vsync_ff = 0; m_adjust_active = 0; m_current_disp_addr = 0; m_light_pen_latched = false; m_has_valid_parameters = false; /* register for state saving */ save_item(NAME(m_hpixels_per_column)); save_item(NAME(m_register_address_latch)); save_item(NAME(m_horiz_char_total)); save_item(NAME(m_horiz_disp)); save_item(NAME(m_horiz_blank_start)); save_item(NAME(m_mode_control)); save_item(NAME(m_cursor_start_ras)); save_item(NAME(m_cursor_end_ras)); save_item(NAME(m_disp_start_addr)); save_item(NAME(m_cursor_addr)); save_item(NAME(m_light_pen_addr)); save_item(NAME(m_light_pen_latched)); save_item(NAME(m_cursor_state)); save_item(NAME(m_cursor_blink_count)); save_item(NAME(m_horiz_blank_end)); save_item(NAME(m_ena_vert_access)); save_item(NAME(m_de_skew)); save_item(NAME(m_horiz_retr_start)); save_item(NAME(m_horiz_retr_end)); save_item(NAME(m_horiz_retr_skew)); save_item(NAME(m_vert_total)); save_item(NAME(m_preset_row_scan)); save_item(NAME(m_byte_panning)); save_item(NAME(m_max_ras_addr)); save_item(NAME(m_scan_doubling)); save_item(NAME(m_cursor_disable)); save_item(NAME(m_cursor_skew)); save_item(NAME(m_vert_retr_start)); save_item(NAME(m_vert_retr_end)); save_item(NAME(m_protect)); save_item(NAME(m_bandwidth)); save_item(NAME(m_vert_disp_end)); save_item(NAME(m_offset)); save_item(NAME(m_underline_loc)); save_item(NAME(m_vert_blank_start)); save_item(NAME(m_vert_blank_end)); save_item(NAME(m_line_compare)); } void crtc_ega_device::device_reset() { /* internal registers other than status remain unchanged, all outputs go low */ if (!m_res_out_de_cb.isnull()) m_res_out_de_cb(false); if (!m_res_out_hsync_cb.isnull()) m_res_out_hsync_cb(false); if (!m_res_out_vsync_cb.isnull()) m_res_out_vsync_cb(false); if (!m_res_out_vblank_cb.isnull()) m_res_out_vblank_cb(false); if (!m_line_timer->enabled()) { m_line_timer->adjust( attotime::from_ticks( m_horiz_char_total + 2, m_clock ) ); } m_light_pen_latched = false; m_cursor_addr = 0; m_line_address = 0; m_horiz_disp = 0; m_cursor_x = 0; m_horiz_blank_start = 0; m_horiz_blank_end = 0; m_vert_disp_end = 0; m_vert_retr_start = 0; m_vert_blank_start = 0; m_line_counter = 0; m_raster_counter = 0; m_horiz_pix_total = 0; m_vert_pix_total = 0; m_max_visible_x = 0; m_max_visible_y = 0; m_hsync_on_pos = 0; m_vsync_on_pos = 0; m_hsync_off_pos = 0; m_vsync_off_pos = 0; }
28.630376
189
0.698465
rjw57
01f0f92c693e278ef12940fe1e794e25c7bc05bb
1,518
cpp
C++
epcforedge/lte/backend/utils/framework/PostRequestDispatcher.cpp
Rajpratik71/native-on-prem
aebaf74c8a54e8d0c24c53c1126e97971dd84e9f
[ "Apache-2.0" ]
14
2019-09-25T14:20:35.000Z
2021-09-20T13:34:21.000Z
epcforedge/lte/backend/utils/framework/PostRequestDispatcher.cpp
Rajpratik71/native-on-prem
aebaf74c8a54e8d0c24c53c1126e97971dd84e9f
[ "Apache-2.0" ]
4
2019-09-27T16:34:00.000Z
2020-09-30T18:24:08.000Z
epcforedge/lte/backend/utils/framework/PostRequestDispatcher.cpp
Rajpratik71/native-on-prem
aebaf74c8a54e8d0c24c53c1126e97971dd84e9f
[ "Apache-2.0" ]
14
2019-09-26T02:13:39.000Z
2021-09-08T09:36:21.000Z
/* SPDX-License-Identifier: Apache-2.0 * Copyright (c) 2019 Intel Corporation */ /** * @file PostRequestDispatcher.cpp * @brief POST method and JSON formatted request dispatcher. ********************************************************************/ #include "PostRequestDispatcher.h" #include "Exception.h" #include "Log.h" void PostRequestDispatcher::dispatchRequest(const string &action, Json::Value &request, Json::Value &response, map<string, string> &headers, map<string, string> &cookies) { OAMAGENT_LOG(INFO, "PostRequestDispatcher with action %s.\n", action.c_str()); if (!action.length()) { OAMAGENT_LOG(ERR, "Dispatch failed.\n"); throw Exception(Exception::DISPATCH_NOTARGET, "Dispatch failed"); } if (requestHandlers.find(action) != requestHandlers.end()) { OAMAGENT_LOG(INFO, "PostRequestDispatcher Find execute handler for the action %s.\n", action.c_str()); static_cast<PostRequestHandler *>(requestHandlers[action])->execute(request, response, headers, cookies); return; } OAMAGENT_LOG(ERR, "Dispatch failed, action: %s.\n", action.c_str()); throw Exception(Exception::DISPATCH_NOTARGET, "Dispatch failed"); } void PostRequestDispatcher::registerHandler(const string &action, PostRequestHandler &handler) { requestHandlers[action] = &handler; }
37.95
113
0.601449
Rajpratik71
01f1e2131441fd254cd167fc079ad21c51e617d4
2,874
hpp
C++
stapl_release/stapl/containers/graph/generators/watts_strogatz_stable.hpp
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
stapl_release/stapl/containers/graph/generators/watts_strogatz_stable.hpp
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
stapl_release/stapl/containers/graph/generators/watts_strogatz_stable.hpp
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
/* // Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a // component of the Texas A&M University System. // All rights reserved. // The information and source code contained herein is the exclusive // property of TEES and may not be disclosed, examined or reproduced // in whole or in part without explicit written authorization from TEES. */ #ifndef STAPL_CONTAINERS_GRAPH_GENERATORS_WS_STABLE_HPP #define STAPL_CONTAINERS_GRAPH_GENERATORS_WS_STABLE_HPP namespace stapl { namespace generators { ////////////////////////////////////////////////////////////////////// /// @brief A stable implementation of watts_strogatz that generates the /// the same random Watts-Strogatz graph for a specified number of /// simulated processors (irrespective to the actual number of processes /// being run on). /// /// @todo Need to fix the stability of @ref ws_rewire and use /// @ref make_watts_strogatz instead. ////////////////////////////////////////////////////////////////////// template<typename G> struct watts_strogatz_stable { protected: G& m_graph; size_t m_n; size_t m_k; double m_p; public: watts_strogatz_stable(G& g, size_t k, double p) : m_graph(g), m_n(g.size()), m_k(k), m_p(p) { } void add_edges(size_t simulated_procs) { size_t p_per = simulated_procs/get_num_locations(); size_t p_start = get_location_id()*p_per; size_t p_end = p_start + p_per; size_t block_size = m_n/simulated_procs; //simulate each processor //(in the loop, p := get_simulated_location_id() and // simulated_procs := get_num_simulated_locations()) for (size_t p = p_start; p < p_end; ++p) { srand48((p+65)*4321); size_t subview_start = block_size*p; size_t subview_end = subview_start+block_size; for (size_t i=subview_start; i<subview_end; ++i) { std::set<size_t> dests; for (size_t k=1; k<m_k/2+1; ++k) { size_t j = (i+k)%m_n; // if we draw a good prob, just add the edge // (there is a chance we already randomly added the edge; // in this case, we should redo the random rewiring) // otherwise, randomly "rewire" the edge if (drand48() >= m_p) { if (!dests.insert(j).second) { while (!dests.insert(generate_random(i)).second); } } else { while (!dests.insert(generate_random(i)).second); } } for (auto&& d : dests) { m_graph.add_edge_async(i, d); } } } } size_t generate_random(size_t source) { size_t dest = drand48()*m_n; while (dest == source) { dest = drand48()*m_n; } return dest; } }; } // namespace generators } // namespace stapl #endif
29.628866
74
0.59325
parasol-ppl
01f4535fe1ba18c4e6e9a9c39a8e769992b73dc8
1,796
cpp
C++
source/ff.graphics/source/sprite_data.cpp
spadapet/ff_game_library
f1bf00f90adde66c2c2aa35b109fe61b8d2c6352
[ "MIT" ]
null
null
null
source/ff.graphics/source/sprite_data.cpp
spadapet/ff_game_library
f1bf00f90adde66c2c2aa35b109fe61b8d2c6352
[ "MIT" ]
null
null
null
source/ff.graphics/source/sprite_data.cpp
spadapet/ff_game_library
f1bf00f90adde66c2c2aa35b109fe61b8d2c6352
[ "MIT" ]
null
null
null
#include "pch.h" #include "sprite_data.h" #include "sprite_type.h" #include "texture.h" #include "texture_view_base.h" ff::sprite_data::sprite_data() : view_(nullptr) , texture_uv_(0, 0, 0, 0) , world_(0, 0, 0, 0) , type_(ff::sprite_type::unknown) {} ff::sprite_data::sprite_data( ff::texture_view_base* view, ff::rect_float texture_uv, ff::rect_float world, ff::sprite_type type) : view_(view) , texture_uv_(texture_uv) , world_(world) , type_((type == ff::sprite_type::unknown && view) ? view->view_texture()->sprite_type() : type) {} ff::sprite_data::sprite_data( ff::texture_view_base* view, ff::rect_float rect, ff::point_float handle, ff::point_float scale, ff::sprite_type type) : view_(view) , texture_uv_(rect / view->view_texture()->size().cast<float>()) , world_(-handle * scale, (rect.size() - handle) * scale) , type_((type == ff::sprite_type::unknown && view) ? view->view_texture()->sprite_type() : type) {} ff::sprite_data::operator bool() const { return this->view_ != nullptr; } ff::texture_view_base* ff::sprite_data::view() const { return this->view_; } const ff::rect_float& ff::sprite_data::texture_uv() const { return this->texture_uv_; } const ff::rect_float& ff::sprite_data::world() const { return this->world_; } ff::sprite_type ff::sprite_data::type() const { return this->type_; } ff::rect_float ff::sprite_data::texture_rect() const { return (this->texture_uv_ * this->view_->view_texture()->size().cast<float>()).normalize(); } ff::point_float ff::sprite_data::scale() const { return this->world_.size() / this->texture_rect().size(); } ff::point_float ff::sprite_data::handle() const { return -this->world_.top_left() / this->scale(); }
23.631579
100
0.6598
spadapet
01f632d1d57e41207b8bb8076ddfbf3aa306bd4f
1,564
cpp
C++
bark/src/JSObject.cpp
Daivuk/onut
b02c5969b36897813de9c574a26d9437b67f189e
[ "MIT" ]
50
2015-06-01T19:23:24.000Z
2021-12-22T02:14:23.000Z
bark/src/JSObject.cpp
Daivuk/onut
b02c5969b36897813de9c574a26d9437b67f189e
[ "MIT" ]
109
2015-07-20T07:43:03.000Z
2021-01-31T21:52:36.000Z
bark/src/JSObject.cpp
Daivuk/onut
b02c5969b36897813de9c574a26d9437b67f189e
[ "MIT" ]
9
2015-07-02T21:36:20.000Z
2019-10-19T04:18:02.000Z
#include "JSObject.h" #include <JSBindings_Macros.h> namespace onut { namespace js { extern duk_context* pContext; // Haxor. This context already contains all standard onut bindings void newUI(duk_context* ctx, const OUIControlRef& pUIControl); } } using namespace onut::js; void* JSObject::js_objects_heap_ptr = nullptr; uint64_t JSObject::next_script_unique_id = 0; void JSObject::initJSObjects() { auto ctx = pContext; // Create empty js object duk_push_object(ctx); duk_put_global_string(ctx, "___js_objects"); // Get it's heap ptr duk_get_global_string(ctx, "___js_objects"); js_objects_heap_ptr = duk_get_heapptr(ctx, -1); duk_pop(ctx); } void JSObject::initJSObject(void* prototype) { js_global_name = "obj_" + std::to_string(next_script_unique_id++); auto ctx = pContext; duk_push_heapptr(ctx, js_objects_heap_ptr); // Create empty js object duk_push_object(ctx); duk_push_pointer(ctx, this); duk_put_prop_string(ctx, -2, "\xff""\xff""data"); if (prototype) { duk_push_heapptr(ctx, prototype); duk_set_prototype(ctx, -2); } duk_put_prop_string(ctx, -2, js_global_name.c_str()); // Get it's heap ptr duk_get_prop_string(ctx, -1, js_global_name.c_str()); js_object = duk_get_heapptr(ctx, -1); duk_pop(ctx); duk_pop(ctx); } JSObject::~JSObject() { auto ctx = pContext; duk_push_heapptr(ctx, js_objects_heap_ptr); duk_del_prop_string(ctx, -1, js_global_name.c_str()); duk_pop(ctx); }
22.666667
104
0.679668
Daivuk
bf082e2a8eed1927b58ebabfbe16d6f45ddb8ac9
51,313
cpp
C++
src/CGL.cpp
colinw7/CGL
8cc10d66173364bd7b54f3412aecd8c22d1bea30
[ "MIT" ]
null
null
null
src/CGL.cpp
colinw7/CGL
8cc10d66173364bd7b54f3412aecd8c22d1bea30
[ "MIT" ]
null
null
null
src/CGL.cpp
colinw7/CGL
8cc10d66173364bd7b54f3412aecd8c22d1bea30
[ "MIT" ]
null
null
null
#include <CGL.h> #include <CGLDisplayList.h> #include <CGLWind.h> #include <CFuncs.h> #include <COSTimer.h> #include <CMathGen.h> #include <CPoint3D.h> #include <CTriangle3D.h> #include <CXMachine.h> #include <CXLibPixelRenderer.h> #include <CImagePixelRenderer.h> #include <CGeomUtil3D.h> #include <CMathRound.h> #include <CStrUtil.h> #include <climits> class CGLEventAdapter : public CXEventAdapter { public: bool idleEvent(); }; //------------------- CGLMgr:: CGLMgr() : current_window_ (NULL), current_window_id_(0), window_rect_ (0,0,300,300), error_num_ (GL_NO_ERROR) { } CGLMgr:: ~CGLMgr() { WindowMap::iterator p1 = window_map_.begin(); WindowMap::iterator p2 = window_map_.end(); for ( ; p1 != p2; ++p1) delete (*p1).second; } CGL * CGLMgr:: getCurrentGL() const { if (current_window_) return current_window_->getGL(); else return NULL; } void CGLMgr:: setWindowPosition(const CIPoint2D &point) { window_rect_.setPosition(point); if (current_window_) current_window_->setPosition(point); } CIPoint2D CGLMgr:: getWindowPosition() const { if (current_window_) return current_window_->getPosition(); else return CIPoint2D(0,0); } void CGLMgr:: setWindowSize(const CISize2D &size) { window_rect_.setSize(size); if (current_window_) current_window_->setSize(size); } CISize2D CGLMgr:: getWindowSize() const { if (current_window_) return current_window_->getSize(); else return CISize2D(1,1); } void CGLMgr:: createWindow(const std::string &name) { int x = window_rect_.getXMin (); int y = window_rect_.getYMin (); int w = window_rect_.getWidth (); int h = window_rect_.getHeight(); if (w <= 0) w = 300; if (h <= 0) h = 300; current_window_ = new CGLWind(x, y, w, h); current_window_->setTitle(name); window_map_[++current_window_id_] = current_window_; current_window_->setId(current_window_id_); } void CGLMgr:: createSubWindow(int window, int x, int y, int width, int height) { CGLWind *parent = window_map_[window]; current_window_ = new CGLWind(parent, x, y, width, height); window_map_[++current_window_id_] = current_window_; current_window_->setId(current_window_id_); } void CGLMgr:: deleteWindow(int window) { WindowMap::iterator p1 = window_map_.find(window); WindowMap::iterator p2 = window_map_.end(); if (p1 != p2) { delete (*p1).second; window_map_.erase(p1); } } uint CGLMgr:: getCurrentWindowId() { return current_window_id_; } uint CGLMgr:: setCurrentWindowId(uint window) { std::swap(current_window_id_, window); current_window_ = window_map_[current_window_id_]; return window; } CGLWind * CGLMgr:: getWindowFromId(uint window) const { WindowMap::const_iterator p1 = window_map_.find(window); WindowMap::const_iterator p2 = window_map_.end(); if (p1 != p2) return (*p1).second; else return NULL; } void CGLMgr:: mainLoop() { CGLEventAdapter adapter; CXMachineInst->setEventAdapter(&adapter); CXMachineInst->mainLoop(); } void CGLMgr:: unimplemented(const std::string &proc) { std::cerr << proc << " Unimplemented" << std::endl; } //------------------- CGL:: CGL(CGLWind *window) : window_ (window), viewport_ (0.0,0.0,0.0,1.0,1.0,1.0), color_buffer_ (NULL), render_mode_ (GL_RENDER), bg_ (0.0, 0.0, 0.0, 1.0), lighting_ (false), flat_shading_ (false), line_width_ (1.0), current_display_list_ (NULL), matrix_mode_ (GL_MODELVIEW), double_buffer_ (true), point_size_ (1.0), depth_near_ (0.0), depth_far_ (1.0), dither_ (false), line_stipple_ (false), line_smooth_ (false), line_smooth_hint_ (GL_DONT_CARE), poly_offset_fill_ (false), poly_stipple_ (false), poly_smooth_ (false), poly_offset_factor_ (0.0), poly_offset_units_ (0.0), front_face_mode_ (GL_FILL), back_face_mode_ (GL_FILL), fog_enabled_ (false), fog_hint_ (GL_DONT_CARE), block_type_ (-1), list_base_ (0), raster_pos_ (NULL, CPoint3D(0,0,0)), color_table_enabled_ (false), convolution_2d_enabled_(false), histogram_enabled_ (false), minmax_enabled_ (false), pixel_zoom_x_ (1), pixel_zoom_y_ (1), texture_next_ind_ (2) { color_buffer_ = new CGLColorBuffer(this); model_view_matrix_stack_ .push_back(CMatrix3DH::newIdentityMatrix()); model_view_imatrix_stack_.push_back(CMatrix3DH::newIdentityMatrix()); projection_matrix_stack_ .push_back(CMatrix3DH::newIdentityMatrix()); projection_imatrix_stack_.push_back(CMatrix3DH::newIdentityMatrix()); texture_matrix_stack_ .push_back(CMatrix3DH::newIdentityMatrix()); color_matrix_stack_ .push_back(CMatrix3DH::newIdentityMatrix()); initLights(); initMaterials(); } CGL:: ~CGL() { for (int i = 0; i < NUM_LIGHTS; ++i) delete lights_[i]; delete color_buffer_; } void CGL:: initLights() { for (int i = 0; i < NUM_LIGHTS; ++i) lights_.push_back(new CGeomLight3D(NULL)); for (int i = 0; i < NUM_LIGHTS; ++i) { lights_[i]->setEnabled(false); lights_[i]->getObject()->moveTo(CPoint3D(0, 0, 1)); lights_[i]->setAmbient (CRGBA(0,0,0)); lights_[i]->setDiffuse (CRGBA(0,0,0)); lights_[i]->setSpecular (CRGBA(0,0,0)); lights_[i]->setPosition (CPoint3D(0,0,1)); lights_[i]->setSpotDirection (CVector3D(0,0,-1)); lights_[i]->setSpotExponent (0); lights_[i]->setSpotCutOff (180); lights_[i]->setDirectional (true); lights_[i]->setConstantAttenuation (1); lights_[i]->setLinearAttenuation (0); lights_[i]->setQuadraticAttenuation(0); } lights_[0]->setDiffuse (CRGBA(1,1,1)); lights_[0]->setSpecular(CRGBA(1,1,1)); } void CGL:: initMaterials() { front_material_.init(); back_material_ .init(); } void CGL:: setDoubleBuffer(bool flag) { double_buffer_ = flag; } void CGL:: setLighting(bool flag) { lighting_ = flag; } void CGL:: setBackground(const CRGBA &bg) { if (executeCommand()) bg_ = bg; if (inDisplayList()) getCurrentDisplayList()->setBackground(bg); } void CGL:: setForeground(const CRGBA &fg) { if (executeCommand()) { fg_ = fg; //front_material_.material.setAmbient(fg); //front_material_.material.setDiffuse(fg); } if (inDisplayList()) getCurrentDisplayList()->setForeground(fg); } void CGL:: setNormal(const CVector3D &normal) { if (executeCommand()) normal_ = normal; if (inDisplayList()) getCurrentDisplayList()->setNormal(normal); } void CGL:: setTexCoord(const CPoint3D &point) { if (executeCommand()) tmap_ = point; if (inDisplayList()) getCurrentDisplayList()->setTexCoord(point); } void CGL:: setMaterial(uint face, uint pname, double param) { if (executeCommand()) { if (pname == GL_SHININESS) { if (face == GL_FRONT || face == GL_FRONT_AND_BACK) setFrontMaterialShininess(param); if (face == GL_BACK || face == GL_FRONT_AND_BACK) setBackMaterialShininess(param); } else CGLMgrInst->setErrorNum(GL_INVALID_ENUM); } if (inDisplayList()) getCurrentDisplayList()->setMaterial(face, pname, param); } void CGL:: setMaterialV(uint face, uint pname, double *params, uint num_params) { if (executeCommand()) { if (pname == GL_AMBIENT) { if (face == GL_FRONT || face == GL_FRONT_AND_BACK) setFrontMaterialAmbient( CRGBA(params[0], params[1], params[2], params[3])); if (face == GL_BACK || face == GL_FRONT_AND_BACK) setBackMaterialAmbient( CRGBA(params[0], params[1], params[2], params[3])); } else if (pname == GL_DIFFUSE) { if (face == GL_FRONT || face == GL_FRONT_AND_BACK) setFrontMaterialDiffuse( CRGBA(params[0], params[1], params[2], params[3])); if (face == GL_BACK || face == GL_FRONT_AND_BACK) setBackMaterialDiffuse( CRGBA(params[0], params[1], params[2], params[3])); } else if (pname == GL_SPECULAR) { if (face == GL_FRONT || face == GL_FRONT_AND_BACK) setFrontMaterialSpecular( CRGBA(params[0], params[1], params[2], params[3])); if (face == GL_BACK || face == GL_FRONT_AND_BACK) setBackMaterialSpecular( CRGBA(params[0], params[1], params[2], params[3])); } else if (pname == GL_EMISSION) { if (face == GL_FRONT || face == GL_FRONT_AND_BACK) setFrontMaterialEmission( CRGBA(params[0], params[1], params[2], params[3])); if (face == GL_BACK || face == GL_FRONT_AND_BACK) setBackMaterialEmission( CRGBA(params[0], params[1], params[2], params[3])); } else if (pname == GL_SHININESS) { if (face == GL_FRONT || face == GL_FRONT_AND_BACK) setFrontMaterialShininess(params[0]); if (face == GL_BACK || face == GL_FRONT_AND_BACK) setFrontMaterialShininess(params[0]); } else if (pname == GL_AMBIENT_AND_DIFFUSE) { if (face == GL_FRONT || face == GL_FRONT_AND_BACK) { setFrontMaterialAmbient( CRGBA(params[0], params[1], params[2], params[3])); setFrontMaterialDiffuse( CRGBA(params[0], params[1], params[2], params[3])); } if (face == GL_BACK || face == GL_FRONT_AND_BACK) { setBackMaterialAmbient( CRGBA(params[0], params[1], params[2], params[3])); setBackMaterialDiffuse( CRGBA(params[0], params[1], params[2], params[3])); } } else if (pname == GL_COLOR_INDEXES) { if (face == GL_FRONT || face == GL_FRONT_AND_BACK) { setFrontMaterialAmbientInd ((int) params[0]); setFrontMaterialDiffuseInd ((int) params[1]); setFrontMaterialSpecularInd((int) params[2]); } if (face == GL_BACK || face == GL_FRONT_AND_BACK) { setBackMaterialAmbientInd ((int) params[0]); setBackMaterialDiffuseInd ((int) params[1]); setBackMaterialSpecularInd((int) params[2]); } } else CGLMgrInst->setErrorNum(GL_INVALID_ENUM); } if (inDisplayList()) getCurrentDisplayList()->setMaterialV(face, pname, params, num_params); } void CGL:: beginBlock(int mode) { if (executeCommand()) { block_type_ = mode; for_each(block_points_.begin(), block_points_.end(), CDeletePointer()); block_points_.clear(); } if (inDisplayList()) getCurrentDisplayList()->beginBlock(mode); } void CGL:: endBlock() { if (executeCommand()) { if (block_type_ == GL_POINTS) { VertexList::iterator p1 = block_points_.begin(); VertexList::iterator p2 = block_points_.end (); for ( ; p1 != p2; ++p1) drawPoint(*p1); } else if (block_type_ == GL_LINES) { int num_lines = block_points_.size()/2; VertexList::iterator p2 = block_points_.begin(); //VertexList::iterator p3 = block_points_.end (); for (int i = 0; i < num_lines; ++i) { VertexList::iterator p1 = p2++; drawLine(*p1, *p2, i == 0); ++p2; } } else if (block_type_ == GL_LINE_STRIP) { int num_lines = 0; if (block_points_.size() >= 2) num_lines = block_points_.size() - 1; VertexList::iterator p2 = block_points_.begin(); //VertexList::iterator p3 = block_points_.end (); for (int i = 0; i < num_lines; ++i) { VertexList::iterator p1 = p2++; drawLine(*p1, *p2, i == 0); } } else if (block_type_ == GL_LINE_LOOP) { if (block_points_.size() <= 2) return; VertexList::iterator p2 = block_points_.begin(); VertexList::iterator p1 = p2++; VertexList::iterator p3 = block_points_.end (); for (int i = 0; p2 != p3; p1 = p2, ++p2, ++i) drawLine(*p1, *p2, i == 0); p2 = block_points_.begin(); if (p2 != p3) drawLine(*p1, *p2, false); } else if (block_type_ == GL_TRIANGLES) { uint num = block_points_.size() / 3; VertexList points; VertexList::iterator p3 = block_points_.begin(); for (uint i = 0; i < num; ++i) { VertexList::iterator p1 = p3++; VertexList::iterator p2 = p3++; points.clear(); points.push_back(*p1); points.push_back(*p2); points.push_back(*p3); drawPolygon(block_type_, points); ++p3; } } else if (block_type_ == GL_TRIANGLE_STRIP) { if (block_points_.size() <= 2) return; uint num = block_points_.size() - 2; VertexList points; VertexList::iterator p3 = block_points_.begin(); VertexList::iterator p1 = p3++; VertexList::iterator p2 = p3++; for (uint i = 1; i <= num; ++i) { points.clear(); if (i & 1) { points.push_back(*p1); points.push_back(*p2); points.push_back(*p3); } else { points.push_back(*p2); points.push_back(*p1); points.push_back(*p3); } drawPolygon(block_type_, points); p1 = p2; p2 = p3++; } } else if (block_type_ == GL_TRIANGLE_FAN) { if (block_points_.size() <= 2) return; uint num = block_points_.size() - 2; VertexList points; VertexList::iterator p3 = block_points_.begin(); VertexList::iterator p1 = p3++; VertexList::iterator p2 = p3++; for (uint i = 1; i <= num; ++i) { points.clear(); points.push_back(*p1); points.push_back(*p2); points.push_back(*p3); drawPolygon(block_type_, points); p2 = p3++; } } else if (block_type_ == GL_QUADS) { uint num = block_points_.size() / 4; VertexList points; VertexList::iterator p4 = block_points_.begin(); for (uint i = 0; i < num; ++i) { VertexList::iterator p1 = p4++; VertexList::iterator p2 = p4++; VertexList::iterator p3 = p4++; points.clear(); points.push_back(*p1); points.push_back(*p2); points.push_back(*p3); points.push_back(*p4); drawPolygon(block_type_, points); ++p4; } } else if (block_type_ == GL_QUAD_STRIP) { if (block_points_.size() < 4) return; uint num = block_points_.size()/2 - 1; VertexList points; VertexList::iterator p4 = block_points_.begin(); for (uint i = 0; i < num; ++i) { VertexList::iterator p1 = p4++; VertexList::iterator p2 = p4++; VertexList::iterator p3 = p4++; points.clear(); points.push_back(*p1); points.push_back(*p2); points.push_back(*p4); points.push_back(*p3); drawPolygon(block_type_, points); p4 = p3; } } else if (block_type_ == GL_POLYGON) drawPolygon(block_type_, block_points_); for_each(block_points_.begin(), block_points_.end(), CDeletePointer()); block_points_.clear(); block_type_ = -1; } if (inDisplayList()) getCurrentDisplayList()->endBlock(); } bool CGL:: inBlock() { return (block_type_ != -1); } void CGL:: addBlockPoint(const CPoint3D &point) { if (executeCommand()) { CGeomVertex3D *vertex = new CGeomVertex3D(NULL, point); if (getForegroundSet()) vertex->setColor(getForeground()); else vertex->setColor(CRGBA(1,1,1)); if (getNormalSet()) vertex->setNormal(getNormal()); if (getTexCoordSet()) vertex->setTextureMap(getTexCoord()); block_points_.push_back(vertex); } if (inDisplayList()) getCurrentDisplayList()->addBlockPoint(point); } void CGL:: addBlockPoint(const CPoint3D &point, const CRGBA &rgba, const CVector3D &normal, const CPoint3D &tmap) { CGeomVertex3D *vertex = new CGeomVertex3D(NULL, point); vertex->setColor (rgba); vertex->setNormal (normal); vertex->setTextureMap(tmap); block_points_.push_back(vertex); } void CGL:: addBlockPoint(const CPoint3D &point, const COptValT<CRGBA> &rgba, const COptValT<CVector3D> &normal, const COptValT<CPoint3D> &tmap) { if (executeCommand()) { CGeomVertex3D *vertex = new CGeomVertex3D(NULL, point); if (rgba.isValid()) vertex->setColor(rgba.getValue()); else vertex->setColor(CRGBA(1,1,1)); if (normal.isValid()) vertex->setNormal(normal.getValue()); if (tmap.isValid()) vertex->setTextureMap(tmap.getValue()); block_points_.push_back(vertex); } if (inDisplayList()) getCurrentDisplayList()->addBlockPoint(point); } void CGL:: updateRasterPos(const CPoint3D &point) { raster_pos_.setModel(point); if (getForegroundSet()) raster_pos_.setColor(getForeground()); else raster_pos_.setColor(CRGBA(1,1,1)); if (getNormalSet()) raster_pos_.setNormal(getNormal()); if (getTexCoordSet()) raster_pos_.setTextureMap(getTexCoord()); transformVertex(&raster_pos_); } void CGL:: drawPoint(CGeomVertex3D *vertex) { // transform point transformVertex(vertex); //------- // transform point if (vertex->getClipSide() == CCLIP_SIDE_OUTSIDE) return; //------- if (getRenderMode() == GL_FEEDBACK) { float data[2]; CGLFeedbackBuffer &feedback = modifyFeedbackBuffer(); data[0] = GL_POINT_TOKEN; feedback.append(data, 1); feedback.append(vertex); return; } #if 0 else if (getRenderMode() == GL_SELECT) { float data[2]; CGLSelectBuffer &select = modifySelectBuffer(); select.append(names); return; } #endif //------- const CPoint3D &point = vertex->getPixel(); const CPoint3D &viewed = vertex->getViewed(); CGLColorBuffer::Point bpoint(point.z, vertex->getColor(), vertex->getVNormal(), vertex->getTextureMap()); if (point_size_ > 1.5) { uint diameter = CMathRound::Round(point_size_); uint radius = diameter >> 1; uint radius2 = radius*radius; if (diameter & 1) { for (uint x = uint(point.x) - radius; x < uint(point.x) + radius; ++x) getColorBuffer().setPoint(x, uint(point.y), bpoint, viewed.z); } for (uint y = 1; y <= radius; ++y) { uint width = CMathRound::Round(sqrt(radius2 - y*y)); for (uint x = uint(point.x) - width; x < uint(point.x) + width; ++x) { getColorBuffer().setPoint(x, uint(point.y) + y, bpoint, viewed.z); getColorBuffer().setPoint(x, uint(point.y) - y, bpoint, viewed.z); } } } else { getColorBuffer().setPoint(uint(point.x), uint(point.y), bpoint, viewed.z); } } void CGL:: drawLine(CGeomVertex3D *vertex1, CGeomVertex3D *vertex2, bool first) { // transform vertices transformVertex(vertex1); transformVertex(vertex2); //------- // clip line (TODO - partial clip) if (vertex1->getClipSide() == CCLIP_SIDE_OUTSIDE && vertex2->getClipSide() == CCLIP_SIDE_OUTSIDE) return; //------- if (getRenderMode() == GL_FEEDBACK) { float data[2]; CGLFeedbackBuffer &feedback = modifyFeedbackBuffer(); data[0] = first ? GL_LINE_RESET_TOKEN : GL_LINE_TOKEN; feedback.append(data, 1); feedback.append(vertex1); feedback.append(vertex2); return; } #if 0 else if (getRenderMode() == GL_SELECT) { float data[2]; CGLSelectBuffer &select = modifySelectBuffer(); select.append(names); return; } #endif //------- // light line if (getLighting()) { CRGBA ambient = getLightModelAmbient(); const CMaterial &material = getFrontMaterial().material; CRGBA rgba = material.getEmission(); rgba += ambient*material.getAmbient(); std::vector<CGeomLight3D *>::const_iterator plight1 = lights_.begin(); std::vector<CGeomLight3D *>::const_iterator plight2 = lights_.end (); for ( ; plight1 != plight2; ++plight1) (*plight1)->lightPoint(rgba, vertex1->getViewed(), vertex1->getVNormal(), material); vertex1->setColor(rgba.clamp()); vertex2->setColor(rgba.clamp()); //getColorBuffer().setDefaultColor(rgba.clamp()); } // draw line getColorBuffer().setLineWidth(uint(getLineWidth())); if (getLineStipple()) getColorBuffer().setLineDash(getLineDash().getIDash()); else getColorBuffer().setLineDash(CILineDash()); // getColorBuffer().setAntiAlias(getLineSmooth()); getColorBuffer().drawLine(vertex1, vertex2); } void CGL:: drawPolygon(uint mode, const VertexList &vertices) { if (vertices.size() < 3) return; //---------- // transform vertices VertexList::const_iterator p1 = vertices.begin(); VertexList::const_iterator p2 = vertices.end (); for ( ; p1 != p2; ++p1) transformVertex(*p1); //------- // cull face (TODO - fix me !!!) CGLColorBuffer &color_buffer = getColorBuffer(); p1 = vertices.begin(); int min_x = 9999; int max_x = -9999; int min_y = 9999; int max_y = -9999; for ( ; p1 != p2; ++p1) { const CPoint3D &point = (*p1)->getPixel(); min_x = std::min(min_x, int(point.x)); min_y = std::min(min_y, int(point.y)); max_x = std::max(max_x, int(point.x)); max_y = std::max(max_y, int(point.y)); } if (max_x < 0 || max_y < 0 || min_x >= (int) color_buffer.getWidth () || min_y >= (int) color_buffer.getHeight()) return; if (getCullFace().getEnabled()) { const CPoint3D &point1 = vertices[0]->getPixel(); const CPoint3D &point2 = vertices[1]->getPixel(); const CPoint3D &point3 = vertices[2]->getPixel(); CTriangle3D triangle(point1, point2, point3); CPolygonOrientation orientation = triangle.orientationXY(); bool is_front = (orientation != getFrontFaceOrient()); if (is_front) { if (getCullFace().getFront()) return; } else { if (getCullFace().getBack()) return; } } //------- // Process Feedback and select if (getRenderMode() == GL_FEEDBACK) { float data[2]; CGLFeedbackBuffer &feedback = modifyFeedbackBuffer(); data[0] = GL_POLYGON_TOKEN; feedback.append(data, 1); VertexList::const_iterator pv1 = vertices.begin(); VertexList::const_iterator pv2 = vertices.end (); for ( ; pv1 != pv2; ++pv1) feedback.append(*pv1); return; } else if (getRenderMode() == GL_SELECT) { CGLSelectBuffer &select = modifySelectBuffer(); VertexList::const_iterator pv1 = vertices.begin(); VertexList::const_iterator pv2 = vertices.end (); int min_z = INT_MAX; int max_z = -INT_MAX; for ( ; pv1 != pv2; ++pv1) { const CPoint3D &point = (*pv1)->getProjected(); int iz = int(INT_MAX*((std::min(std::max(point.z, -1.0), 1.0) + 1)/2.0)); min_z = std::min(min_z, iz); max_z = std::max(max_z, iz); } const CGL::NameStack &stack = getNameStack(); CGL::NameStack::const_iterator pn1 = stack.begin(); CGL::NameStack::const_iterator pn2 = stack.end (); CGLSelectBuffer::NameList names; for ( ; pn1 != pn2; ++pn1) names.push_back(*pn1); select.addHit(min_z, max_z, names); return; } //------- // draw face CPoint3D mid_point; CVector3D normal; if (getLighting()) { CRGBA ambient = getLightModelAmbient(); if (getFlatShading()) { const CMaterial &material = getFrontMaterial().material; CRGBA rgba = material.getEmission(); rgba += ambient*material.getAmbient(); mid_point = CGeomUtil3D::getMidPoint(vertices); normal = CGeomUtil3D::getNormal (vertices); std::vector<CGeomLight3D *>::const_iterator plight1 = lights_.begin(); std::vector<CGeomLight3D *>::const_iterator plight2 = lights_.end (); for ( ; plight1 != plight2; ++plight1) (*plight1)->lightPoint(rgba, mid_point, normal, material); getColorBuffer().setDefaultColor(rgba.clamp()); } else { const CMaterial &material = getFrontMaterial().material; normal = CGeomUtil3D::getNormal(vertices); VertexList::const_iterator pv1 = vertices.begin(); VertexList::const_iterator pv2 = vertices.end (); for ( ; pv1 != pv2; ++pv1) { CRGBA rgba = material.getEmission(); rgba += ambient*material.getAmbient(); std::vector<CGeomLight3D *>::const_iterator plight1 = lights_.begin(); std::vector<CGeomLight3D *>::const_iterator plight2 = lights_.end (); for ( ; plight1 != plight2; ++plight1) { if ((*pv1)->getNormalSet()) (*plight1)->lightPoint(rgba, (*pv1)->getViewed(), (*pv1)->getVNormal(), material); else (*plight1)->lightPoint(rgba, (*pv1)->getViewed(), normal, material); } (*pv1)->setColor(rgba.clamp()); } } } else { // Default color is last vertex color except for // single polygon when it's the first (need mode) if (mode == GL_POLYGON) getColorBuffer().setDefaultColor(vertices.front()->getColor()); else getColorBuffer().setDefaultColor(vertices.back ()->getColor()); } if (getFrontFaceMode() == GL_FILL) { if (poly_offset_fill_) { double m = 1.0 ; // TODO calc polgon maximum depth slope double r = 1E-6; // TODO better value ? double dz = m*getPolyOffsetFactor() + r*getPolyOffsetUnits(); VertexList::const_iterator pv1 = vertices.begin(); VertexList::const_iterator pv2 = vertices.end (); for ( ; pv1 != pv2; ++pv1) { CPoint3D &pixel = const_cast<CPoint3D &>((*pv1)->getPixel()); pixel.z += dz; } getColorBuffer().fillPolygon(vertices); pv1 = vertices.begin(); for ( ; pv1 != pv2; ++pv1) { CPoint3D &pixel = const_cast<CPoint3D &>((*pv1)->getPixel()); pixel.z -= dz; } } else getColorBuffer().fillPolygon(vertices); } else if (getFrontFaceMode() == GL_LINE) getColorBuffer().drawLines(vertices); else if (getFrontFaceMode() == GL_POINT) getColorBuffer().drawPoints(vertices); } void CGL:: transformVertex(CGeomVertex3D *vertex) { #if 0 // left, right, top, bottom, front, back planes static CNPlane3D planex1( 1, 0, 0, 1); static CNPlane3D planex2(-1, 0, 0, 1); static CNPlane3D planey1( 0, 1, 0, 1); static CNPlane3D planey2( 0, -1, 0, 1); static CNPlane3D planez1( 0, 0, 1, 1); static CNPlane3D planez2( 0, 0, -1, 1); #endif CPoint3D vpoint, jpoint, ppoint; // model to view CMatrix3DH *model_matrix = getMatrix(GL_MODELVIEW); model_matrix->multiplyPoint(vertex->getModel(), vpoint); vertex->setViewed(vpoint); if (vertex->getNormalSet()) { CMatrix3DH *imodel_matrix = getIMatrix(GL_MODELVIEW); CMatrix3DH imodel_matrixt = imodel_matrix->transposed(); CVector3D vnormal; imodel_matrixt.multiplyVector(vertex->getNormal(), vnormal); vertex->setVNormal(vnormal); } //-------- vertex->setClipSide(CCLIP_SIDE_INSIDE); // clip to extra matrices for (uint i = 0; i < MAX_CLIP_PLANES; ++i) { // TODO: transform by transpose inverse modelview if (! clipPlaneEnabled(i)) continue; if (vertex->getClipSide() != CCLIP_SIDE_OUTSIDE) vertex->setClipSide(getClipSide(i, vpoint)); } //-------- // project CMatrix3DH *project_matrix = getMatrix(GL_PROJECTION); project_matrix->multiplyPoint(vpoint, jpoint); vertex->setProjected(jpoint); //-------- // clip to view plane x,y,z = +/- w if (jpoint.x < -1 || jpoint.x > 1 || jpoint.y < -1 || jpoint.y > 1 || jpoint.z < -1 || jpoint.z > 1) vertex->setClipSide(CCLIP_SIDE_OUTSIDE); //-------- // to pixel pixel_matrix_.multiplyPoint(jpoint, ppoint); vertex->setPixel(ppoint); } void CGL:: untransformVertex(CGeomVertex3D *vertex) { CPoint3D mpoint, vpoint, jpoint; ipixel_matrix_.multiplyPoint(vertex->getPixel(), jpoint); vertex->setProjected(jpoint); CMatrix3DH *iproject_matrix = getIMatrix(GL_PROJECTION); iproject_matrix->multiplyPoint(jpoint, vpoint); vertex->setViewed(vpoint); CMatrix3DH *imodel_matrix = getIMatrix(GL_MODELVIEW); imodel_matrix->multiplyPoint(vpoint, mpoint); vertex->setModel(mpoint); } void CGL:: resize(int w, int h) { getColorBuffer().resize(w, h); getAccumBuffer().resize(w, h); } #if 0 void CGL:: updateSize(int width, int height, bool *changed) { if (window_rect_.getSize() == CISize2D(width, height)) { *changed = false; return; } *changed = true; window_rect_.setSize(CISize2D(width, height)); } #endif bool CGL:: executeCommand() const { return (! inDisplayList() || getCurrentDisplayList()->getExecute()); } int CGL:: createDisplayList() { CGLDisplayList *display_list = new CGLDisplayList; uint id = display_list->getId(); display_list_map_[id] = display_list; return id; } bool CGL:: startDisplayList(uint id, bool execute) { CGLDisplayList *display_list = lookupDisplayList(id); if (! display_list) { display_list = new CGLDisplayList(id); display_list_map_[id] = display_list; } else display_list->clear(); display_list->setExecute(execute); current_display_list_ = display_list; return true; } bool CGL:: endDisplayList() { current_display_list_ = NULL; return true; } bool CGL:: inDisplayList() const { return (current_display_list_ != NULL); } bool CGL:: executeDisplayList(uint id) { CGLDisplayList *display_list = lookupDisplayList(id); if (display_list) return display_list->execute(this); else return false; } bool CGL:: isDisplayList(uint id) { CGLDisplayList *display_list = lookupDisplayList(id); return (display_list != NULL); } CGLDisplayList * CGL:: lookupDisplayList(uint id) { DisplayListMap::const_iterator pdisplay_list1 = display_list_map_.find(id); DisplayListMap::const_iterator pdisplay_list2 = display_list_map_.end (); if (pdisplay_list1 != pdisplay_list2) return (*pdisplay_list1).second; return NULL; } void CGL:: deleteDisplayList(uint id) { if (display_list_map_.find(id) != display_list_map_.end()) { delete display_list_map_[id]; display_list_map_[id] = NULL; } } bool CGL:: pushMatrix() { CMatrix3DH *matrix = getMatrix(); if (matrix_mode_ == GL_MODELVIEW) { model_view_matrix_stack_ .push_back(new CMatrix3DH(*matrix)); model_view_imatrix_stack_.push_back(new CMatrix3DH(matrix->inverse())); } else if (matrix_mode_ == GL_PROJECTION) { projection_matrix_stack_ .push_back(new CMatrix3DH(*matrix)); projection_imatrix_stack_.push_back(new CMatrix3DH(matrix->inverse())); } else if (matrix_mode_ == GL_TEXTURE) texture_matrix_stack_.push_back(new CMatrix3DH(*matrix)); else if (matrix_mode_ == GL_COLOR) color_matrix_stack_.push_back(new CMatrix3DH(*matrix)); return true; } bool CGL:: popMatrix() { if (matrix_mode_ == GL_MODELVIEW) { if (model_view_matrix_stack_.size() <= 1) return false; CMatrix3DH *matrix = getMatrix(); CMatrix3DH *imatrix = getIMatrix(); model_view_matrix_stack_ .pop_back(); model_view_imatrix_stack_.pop_back(); delete matrix; delete imatrix; } else if (matrix_mode_ == GL_PROJECTION) { if (projection_matrix_stack_.size() <= 1) return false; CMatrix3DH *matrix = getMatrix(); CMatrix3DH *imatrix = getIMatrix(); projection_matrix_stack_ .pop_back(); projection_imatrix_stack_.pop_back(); delete matrix; delete imatrix; } else if (matrix_mode_ == GL_TEXTURE) { if (texture_matrix_stack_.size() <= 1) return false; CMatrix3DH *matrix = getMatrix(); texture_matrix_stack_.pop_back(); delete matrix; } else if (matrix_mode_ == GL_COLOR) { if (color_matrix_stack_.size() <= 1) return false; CMatrix3DH *matrix = getMatrix(); color_matrix_stack_.pop_back(); delete matrix; } return true; } void CGL:: updateIMatrix(CMatrix3DH *matrix) { if (matrix_mode_ == GL_MODELVIEW || matrix_mode_ == GL_PROJECTION) { CMatrix3DH *imatrix = getIMatrix(); *imatrix = matrix->inverse(); } } void CGL:: rotateMatrix(double angle, double x, double y, double z) { double angle1 = CMathGen::DegToRad(angle); CMatrix3DH matrix; CVector3D axis(x, y, z); matrix.setGenRotation(axis, angle1, CMathGen::LEFT_HANDEDNESS); if (executeCommand()) multMatrix(&matrix); if (inDisplayList()) getCurrentDisplayList()->multMatrix(matrix); } void CGL:: scaleMatrix(double x, double y, double z) { CMatrix3DH matrix; matrix.setScale(x, y, z); if (executeCommand()) multMatrix(&matrix); if (inDisplayList()) getCurrentDisplayList()->multMatrix(matrix); } void CGL:: translateMatrix(double x, double y, double z) { CMatrix3DH matrix; matrix.setTranslation(x, y, z); if (executeCommand()) multMatrix(&matrix); if (inDisplayList()) getCurrentDisplayList()->multMatrix(matrix); } void CGL:: initMatrix() { CMatrix3DH *current_matrix = getMatrix(); current_matrix->setIdentity(); updateIMatrix(current_matrix); } void CGL:: setMatrix(CMatrix3DH *matrix) { CMatrix3DH *current_matrix = getMatrix(); *current_matrix = *matrix; updateIMatrix(current_matrix); } void CGL:: multMatrix(CMatrix3DH *matrix) { CMatrix3DH *current_matrix = getMatrix(); *current_matrix *= *matrix; updateIMatrix(current_matrix); } CMatrix3DH * CGL:: getMatrix() const { return getMatrix(matrix_mode_); } CMatrix3DH * CGL:: getIMatrix() const { return getIMatrix(matrix_mode_); } CMatrix3DH * CGL:: getMatrix(int mode) const { if (mode == GL_MODELVIEW) return model_view_matrix_stack_[model_view_matrix_stack_.size() - 1]; else if (mode == GL_PROJECTION) return projection_matrix_stack_[projection_matrix_stack_.size() - 1]; else if (mode == GL_TEXTURE) return texture_matrix_stack_[texture_matrix_stack_.size() - 1]; else if (mode == GL_COLOR) return color_matrix_stack_[color_matrix_stack_.size() - 1]; else return NULL; } CMatrix3DH * CGL:: getIMatrix(int mode) const { if (mode == GL_MODELVIEW) return model_view_imatrix_stack_[model_view_matrix_stack_.size() - 1]; else if (mode == GL_PROJECTION) return projection_imatrix_stack_[projection_matrix_stack_.size() - 1]; else { std::cerr << "Calc IMatrix" << std::endl; static CMatrix3DH imatrix; CMatrix3DH *matrix = getMatrix(mode); imatrix = matrix->inverse(); return &imatrix; } } void CGL:: drawBitmap(uint width, uint height, double xorig, double yorig, double xmove, double ymove, const uchar *bitmap) { if (executeCommand()) drawBitmapI(width, height, xorig, yorig, xmove, ymove, bitmap); if (inDisplayList()) getCurrentDisplayList()->bitmap(width, height, xorig, yorig, xmove, ymove, bitmap); } void CGL:: drawBitmapI(uint width, uint height, double xorig, double yorig, double xmove, double ymove, const uchar *bitmap) { if (bitmap != NULL) { CGLColorBuffer &color_buffer = getColorBuffer(); const CPoint3D &point = getRasterPos().getPixel(); const CPoint3D &viewed = getRasterPos().getViewed(); const CRGBA &rgba = getRasterPos().getColor(); CGLColorBuffer::Point bpoint(1, rgba); uint width1 = (width + 7) >> 3; const uchar *p = bitmap; double yp = point.y + yorig; for (uint y = 0; y < height; ++y, ++yp) { double xp = point.x + xorig; for (uint x1 = 0, x = 0; x1 < width1; ++x1, ++p) { for (uint b = 0; b < 8 && x < width; ++b, ++x, ++xp) { if (*p & (1 << (7 - b))) color_buffer.setPoint(uint(xp), uint(yp), bpoint, viewed.z); } } } } CPoint3D mpoint = getRasterPos().getModel(); mpoint.x += xmove; mpoint.y += ymove; CGeomVertex3D vertex = getRasterPos(); vertex.setModel(mpoint); transformVertex(&vertex); setRasterPos(vertex); } void CGL:: drawRGBAImage(uint width, uint height, const uchar *image, uint num_components, bool reverse) { static uint image_buffer_size; static CRGBA *image_buffer1, *image_buffer2; if (image == NULL) return; //------- uint size = width*height; if (size > image_buffer_size) { delete [] image_buffer1; delete [] image_buffer2; image_buffer_size = size; image_buffer1 = new CRGBA [image_buffer_size]; image_buffer2 = new CRGBA [image_buffer_size]; } //------- // draw image into buffer and apply pixel transfer double factor = 1.0/255.0; const uchar *ip = image; CRGBA *op = image_buffer1; const CGLPixelTransfer &pixel_transfer = getPixelTransfer(); if (num_components == 3) { double r, g, b; for (uint y = 0; y < height; ++y) { for (uint x = 0; x < width; ++x, ip += 3, ++op) { if (! reverse) { r = ip[0]*factor; g = ip[1]*factor; b = ip[2]*factor; } else { r = ip[2]*factor; g = ip[1]*factor; b = ip[0]*factor; } r = r*pixel_transfer.getRedScale () + pixel_transfer.getRedBias (); g = g*pixel_transfer.getGreenScale() + pixel_transfer.getGreenBias(); b = b*pixel_transfer.getBlueScale () + pixel_transfer.getBlueBias (); *op = CRGBA(r, g, b); } } } else { double r, g, b, a; for (uint y = 0; y < height; ++y) { for (uint x = 0; x < width; ++x, ip += 4, ++op) { if (! reverse) { r = ip[0]*factor; g = ip[1]*factor; b = ip[2]*factor; } else { r = ip[2]*factor; g = ip[1]*factor; b = ip[0]*factor; } a = ip[3]*factor; r = r*pixel_transfer.getRedScale () + pixel_transfer.getRedBias (); g = g*pixel_transfer.getGreenScale() + pixel_transfer.getGreenBias(); b = b*pixel_transfer.getBlueScale () + pixel_transfer.getBlueBias (); a = a*pixel_transfer.getAlphaScale() + pixel_transfer.getAlphaBias(); *op = CRGBA(r, g, b, a); } } } //------ // apply color table if (getColorTableEnabled()) { const CGLColorTable &color_table = getColorTable(); op = image_buffer1; for (uint y = 0; y < height; ++y) for (uint x = 0; x < width; ++x, ++op) *op = color_table.remap(*op); } //------ // apply convolution if (getConvolution2DEnabled()) { const CGLConvolutionFilter2D &filter = getConvolution2D(); uint fwidth = filter.getWidth (); uint fheight = filter.getHeight(); int dx = fwidth >> 1; int dy = fheight >> 1; for (uint i = 0; i < image_buffer_size; ++i) image_buffer2[i] = image_buffer1[i]; for (uint y = dy; y < height - dy; ++y) { op = &image_buffer1[y*width + dx]; for (uint x = dx; x < width - dx; ++x, ++op) { CRGBA rgba(0,0,0); for (uint y1 = 0; y1 < fheight; ++y1) { for (uint x1 = 0; x1 < fwidth; ++x1) { const CRGBA &rgba1 = image_buffer2[(y + y1 - dy)*width + x + x1 - dx]; const CRGBA &rgba2 = filter.getValue(x1, y1); rgba += (rgba1*rgba2); } } *op = rgba.clamp(); } } } //------ // apply color_matrix CMatrix3DH *color_matrix = getMatrix(GL_COLOR); if (! color_matrix->isIdentity()) { double r, g, b, a; op = image_buffer1; for (uint y = 0; y < height; ++y) { for (uint x = 0; x < width; ++x, ++op) { (*op).getRGBA(&r, &g, &b, &a); color_matrix->preMultiplyPoint(r, g, b, a, &r, &g, &b, &a); (*op).setRGBA(r, g, b, a); } } } //------ // calc histogram if (getHistogramEnabled()) { calcHistogram(image_buffer1, width, height); if (getHistogram().getSink()) return; } //------ // calc min max if (getMinmaxEnabled()) { calcMinmax(image_buffer1, width, height); if (getMinmax().getSink()) return; } //------ // add image to color buffer CGLColorBuffer &color_buffer = getColorBuffer(); CGLColorBuffer::Point bpoint; const CPoint3D &point = getRasterPos().getPixel(); const CPoint3D &viewed = getRasterPos().getViewed(); CRGBA rgba = getRasterPos().getColor(); op = image_buffer1; double xs = getPixelZoomX(); double ys = getPixelZoomY(); double yp1 = point.y; double yp2 = yp1 + ys; for (uint y = 0; y < height; ++y, yp1 = yp2, yp2 += ys) { double xp1 = point.x; double xp2 = xp1 + xs; for (uint x = 0; x < width; ++x, xp1 = xp2, xp2 += xs, ++op) { bpoint.rgba = *op; uint nx = std::abs(int(xp2) - int(xp1)); for (uint ix = 0, xs1 = uint(xp1); ix <= nx; ++ix, ++xs1) { uint ny = std::abs(int(yp2) - int(yp1)); for (uint iy = 0, ys1 = uint(yp1); iy <= ny; ++iy, ++ys1) { color_buffer.setPoint(xs1, ys1, bpoint, viewed.z); } } } } } void CGL:: copyColorImage(int x, int y, uint width, uint height, uint num_components) { uchar *pixels = new uchar [num_components*width*height]; readColorImage(x, y, width, height, pixels, num_components, false); drawRGBAImage(width, height, pixels, num_components, false); delete [] pixels; } void CGL:: readColorImage(int x, int y, uint width, uint height, uchar *pixels, uint num_components, bool process) { CGeomVertex3D vertex(NULL, CPoint3D(x, y, 0)); transformVertex(&vertex); const CPoint3D &point = vertex.getPixel(); uchar *p = pixels; CRGBA rgba; double r, g, b, a; double factor = 255.0; const CGLPixelTransfer &pixel_transfer = getPixelTransfer(); CGLColorBuffer &color_buffer = getColorBuffer(); double yp = point.y; for (uint y1 = 0; y1 < height; ++y1, yp += 1) { double xp = point.x; if (num_components == 4) { for (uint x1 = 0; x1 < width; ++x1, xp += 1, p += 4) { const CGLColorBuffer::Point &xpoint = color_buffer.getPoint(uint(xp), uint(yp)); r = xpoint.rgba.getRed (); g = xpoint.rgba.getGreen(); b = xpoint.rgba.getBlue (); a = xpoint.rgba.getAlpha(); if (process) { r = r*pixel_transfer.getRedScale () + pixel_transfer.getRedBias (); g = g*pixel_transfer.getGreenScale() + pixel_transfer.getGreenBias(); b = b*pixel_transfer.getBlueScale () + pixel_transfer.getBlueBias (); a = a*pixel_transfer.getAlphaScale() + pixel_transfer.getAlphaBias(); } p[0] = int(r*factor); p[1] = int(g*factor); p[2] = int(b*factor); p[3] = int(a*factor); } } else { for (uint x1 = 0; x1 < width; ++x1, xp += 1, p += 3) { const CGLColorBuffer::Point &xpoint = color_buffer.getPoint(uint(xp), uint(yp)); r = xpoint.rgba.getRed (); g = xpoint.rgba.getGreen(); b = xpoint.rgba.getBlue (); if (process) { r = r*pixel_transfer.getRedScale () + pixel_transfer.getRedBias (); g = g*pixel_transfer.getGreenScale() + pixel_transfer.getGreenBias(); b = b*pixel_transfer.getBlueScale () + pixel_transfer.getBlueBias (); } p[0] = int(r*factor); p[1] = int(g*factor); p[2] = int(b*factor); } } } } void CGL:: calcHistogram(const CRGBA *image, uint width, uint height) { CGLHistogram histogram = getHistogram(); uint type = histogram.getType(); uint hw = histogram.getWidth(); if (hw == 0) return; for (uint i = 0; i < hw; ++i) histogram.setValue(i, CRGBA(0,0,0,0)); if (type == GL_RGB || type == GL_RGBA) { uint ir, ig, ib, ia; CRGBA rgba, hrgba; const CRGBA *p = image; for (uint y = 0; y < height; ++y) { for (uint x = 0; x < width; ++x, ++p) { hrgba = (*p)*(hw - 1); ir = uint(hrgba.getRed ()); ig = uint(hrgba.getGreen()); ib = uint(hrgba.getBlue ()); ia = uint(hrgba.getAlpha()); rgba = histogram.getValue(ir); rgba.setRed (rgba.getRed () + 1); histogram.setValue(ir, rgba); //---- rgba = histogram.getValue(ig); rgba.setGreen(rgba.getGreen() + 1); histogram.setValue(ig, rgba); //---- rgba = histogram.getValue(ib); rgba.setBlue (rgba.getBlue () + 1); histogram.setValue(ib, rgba); //---- rgba = histogram.getValue(ia); rgba.setAlpha(rgba.getAlpha() + 1); histogram.setValue(ia, rgba); } } } setHistogram(histogram); } void CGL:: calcMinmax(const CRGBA *image, uint width, uint height) { CGLMinmax minmax = getMinmax(); uint type = minmax.getType(); CRGBA minv( 1E50, 1E50, 1E50, 1E50); CRGBA maxv(-1E50, -1E50, -1E50, -1E50); if (type == GL_RGB || type == GL_RGBA) { CRGBA rgba; const CRGBA *p = image; for (uint y = 0; y < height; ++y) { for (uint x = 0; x < width; ++x, ++p) { rgba = *p; minv.setRed (std::min(minv.getRed (), rgba.getRed ())); minv.setGreen(std::min(minv.getGreen(), rgba.getGreen())); minv.setBlue (std::min(minv.getBlue (), rgba.getBlue ())); minv.setAlpha(std::min(minv.getAlpha(), rgba.getAlpha())); maxv.setRed (std::max(maxv.getRed (), rgba.getRed ())); maxv.setGreen(std::max(maxv.getGreen(), rgba.getGreen())); maxv.setBlue (std::max(maxv.getBlue (), rgba.getBlue ())); maxv.setAlpha(std::max(maxv.getAlpha(), rgba.getAlpha())); } } } minmax.setMin(minv); minmax.setMax(maxv); setMinmax(minmax); } void CGL:: setClipPlane(int pid, const double *equation) { CMatrix3DH *imatrix = getIMatrix(); double x, y, z, w; imatrix->preMultiplyPoint(equation[0], equation[1], equation[2], equation[3], &x, &y, &z, &w); clip_plane_[pid].setPlane(CNPlane3D(x, y, z, w)); } void CGL:: enableClipPlane(int pid) { clip_plane_[pid].setEnabled(true); } void CGL:: disableClipPlane(int pid) { clip_plane_[pid].setEnabled(false); } CClipSide CGL:: getClipSide(int pid, const CPoint3D &point) const { const CNPlane3D &plane = clip_plane_[pid].getPlane(); double f = plane.value(point); if (f > 0) return CCLIP_SIDE_INSIDE; else if (f < 0) return CCLIP_SIDE_OUTSIDE; else return CCLIP_SIDE_ON; } void CGL:: setViewport(double x1, double y1, double x2, double y2) { // int height = window_->getSize().getHeight(); // y1 = height - 1 - y1; // y2 = height - 1 - y2; viewport_.setXMin(x1); viewport_.setYMin(y1); viewport_.setXMax(x2); viewport_.setYMax(y2); double z1 = viewport_.getZMin(); double z2 = viewport_.getZMax(); pixel_matrix_.setTransform(-1, -1, -1, 1, 1, 1, x1, y1, z1, x2, y2, z2); ipixel_matrix_ = pixel_matrix_.inverse(); } void CGL:: getViewport(double *x1, double *y1, double *x2, double *y2) { *x1 = viewport_.getXMin(); *y1 = viewport_.getYMin(); *x2 = viewport_.getXMax(); *y2 = viewport_.getYMax(); } void CGL:: setFont(CFontPtr font) { CXLibPixelRenderer *renderer = window_->getXRenderer(); renderer->setFont(font); } void CGL:: drawChar(char c) { CGLColorBuffer &color_buffer = getColorBuffer(); CPoint3D point = getRasterPos().getPixel(); const CPoint3D &viewed = getRasterPos().getViewed(); CRGBA rgba = getRasterPos().getColor(); CGLColorBuffer::Point bpoint(point.z, rgba); CXLibPixelRenderer *renderer = window_->getXRenderer(); CFontPtr font; renderer->getFont(font); CImagePtr image = font->getCharImage(c); int iwidth = image->getWidth (); int iheight = image->getHeight(); int ascent = font->getICharAscent(); int x1 = 0; int x2 = iwidth - 1; int y1 = 0; int y2 = iheight - 1; CRGBA irgba; for (int yy = y1; yy <= y2; ++yy) { for (int xx = x1; xx <= x2; ++xx) { image->getRGBAPixel(xx, yy, irgba); if (irgba.getAlpha() < 0.5) continue; int x = int(point.x) + xx; int y = int(point.y) - yy + ascent; color_buffer.setPoint(x, y, bpoint, viewed.z); } } point.x += iwidth; CGeomVertex3D vertex = getRasterPos(); vertex.setPixel(point); untransformVertex(&vertex); setRasterPos(vertex); } void CGL:: accumLoadAdd(double scale) { CGLColorBuffer &color_buffer = getColorBuffer(); CGLAccumBuffer &accum_buffer = getAccumBuffer(); uint w = color_buffer.getWidth (); uint h = color_buffer.getHeight(); for (uint y = 0; y < h; ++y) { for (uint x = 0; x < w; ++x) { const CGLColorBuffer::Point &point = color_buffer.getPoint(x, y); const CRGBA &rgba = accum_buffer.getPoint(x, y); accum_buffer.setPoint(x, y, rgba + point.rgba*scale); } } } void CGL:: accumLoad(double scale) { CGLColorBuffer &color_buffer = getColorBuffer(); CGLAccumBuffer &accum_buffer = getAccumBuffer(); uint w = color_buffer.getWidth (); uint h = color_buffer.getHeight(); for (uint y = 0; y < h; ++y) { for (uint x = 0; x < w; ++x) { const CGLColorBuffer::Point &point = color_buffer.getPoint(x, y); accum_buffer.setPoint(x, y, point.rgba*scale); } } } void CGL:: accumUnload(double scale) { CGLColorBuffer &color_buffer = getColorBuffer(); CGLAccumBuffer &accum_buffer = getAccumBuffer(); uint w = color_buffer.getWidth (); uint h = color_buffer.getHeight(); for (uint y = 0; y < h; ++y) { for (uint x = 0; x < w; ++x) { const CRGBA &rgba = accum_buffer.getPoint(x, y); CGLColorBuffer::Point point = color_buffer.getPoint(x, y); color_buffer.setColor(x, y, rgba*scale); } } } void CGL:: accumAdd(double factor) { CGLAccumBuffer &accum_buffer = getAccumBuffer(); uint w = accum_buffer.getWidth (); uint h = accum_buffer.getHeight(); for (uint y = 0; y < h; ++y) { for (uint x = 0; x < w; ++x) { const CRGBA &rgba = accum_buffer.getPoint(x, y); accum_buffer.setPoint(x, y, rgba + factor); } } } void CGL:: accumMult(double factor) { CGLAccumBuffer &accum_buffer = getAccumBuffer(); uint w = accum_buffer.getWidth (); uint h = accum_buffer.getHeight(); for (uint y = 0; y < h; ++y) { for (uint x = 0; x < w; ++x) { const CRGBA &rgba = accum_buffer.getPoint(x, y); accum_buffer.setPoint(x, y, rgba*factor); } } } //-------- bool CGLEventAdapter:: idleEvent() { CGLWindMgrInst->idle(); COSTimer::msleep(50); return true; } //-------- void CGL:: save(CGLLightingBits &bits) const { bits.color_material = color_material_; bits.light_model = light_model_; bits.lights = lights_; bits.lighting = lighting_; bits.front_material = front_material_; bits.back_material = back_material_; bits.flat_shading = flat_shading_; } void CGL:: restore(const CGLLightingBits &bits) { color_material_ = bits.color_material; light_model_ = bits.light_model; lights_ = bits.lights; lighting_ = bits.lighting; front_material_ = bits.front_material; back_material_ = bits.back_material; flat_shading_ = bits.flat_shading; } //-------------------- void CGLLightingBits:: save(CGL *gl) { gl->save(*this); } void CGLLightingBits:: restore(CGL *gl) { gl->restore(*this); }
22.041667
96
0.616413
colinw7
bf0a28c1c6cf3ebcef4fb261bed0728fe7020cf9
11,299
cpp
C++
gpk/gpk_framework.cpp
Gorbylord/gpk
89ad121d3946b41f802a0bc260ff07e658cbd26e
[ "MIT" ]
null
null
null
gpk/gpk_framework.cpp
Gorbylord/gpk
89ad121d3946b41f802a0bc260ff07e658cbd26e
[ "MIT" ]
null
null
null
gpk/gpk_framework.cpp
Gorbylord/gpk
89ad121d3946b41f802a0bc260ff07e658cbd26e
[ "MIT" ]
null
null
null
// Tip: Best viewed with zoom level at 81%. // Tip: Hold Left ALT + SHIFT while tapping or holding the arrow keys in order to select multiple columns and write on them at once. // Also useful for copy & paste operations in which you need to copy a bunch of variable or function names and you can't afford the time of copying them one by one. #include "gpk_framework.h" #include "gpk_safe.h" #if defined(GPK_WINDOWS) # include <Windows.h> # include <ShellScalingApi.h> // for GetDpiForMonitor() #endif struct SDisplayInput { ::gpk::SDisplay & Display; ::gpk::ptr_obj<::gpk::SInput> Input; }; ::gpk::error_t gpk::updateFramework (::gpk::SFramework& framework) { if(0 == framework.Input) framework.Input.create(); SInput & input = *framework.Input; input.KeyboardPrevious = input.KeyboardCurrent; input.MousePrevious = input.MouseCurrent; input.MouseCurrent.Deltas = {}; ::gpk::SFrameInfo & frameInfo = framework.FrameInfo; ::gpk::STimer & timer = framework.Timer; timer .Frame(); frameInfo .Frame(::gpk::min(timer.LastTimeMicroseconds, 200000ULL)); ::gpk::SDisplay & mainWindow = framework.MainDisplay; ::gpk::error_t updateResult = ::gpk::displayUpdateTick(mainWindow); ree_if(errored(updateResult), "Not sure why this would fail."); rvi_if(1, mainWindow.Closed, "Application exiting because the main window was closed."); rvi_if(1, 1 == updateResult, "Application exiting because the WM_QUIT message was processed."); ::gpk::ptr_obj<::gpk::SRenderTarget<::gpk::SFramework::TTexel, uint32_t>> offscreen = framework.MainDisplayOffscreen; #if defined(GPK_WINDOWS) if(mainWindow.PlatformDetail.WindowHandle) { #endif if(offscreen && offscreen->Color.Texels.size()) error_if(errored(::gpk::displayPresentTarget(mainWindow, offscreen->Color.View)), "Unknown error."); } if(0 != framework.MainDisplay.PlatformDetail.WindowHandle) { RECT rcWindow = {}; ::GetWindowRect(framework.MainDisplay.PlatformDetail.WindowHandle, &rcWindow); POINT point = {rcWindow.left + 8, rcWindow.top}; ::gpk::SCoord2<uint32_t> dpi = {96, 96}; HMONITOR hMonitor = ::MonitorFromPoint(point, MONITOR_DEFAULTTONEAREST); HRESULT hr = ::GetDpiForMonitor(hMonitor, MDT_EFFECTIVE_DPI, &dpi.x, &dpi.y); if(0 == hr && (framework.GUI.Zoom.DPI * 96).Cast<uint32_t>() != dpi) { framework.GUI.Zoom.DPI = {dpi.x / 96.0, dpi.y / 96.0}; ::gpk::guiUpdateMetrics(framework.GUI, offscreen->Color.View.metrics(), true); } } return 0; } #include <Windowsx.h> static constexpr const uint32_t BMP_SCREEN_WIDTH = 1280; static constexpr const uint32_t BMP_SCREEN_HEIGHT = uint32_t(::BMP_SCREEN_WIDTH * (9.0 / 16.0)); static ::RECT minClientRect = {100, 100, 100 + 320, 100 + 200}; //extern ::SApplication * g_ApplicationInstance ; #if defined(GPK_WINDOWS) static LRESULT WINAPI mainWndProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { //::SApplication & applicationInstance = *g_ApplicationInstance; static const int adjustedMinRect = ::AdjustWindowRectEx(&minClientRect, WS_OVERLAPPEDWINDOW, FALSE, 0); ::SDisplayInput * actualMainDisplay = (::SDisplayInput*)::GetWindowLongPtrA(hWnd, GWLP_USERDATA); ::gpk::SDisplay dummyDisplay = {}; // we need this to create the reference in case the display pointer isn't there. ::gpk::SInput dummyInput = {}; ::gpk::SDisplay & mainDisplay = (actualMainDisplay) ? actualMainDisplay->Display : dummyDisplay; ::gpk::SInput & input = (actualMainDisplay && actualMainDisplay->Input) ? *actualMainDisplay->Input : dummyInput; ::gpk::SDisplayPlatformDetail & displayDetail = mainDisplay.PlatformDetail; int32_t zDelta = {}; switch(uMsg) { default: break; case WM_CLOSE : ::DestroyWindow(hWnd); return 0; case WM_KEYDOWN : if(wParam > ::gpk::size(input.KeyboardPrevious.KeyState)) break; input.KeyboardCurrent.KeyState[wParam] = 1; return 0; case WM_KEYUP : if(wParam > ::gpk::size(input.KeyboardPrevious.KeyState)) break; input.KeyboardCurrent.KeyState[wParam] = 0; return 0; case WM_LBUTTONDOWN : info_printf("Down"); if(0 > ::gpk::size(input.MouseCurrent.ButtonState)) break; input.MouseCurrent.ButtonState[0] = 1; return 0; case WM_LBUTTONDBLCLK : info_printf("Down"); if(0 > ::gpk::size(input.MouseCurrent.ButtonState)) break; input.MouseCurrent.ButtonState[0] = 1; return 0; case WM_LBUTTONUP : info_printf("Up" ); if(0 > ::gpk::size(input.MouseCurrent.ButtonState)) break; input.MouseCurrent.ButtonState[0] = 0; return 0; case WM_RBUTTONDOWN : info_printf("Down"); if(1 > ::gpk::size(input.MouseCurrent.ButtonState)) break; input.MouseCurrent.ButtonState[1] = 1; return 0; case WM_RBUTTONDBLCLK : info_printf("Down"); if(1 > ::gpk::size(input.MouseCurrent.ButtonState)) break; input.MouseCurrent.ButtonState[1] = 1; return 0; case WM_RBUTTONUP : info_printf("Up" ); if(1 > ::gpk::size(input.MouseCurrent.ButtonState)) break; input.MouseCurrent.ButtonState[1] = 0; return 0; case WM_MBUTTONDOWN : info_printf("Down"); if(2 > ::gpk::size(input.MouseCurrent.ButtonState)) break; input.MouseCurrent.ButtonState[2] = 1; return 0; case WM_MBUTTONDBLCLK : info_printf("Down"); if(2 > ::gpk::size(input.MouseCurrent.ButtonState)) break; input.MouseCurrent.ButtonState[2] = 1; return 0; case WM_MBUTTONUP : info_printf("Up" ); if(2 > ::gpk::size(input.MouseCurrent.ButtonState)) break; input.MouseCurrent.ButtonState[2] = 0; return 0; case WM_MOUSEWHEEL : zDelta = GET_WHEEL_DELTA_WPARAM(wParam); input.MouseCurrent.Deltas.z = zDelta; return 0; case WM_MOUSEMOVE : { int32_t xPos = GET_X_LPARAM(lParam); int32_t yPos = GET_Y_LPARAM(lParam); input.MouseCurrent.Position.x = ::gpk::clamp(xPos, 0, (int32_t)mainDisplay.Size.x); input.MouseCurrent.Position.y = ::gpk::clamp(yPos, 0, (int32_t)mainDisplay.Size.y); input.MouseCurrent.Deltas.x = input.MouseCurrent.Position.x - input.MousePrevious.Position.x; input.MouseCurrent.Deltas.y = input.MouseCurrent.Position.y - input.MousePrevious.Position.y; return 0; } case WM_GETMINMAXINFO : // Catch this message so to prevent the window from becoming too small. ((::MINMAXINFO*)lParam)->ptMinTrackSize = {minClientRect.right - minClientRect.left, minClientRect.bottom - minClientRect.top}; return 0; case WM_SIZE : if(lParam) { ::gpk::SCoord2<uint32_t> newMetrics = ::gpk::SCoord2<WORD>{LOWORD(lParam), HIWORD(lParam)}.Cast<uint32_t>(); if(newMetrics != mainDisplay.Size) { mainDisplay.PreviousSize = mainDisplay.Size; mainDisplay.Size = newMetrics; mainDisplay.Resized = true; mainDisplay.Repaint = true; char buffer [256] = {}; //sprintf_s(buffer, "[%u x %u]. Last frame seconds: %g. ", (uint32_t)newMetrics.x, (uint32_t)newMetrics.y, applicationInstance.Framework.Timer.LastTimeSeconds); sprintf_s(buffer, "[%u x %u].", (uint32_t)newMetrics.x, (uint32_t)newMetrics.y); #if defined(UNICODE) #else SetWindowText(mainDisplay.PlatformDetail.WindowHandle, buffer); #endif } } if( wParam == SIZE_MINIMIZED ) { mainDisplay.MinOrMaxed = mainDisplay.NoDraw = true; } else if( wParam == SIZE_MAXIMIZED ) { mainDisplay.Resized = mainDisplay.MinOrMaxed = true; mainDisplay.NoDraw = false; } else if( wParam == SIZE_RESTORED ) { mainDisplay.Resized = true; mainDisplay.MinOrMaxed = true; mainDisplay.NoDraw = false; } else { //State.Resized = true; ? mainDisplay.MinOrMaxed = mainDisplay.NoDraw = false; } break; case WM_PAINT : break; case WM_DESTROY : ::SDisplayInput * oldInput = (::SDisplayInput*)::SetWindowLongPtrA(displayDetail.WindowHandle, GWLP_USERDATA, 0); displayDetail.WindowHandle = 0; mainDisplay.Closed = true; safe_delete(oldInput); ::PostQuitMessage(0); return 0; } return DefWindowProc(hWnd, uMsg, wParam, lParam); } static void initWndClass (::HINSTANCE hInstance, const TCHAR* className, WNDPROC wndProc, ::WNDCLASSEX& wndClassToInit) { wndClassToInit = {sizeof(::WNDCLASSEX),}; wndClassToInit.lpfnWndProc = wndProc; wndClassToInit.hInstance = hInstance; wndClassToInit.hIcon = LoadIcon (NULL, IDC_ICON); wndClassToInit.hCursor = LoadCursor(NULL, IDC_ARROW); wndClassToInit.hbrBackground = (::HBRUSH)(COLOR_3DFACE + 1); wndClassToInit.lpszClassName = className; wndClassToInit.style = CS_DBLCLKS; } #endif ::gpk::error_t gpk::mainWindowDestroy (::gpk::SDisplay& mainWindow) { ::DestroyWindow(mainWindow.PlatformDetail.WindowHandle); ::gpk::displayUpdate(mainWindow); return 0; } ::gpk::error_t gpk::mainWindowCreate (::gpk::SDisplay& mainWindow, ::gpk::SRuntimeValuesDetail& runtimeValues, ::gpk::ptr_obj<SInput>& displayInput) { if(0 == displayInput) displayInput.create(); ::gpk::SDisplayPlatformDetail & displayDetail = mainWindow.PlatformDetail; HINSTANCE hInstance = runtimeValues.EntryPointArgsWin.hInstance; ::initWndClass(hInstance, displayDetail.WindowClassName, ::mainWndProc, displayDetail.WindowClass); ::RegisterClassEx(&displayDetail.WindowClass); mainWindow.Size = {::BMP_SCREEN_WIDTH, ::BMP_SCREEN_HEIGHT}; ::RECT finalClientRect = {100, 100, 100 + (LONG)mainWindow.Size.x, 100 + (LONG)mainWindow.Size.y}; DWORD windowStyle = WS_OVERLAPPEDWINDOW; //WS_POPUP; ::AdjustWindowRectEx(&finalClientRect, windowStyle, FALSE, 0); mainWindow.PlatformDetail.WindowHandle = ::CreateWindowEx(0, displayDetail.WindowClassName, TEXT("Window"), windowStyle | CS_DBLCLKS , finalClientRect.left , finalClientRect.top , finalClientRect.right - finalClientRect.left , finalClientRect.bottom - finalClientRect.top , 0, 0, displayDetail.WindowClass.hInstance, 0 ); ::SetWindowLongPtrA(mainWindow.PlatformDetail.WindowHandle, GWLP_USERDATA, (LONG_PTR)new SDisplayInput{mainWindow, displayInput}); ::ShowWindow (displayDetail.WindowHandle, SW_SHOW); ::UpdateWindow (displayDetail.WindowHandle); return 0; }
58.848958
177
0.637048
Gorbylord
bf0a4dc3e816eef27a28a44d2baffaabc59559b2
145
cpp
C++
WhileFalsePhysics/Source/WhileFalsePhysics/Private/Physics/WhileFalsePhysicsStatics.cpp
WhileFalseStudios/unreal-wfs
d11ae208f939b994771dd8653c17aac762382a1f
[ "MIT" ]
null
null
null
WhileFalsePhysics/Source/WhileFalsePhysics/Private/Physics/WhileFalsePhysicsStatics.cpp
WhileFalseStudios/unreal-wfs
d11ae208f939b994771dd8653c17aac762382a1f
[ "MIT" ]
null
null
null
WhileFalsePhysics/Source/WhileFalsePhysics/Private/Physics/WhileFalsePhysicsStatics.cpp
WhileFalseStudios/unreal-wfs
d11ae208f939b994771dd8653c17aac762382a1f
[ "MIT" ]
null
null
null
// Copyright (c) While False Studios 2019. Released under the MIT license. See LICENSE for more details. #include "WhileFalsePhysicsStatics.h"
29
104
0.77931
WhileFalseStudios
bf0beb8df1bbf9ddae3eb03d7882cb51bc51df58
8,966
tcc
C++
Code/Components/Synthesis/synthesis/current/measurementequation/ImageConvolver.tcc
rtobar/askapsoft
6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
1
2020-06-18T08:37:43.000Z
2020-06-18T08:37:43.000Z
Code/Components/Synthesis/synthesis/current/measurementequation/ImageConvolver.tcc
ATNF/askapsoft
d839c052d5c62ad8a511e58cd4b6548491a6006f
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
null
null
null
Code/Components/Synthesis/synthesis/current/measurementequation/ImageConvolver.tcc
ATNF/askapsoft
d839c052d5c62ad8a511e58cd4b6548491a6006f
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
null
null
null
/// @copyright (c) 1995,1996,1997,1998,1999,2000,2001,2002 /// Associated Universities, Inc. Washington DC, USA. /// @copyright (c) 2012 CSIRO /// /// This file is part of the ASKAP software distribution. /// /// The ASKAP software distribution is free software: you can redistribute it /// and/or modify it under the terms of the GNU General Public License as /// published by the Free Software Foundation; either version 2 of the License, /// or (at your option) any later version. /// /// This program is distributed in the hope that it will be useful, /// but WITHOUT ANY WARRANTY; without even the implied warranty of /// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /// GNU General Public License for more details. /// /// You should have received a copy of the GNU General Public License /// along with this program; if not, write to the Free Software /// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /// /// NOTE: This file was imported from casacore as it is scheduled to be removed /// from the casacore distribution. // Include own header file first #include <measurementequation/ImageConvolver.h> // ASKAPsoft includes #include <askap/AskapLogging.h> #include <askap/AskapError.h> #include <casacore/casa/aips.h> #include <casacore/casa/Exceptions/Error.h> #include <casacore/casa/Logging/LogIO.h> #include <casacore/casa/BasicMath/Math.h> #include <casacore/casa/BasicSL/String.h> #include <casacore/images/Images/PagedImage.h> #include <casacore/images/Images/TempImage.h> #include <casacore/images/Regions/RegionHandler.h> #include <casacore/images/Regions/ImageRegion.h> #include <casacore/images/Images/ImageUtilities.h> #include <casacore/lattices/Lattices/ArrayLattice.h> #include <casacore/lattices/LatticeMath/LatticeConvolver.h> #include <casacore/lattices/Lattices/LatticeUtilities.h> #include <casacore/lattices/LEL/LatticeExpr.h> #include <casacore/lattices/LEL/LatticeExprNode.h> #include <casacore/coordinates/Coordinates/CoordinateUtil.h> #include <casacore/casa/iostream.h> ASKAP_LOGGER(imageconvlogger, ".measurementequation.imageconvolver"); namespace askap { namespace synthesis { template <typename T> ImageConvolver<T>::ImageConvolver() { } template <typename T> ImageConvolver<T>::~ImageConvolver() { } using namespace casa; template <typename T> void ImageConvolver<T>::convolve(casa::ImageInterface<T>& imageOut, casa::ImageInterface<T>& imageIn, const casa::ImageInterface<T>& kernel, ScaleTypes scaleType, casa::Double scale, casa::Bool copyMiscellaneous, casa::Bool warnOnly) { // Check Coordinates checkCoordinates(imageIn.coordinates(), kernel.coordinates(), warnOnly); // Convolve convolve(imageOut, imageIn, kernel, scaleType, scale, copyMiscellaneous); } template <typename T> void ImageConvolver<T>::convolve(casa::ImageInterface<T>& imageOut, casa::ImageInterface<T>& imageIn, const casa::Array<T>& kernel, ScaleTypes scaleType, casa::Double scale, casa::Bool copyMiscellaneous) { casa::ArrayLattice<T> kernelLattice(kernel); convolve(imageOut, imageIn, kernelLattice, scaleType, scale, copyMiscellaneous); } template <typename T> void ImageConvolver<T>::convolve(casa::ImageInterface<T>& imageOut, casa::ImageInterface<T>& imageIn, const Lattice<T>& kernel, ScaleTypes scaleType, casa::Double scale, casa::Bool copyMiscellaneous) { // Check const casa::IPosition& inShape = imageIn.shape(); const casa::IPosition& outShape = imageOut.shape(); if (!inShape.isEqual(outShape)) { ASKAPTHROW(AskapError, "Input and output images must have same shape"); } if (kernel.ndim() > imageIn.ndim()) { ASKAPTHROW(AskapError, "Kernel lattice has more axes than the image!"); } // Add degenerate axes if needed casa::Lattice<T>* pNewKernel = 0; casa::LatticeUtilities::addDegenerateAxes(pNewKernel, kernel, inShape.nelements()); // Normalize kernel. casa::LatticeExprNode node; if (scaleType == AUTOSCALE) { node = casa::LatticeExprNode((*pNewKernel) / sum(*pNewKernel)); } else if (scaleType == SCALE) { T t = static_cast<T>(scale); node = casa::LatticeExprNode(t * (*pNewKernel)); } else if (scaleType == NONE) { node = casa::LatticeExprNode(*pNewKernel); } casa::LatticeExpr<T> kernelExpr(node); // Create convolver casa::LatticeConvolver<T> lc(kernelExpr, imageIn.shape(), casa::ConvEnums::LINEAR); if (imageIn.isMasked()) { // Generate output mask if needed makeMask(imageOut); // Copy input mask to output. Copy input pixels // and set to zero where masked casa::LogIO os; casa::LatticeUtilities::copyDataAndMask(os, imageOut, imageIn, True); // Convolve in situ lc.convolve(imageOut); } else { // Convolve to output lc.convolve(imageOut, imageIn); } // Overwrite output CoordinateSystem imageOut.setCoordinateInfo(imageIn.coordinates()); // Copy miscellaneous things across as required if (copyMiscellaneous) casa::ImageUtilities::copyMiscellaneous(imageOut, imageIn); // Delete the restoring beam (should really check that the beam is in the // plane of convolution) casa::ImageInfo ii = imageOut.imageInfo(); ii.removeRestoringBeam(); imageOut.setImageInfo(ii); // Clean up delete pNewKernel; } template <typename T> void ImageConvolver<T>::makeMask(casa::ImageInterface<T>& out) const { if (out.canDefineRegion()) { // Generate mask name casa::String maskName = out.makeUniqueRegionName(String("mask"), 0); // Make the mask if it does not exist if (!out.hasRegion(maskName, casa::RegionHandler::Masks)) { out.makeMask(maskName, true, true, false, true); ASKAPLOG_DEBUG_STR(imageconvlogger, "Created mask `" << maskName << "'"); } } else { ASKAPLOG_WARN_STR(imageconvlogger, "Cannot make requested mask for this type of image"); } } template <typename T> void ImageConvolver<T>::checkCoordinates(const casa::CoordinateSystem& cSysImage, const casa::CoordinateSystem& cSysKernel, casa::Bool warnOnly) const { const casa::uInt nPixelAxesK = cSysKernel.nPixelAxes(); const casa::uInt nPixelAxesI = cSysImage.nPixelAxes(); if (nPixelAxesK > nPixelAxesI) { ASKAPTHROW(AskapError, "Kernel has more pixel axes than the image"); } const casa::uInt nWorldAxesK = cSysKernel.nWorldAxes(); const casa::uInt nWorldAxesI = cSysImage.nWorldAxes(); if (nWorldAxesK > nWorldAxesI) { ASKAPTHROW(AskapError, "Kernel has more world axes than the image"); } const casa::Vector<casa::Double>& incrI = cSysImage.increment(); const casa::Vector<casa::Double>& incrK = cSysKernel.increment(); const casa::Vector<String>& unitI = cSysImage.worldAxisUnits(); const casa::Vector<String>& unitK = cSysKernel.worldAxisUnits(); for (casa::uInt i = 0; i < nWorldAxesK; i++) { // Compare Coordinate types and reference if (casa::CoordinateUtil::findWorldAxis(cSysImage, i) != casa::CoordinateUtil::findWorldAxis(cSysKernel, i)) { if (warnOnly) { ASKAPLOG_WARN_STR(imageconvlogger, "Coordinate types are not the same for axis " << i + 1); } else { ASKAPTHROW(AskapError, "Coordinate types are not the same for axis " << i + 1); } } // Compare units const casa::Unit u1(unitI[i]); const casa::Unit u2(unitK[i]); if (u1 != u2) { if (warnOnly) { ASKAPLOG_WARN_STR(imageconvlogger, "Axis units are not consistent for axis " << i + 1); } else { ASKAPTHROW(AskapError, "Axis units are not consistent for axis " << i + 1); } } // Compare increments ; this is not a very correct test as there may be // values in the LinearTransform inside the coordinate. Should really // convert some values... See how we go. casa::Quantum<casa::Double> q2(incrK[i], u2); casa::Double val2 = q2.getValue(u1); if (!near(incrI[i], val2, 1.0e-6)) { if (warnOnly) { ASKAPLOG_WARN_STR(imageconvlogger, "Axis increments are not consistent for axis " << i + 1); } else { ASKAPTHROW(AskapError,"Axis increments are not consistent for axis " << i + 1); } } } } } // End namespace synthesis } // End namespace askap
37.672269
108
0.650457
rtobar
bf0f5eb1c7ceb56cc73f7d64be764b1a5029d332
3,595
cc
C++
components/offline_pages/core/offline_page_metadata_store_test_util.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
components/offline_pages/core/offline_page_metadata_store_test_util.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
components/offline_pages/core/offline_page_metadata_store_test_util.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/offline_pages/core/offline_page_metadata_store_test_util.h" #include <memory> #include <utility> #include "base/bind.h" #include "base/callback_forward.h" #include "base/callback_helpers.h" #include "base/logging.h" #include "base/memory/ptr_util.h" #include "base/run_loop.h" #include "base/test/bind.h" #include "base/threading/thread_task_runner_handle.h" #include "components/offline_pages/core/model/add_page_task.h" #include "components/offline_pages/core/model/get_pages_task.h" #include "components/offline_pages/core/offline_page_types.h" #include "sql/database.h" #include "sql/statement.h" #include "testing/gtest/include/gtest/gtest.h" namespace offline_pages { namespace { int64_t GetPageCountSync(sql::Database* db) { static const char kSql[] = "SELECT count(*) FROM offlinepages_v1"; sql::Statement statement(db->GetCachedStatement(SQL_FROM_HERE, kSql)); if (statement.Step()) { return statement.ColumnInt64(0); } return 0UL; } } // namespace OfflinePageMetadataStoreTestUtil::OfflinePageMetadataStoreTestUtil() : store_ptr_(nullptr) {} OfflinePageMetadataStoreTestUtil::~OfflinePageMetadataStoreTestUtil() {} void OfflinePageMetadataStoreTestUtil::BuildStore() { if (!temp_directory_.IsValid() && !temp_directory_.CreateUniqueTempDir()) { DVLOG(1) << "temp_directory_ not created"; return; } store_ = std::make_unique<OfflinePageMetadataStore>( base::ThreadTaskRunnerHandle::Get(), temp_directory_.GetPath()); store_ptr_ = store_.get(); } void OfflinePageMetadataStoreTestUtil::BuildStoreInMemory() { store_ = std::make_unique<OfflinePageMetadataStore>( base::ThreadTaskRunnerHandle::Get()); store_ptr_ = store_.get(); } void OfflinePageMetadataStoreTestUtil::DeleteStore() { store_.reset(); store_ptr_ = nullptr; } std::unique_ptr<OfflinePageMetadataStore> OfflinePageMetadataStoreTestUtil::ReleaseStore() { return std::move(store_); } void OfflinePageMetadataStoreTestUtil::InsertItem(const OfflinePageItem& page) { base::RunLoop run_loop; AddPageResult result; auto task = std::make_unique<AddPageTask>( store(), page, base::BindLambdaForTesting([&](AddPageResult cb_result) { result = cb_result; run_loop.Quit(); })); task->Execute(base::DoNothing()); run_loop.Run(); EXPECT_EQ(AddPageResult::SUCCESS, result); } int64_t OfflinePageMetadataStoreTestUtil::GetPageCount() { base::RunLoop run_loop; int64_t count = 0; store()->Execute( base::BindOnce(&GetPageCountSync), base::BindOnce(base::BindLambdaForTesting([&](int64_t cb_count) { count = cb_count; run_loop.Quit(); })), int64_t()); run_loop.Run(); return count; } std::unique_ptr<OfflinePageItem> OfflinePageMetadataStoreTestUtil::GetPageByOfflineId(int64_t offline_id) { base::RunLoop run_loop; PageCriteria criteria; criteria.offline_ids = std::vector<int64_t>{offline_id}; OfflinePageItem* page = nullptr; auto task = std::make_unique<GetPagesTask>( store(), criteria, base::BindOnce(base::BindLambdaForTesting( [&](const std::vector<OfflinePageItem>& cb_pages) { if (!cb_pages.empty()) page = new OfflinePageItem(cb_pages[0]); run_loop.Quit(); }))); task->Execute(base::DoNothing()); run_loop.Run(); return base::WrapUnique<OfflinePageItem>(page); } } // namespace offline_pages
30.210084
80
0.728234
iridium-browser
bf0fadf1596579574ca4ca32f0b406c13ebe9e66
1,912
cpp
C++
src/prefetch_static.cpp
realead/prefetchstudy
6da174ea7bd193baa982a7f1b29b23fcd1157095
[ "MIT" ]
null
null
null
src/prefetch_static.cpp
realead/prefetchstudy
6da174ea7bd193baa982a7f1b29b23fcd1157095
[ "MIT" ]
null
null
null
src/prefetch_static.cpp
realead/prefetchstudy
6da174ea7bd193baa982a7f1b29b23fcd1157095
[ "MIT" ]
null
null
null
#include <vector> #include <iostream> #include <iomanip> #include <timeitmagic.h> const int BLOCK_SIZE=8; template<bool prefetch> struct Worker{ double *mem; int n; int times; double result; void operator()(){ int cnt=0; for(int i=0;i<n;i+=BLOCK_SIZE){ //prefetch memory block used in the next iteration if(prefetch){ __builtin_prefetch(mem+cnt+BLOCK_SIZE); } //process a cache line for(int j=0;j<BLOCK_SIZE;j++){ double d=mem[cnt]; //do some work, which cannot be optimized away for(int t=0;t<times;t++){ d=(d-mem[cnt])+mem[cnt]; } result+=d; cnt++; } } } Worker(std::vector<double> &mem_): mem(mem_.data()),n(static_cast<int>(mem_.size())), times(0), result(1.0) {} }; const int N=BLOCK_SIZE*1000000; const int ITER=2; const int TRIES=5; int main(){ //init working memory: double val; std::cin>>val; std::vector<double> vec(N); for(int i=0;i<N;i++) vec[i]=i+val; Worker<false> without_prefetch(vec); Worker<true> with_prefetch(vec); std::cout<<"#work\ttime no prefetch\ttime prefetch\tfactor\n"; std::cout<<std::setprecision(17); for(int t=0;t<20;t++){ without_prefetch.times=t; with_prefetch.times=t; double time_no_prefetch=timeitmagic::timeit(without_prefetch, TRIES, ITER).time; double time_with_prefetch=timeitmagic::timeit(with_prefetch, TRIES, ITER).time; std::cout<<t<<"\t" <<time_no_prefetch<<"\t" <<time_with_prefetch<<"\t" <<(time_no_prefetch/time_with_prefetch)<<"\n"; } //ensure that nothing is optimized away: std::cout<<"Results: "<<without_prefetch.result<<" vs. "<<with_prefetch.result<<"\n"; }
25.157895
88
0.567992
realead
bf10aed3ac07abbaf02639a13dce4e78e1f9492c
80,912
cpp
C++
generate/JavaScriptLexer.cpp
yanmingsohu/Polydeuces
93dbe99d37e8724babc3593314da1ca2df114bfa
[ "MIT" ]
1
2021-06-15T02:56:18.000Z
2021-06-15T02:56:18.000Z
generate/JavaScriptLexer.cpp
yanmingsohu/Polydeuces
93dbe99d37e8724babc3593314da1ca2df114bfa
[ "MIT" ]
null
null
null
generate/JavaScriptLexer.cpp
yanmingsohu/Polydeuces
93dbe99d37e8724babc3593314da1ca2df114bfa
[ "MIT" ]
null
null
null
// Auto generated by 'pitch-garammars'/'generate-src' script #include "gcomm.h" #include "JavaScriptBaseLexer.h" #include "JavaScriptBaseParser.h" // Generated from D:\Polydeuces\generate\JavaScriptLexer.g4 by ANTLR 4.7.2 #include "JavaScriptLexer.h" using namespace antlr4; using namespace PolydeucesEngine; JavaScriptLexer::JavaScriptLexer(CharStream *input) : JavaScriptBaseLexer(input) { _interpreter = new atn::LexerATNSimulator(this, _atn, _decisionToDFA, _sharedContextCache); } JavaScriptLexer::~JavaScriptLexer() { delete _interpreter; } std::string JavaScriptLexer::getGrammarFileName() const { return "JavaScriptLexer.g4"; } const std::vector<std::string>& JavaScriptLexer::getRuleNames() const { return _ruleNames; } const std::vector<std::string>& JavaScriptLexer::getChannelNames() const { return _channelNames; } const std::vector<std::string>& JavaScriptLexer::getModeNames() const { return _modeNames; } const std::vector<std::string>& JavaScriptLexer::getTokenNames() const { return _tokenNames; } dfa::Vocabulary& JavaScriptLexer::getVocabulary() const { return _vocabulary; } const std::vector<uint16_t> JavaScriptLexer::getSerializedATN() const { return _serializedATN; } const atn::ATN& JavaScriptLexer::getATN() const { return _atn; } void JavaScriptLexer::action(RuleContext *context, size_t ruleIndex, size_t actionIndex) { switch (ruleIndex) { case 8: OpenBraceAction(dynamic_cast<antlr4::RuleContext *>(context), actionIndex); break; case 9: CloseBraceAction(dynamic_cast<antlr4::RuleContext *>(context), actionIndex); break; case 116: StringLiteralAction(dynamic_cast<antlr4::RuleContext *>(context), actionIndex); break; default: break; } } bool JavaScriptLexer::sempred(RuleContext *context, size_t ruleIndex, size_t predicateIndex) { switch (ruleIndex) { case 0: return HashBangLineSempred(dynamic_cast<antlr4::RuleContext *>(context), predicateIndex); case 3: return RegularExpressionLiteralSempred(dynamic_cast<antlr4::RuleContext *>(context), predicateIndex); case 62: return OctalIntegerLiteralSempred(dynamic_cast<antlr4::RuleContext *>(context), predicateIndex); case 106: return ImplementsSempred(dynamic_cast<antlr4::RuleContext *>(context), predicateIndex); case 107: return LetSempred(dynamic_cast<antlr4::RuleContext *>(context), predicateIndex); case 108: return PrivateSempred(dynamic_cast<antlr4::RuleContext *>(context), predicateIndex); case 109: return PublicSempred(dynamic_cast<antlr4::RuleContext *>(context), predicateIndex); case 110: return InterfaceSempred(dynamic_cast<antlr4::RuleContext *>(context), predicateIndex); case 111: return PackageSempred(dynamic_cast<antlr4::RuleContext *>(context), predicateIndex); case 112: return ProtectedSempred(dynamic_cast<antlr4::RuleContext *>(context), predicateIndex); case 113: return StaticSempred(dynamic_cast<antlr4::RuleContext *>(context), predicateIndex); case 114: return YieldSempred(dynamic_cast<antlr4::RuleContext *>(context), predicateIndex); default: break; } return true; } void JavaScriptLexer::OpenBraceAction(antlr4::RuleContext *context, size_t actionIndex) { switch (actionIndex) { case 0: this->ProcessOpenBrace(); break; default: break; } } void JavaScriptLexer::CloseBraceAction(antlr4::RuleContext *context, size_t actionIndex) { switch (actionIndex) { case 1: this->ProcessCloseBrace(); break; default: break; } } void JavaScriptLexer::StringLiteralAction(antlr4::RuleContext *context, size_t actionIndex) { switch (actionIndex) { case 2: this->ProcessStringLiteral(); break; default: break; } } bool JavaScriptLexer::HashBangLineSempred(antlr4::RuleContext *_localctx, size_t predicateIndex) { switch (predicateIndex) { case 0: return this->IsStartOfFile(); default: break; } return true; } bool JavaScriptLexer::RegularExpressionLiteralSempred(antlr4::RuleContext *_localctx, size_t predicateIndex) { switch (predicateIndex) { case 1: return this->IsRegexPossible(); default: break; } return true; } bool JavaScriptLexer::OctalIntegerLiteralSempred(antlr4::RuleContext *_localctx, size_t predicateIndex) { switch (predicateIndex) { case 2: return !this->IsStrictMode(); default: break; } return true; } bool JavaScriptLexer::ImplementsSempred(antlr4::RuleContext *_localctx, size_t predicateIndex) { switch (predicateIndex) { case 3: return this->IsStrictMode(); default: break; } return true; } bool JavaScriptLexer::LetSempred(antlr4::RuleContext *_localctx, size_t predicateIndex) { switch (predicateIndex) { case 4: return this->IsStrictMode(); default: break; } return true; } bool JavaScriptLexer::PrivateSempred(antlr4::RuleContext *_localctx, size_t predicateIndex) { switch (predicateIndex) { case 5: return this->IsStrictMode(); default: break; } return true; } bool JavaScriptLexer::PublicSempred(antlr4::RuleContext *_localctx, size_t predicateIndex) { switch (predicateIndex) { case 6: return this->IsStrictMode(); default: break; } return true; } bool JavaScriptLexer::InterfaceSempred(antlr4::RuleContext *_localctx, size_t predicateIndex) { switch (predicateIndex) { case 7: return this->IsStrictMode(); default: break; } return true; } bool JavaScriptLexer::PackageSempred(antlr4::RuleContext *_localctx, size_t predicateIndex) { switch (predicateIndex) { case 8: return this->IsStrictMode(); default: break; } return true; } bool JavaScriptLexer::ProtectedSempred(antlr4::RuleContext *_localctx, size_t predicateIndex) { switch (predicateIndex) { case 9: return this->IsStrictMode(); default: break; } return true; } bool JavaScriptLexer::StaticSempred(antlr4::RuleContext *_localctx, size_t predicateIndex) { switch (predicateIndex) { case 10: return this->IsStrictMode(); default: break; } return true; } bool JavaScriptLexer::YieldSempred(antlr4::RuleContext *_localctx, size_t predicateIndex) { switch (predicateIndex) { case 11: return this->IsStrictMode(); default: break; } return true; } // Static vars and initialization. std::vector<dfa::DFA> JavaScriptLexer::_decisionToDFA; atn::PredictionContextCache JavaScriptLexer::_sharedContextCache; // We own the ATN which in turn owns the ATN states. atn::ATN JavaScriptLexer::_atn; std::vector<uint16_t> JavaScriptLexer::_serializedATN; std::vector<std::string> JavaScriptLexer::_ruleNames = { u8"HashBangLine", u8"MultiLineComment", u8"SingleLineComment", u8"RegularExpressionLiteral", u8"OpenBracket", u8"CloseBracket", u8"OpenParen", u8"CloseParen", u8"OpenBrace", u8"CloseBrace", u8"SemiColon", u8"Comma", u8"Assign", u8"QuestionMark", u8"Colon", u8"Ellipsis", u8"Dot", u8"PlusPlus", u8"MinusMinus", u8"Plus", u8"Minus", u8"BitNot", u8"Not", u8"Multiply", u8"Divide", u8"Modulus", u8"Power", u8"NullCoalesce", u8"Hashtag", u8"RightShiftArithmetic", u8"LeftShiftArithmetic", u8"RightShiftLogical", u8"LessThan", u8"MoreThan", u8"LessThanEquals", u8"GreaterThanEquals", u8"Equals_", u8"NotEquals", u8"IdentityEquals", u8"IdentityNotEquals", u8"BitAnd", u8"BitXOr", u8"BitOr", u8"And", u8"Or", u8"MultiplyAssign", u8"DivideAssign", u8"ModulusAssign", u8"PlusAssign", u8"MinusAssign", u8"LeftShiftArithmeticAssign", u8"RightShiftArithmeticAssign", u8"RightShiftLogicalAssign", u8"BitAndAssign", u8"BitXorAssign", u8"BitOrAssign", u8"PowerAssign", u8"ARROW", u8"NullLiteral", u8"BooleanLiteral", u8"DecimalLiteral", u8"HexIntegerLiteral", u8"OctalIntegerLiteral", u8"OctalIntegerLiteral2", u8"BinaryIntegerLiteral", u8"BigHexIntegerLiteral", u8"BigOctalIntegerLiteral", u8"BigBinaryIntegerLiteral", u8"BigDecimalIntegerLiteral", u8"Break", u8"Do", u8"Instanceof", u8"Typeof", u8"Case", u8"Else", u8"New", u8"Var", u8"Catch", u8"Finally", u8"Return", u8"Void", u8"Continue", u8"For", u8"Switch", u8"While", u8"Debugger", u8"Function", u8"This", u8"With", u8"Default", u8"If", u8"Throw", u8"Delete", u8"In", u8"Try", u8"As", u8"From", u8"Class", u8"Enum", u8"Extends", u8"Super", u8"Const", u8"Export", u8"Import", u8"Async", u8"Await", u8"Implements", u8"Let", u8"Private", u8"Public", u8"Interface", u8"Package", u8"Protected", u8"Static", u8"Yield", u8"Identifier", u8"StringLiteral", u8"TemplateStringLiteral", u8"WhiteSpaces", u8"LineTerminator", u8"HtmlComment", u8"CDataComment", u8"UnexpectedCharacter", u8"DoubleStringCharacter", u8"SingleStringCharacter", u8"EscapeSequence", u8"CharacterEscapeSequence", u8"HexEscapeSequence", u8"UnicodeEscapeSequence", u8"ExtendedUnicodeEscapeSequence", u8"SingleEscapeCharacter", u8"NonEscapeCharacter", u8"EscapeCharacter", u8"LineContinuation", u8"HexDigit", u8"DecimalIntegerLiteral", u8"ExponentPart", u8"IdentifierPart", u8"IdentifierStart", u8"UnicodeLetter", u8"UnicodeCombiningMark", u8"UnicodeDigit", u8"UnicodeConnectorPunctuation", u8"RegularExpressionFirstChar", u8"RegularExpressionChar", u8"RegularExpressionClassChar", u8"RegularExpressionBackslashSequence" }; std::vector<std::string> JavaScriptLexer::_channelNames = { "DEFAULT_TOKEN_CHANNEL", "HIDDEN", u8"ERROR" }; std::vector<std::string> JavaScriptLexer::_modeNames = { u8"DEFAULT_MODE" }; std::vector<std::string> JavaScriptLexer::_literalNames = { "", "", "", "", "", u8"'['", u8"']'", u8"'('", u8"')'", u8"'{'", u8"'}'", u8"';'", u8"','", u8"'='", u8"'?'", u8"':'", u8"'...'", u8"'.'", u8"'++'", u8"'--'", u8"'+'", u8"'-'", u8"'~'", u8"'!'", u8"'*'", u8"'/'", u8"'%'", u8"'**'", u8"'??'", u8"'#'", u8"'>>'", u8"'<<'", u8"'>>>'", u8"'<'", u8"'>'", u8"'<='", u8"'>='", u8"'=='", u8"'!='", u8"'==='", u8"'!=='", u8"'&'", u8"'^'", u8"'|'", u8"'&&'", u8"'||'", u8"'*='", u8"'/='", u8"'%='", u8"'+='", u8"'-='", u8"'<<='", u8"'>>='", u8"'>>>='", u8"'&='", u8"'^='", u8"'|='", u8"'**='", u8"'=>'", u8"'null'", "", "", "", "", "", "", "", "", "", "", u8"'break'", u8"'do'", u8"'instanceof'", u8"'typeof'", u8"'case'", u8"'else'", u8"'new'", u8"'var'", u8"'catch'", u8"'finally'", u8"'return'", u8"'void'", u8"'continue'", u8"'for'", u8"'switch'", u8"'while'", u8"'debugger'", u8"'function'", u8"'this'", u8"'with'", u8"'default'", u8"'if'", u8"'throw'", u8"'delete'", u8"'in'", u8"'try'", u8"'as'", u8"'from'", u8"'class'", u8"'enum'", u8"'extends'", u8"'super'", u8"'const'", u8"'export'", u8"'import'", u8"'async'", u8"'await'", u8"'implements'", u8"'let'", u8"'private'", u8"'public'", u8"'interface'", u8"'package'", u8"'protected'", u8"'static'", u8"'yield'" }; std::vector<std::string> JavaScriptLexer::_symbolicNames = { "", u8"HashBangLine", u8"MultiLineComment", u8"SingleLineComment", u8"RegularExpressionLiteral", u8"OpenBracket", u8"CloseBracket", u8"OpenParen", u8"CloseParen", u8"OpenBrace", u8"CloseBrace", u8"SemiColon", u8"Comma", u8"Assign", u8"QuestionMark", u8"Colon", u8"Ellipsis", u8"Dot", u8"PlusPlus", u8"MinusMinus", u8"Plus", u8"Minus", u8"BitNot", u8"Not", u8"Multiply", u8"Divide", u8"Modulus", u8"Power", u8"NullCoalesce", u8"Hashtag", u8"RightShiftArithmetic", u8"LeftShiftArithmetic", u8"RightShiftLogical", u8"LessThan", u8"MoreThan", u8"LessThanEquals", u8"GreaterThanEquals", u8"Equals_", u8"NotEquals", u8"IdentityEquals", u8"IdentityNotEquals", u8"BitAnd", u8"BitXOr", u8"BitOr", u8"And", u8"Or", u8"MultiplyAssign", u8"DivideAssign", u8"ModulusAssign", u8"PlusAssign", u8"MinusAssign", u8"LeftShiftArithmeticAssign", u8"RightShiftArithmeticAssign", u8"RightShiftLogicalAssign", u8"BitAndAssign", u8"BitXorAssign", u8"BitOrAssign", u8"PowerAssign", u8"ARROW", u8"NullLiteral", u8"BooleanLiteral", u8"DecimalLiteral", u8"HexIntegerLiteral", u8"OctalIntegerLiteral", u8"OctalIntegerLiteral2", u8"BinaryIntegerLiteral", u8"BigHexIntegerLiteral", u8"BigOctalIntegerLiteral", u8"BigBinaryIntegerLiteral", u8"BigDecimalIntegerLiteral", u8"Break", u8"Do", u8"Instanceof", u8"Typeof", u8"Case", u8"Else", u8"New", u8"Var", u8"Catch", u8"Finally", u8"Return", u8"Void", u8"Continue", u8"For", u8"Switch", u8"While", u8"Debugger", u8"Function", u8"This", u8"With", u8"Default", u8"If", u8"Throw", u8"Delete", u8"In", u8"Try", u8"As", u8"From", u8"Class", u8"Enum", u8"Extends", u8"Super", u8"Const", u8"Export", u8"Import", u8"Async", u8"Await", u8"Implements", u8"Let", u8"Private", u8"Public", u8"Interface", u8"Package", u8"Protected", u8"Static", u8"Yield", u8"Identifier", u8"StringLiteral", u8"TemplateStringLiteral", u8"WhiteSpaces", u8"LineTerminator", u8"HtmlComment", u8"CDataComment", u8"UnexpectedCharacter" }; dfa::Vocabulary JavaScriptLexer::_vocabulary(_literalNames, _symbolicNames); std::vector<std::string> JavaScriptLexer::_tokenNames; JavaScriptLexer::Initializer::Initializer() { // This code could be in a static initializer lambda, but VS doesn't allow access to private class members from there. for (size_t i = 0; i < _symbolicNames.size(); ++i) { std::string name = _vocabulary.getLiteralName(i); if (name.empty()) { name = _vocabulary.getSymbolicName(i); } if (name.empty()) { _tokenNames.push_back("<INVALID>"); } else { _tokenNames.push_back(name); } } _serializedATN = { 0x3, 0x608b, 0xa72a, 0x8133, 0xb9ed, 0x417c, 0x3be7, 0x7786, 0x5964, 0x2, 0x7d, 0x484, 0x8, 0x1, 0x4, 0x2, 0x9, 0x2, 0x4, 0x3, 0x9, 0x3, 0x4, 0x4, 0x9, 0x4, 0x4, 0x5, 0x9, 0x5, 0x4, 0x6, 0x9, 0x6, 0x4, 0x7, 0x9, 0x7, 0x4, 0x8, 0x9, 0x8, 0x4, 0x9, 0x9, 0x9, 0x4, 0xa, 0x9, 0xa, 0x4, 0xb, 0x9, 0xb, 0x4, 0xc, 0x9, 0xc, 0x4, 0xd, 0x9, 0xd, 0x4, 0xe, 0x9, 0xe, 0x4, 0xf, 0x9, 0xf, 0x4, 0x10, 0x9, 0x10, 0x4, 0x11, 0x9, 0x11, 0x4, 0x12, 0x9, 0x12, 0x4, 0x13, 0x9, 0x13, 0x4, 0x14, 0x9, 0x14, 0x4, 0x15, 0x9, 0x15, 0x4, 0x16, 0x9, 0x16, 0x4, 0x17, 0x9, 0x17, 0x4, 0x18, 0x9, 0x18, 0x4, 0x19, 0x9, 0x19, 0x4, 0x1a, 0x9, 0x1a, 0x4, 0x1b, 0x9, 0x1b, 0x4, 0x1c, 0x9, 0x1c, 0x4, 0x1d, 0x9, 0x1d, 0x4, 0x1e, 0x9, 0x1e, 0x4, 0x1f, 0x9, 0x1f, 0x4, 0x20, 0x9, 0x20, 0x4, 0x21, 0x9, 0x21, 0x4, 0x22, 0x9, 0x22, 0x4, 0x23, 0x9, 0x23, 0x4, 0x24, 0x9, 0x24, 0x4, 0x25, 0x9, 0x25, 0x4, 0x26, 0x9, 0x26, 0x4, 0x27, 0x9, 0x27, 0x4, 0x28, 0x9, 0x28, 0x4, 0x29, 0x9, 0x29, 0x4, 0x2a, 0x9, 0x2a, 0x4, 0x2b, 0x9, 0x2b, 0x4, 0x2c, 0x9, 0x2c, 0x4, 0x2d, 0x9, 0x2d, 0x4, 0x2e, 0x9, 0x2e, 0x4, 0x2f, 0x9, 0x2f, 0x4, 0x30, 0x9, 0x30, 0x4, 0x31, 0x9, 0x31, 0x4, 0x32, 0x9, 0x32, 0x4, 0x33, 0x9, 0x33, 0x4, 0x34, 0x9, 0x34, 0x4, 0x35, 0x9, 0x35, 0x4, 0x36, 0x9, 0x36, 0x4, 0x37, 0x9, 0x37, 0x4, 0x38, 0x9, 0x38, 0x4, 0x39, 0x9, 0x39, 0x4, 0x3a, 0x9, 0x3a, 0x4, 0x3b, 0x9, 0x3b, 0x4, 0x3c, 0x9, 0x3c, 0x4, 0x3d, 0x9, 0x3d, 0x4, 0x3e, 0x9, 0x3e, 0x4, 0x3f, 0x9, 0x3f, 0x4, 0x40, 0x9, 0x40, 0x4, 0x41, 0x9, 0x41, 0x4, 0x42, 0x9, 0x42, 0x4, 0x43, 0x9, 0x43, 0x4, 0x44, 0x9, 0x44, 0x4, 0x45, 0x9, 0x45, 0x4, 0x46, 0x9, 0x46, 0x4, 0x47, 0x9, 0x47, 0x4, 0x48, 0x9, 0x48, 0x4, 0x49, 0x9, 0x49, 0x4, 0x4a, 0x9, 0x4a, 0x4, 0x4b, 0x9, 0x4b, 0x4, 0x4c, 0x9, 0x4c, 0x4, 0x4d, 0x9, 0x4d, 0x4, 0x4e, 0x9, 0x4e, 0x4, 0x4f, 0x9, 0x4f, 0x4, 0x50, 0x9, 0x50, 0x4, 0x51, 0x9, 0x51, 0x4, 0x52, 0x9, 0x52, 0x4, 0x53, 0x9, 0x53, 0x4, 0x54, 0x9, 0x54, 0x4, 0x55, 0x9, 0x55, 0x4, 0x56, 0x9, 0x56, 0x4, 0x57, 0x9, 0x57, 0x4, 0x58, 0x9, 0x58, 0x4, 0x59, 0x9, 0x59, 0x4, 0x5a, 0x9, 0x5a, 0x4, 0x5b, 0x9, 0x5b, 0x4, 0x5c, 0x9, 0x5c, 0x4, 0x5d, 0x9, 0x5d, 0x4, 0x5e, 0x9, 0x5e, 0x4, 0x5f, 0x9, 0x5f, 0x4, 0x60, 0x9, 0x60, 0x4, 0x61, 0x9, 0x61, 0x4, 0x62, 0x9, 0x62, 0x4, 0x63, 0x9, 0x63, 0x4, 0x64, 0x9, 0x64, 0x4, 0x65, 0x9, 0x65, 0x4, 0x66, 0x9, 0x66, 0x4, 0x67, 0x9, 0x67, 0x4, 0x68, 0x9, 0x68, 0x4, 0x69, 0x9, 0x69, 0x4, 0x6a, 0x9, 0x6a, 0x4, 0x6b, 0x9, 0x6b, 0x4, 0x6c, 0x9, 0x6c, 0x4, 0x6d, 0x9, 0x6d, 0x4, 0x6e, 0x9, 0x6e, 0x4, 0x6f, 0x9, 0x6f, 0x4, 0x70, 0x9, 0x70, 0x4, 0x71, 0x9, 0x71, 0x4, 0x72, 0x9, 0x72, 0x4, 0x73, 0x9, 0x73, 0x4, 0x74, 0x9, 0x74, 0x4, 0x75, 0x9, 0x75, 0x4, 0x76, 0x9, 0x76, 0x4, 0x77, 0x9, 0x77, 0x4, 0x78, 0x9, 0x78, 0x4, 0x79, 0x9, 0x79, 0x4, 0x7a, 0x9, 0x7a, 0x4, 0x7b, 0x9, 0x7b, 0x4, 0x7c, 0x9, 0x7c, 0x4, 0x7d, 0x9, 0x7d, 0x4, 0x7e, 0x9, 0x7e, 0x4, 0x7f, 0x9, 0x7f, 0x4, 0x80, 0x9, 0x80, 0x4, 0x81, 0x9, 0x81, 0x4, 0x82, 0x9, 0x82, 0x4, 0x83, 0x9, 0x83, 0x4, 0x84, 0x9, 0x84, 0x4, 0x85, 0x9, 0x85, 0x4, 0x86, 0x9, 0x86, 0x4, 0x87, 0x9, 0x87, 0x4, 0x88, 0x9, 0x88, 0x4, 0x89, 0x9, 0x89, 0x4, 0x8a, 0x9, 0x8a, 0x4, 0x8b, 0x9, 0x8b, 0x4, 0x8c, 0x9, 0x8c, 0x4, 0x8d, 0x9, 0x8d, 0x4, 0x8e, 0x9, 0x8e, 0x4, 0x8f, 0x9, 0x8f, 0x4, 0x90, 0x9, 0x90, 0x4, 0x91, 0x9, 0x91, 0x4, 0x92, 0x9, 0x92, 0x4, 0x93, 0x9, 0x93, 0x4, 0x94, 0x9, 0x94, 0x3, 0x2, 0x3, 0x2, 0x3, 0x2, 0x3, 0x2, 0x3, 0x2, 0x7, 0x2, 0x12f, 0xa, 0x2, 0xc, 0x2, 0xe, 0x2, 0x132, 0xb, 0x2, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x7, 0x3, 0x138, 0xa, 0x3, 0xc, 0x3, 0xe, 0x3, 0x13b, 0xb, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x4, 0x3, 0x4, 0x3, 0x4, 0x7, 0x4, 0x146, 0xa, 0x4, 0xc, 0x4, 0xe, 0x4, 0x149, 0xb, 0x4, 0x3, 0x4, 0x3, 0x4, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x7, 0x5, 0x150, 0xa, 0x5, 0xc, 0x5, 0xe, 0x5, 0x153, 0xb, 0x5, 0x3, 0x5, 0x3, 0x5, 0x3, 0x5, 0x7, 0x5, 0x158, 0xa, 0x5, 0xc, 0x5, 0xe, 0x5, 0x15b, 0xb, 0x5, 0x3, 0x6, 0x3, 0x6, 0x3, 0x7, 0x3, 0x7, 0x3, 0x8, 0x3, 0x8, 0x3, 0x9, 0x3, 0x9, 0x3, 0xa, 0x3, 0xa, 0x3, 0xa, 0x3, 0xb, 0x3, 0xb, 0x3, 0xb, 0x3, 0xc, 0x3, 0xc, 0x3, 0xd, 0x3, 0xd, 0x3, 0xe, 0x3, 0xe, 0x3, 0xf, 0x3, 0xf, 0x3, 0x10, 0x3, 0x10, 0x3, 0x11, 0x3, 0x11, 0x3, 0x11, 0x3, 0x11, 0x3, 0x12, 0x3, 0x12, 0x3, 0x13, 0x3, 0x13, 0x3, 0x13, 0x3, 0x14, 0x3, 0x14, 0x3, 0x14, 0x3, 0x15, 0x3, 0x15, 0x3, 0x16, 0x3, 0x16, 0x3, 0x17, 0x3, 0x17, 0x3, 0x18, 0x3, 0x18, 0x3, 0x19, 0x3, 0x19, 0x3, 0x1a, 0x3, 0x1a, 0x3, 0x1b, 0x3, 0x1b, 0x3, 0x1c, 0x3, 0x1c, 0x3, 0x1c, 0x3, 0x1d, 0x3, 0x1d, 0x3, 0x1d, 0x3, 0x1e, 0x3, 0x1e, 0x3, 0x1f, 0x3, 0x1f, 0x3, 0x1f, 0x3, 0x20, 0x3, 0x20, 0x3, 0x20, 0x3, 0x21, 0x3, 0x21, 0x3, 0x21, 0x3, 0x21, 0x3, 0x22, 0x3, 0x22, 0x3, 0x23, 0x3, 0x23, 0x3, 0x24, 0x3, 0x24, 0x3, 0x24, 0x3, 0x25, 0x3, 0x25, 0x3, 0x25, 0x3, 0x26, 0x3, 0x26, 0x3, 0x26, 0x3, 0x27, 0x3, 0x27, 0x3, 0x27, 0x3, 0x28, 0x3, 0x28, 0x3, 0x28, 0x3, 0x28, 0x3, 0x29, 0x3, 0x29, 0x3, 0x29, 0x3, 0x29, 0x3, 0x2a, 0x3, 0x2a, 0x3, 0x2b, 0x3, 0x2b, 0x3, 0x2c, 0x3, 0x2c, 0x3, 0x2d, 0x3, 0x2d, 0x3, 0x2d, 0x3, 0x2e, 0x3, 0x2e, 0x3, 0x2e, 0x3, 0x2f, 0x3, 0x2f, 0x3, 0x2f, 0x3, 0x30, 0x3, 0x30, 0x3, 0x30, 0x3, 0x31, 0x3, 0x31, 0x3, 0x31, 0x3, 0x32, 0x3, 0x32, 0x3, 0x32, 0x3, 0x33, 0x3, 0x33, 0x3, 0x33, 0x3, 0x34, 0x3, 0x34, 0x3, 0x34, 0x3, 0x34, 0x3, 0x35, 0x3, 0x35, 0x3, 0x35, 0x3, 0x35, 0x3, 0x36, 0x3, 0x36, 0x3, 0x36, 0x3, 0x36, 0x3, 0x36, 0x3, 0x37, 0x3, 0x37, 0x3, 0x37, 0x3, 0x38, 0x3, 0x38, 0x3, 0x38, 0x3, 0x39, 0x3, 0x39, 0x3, 0x39, 0x3, 0x3a, 0x3, 0x3a, 0x3, 0x3a, 0x3, 0x3a, 0x3, 0x3b, 0x3, 0x3b, 0x3, 0x3b, 0x3, 0x3c, 0x3, 0x3c, 0x3, 0x3c, 0x3, 0x3c, 0x3, 0x3c, 0x3, 0x3d, 0x3, 0x3d, 0x3, 0x3d, 0x3, 0x3d, 0x3, 0x3d, 0x3, 0x3d, 0x3, 0x3d, 0x3, 0x3d, 0x3, 0x3d, 0x5, 0x3d, 0x1ff, 0xa, 0x3d, 0x3, 0x3e, 0x3, 0x3e, 0x3, 0x3e, 0x3, 0x3e, 0x7, 0x3e, 0x205, 0xa, 0x3e, 0xc, 0x3e, 0xe, 0x3e, 0x208, 0xb, 0x3e, 0x3, 0x3e, 0x5, 0x3e, 0x20b, 0xa, 0x3e, 0x3, 0x3e, 0x3, 0x3e, 0x3, 0x3e, 0x7, 0x3e, 0x210, 0xa, 0x3e, 0xc, 0x3e, 0xe, 0x3e, 0x213, 0xb, 0x3e, 0x3, 0x3e, 0x5, 0x3e, 0x216, 0xa, 0x3e, 0x3, 0x3e, 0x3, 0x3e, 0x5, 0x3e, 0x21a, 0xa, 0x3e, 0x5, 0x3e, 0x21c, 0xa, 0x3e, 0x3, 0x3f, 0x3, 0x3f, 0x3, 0x3f, 0x3, 0x3f, 0x7, 0x3f, 0x222, 0xa, 0x3f, 0xc, 0x3f, 0xe, 0x3f, 0x225, 0xb, 0x3f, 0x3, 0x40, 0x3, 0x40, 0x6, 0x40, 0x229, 0xa, 0x40, 0xd, 0x40, 0xe, 0x40, 0x22a, 0x3, 0x40, 0x3, 0x40, 0x3, 0x41, 0x3, 0x41, 0x3, 0x41, 0x3, 0x41, 0x7, 0x41, 0x233, 0xa, 0x41, 0xc, 0x41, 0xe, 0x41, 0x236, 0xb, 0x41, 0x3, 0x42, 0x3, 0x42, 0x3, 0x42, 0x3, 0x42, 0x7, 0x42, 0x23c, 0xa, 0x42, 0xc, 0x42, 0xe, 0x42, 0x23f, 0xb, 0x42, 0x3, 0x43, 0x3, 0x43, 0x3, 0x43, 0x3, 0x43, 0x7, 0x43, 0x245, 0xa, 0x43, 0xc, 0x43, 0xe, 0x43, 0x248, 0xb, 0x43, 0x3, 0x43, 0x3, 0x43, 0x3, 0x44, 0x3, 0x44, 0x3, 0x44, 0x3, 0x44, 0x7, 0x44, 0x250, 0xa, 0x44, 0xc, 0x44, 0xe, 0x44, 0x253, 0xb, 0x44, 0x3, 0x44, 0x3, 0x44, 0x3, 0x45, 0x3, 0x45, 0x3, 0x45, 0x3, 0x45, 0x7, 0x45, 0x25b, 0xa, 0x45, 0xc, 0x45, 0xe, 0x45, 0x25e, 0xb, 0x45, 0x3, 0x45, 0x3, 0x45, 0x3, 0x46, 0x3, 0x46, 0x3, 0x46, 0x3, 0x47, 0x3, 0x47, 0x3, 0x47, 0x3, 0x47, 0x3, 0x47, 0x3, 0x47, 0x3, 0x48, 0x3, 0x48, 0x3, 0x48, 0x3, 0x49, 0x3, 0x49, 0x3, 0x49, 0x3, 0x49, 0x3, 0x49, 0x3, 0x49, 0x3, 0x49, 0x3, 0x49, 0x3, 0x49, 0x3, 0x49, 0x3, 0x49, 0x3, 0x4a, 0x3, 0x4a, 0x3, 0x4a, 0x3, 0x4a, 0x3, 0x4a, 0x3, 0x4a, 0x3, 0x4a, 0x3, 0x4b, 0x3, 0x4b, 0x3, 0x4b, 0x3, 0x4b, 0x3, 0x4b, 0x3, 0x4c, 0x3, 0x4c, 0x3, 0x4c, 0x3, 0x4c, 0x3, 0x4c, 0x3, 0x4d, 0x3, 0x4d, 0x3, 0x4d, 0x3, 0x4d, 0x3, 0x4e, 0x3, 0x4e, 0x3, 0x4e, 0x3, 0x4e, 0x3, 0x4f, 0x3, 0x4f, 0x3, 0x4f, 0x3, 0x4f, 0x3, 0x4f, 0x3, 0x4f, 0x3, 0x50, 0x3, 0x50, 0x3, 0x50, 0x3, 0x50, 0x3, 0x50, 0x3, 0x50, 0x3, 0x50, 0x3, 0x50, 0x3, 0x51, 0x3, 0x51, 0x3, 0x51, 0x3, 0x51, 0x3, 0x51, 0x3, 0x51, 0x3, 0x51, 0x3, 0x52, 0x3, 0x52, 0x3, 0x52, 0x3, 0x52, 0x3, 0x52, 0x3, 0x53, 0x3, 0x53, 0x3, 0x53, 0x3, 0x53, 0x3, 0x53, 0x3, 0x53, 0x3, 0x53, 0x3, 0x53, 0x3, 0x53, 0x3, 0x54, 0x3, 0x54, 0x3, 0x54, 0x3, 0x54, 0x3, 0x55, 0x3, 0x55, 0x3, 0x55, 0x3, 0x55, 0x3, 0x55, 0x3, 0x55, 0x3, 0x55, 0x3, 0x56, 0x3, 0x56, 0x3, 0x56, 0x3, 0x56, 0x3, 0x56, 0x3, 0x56, 0x3, 0x57, 0x3, 0x57, 0x3, 0x57, 0x3, 0x57, 0x3, 0x57, 0x3, 0x57, 0x3, 0x57, 0x3, 0x57, 0x3, 0x57, 0x3, 0x58, 0x3, 0x58, 0x3, 0x58, 0x3, 0x58, 0x3, 0x58, 0x3, 0x58, 0x3, 0x58, 0x3, 0x58, 0x3, 0x58, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x59, 0x3, 0x5a, 0x3, 0x5a, 0x3, 0x5a, 0x3, 0x5a, 0x3, 0x5a, 0x3, 0x5b, 0x3, 0x5b, 0x3, 0x5b, 0x3, 0x5b, 0x3, 0x5b, 0x3, 0x5b, 0x3, 0x5b, 0x3, 0x5b, 0x3, 0x5c, 0x3, 0x5c, 0x3, 0x5c, 0x3, 0x5d, 0x3, 0x5d, 0x3, 0x5d, 0x3, 0x5d, 0x3, 0x5d, 0x3, 0x5d, 0x3, 0x5e, 0x3, 0x5e, 0x3, 0x5e, 0x3, 0x5e, 0x3, 0x5e, 0x3, 0x5e, 0x3, 0x5e, 0x3, 0x5f, 0x3, 0x5f, 0x3, 0x5f, 0x3, 0x60, 0x3, 0x60, 0x3, 0x60, 0x3, 0x60, 0x3, 0x61, 0x3, 0x61, 0x3, 0x61, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x62, 0x3, 0x63, 0x3, 0x63, 0x3, 0x63, 0x3, 0x63, 0x3, 0x63, 0x3, 0x63, 0x3, 0x64, 0x3, 0x64, 0x3, 0x64, 0x3, 0x64, 0x3, 0x64, 0x3, 0x65, 0x3, 0x65, 0x3, 0x65, 0x3, 0x65, 0x3, 0x65, 0x3, 0x65, 0x3, 0x65, 0x3, 0x65, 0x3, 0x66, 0x3, 0x66, 0x3, 0x66, 0x3, 0x66, 0x3, 0x66, 0x3, 0x66, 0x3, 0x67, 0x3, 0x67, 0x3, 0x67, 0x3, 0x67, 0x3, 0x67, 0x3, 0x67, 0x3, 0x68, 0x3, 0x68, 0x3, 0x68, 0x3, 0x68, 0x3, 0x68, 0x3, 0x68, 0x3, 0x68, 0x3, 0x69, 0x3, 0x69, 0x3, 0x69, 0x3, 0x69, 0x3, 0x69, 0x3, 0x69, 0x3, 0x69, 0x3, 0x6a, 0x3, 0x6a, 0x3, 0x6a, 0x3, 0x6a, 0x3, 0x6a, 0x3, 0x6a, 0x3, 0x6b, 0x3, 0x6b, 0x3, 0x6b, 0x3, 0x6b, 0x3, 0x6b, 0x3, 0x6b, 0x3, 0x6c, 0x3, 0x6c, 0x3, 0x6c, 0x3, 0x6c, 0x3, 0x6c, 0x3, 0x6c, 0x3, 0x6c, 0x3, 0x6c, 0x3, 0x6c, 0x3, 0x6c, 0x3, 0x6c, 0x3, 0x6c, 0x3, 0x6c, 0x3, 0x6d, 0x3, 0x6d, 0x3, 0x6d, 0x3, 0x6d, 0x3, 0x6d, 0x3, 0x6d, 0x3, 0x6e, 0x3, 0x6e, 0x3, 0x6e, 0x3, 0x6e, 0x3, 0x6e, 0x3, 0x6e, 0x3, 0x6e, 0x3, 0x6e, 0x3, 0x6e, 0x3, 0x6e, 0x3, 0x6f, 0x3, 0x6f, 0x3, 0x6f, 0x3, 0x6f, 0x3, 0x6f, 0x3, 0x6f, 0x3, 0x6f, 0x3, 0x6f, 0x3, 0x6f, 0x3, 0x70, 0x3, 0x70, 0x3, 0x70, 0x3, 0x70, 0x3, 0x70, 0x3, 0x70, 0x3, 0x70, 0x3, 0x70, 0x3, 0x70, 0x3, 0x70, 0x3, 0x70, 0x3, 0x70, 0x3, 0x71, 0x3, 0x71, 0x3, 0x71, 0x3, 0x71, 0x3, 0x71, 0x3, 0x71, 0x3, 0x71, 0x3, 0x71, 0x3, 0x71, 0x3, 0x71, 0x3, 0x72, 0x3, 0x72, 0x3, 0x72, 0x3, 0x72, 0x3, 0x72, 0x3, 0x72, 0x3, 0x72, 0x3, 0x72, 0x3, 0x72, 0x3, 0x72, 0x3, 0x72, 0x3, 0x72, 0x3, 0x73, 0x3, 0x73, 0x3, 0x73, 0x3, 0x73, 0x3, 0x73, 0x3, 0x73, 0x3, 0x73, 0x3, 0x73, 0x3, 0x73, 0x3, 0x74, 0x3, 0x74, 0x3, 0x74, 0x3, 0x74, 0x3, 0x74, 0x3, 0x74, 0x3, 0x74, 0x3, 0x74, 0x3, 0x75, 0x3, 0x75, 0x7, 0x75, 0x39d, 0xa, 0x75, 0xc, 0x75, 0xe, 0x75, 0x3a0, 0xb, 0x75, 0x3, 0x76, 0x3, 0x76, 0x7, 0x76, 0x3a4, 0xa, 0x76, 0xc, 0x76, 0xe, 0x76, 0x3a7, 0xb, 0x76, 0x3, 0x76, 0x3, 0x76, 0x3, 0x76, 0x7, 0x76, 0x3ac, 0xa, 0x76, 0xc, 0x76, 0xe, 0x76, 0x3af, 0xb, 0x76, 0x3, 0x76, 0x5, 0x76, 0x3b2, 0xa, 0x76, 0x3, 0x76, 0x3, 0x76, 0x3, 0x77, 0x3, 0x77, 0x3, 0x77, 0x3, 0x77, 0x7, 0x77, 0x3ba, 0xa, 0x77, 0xc, 0x77, 0xe, 0x77, 0x3bd, 0xb, 0x77, 0x3, 0x77, 0x3, 0x77, 0x3, 0x78, 0x6, 0x78, 0x3c2, 0xa, 0x78, 0xd, 0x78, 0xe, 0x78, 0x3c3, 0x3, 0x78, 0x3, 0x78, 0x3, 0x79, 0x3, 0x79, 0x3, 0x79, 0x3, 0x79, 0x3, 0x7a, 0x3, 0x7a, 0x3, 0x7a, 0x3, 0x7a, 0x3, 0x7a, 0x3, 0x7a, 0x7, 0x7a, 0x3d2, 0xa, 0x7a, 0xc, 0x7a, 0xe, 0x7a, 0x3d5, 0xb, 0x7a, 0x3, 0x7a, 0x3, 0x7a, 0x3, 0x7a, 0x3, 0x7a, 0x3, 0x7a, 0x3, 0x7a, 0x3, 0x7b, 0x3, 0x7b, 0x3, 0x7b, 0x3, 0x7b, 0x3, 0x7b, 0x3, 0x7b, 0x3, 0x7b, 0x3, 0x7b, 0x3, 0x7b, 0x3, 0x7b, 0x3, 0x7b, 0x7, 0x7b, 0x3e8, 0xa, 0x7b, 0xc, 0x7b, 0xe, 0x7b, 0x3eb, 0xb, 0x7b, 0x3, 0x7b, 0x3, 0x7b, 0x3, 0x7b, 0x3, 0x7b, 0x3, 0x7b, 0x3, 0x7b, 0x3, 0x7c, 0x3, 0x7c, 0x3, 0x7c, 0x3, 0x7c, 0x3, 0x7d, 0x3, 0x7d, 0x3, 0x7d, 0x3, 0x7d, 0x5, 0x7d, 0x3fb, 0xa, 0x7d, 0x3, 0x7e, 0x3, 0x7e, 0x3, 0x7e, 0x3, 0x7e, 0x5, 0x7e, 0x401, 0xa, 0x7e, 0x3, 0x7f, 0x3, 0x7f, 0x3, 0x7f, 0x3, 0x7f, 0x3, 0x7f, 0x5, 0x7f, 0x408, 0xa, 0x7f, 0x3, 0x80, 0x3, 0x80, 0x5, 0x80, 0x40c, 0xa, 0x80, 0x3, 0x81, 0x3, 0x81, 0x3, 0x81, 0x3, 0x81, 0x3, 0x82, 0x3, 0x82, 0x3, 0x82, 0x3, 0x82, 0x3, 0x82, 0x3, 0x82, 0x3, 0x82, 0x3, 0x82, 0x3, 0x82, 0x3, 0x82, 0x6, 0x82, 0x41c, 0xa, 0x82, 0xd, 0x82, 0xe, 0x82, 0x41d, 0x3, 0x82, 0x3, 0x82, 0x5, 0x82, 0x422, 0xa, 0x82, 0x3, 0x83, 0x3, 0x83, 0x3, 0x83, 0x6, 0x83, 0x427, 0xa, 0x83, 0xd, 0x83, 0xe, 0x83, 0x428, 0x3, 0x83, 0x3, 0x83, 0x3, 0x84, 0x3, 0x84, 0x3, 0x85, 0x3, 0x85, 0x3, 0x86, 0x3, 0x86, 0x5, 0x86, 0x433, 0xa, 0x86, 0x3, 0x87, 0x3, 0x87, 0x3, 0x87, 0x3, 0x88, 0x3, 0x88, 0x3, 0x89, 0x3, 0x89, 0x3, 0x89, 0x7, 0x89, 0x43d, 0xa, 0x89, 0xc, 0x89, 0xe, 0x89, 0x440, 0xb, 0x89, 0x5, 0x89, 0x442, 0xa, 0x89, 0x3, 0x8a, 0x3, 0x8a, 0x5, 0x8a, 0x446, 0xa, 0x8a, 0x3, 0x8a, 0x6, 0x8a, 0x449, 0xa, 0x8a, 0xd, 0x8a, 0xe, 0x8a, 0x44a, 0x3, 0x8b, 0x3, 0x8b, 0x3, 0x8b, 0x3, 0x8b, 0x3, 0x8b, 0x5, 0x8b, 0x452, 0xa, 0x8b, 0x3, 0x8c, 0x3, 0x8c, 0x3, 0x8c, 0x3, 0x8c, 0x5, 0x8c, 0x458, 0xa, 0x8c, 0x3, 0x8d, 0x5, 0x8d, 0x45b, 0xa, 0x8d, 0x3, 0x8e, 0x5, 0x8e, 0x45e, 0xa, 0x8e, 0x3, 0x8f, 0x5, 0x8f, 0x461, 0xa, 0x8f, 0x3, 0x90, 0x5, 0x90, 0x464, 0xa, 0x90, 0x3, 0x91, 0x3, 0x91, 0x3, 0x91, 0x3, 0x91, 0x7, 0x91, 0x46a, 0xa, 0x91, 0xc, 0x91, 0xe, 0x91, 0x46d, 0xb, 0x91, 0x3, 0x91, 0x5, 0x91, 0x470, 0xa, 0x91, 0x3, 0x92, 0x3, 0x92, 0x3, 0x92, 0x3, 0x92, 0x7, 0x92, 0x476, 0xa, 0x92, 0xc, 0x92, 0xe, 0x92, 0x479, 0xb, 0x92, 0x3, 0x92, 0x5, 0x92, 0x47c, 0xa, 0x92, 0x3, 0x93, 0x3, 0x93, 0x5, 0x93, 0x480, 0xa, 0x93, 0x3, 0x94, 0x3, 0x94, 0x3, 0x94, 0x5, 0x139, 0x3d3, 0x3e9, 0x2, 0x95, 0x3, 0x3, 0x5, 0x4, 0x7, 0x5, 0x9, 0x6, 0xb, 0x7, 0xd, 0x8, 0xf, 0x9, 0x11, 0xa, 0x13, 0xb, 0x15, 0xc, 0x17, 0xd, 0x19, 0xe, 0x1b, 0xf, 0x1d, 0x10, 0x1f, 0x11, 0x21, 0x12, 0x23, 0x13, 0x25, 0x14, 0x27, 0x15, 0x29, 0x16, 0x2b, 0x17, 0x2d, 0x18, 0x2f, 0x19, 0x31, 0x1a, 0x33, 0x1b, 0x35, 0x1c, 0x37, 0x1d, 0x39, 0x1e, 0x3b, 0x1f, 0x3d, 0x20, 0x3f, 0x21, 0x41, 0x22, 0x43, 0x23, 0x45, 0x24, 0x47, 0x25, 0x49, 0x26, 0x4b, 0x27, 0x4d, 0x28, 0x4f, 0x29, 0x51, 0x2a, 0x53, 0x2b, 0x55, 0x2c, 0x57, 0x2d, 0x59, 0x2e, 0x5b, 0x2f, 0x5d, 0x30, 0x5f, 0x31, 0x61, 0x32, 0x63, 0x33, 0x65, 0x34, 0x67, 0x35, 0x69, 0x36, 0x6b, 0x37, 0x6d, 0x38, 0x6f, 0x39, 0x71, 0x3a, 0x73, 0x3b, 0x75, 0x3c, 0x77, 0x3d, 0x79, 0x3e, 0x7b, 0x3f, 0x7d, 0x40, 0x7f, 0x41, 0x81, 0x42, 0x83, 0x43, 0x85, 0x44, 0x87, 0x45, 0x89, 0x46, 0x8b, 0x47, 0x8d, 0x48, 0x8f, 0x49, 0x91, 0x4a, 0x93, 0x4b, 0x95, 0x4c, 0x97, 0x4d, 0x99, 0x4e, 0x9b, 0x4f, 0x9d, 0x50, 0x9f, 0x51, 0xa1, 0x52, 0xa3, 0x53, 0xa5, 0x54, 0xa7, 0x55, 0xa9, 0x56, 0xab, 0x57, 0xad, 0x58, 0xaf, 0x59, 0xb1, 0x5a, 0xb3, 0x5b, 0xb5, 0x5c, 0xb7, 0x5d, 0xb9, 0x5e, 0xbb, 0x5f, 0xbd, 0x60, 0xbf, 0x61, 0xc1, 0x62, 0xc3, 0x63, 0xc5, 0x64, 0xc7, 0x65, 0xc9, 0x66, 0xcb, 0x67, 0xcd, 0x68, 0xcf, 0x69, 0xd1, 0x6a, 0xd3, 0x6b, 0xd5, 0x6c, 0xd7, 0x6d, 0xd9, 0x6e, 0xdb, 0x6f, 0xdd, 0x70, 0xdf, 0x71, 0xe1, 0x72, 0xe3, 0x73, 0xe5, 0x74, 0xe7, 0x75, 0xe9, 0x76, 0xeb, 0x77, 0xed, 0x78, 0xef, 0x79, 0xf1, 0x7a, 0xf3, 0x7b, 0xf5, 0x7c, 0xf7, 0x7d, 0xf9, 0x2, 0xfb, 0x2, 0xfd, 0x2, 0xff, 0x2, 0x101, 0x2, 0x103, 0x2, 0x105, 0x2, 0x107, 0x2, 0x109, 0x2, 0x10b, 0x2, 0x10d, 0x2, 0x10f, 0x2, 0x111, 0x2, 0x113, 0x2, 0x115, 0x2, 0x117, 0x2, 0x119, 0x2, 0x11b, 0x2, 0x11d, 0x2, 0x11f, 0x2, 0x121, 0x2, 0x123, 0x2, 0x125, 0x2, 0x127, 0x2, 0x3, 0x2, 0x20, 0x5, 0x2, 0xc, 0xc, 0xf, 0xf, 0x202a, 0x202b, 0x3, 0x2, 0x32, 0x3b, 0x4, 0x2, 0x32, 0x3b, 0x61, 0x61, 0x4, 0x2, 0x5a, 0x5a, 0x7a, 0x7a, 0x5, 0x2, 0x32, 0x3b, 0x43, 0x48, 0x63, 0x68, 0x3, 0x2, 0x32, 0x39, 0x4, 0x2, 0x51, 0x51, 0x71, 0x71, 0x4, 0x2, 0x32, 0x39, 0x61, 0x61, 0x4, 0x2, 0x44, 0x44, 0x64, 0x64, 0x3, 0x2, 0x32, 0x33, 0x4, 0x2, 0x32, 0x33, 0x61, 0x61, 0x3, 0x2, 0x62, 0x62, 0x6, 0x2, 0xb, 0xb, 0xd, 0xe, 0x22, 0x22, 0xa2, 0xa2, 0x6, 0x2, 0xc, 0xc, 0xf, 0xf, 0x24, 0x24, 0x5e, 0x5e, 0x6, 0x2, 0xc, 0xc, 0xf, 0xf, 0x29, 0x29, 0x5e, 0x5e, 0xb, 0x2, 0x24, 0x24, 0x29, 0x29, 0x5e, 0x5e, 0x64, 0x64, 0x68, 0x68, 0x70, 0x70, 0x74, 0x74, 0x76, 0x76, 0x78, 0x78, 0xe, 0x2, 0xc, 0xc, 0xf, 0xf, 0x24, 0x24, 0x29, 0x29, 0x32, 0x3b, 0x5e, 0x5e, 0x64, 0x64, 0x68, 0x68, 0x70, 0x70, 0x74, 0x74, 0x76, 0x78, 0x7a, 0x7a, 0x5, 0x2, 0x32, 0x3b, 0x77, 0x77, 0x7a, 0x7a, 0x6, 0x2, 0x32, 0x3b, 0x43, 0x48, 0x61, 0x61, 0x63, 0x68, 0x3, 0x2, 0x33, 0x3b, 0x4, 0x2, 0x47, 0x47, 0x67, 0x67, 0x4, 0x2, 0x2d, 0x2d, 0x2f, 0x2f, 0x4, 0x2, 0x26, 0x26, 0x61, 0x61, 0x101, 0x2, 0x43, 0x5c, 0x63, 0x7c, 0xac, 0xac, 0xb7, 0xb7, 0xbc, 0xbc, 0xc2, 0xd8, 0xda, 0xf8, 0xfa, 0x221, 0x224, 0x235, 0x252, 0x2af, 0x2b2, 0x2ba, 0x2bd, 0x2c3, 0x2d2, 0x2d3, 0x2e2, 0x2e6, 0x2f0, 0x2f0, 0x37c, 0x37c, 0x388, 0x388, 0x38a, 0x38c, 0x38e, 0x38e, 0x390, 0x3a3, 0x3a5, 0x3d0, 0x3d2, 0x3d9, 0x3dc, 0x3f5, 0x402, 0x483, 0x48e, 0x4c6, 0x4c9, 0x4ca, 0x4cd, 0x4ce, 0x4d2, 0x4f7, 0x4fa, 0x4fb, 0x533, 0x558, 0x55b, 0x55b, 0x563, 0x589, 0x5d2, 0x5ec, 0x5f2, 0x5f4, 0x623, 0x63c, 0x642, 0x64c, 0x673, 0x6d5, 0x6d7, 0x6d7, 0x6e7, 0x6e8, 0x6fc, 0x6fe, 0x712, 0x712, 0x714, 0x72e, 0x782, 0x7a7, 0x907, 0x93b, 0x93f, 0x93f, 0x952, 0x952, 0x95a, 0x963, 0x987, 0x98e, 0x991, 0x992, 0x995, 0x9aa, 0x9ac, 0x9b2, 0x9b4, 0x9b4, 0x9b8, 0x9bb, 0x9de, 0x9df, 0x9e1, 0x9e3, 0x9f2, 0x9f3, 0xa07, 0xa0c, 0xa11, 0xa12, 0xa15, 0xa2a, 0xa2c, 0xa32, 0xa34, 0xa35, 0xa37, 0xa38, 0xa3a, 0xa3b, 0xa5b, 0xa5e, 0xa60, 0xa60, 0xa74, 0xa76, 0xa87, 0xa8d, 0xa8f, 0xa8f, 0xa91, 0xa93, 0xa95, 0xaaa, 0xaac, 0xab2, 0xab4, 0xab5, 0xab7, 0xabb, 0xabf, 0xabf, 0xad2, 0xad2, 0xae2, 0xae2, 0xb07, 0xb0e, 0xb11, 0xb12, 0xb15, 0xb2a, 0xb2c, 0xb32, 0xb34, 0xb35, 0xb38, 0xb3b, 0xb3f, 0xb3f, 0xb5e, 0xb5f, 0xb61, 0xb63, 0xb87, 0xb8c, 0xb90, 0xb92, 0xb94, 0xb97, 0xb9b, 0xb9c, 0xb9e, 0xb9e, 0xba0, 0xba1, 0xba5, 0xba6, 0xbaa, 0xbac, 0xbb0, 0xbb7, 0xbb9, 0xbbb, 0xc07, 0xc0e, 0xc10, 0xc12, 0xc14, 0xc2a, 0xc2c, 0xc35, 0xc37, 0xc3b, 0xc62, 0xc63, 0xc87, 0xc8e, 0xc90, 0xc92, 0xc94, 0xcaa, 0xcac, 0xcb5, 0xcb7, 0xcbb, 0xce0, 0xce0, 0xce2, 0xce3, 0xd07, 0xd0e, 0xd10, 0xd12, 0xd14, 0xd2a, 0xd2c, 0xd3b, 0xd62, 0xd63, 0xd87, 0xd98, 0xd9c, 0xdb3, 0xdb5, 0xdbd, 0xdbf, 0xdbf, 0xdc2, 0xdc8, 0xe03, 0xe32, 0xe34, 0xe35, 0xe42, 0xe48, 0xe83, 0xe84, 0xe86, 0xe86, 0xe89, 0xe8a, 0xe8c, 0xe8c, 0xe8f, 0xe8f, 0xe96, 0xe99, 0xe9b, 0xea1, 0xea3, 0xea5, 0xea7, 0xea7, 0xea9, 0xea9, 0xeac, 0xead, 0xeaf, 0xeb2, 0xeb4, 0xeb5, 0xebf, 0xec6, 0xec8, 0xec8, 0xede, 0xedf, 0xf02, 0xf02, 0xf42, 0xf6c, 0xf8a, 0xf8d, 0x1002, 0x1023, 0x1025, 0x1029, 0x102b, 0x102c, 0x1052, 0x1057, 0x10a2, 0x10c7, 0x10d2, 0x10f8, 0x1102, 0x115b, 0x1161, 0x11a4, 0x11aa, 0x11fb, 0x1202, 0x1208, 0x120a, 0x1248, 0x124a, 0x124a, 0x124c, 0x124f, 0x1252, 0x1258, 0x125a, 0x125a, 0x125c, 0x125f, 0x1262, 0x1288, 0x128a, 0x128a, 0x128c, 0x128f, 0x1292, 0x12b0, 0x12b2, 0x12b2, 0x12b4, 0x12b7, 0x12ba, 0x12c0, 0x12c2, 0x12c2, 0x12c4, 0x12c7, 0x12ca, 0x12d0, 0x12d2, 0x12d8, 0x12da, 0x12f0, 0x12f2, 0x1310, 0x1312, 0x1312, 0x1314, 0x1317, 0x131a, 0x1320, 0x1322, 0x1348, 0x134a, 0x135c, 0x13a2, 0x13f6, 0x1403, 0x1678, 0x1683, 0x169c, 0x16a2, 0x16ec, 0x1782, 0x17b5, 0x1822, 0x1879, 0x1882, 0x18aa, 0x1e02, 0x1e9d, 0x1ea2, 0x1efb, 0x1f02, 0x1f17, 0x1f1a, 0x1f1f, 0x1f22, 0x1f47, 0x1f4a, 0x1f4f, 0x1f52, 0x1f59, 0x1f5b, 0x1f5b, 0x1f5d, 0x1f5d, 0x1f5f, 0x1f5f, 0x1f61, 0x1f7f, 0x1f82, 0x1fb6, 0x1fb8, 0x1fbe, 0x1fc0, 0x1fc0, 0x1fc4, 0x1fc6, 0x1fc8, 0x1fce, 0x1fd2, 0x1fd5, 0x1fd8, 0x1fdd, 0x1fe2, 0x1fee, 0x1ff4, 0x1ff6, 0x1ff8, 0x1ffe, 0x2081, 0x2081, 0x2104, 0x2104, 0x2109, 0x2109, 0x210c, 0x2115, 0x2117, 0x2117, 0x211b, 0x211f, 0x2126, 0x2126, 0x2128, 0x2128, 0x212a, 0x212a, 0x212c, 0x212f, 0x2131, 0x2133, 0x2135, 0x213b, 0x2162, 0x2185, 0x3007, 0x3009, 0x3023, 0x302b, 0x3033, 0x3037, 0x303a, 0x303c, 0x3043, 0x3096, 0x309f, 0x30a0, 0x30a3, 0x30fc, 0x30fe, 0x3100, 0x3107, 0x312e, 0x3133, 0x3190, 0x31a2, 0x31b9, 0x3402, 0x4dc1, 0x4e02, 0xa48e, 0xac02, 0xac02, 0xd7a5, 0xd7a5, 0xf902, 0xfa2f, 0xfb02, 0xfb08, 0xfb15, 0xfb19, 0xfb1f, 0xfb1f, 0xfb21, 0xfb2a, 0xfb2c, 0xfb38, 0xfb3a, 0xfb3e, 0xfb40, 0xfb40, 0xfb42, 0xfb43, 0xfb45, 0xfb46, 0xfb48, 0xfbb3, 0xfbd5, 0xfd3f, 0xfd52, 0xfd91, 0xfd94, 0xfdc9, 0xfdf2, 0xfdfd, 0xfe72, 0xfe74, 0xfe76, 0xfe76, 0xfe78, 0xfefe, 0xff23, 0xff3c, 0xff43, 0xff5c, 0xff68, 0xffc0, 0xffc4, 0xffc9, 0xffcc, 0xffd1, 0xffd4, 0xffd9, 0xffdc, 0xffde, 0x66, 0x2, 0x302, 0x350, 0x362, 0x364, 0x485, 0x488, 0x593, 0x5a3, 0x5a5, 0x5bb, 0x5bd, 0x5bf, 0x5c1, 0x5c1, 0x5c3, 0x5c4, 0x5c6, 0x5c6, 0x64d, 0x657, 0x672, 0x672, 0x6d8, 0x6de, 0x6e1, 0x6e6, 0x6e9, 0x6ea, 0x6ec, 0x6ef, 0x713, 0x713, 0x732, 0x74c, 0x7a8, 0x7b2, 0x903, 0x905, 0x93e, 0x93e, 0x940, 0x94f, 0x953, 0x956, 0x964, 0x965, 0x983, 0x985, 0x9be, 0x9c6, 0x9c9, 0x9ca, 0x9cd, 0x9cf, 0x9d9, 0x9d9, 0x9e4, 0x9e5, 0xa04, 0xa04, 0xa3e, 0xa3e, 0xa40, 0xa44, 0xa49, 0xa4a, 0xa4d, 0xa4f, 0xa72, 0xa73, 0xa83, 0xa85, 0xabe, 0xabe, 0xac0, 0xac7, 0xac9, 0xacb, 0xacd, 0xacf, 0xb03, 0xb05, 0xb3e, 0xb3e, 0xb40, 0xb45, 0xb49, 0xb4a, 0xb4d, 0xb4f, 0xb58, 0xb59, 0xb84, 0xb85, 0xbc0, 0xbc4, 0xbc8, 0xbca, 0xbcc, 0xbcf, 0xbd9, 0xbd9, 0xc03, 0xc05, 0xc40, 0xc46, 0xc48, 0xc4a, 0xc4c, 0xc4f, 0xc57, 0xc58, 0xc84, 0xc85, 0xcc0, 0xcc6, 0xcc8, 0xcca, 0xccc, 0xccf, 0xcd7, 0xcd8, 0xd04, 0xd05, 0xd40, 0xd45, 0xd48, 0xd4a, 0xd4c, 0xd4f, 0xd59, 0xd59, 0xd84, 0xd85, 0xdcc, 0xdcc, 0xdd1, 0xdd6, 0xdd8, 0xdd8, 0xdda, 0xde1, 0xdf4, 0xdf5, 0xe33, 0xe33, 0xe36, 0xe3c, 0xe49, 0xe50, 0xeb3, 0xeb3, 0xeb6, 0xebb, 0xebd, 0xebe, 0xeca, 0xecf, 0xf1a, 0xf1b, 0xf37, 0xf37, 0xf39, 0xf39, 0xf3b, 0xf3b, 0xf40, 0xf41, 0xf73, 0xf86, 0xf88, 0xf89, 0xf92, 0xf99, 0xf9b, 0xfbe, 0xfc8, 0xfc8, 0x102e, 0x1034, 0x1038, 0x103b, 0x1058, 0x105b, 0x17b6, 0x17d5, 0x18ab, 0x18ab, 0x20d2, 0x20de, 0x20e3, 0x20e3, 0x302c, 0x3031, 0x309b, 0x309c, 0xfb20, 0xfb20, 0xfe22, 0xfe25, 0x16, 0x2, 0x32, 0x3b, 0x662, 0x66b, 0x6f2, 0x6fb, 0x968, 0x971, 0x9e8, 0x9f1, 0xa68, 0xa71, 0xae8, 0xaf1, 0xb68, 0xb71, 0xbe9, 0xbf1, 0xc68, 0xc71, 0xce8, 0xcf1, 0xd68, 0xd71, 0xe52, 0xe5b, 0xed2, 0xedb, 0xf22, 0xf2b, 0x1042, 0x104b, 0x136b, 0x1373, 0x17e2, 0x17eb, 0x1812, 0x181b, 0xff12, 0xff1b, 0x9, 0x2, 0x61, 0x61, 0x2041, 0x2042, 0x30fd, 0x30fd, 0xfe35, 0xfe36, 0xfe4f, 0xfe51, 0xff41, 0xff41, 0xff67, 0xff67, 0x8, 0x2, 0xc, 0xc, 0xf, 0xf, 0x2c, 0x2c, 0x31, 0x31, 0x5d, 0x5e, 0x202a, 0x202b, 0x7, 0x2, 0xc, 0xc, 0xf, 0xf, 0x31, 0x31, 0x5d, 0x5e, 0x202a, 0x202b, 0x6, 0x2, 0xc, 0xc, 0xf, 0xf, 0x5e, 0x5f, 0x202a, 0x202b, 0x2, 0x4a6, 0x2, 0x3, 0x3, 0x2, 0x2, 0x2, 0x2, 0x5, 0x3, 0x2, 0x2, 0x2, 0x2, 0x7, 0x3, 0x2, 0x2, 0x2, 0x2, 0x9, 0x3, 0x2, 0x2, 0x2, 0x2, 0xb, 0x3, 0x2, 0x2, 0x2, 0x2, 0xd, 0x3, 0x2, 0x2, 0x2, 0x2, 0xf, 0x3, 0x2, 0x2, 0x2, 0x2, 0x11, 0x3, 0x2, 0x2, 0x2, 0x2, 0x13, 0x3, 0x2, 0x2, 0x2, 0x2, 0x15, 0x3, 0x2, 0x2, 0x2, 0x2, 0x17, 0x3, 0x2, 0x2, 0x2, 0x2, 0x19, 0x3, 0x2, 0x2, 0x2, 0x2, 0x1b, 0x3, 0x2, 0x2, 0x2, 0x2, 0x1d, 0x3, 0x2, 0x2, 0x2, 0x2, 0x1f, 0x3, 0x2, 0x2, 0x2, 0x2, 0x21, 0x3, 0x2, 0x2, 0x2, 0x2, 0x23, 0x3, 0x2, 0x2, 0x2, 0x2, 0x25, 0x3, 0x2, 0x2, 0x2, 0x2, 0x27, 0x3, 0x2, 0x2, 0x2, 0x2, 0x29, 0x3, 0x2, 0x2, 0x2, 0x2, 0x2b, 0x3, 0x2, 0x2, 0x2, 0x2, 0x2d, 0x3, 0x2, 0x2, 0x2, 0x2, 0x2f, 0x3, 0x2, 0x2, 0x2, 0x2, 0x31, 0x3, 0x2, 0x2, 0x2, 0x2, 0x33, 0x3, 0x2, 0x2, 0x2, 0x2, 0x35, 0x3, 0x2, 0x2, 0x2, 0x2, 0x37, 0x3, 0x2, 0x2, 0x2, 0x2, 0x39, 0x3, 0x2, 0x2, 0x2, 0x2, 0x3b, 0x3, 0x2, 0x2, 0x2, 0x2, 0x3d, 0x3, 0x2, 0x2, 0x2, 0x2, 0x3f, 0x3, 0x2, 0x2, 0x2, 0x2, 0x41, 0x3, 0x2, 0x2, 0x2, 0x2, 0x43, 0x3, 0x2, 0x2, 0x2, 0x2, 0x45, 0x3, 0x2, 0x2, 0x2, 0x2, 0x47, 0x3, 0x2, 0x2, 0x2, 0x2, 0x49, 0x3, 0x2, 0x2, 0x2, 0x2, 0x4b, 0x3, 0x2, 0x2, 0x2, 0x2, 0x4d, 0x3, 0x2, 0x2, 0x2, 0x2, 0x4f, 0x3, 0x2, 0x2, 0x2, 0x2, 0x51, 0x3, 0x2, 0x2, 0x2, 0x2, 0x53, 0x3, 0x2, 0x2, 0x2, 0x2, 0x55, 0x3, 0x2, 0x2, 0x2, 0x2, 0x57, 0x3, 0x2, 0x2, 0x2, 0x2, 0x59, 0x3, 0x2, 0x2, 0x2, 0x2, 0x5b, 0x3, 0x2, 0x2, 0x2, 0x2, 0x5d, 0x3, 0x2, 0x2, 0x2, 0x2, 0x5f, 0x3, 0x2, 0x2, 0x2, 0x2, 0x61, 0x3, 0x2, 0x2, 0x2, 0x2, 0x63, 0x3, 0x2, 0x2, 0x2, 0x2, 0x65, 0x3, 0x2, 0x2, 0x2, 0x2, 0x67, 0x3, 0x2, 0x2, 0x2, 0x2, 0x69, 0x3, 0x2, 0x2, 0x2, 0x2, 0x6b, 0x3, 0x2, 0x2, 0x2, 0x2, 0x6d, 0x3, 0x2, 0x2, 0x2, 0x2, 0x6f, 0x3, 0x2, 0x2, 0x2, 0x2, 0x71, 0x3, 0x2, 0x2, 0x2, 0x2, 0x73, 0x3, 0x2, 0x2, 0x2, 0x2, 0x75, 0x3, 0x2, 0x2, 0x2, 0x2, 0x77, 0x3, 0x2, 0x2, 0x2, 0x2, 0x79, 0x3, 0x2, 0x2, 0x2, 0x2, 0x7b, 0x3, 0x2, 0x2, 0x2, 0x2, 0x7d, 0x3, 0x2, 0x2, 0x2, 0x2, 0x7f, 0x3, 0x2, 0x2, 0x2, 0x2, 0x81, 0x3, 0x2, 0x2, 0x2, 0x2, 0x83, 0x3, 0x2, 0x2, 0x2, 0x2, 0x85, 0x3, 0x2, 0x2, 0x2, 0x2, 0x87, 0x3, 0x2, 0x2, 0x2, 0x2, 0x89, 0x3, 0x2, 0x2, 0x2, 0x2, 0x8b, 0x3, 0x2, 0x2, 0x2, 0x2, 0x8d, 0x3, 0x2, 0x2, 0x2, 0x2, 0x8f, 0x3, 0x2, 0x2, 0x2, 0x2, 0x91, 0x3, 0x2, 0x2, 0x2, 0x2, 0x93, 0x3, 0x2, 0x2, 0x2, 0x2, 0x95, 0x3, 0x2, 0x2, 0x2, 0x2, 0x97, 0x3, 0x2, 0x2, 0x2, 0x2, 0x99, 0x3, 0x2, 0x2, 0x2, 0x2, 0x9b, 0x3, 0x2, 0x2, 0x2, 0x2, 0x9d, 0x3, 0x2, 0x2, 0x2, 0x2, 0x9f, 0x3, 0x2, 0x2, 0x2, 0x2, 0xa1, 0x3, 0x2, 0x2, 0x2, 0x2, 0xa3, 0x3, 0x2, 0x2, 0x2, 0x2, 0xa5, 0x3, 0x2, 0x2, 0x2, 0x2, 0xa7, 0x3, 0x2, 0x2, 0x2, 0x2, 0xa9, 0x3, 0x2, 0x2, 0x2, 0x2, 0xab, 0x3, 0x2, 0x2, 0x2, 0x2, 0xad, 0x3, 0x2, 0x2, 0x2, 0x2, 0xaf, 0x3, 0x2, 0x2, 0x2, 0x2, 0xb1, 0x3, 0x2, 0x2, 0x2, 0x2, 0xb3, 0x3, 0x2, 0x2, 0x2, 0x2, 0xb5, 0x3, 0x2, 0x2, 0x2, 0x2, 0xb7, 0x3, 0x2, 0x2, 0x2, 0x2, 0xb9, 0x3, 0x2, 0x2, 0x2, 0x2, 0xbb, 0x3, 0x2, 0x2, 0x2, 0x2, 0xbd, 0x3, 0x2, 0x2, 0x2, 0x2, 0xbf, 0x3, 0x2, 0x2, 0x2, 0x2, 0xc1, 0x3, 0x2, 0x2, 0x2, 0x2, 0xc3, 0x3, 0x2, 0x2, 0x2, 0x2, 0xc5, 0x3, 0x2, 0x2, 0x2, 0x2, 0xc7, 0x3, 0x2, 0x2, 0x2, 0x2, 0xc9, 0x3, 0x2, 0x2, 0x2, 0x2, 0xcb, 0x3, 0x2, 0x2, 0x2, 0x2, 0xcd, 0x3, 0x2, 0x2, 0x2, 0x2, 0xcf, 0x3, 0x2, 0x2, 0x2, 0x2, 0xd1, 0x3, 0x2, 0x2, 0x2, 0x2, 0xd3, 0x3, 0x2, 0x2, 0x2, 0x2, 0xd5, 0x3, 0x2, 0x2, 0x2, 0x2, 0xd7, 0x3, 0x2, 0x2, 0x2, 0x2, 0xd9, 0x3, 0x2, 0x2, 0x2, 0x2, 0xdb, 0x3, 0x2, 0x2, 0x2, 0x2, 0xdd, 0x3, 0x2, 0x2, 0x2, 0x2, 0xdf, 0x3, 0x2, 0x2, 0x2, 0x2, 0xe1, 0x3, 0x2, 0x2, 0x2, 0x2, 0xe3, 0x3, 0x2, 0x2, 0x2, 0x2, 0xe5, 0x3, 0x2, 0x2, 0x2, 0x2, 0xe7, 0x3, 0x2, 0x2, 0x2, 0x2, 0xe9, 0x3, 0x2, 0x2, 0x2, 0x2, 0xeb, 0x3, 0x2, 0x2, 0x2, 0x2, 0xed, 0x3, 0x2, 0x2, 0x2, 0x2, 0xef, 0x3, 0x2, 0x2, 0x2, 0x2, 0xf1, 0x3, 0x2, 0x2, 0x2, 0x2, 0xf3, 0x3, 0x2, 0x2, 0x2, 0x2, 0xf5, 0x3, 0x2, 0x2, 0x2, 0x2, 0xf7, 0x3, 0x2, 0x2, 0x2, 0x3, 0x129, 0x3, 0x2, 0x2, 0x2, 0x5, 0x133, 0x3, 0x2, 0x2, 0x2, 0x7, 0x141, 0x3, 0x2, 0x2, 0x2, 0x9, 0x14c, 0x3, 0x2, 0x2, 0x2, 0xb, 0x15c, 0x3, 0x2, 0x2, 0x2, 0xd, 0x15e, 0x3, 0x2, 0x2, 0x2, 0xf, 0x160, 0x3, 0x2, 0x2, 0x2, 0x11, 0x162, 0x3, 0x2, 0x2, 0x2, 0x13, 0x164, 0x3, 0x2, 0x2, 0x2, 0x15, 0x167, 0x3, 0x2, 0x2, 0x2, 0x17, 0x16a, 0x3, 0x2, 0x2, 0x2, 0x19, 0x16c, 0x3, 0x2, 0x2, 0x2, 0x1b, 0x16e, 0x3, 0x2, 0x2, 0x2, 0x1d, 0x170, 0x3, 0x2, 0x2, 0x2, 0x1f, 0x172, 0x3, 0x2, 0x2, 0x2, 0x21, 0x174, 0x3, 0x2, 0x2, 0x2, 0x23, 0x178, 0x3, 0x2, 0x2, 0x2, 0x25, 0x17a, 0x3, 0x2, 0x2, 0x2, 0x27, 0x17d, 0x3, 0x2, 0x2, 0x2, 0x29, 0x180, 0x3, 0x2, 0x2, 0x2, 0x2b, 0x182, 0x3, 0x2, 0x2, 0x2, 0x2d, 0x184, 0x3, 0x2, 0x2, 0x2, 0x2f, 0x186, 0x3, 0x2, 0x2, 0x2, 0x31, 0x188, 0x3, 0x2, 0x2, 0x2, 0x33, 0x18a, 0x3, 0x2, 0x2, 0x2, 0x35, 0x18c, 0x3, 0x2, 0x2, 0x2, 0x37, 0x18e, 0x3, 0x2, 0x2, 0x2, 0x39, 0x191, 0x3, 0x2, 0x2, 0x2, 0x3b, 0x194, 0x3, 0x2, 0x2, 0x2, 0x3d, 0x196, 0x3, 0x2, 0x2, 0x2, 0x3f, 0x199, 0x3, 0x2, 0x2, 0x2, 0x41, 0x19c, 0x3, 0x2, 0x2, 0x2, 0x43, 0x1a0, 0x3, 0x2, 0x2, 0x2, 0x45, 0x1a2, 0x3, 0x2, 0x2, 0x2, 0x47, 0x1a4, 0x3, 0x2, 0x2, 0x2, 0x49, 0x1a7, 0x3, 0x2, 0x2, 0x2, 0x4b, 0x1aa, 0x3, 0x2, 0x2, 0x2, 0x4d, 0x1ad, 0x3, 0x2, 0x2, 0x2, 0x4f, 0x1b0, 0x3, 0x2, 0x2, 0x2, 0x51, 0x1b4, 0x3, 0x2, 0x2, 0x2, 0x53, 0x1b8, 0x3, 0x2, 0x2, 0x2, 0x55, 0x1ba, 0x3, 0x2, 0x2, 0x2, 0x57, 0x1bc, 0x3, 0x2, 0x2, 0x2, 0x59, 0x1be, 0x3, 0x2, 0x2, 0x2, 0x5b, 0x1c1, 0x3, 0x2, 0x2, 0x2, 0x5d, 0x1c4, 0x3, 0x2, 0x2, 0x2, 0x5f, 0x1c7, 0x3, 0x2, 0x2, 0x2, 0x61, 0x1ca, 0x3, 0x2, 0x2, 0x2, 0x63, 0x1cd, 0x3, 0x2, 0x2, 0x2, 0x65, 0x1d0, 0x3, 0x2, 0x2, 0x2, 0x67, 0x1d3, 0x3, 0x2, 0x2, 0x2, 0x69, 0x1d7, 0x3, 0x2, 0x2, 0x2, 0x6b, 0x1db, 0x3, 0x2, 0x2, 0x2, 0x6d, 0x1e0, 0x3, 0x2, 0x2, 0x2, 0x6f, 0x1e3, 0x3, 0x2, 0x2, 0x2, 0x71, 0x1e6, 0x3, 0x2, 0x2, 0x2, 0x73, 0x1e9, 0x3, 0x2, 0x2, 0x2, 0x75, 0x1ed, 0x3, 0x2, 0x2, 0x2, 0x77, 0x1f0, 0x3, 0x2, 0x2, 0x2, 0x79, 0x1fe, 0x3, 0x2, 0x2, 0x2, 0x7b, 0x21b, 0x3, 0x2, 0x2, 0x2, 0x7d, 0x21d, 0x3, 0x2, 0x2, 0x2, 0x7f, 0x226, 0x3, 0x2, 0x2, 0x2, 0x81, 0x22e, 0x3, 0x2, 0x2, 0x2, 0x83, 0x237, 0x3, 0x2, 0x2, 0x2, 0x85, 0x240, 0x3, 0x2, 0x2, 0x2, 0x87, 0x24b, 0x3, 0x2, 0x2, 0x2, 0x89, 0x256, 0x3, 0x2, 0x2, 0x2, 0x8b, 0x261, 0x3, 0x2, 0x2, 0x2, 0x8d, 0x264, 0x3, 0x2, 0x2, 0x2, 0x8f, 0x26a, 0x3, 0x2, 0x2, 0x2, 0x91, 0x26d, 0x3, 0x2, 0x2, 0x2, 0x93, 0x278, 0x3, 0x2, 0x2, 0x2, 0x95, 0x27f, 0x3, 0x2, 0x2, 0x2, 0x97, 0x284, 0x3, 0x2, 0x2, 0x2, 0x99, 0x289, 0x3, 0x2, 0x2, 0x2, 0x9b, 0x28d, 0x3, 0x2, 0x2, 0x2, 0x9d, 0x291, 0x3, 0x2, 0x2, 0x2, 0x9f, 0x297, 0x3, 0x2, 0x2, 0x2, 0xa1, 0x29f, 0x3, 0x2, 0x2, 0x2, 0xa3, 0x2a6, 0x3, 0x2, 0x2, 0x2, 0xa5, 0x2ab, 0x3, 0x2, 0x2, 0x2, 0xa7, 0x2b4, 0x3, 0x2, 0x2, 0x2, 0xa9, 0x2b8, 0x3, 0x2, 0x2, 0x2, 0xab, 0x2bf, 0x3, 0x2, 0x2, 0x2, 0xad, 0x2c5, 0x3, 0x2, 0x2, 0x2, 0xaf, 0x2ce, 0x3, 0x2, 0x2, 0x2, 0xb1, 0x2d7, 0x3, 0x2, 0x2, 0x2, 0xb3, 0x2dc, 0x3, 0x2, 0x2, 0x2, 0xb5, 0x2e1, 0x3, 0x2, 0x2, 0x2, 0xb7, 0x2e9, 0x3, 0x2, 0x2, 0x2, 0xb9, 0x2ec, 0x3, 0x2, 0x2, 0x2, 0xbb, 0x2f2, 0x3, 0x2, 0x2, 0x2, 0xbd, 0x2f9, 0x3, 0x2, 0x2, 0x2, 0xbf, 0x2fc, 0x3, 0x2, 0x2, 0x2, 0xc1, 0x300, 0x3, 0x2, 0x2, 0x2, 0xc3, 0x303, 0x3, 0x2, 0x2, 0x2, 0xc5, 0x308, 0x3, 0x2, 0x2, 0x2, 0xc7, 0x30e, 0x3, 0x2, 0x2, 0x2, 0xc9, 0x313, 0x3, 0x2, 0x2, 0x2, 0xcb, 0x31b, 0x3, 0x2, 0x2, 0x2, 0xcd, 0x321, 0x3, 0x2, 0x2, 0x2, 0xcf, 0x327, 0x3, 0x2, 0x2, 0x2, 0xd1, 0x32e, 0x3, 0x2, 0x2, 0x2, 0xd3, 0x335, 0x3, 0x2, 0x2, 0x2, 0xd5, 0x33b, 0x3, 0x2, 0x2, 0x2, 0xd7, 0x341, 0x3, 0x2, 0x2, 0x2, 0xd9, 0x34e, 0x3, 0x2, 0x2, 0x2, 0xdb, 0x354, 0x3, 0x2, 0x2, 0x2, 0xdd, 0x35e, 0x3, 0x2, 0x2, 0x2, 0xdf, 0x367, 0x3, 0x2, 0x2, 0x2, 0xe1, 0x373, 0x3, 0x2, 0x2, 0x2, 0xe3, 0x37d, 0x3, 0x2, 0x2, 0x2, 0xe5, 0x389, 0x3, 0x2, 0x2, 0x2, 0xe7, 0x392, 0x3, 0x2, 0x2, 0x2, 0xe9, 0x39a, 0x3, 0x2, 0x2, 0x2, 0xeb, 0x3b1, 0x3, 0x2, 0x2, 0x2, 0xed, 0x3b5, 0x3, 0x2, 0x2, 0x2, 0xef, 0x3c1, 0x3, 0x2, 0x2, 0x2, 0xf1, 0x3c7, 0x3, 0x2, 0x2, 0x2, 0xf3, 0x3cb, 0x3, 0x2, 0x2, 0x2, 0xf5, 0x3dc, 0x3, 0x2, 0x2, 0x2, 0xf7, 0x3f2, 0x3, 0x2, 0x2, 0x2, 0xf9, 0x3fa, 0x3, 0x2, 0x2, 0x2, 0xfb, 0x400, 0x3, 0x2, 0x2, 0x2, 0xfd, 0x407, 0x3, 0x2, 0x2, 0x2, 0xff, 0x40b, 0x3, 0x2, 0x2, 0x2, 0x101, 0x40d, 0x3, 0x2, 0x2, 0x2, 0x103, 0x421, 0x3, 0x2, 0x2, 0x2, 0x105, 0x423, 0x3, 0x2, 0x2, 0x2, 0x107, 0x42c, 0x3, 0x2, 0x2, 0x2, 0x109, 0x42e, 0x3, 0x2, 0x2, 0x2, 0x10b, 0x432, 0x3, 0x2, 0x2, 0x2, 0x10d, 0x434, 0x3, 0x2, 0x2, 0x2, 0x10f, 0x437, 0x3, 0x2, 0x2, 0x2, 0x111, 0x441, 0x3, 0x2, 0x2, 0x2, 0x113, 0x443, 0x3, 0x2, 0x2, 0x2, 0x115, 0x451, 0x3, 0x2, 0x2, 0x2, 0x117, 0x457, 0x3, 0x2, 0x2, 0x2, 0x119, 0x45a, 0x3, 0x2, 0x2, 0x2, 0x11b, 0x45d, 0x3, 0x2, 0x2, 0x2, 0x11d, 0x460, 0x3, 0x2, 0x2, 0x2, 0x11f, 0x463, 0x3, 0x2, 0x2, 0x2, 0x121, 0x46f, 0x3, 0x2, 0x2, 0x2, 0x123, 0x47b, 0x3, 0x2, 0x2, 0x2, 0x125, 0x47f, 0x3, 0x2, 0x2, 0x2, 0x127, 0x481, 0x3, 0x2, 0x2, 0x2, 0x129, 0x12a, 0x6, 0x2, 0x2, 0x2, 0x12a, 0x12b, 0x7, 0x25, 0x2, 0x2, 0x12b, 0x12c, 0x7, 0x23, 0x2, 0x2, 0x12c, 0x130, 0x3, 0x2, 0x2, 0x2, 0x12d, 0x12f, 0xa, 0x2, 0x2, 0x2, 0x12e, 0x12d, 0x3, 0x2, 0x2, 0x2, 0x12f, 0x132, 0x3, 0x2, 0x2, 0x2, 0x130, 0x12e, 0x3, 0x2, 0x2, 0x2, 0x130, 0x131, 0x3, 0x2, 0x2, 0x2, 0x131, 0x4, 0x3, 0x2, 0x2, 0x2, 0x132, 0x130, 0x3, 0x2, 0x2, 0x2, 0x133, 0x134, 0x7, 0x31, 0x2, 0x2, 0x134, 0x135, 0x7, 0x2c, 0x2, 0x2, 0x135, 0x139, 0x3, 0x2, 0x2, 0x2, 0x136, 0x138, 0xb, 0x2, 0x2, 0x2, 0x137, 0x136, 0x3, 0x2, 0x2, 0x2, 0x138, 0x13b, 0x3, 0x2, 0x2, 0x2, 0x139, 0x13a, 0x3, 0x2, 0x2, 0x2, 0x139, 0x137, 0x3, 0x2, 0x2, 0x2, 0x13a, 0x13c, 0x3, 0x2, 0x2, 0x2, 0x13b, 0x139, 0x3, 0x2, 0x2, 0x2, 0x13c, 0x13d, 0x7, 0x2c, 0x2, 0x2, 0x13d, 0x13e, 0x7, 0x31, 0x2, 0x2, 0x13e, 0x13f, 0x3, 0x2, 0x2, 0x2, 0x13f, 0x140, 0x8, 0x3, 0x2, 0x2, 0x140, 0x6, 0x3, 0x2, 0x2, 0x2, 0x141, 0x142, 0x7, 0x31, 0x2, 0x2, 0x142, 0x143, 0x7, 0x31, 0x2, 0x2, 0x143, 0x147, 0x3, 0x2, 0x2, 0x2, 0x144, 0x146, 0xa, 0x2, 0x2, 0x2, 0x145, 0x144, 0x3, 0x2, 0x2, 0x2, 0x146, 0x149, 0x3, 0x2, 0x2, 0x2, 0x147, 0x145, 0x3, 0x2, 0x2, 0x2, 0x147, 0x148, 0x3, 0x2, 0x2, 0x2, 0x148, 0x14a, 0x3, 0x2, 0x2, 0x2, 0x149, 0x147, 0x3, 0x2, 0x2, 0x2, 0x14a, 0x14b, 0x8, 0x4, 0x2, 0x2, 0x14b, 0x8, 0x3, 0x2, 0x2, 0x2, 0x14c, 0x14d, 0x7, 0x31, 0x2, 0x2, 0x14d, 0x151, 0x5, 0x121, 0x91, 0x2, 0x14e, 0x150, 0x5, 0x123, 0x92, 0x2, 0x14f, 0x14e, 0x3, 0x2, 0x2, 0x2, 0x150, 0x153, 0x3, 0x2, 0x2, 0x2, 0x151, 0x14f, 0x3, 0x2, 0x2, 0x2, 0x151, 0x152, 0x3, 0x2, 0x2, 0x2, 0x152, 0x154, 0x3, 0x2, 0x2, 0x2, 0x153, 0x151, 0x3, 0x2, 0x2, 0x2, 0x154, 0x155, 0x6, 0x5, 0x3, 0x2, 0x155, 0x159, 0x7, 0x31, 0x2, 0x2, 0x156, 0x158, 0x5, 0x115, 0x8b, 0x2, 0x157, 0x156, 0x3, 0x2, 0x2, 0x2, 0x158, 0x15b, 0x3, 0x2, 0x2, 0x2, 0x159, 0x157, 0x3, 0x2, 0x2, 0x2, 0x159, 0x15a, 0x3, 0x2, 0x2, 0x2, 0x15a, 0xa, 0x3, 0x2, 0x2, 0x2, 0x15b, 0x159, 0x3, 0x2, 0x2, 0x2, 0x15c, 0x15d, 0x7, 0x5d, 0x2, 0x2, 0x15d, 0xc, 0x3, 0x2, 0x2, 0x2, 0x15e, 0x15f, 0x7, 0x5f, 0x2, 0x2, 0x15f, 0xe, 0x3, 0x2, 0x2, 0x2, 0x160, 0x161, 0x7, 0x2a, 0x2, 0x2, 0x161, 0x10, 0x3, 0x2, 0x2, 0x2, 0x162, 0x163, 0x7, 0x2b, 0x2, 0x2, 0x163, 0x12, 0x3, 0x2, 0x2, 0x2, 0x164, 0x165, 0x7, 0x7d, 0x2, 0x2, 0x165, 0x166, 0x8, 0xa, 0x3, 0x2, 0x166, 0x14, 0x3, 0x2, 0x2, 0x2, 0x167, 0x168, 0x7, 0x7f, 0x2, 0x2, 0x168, 0x169, 0x8, 0xb, 0x4, 0x2, 0x169, 0x16, 0x3, 0x2, 0x2, 0x2, 0x16a, 0x16b, 0x7, 0x3d, 0x2, 0x2, 0x16b, 0x18, 0x3, 0x2, 0x2, 0x2, 0x16c, 0x16d, 0x7, 0x2e, 0x2, 0x2, 0x16d, 0x1a, 0x3, 0x2, 0x2, 0x2, 0x16e, 0x16f, 0x7, 0x3f, 0x2, 0x2, 0x16f, 0x1c, 0x3, 0x2, 0x2, 0x2, 0x170, 0x171, 0x7, 0x41, 0x2, 0x2, 0x171, 0x1e, 0x3, 0x2, 0x2, 0x2, 0x172, 0x173, 0x7, 0x3c, 0x2, 0x2, 0x173, 0x20, 0x3, 0x2, 0x2, 0x2, 0x174, 0x175, 0x7, 0x30, 0x2, 0x2, 0x175, 0x176, 0x7, 0x30, 0x2, 0x2, 0x176, 0x177, 0x7, 0x30, 0x2, 0x2, 0x177, 0x22, 0x3, 0x2, 0x2, 0x2, 0x178, 0x179, 0x7, 0x30, 0x2, 0x2, 0x179, 0x24, 0x3, 0x2, 0x2, 0x2, 0x17a, 0x17b, 0x7, 0x2d, 0x2, 0x2, 0x17b, 0x17c, 0x7, 0x2d, 0x2, 0x2, 0x17c, 0x26, 0x3, 0x2, 0x2, 0x2, 0x17d, 0x17e, 0x7, 0x2f, 0x2, 0x2, 0x17e, 0x17f, 0x7, 0x2f, 0x2, 0x2, 0x17f, 0x28, 0x3, 0x2, 0x2, 0x2, 0x180, 0x181, 0x7, 0x2d, 0x2, 0x2, 0x181, 0x2a, 0x3, 0x2, 0x2, 0x2, 0x182, 0x183, 0x7, 0x2f, 0x2, 0x2, 0x183, 0x2c, 0x3, 0x2, 0x2, 0x2, 0x184, 0x185, 0x7, 0x80, 0x2, 0x2, 0x185, 0x2e, 0x3, 0x2, 0x2, 0x2, 0x186, 0x187, 0x7, 0x23, 0x2, 0x2, 0x187, 0x30, 0x3, 0x2, 0x2, 0x2, 0x188, 0x189, 0x7, 0x2c, 0x2, 0x2, 0x189, 0x32, 0x3, 0x2, 0x2, 0x2, 0x18a, 0x18b, 0x7, 0x31, 0x2, 0x2, 0x18b, 0x34, 0x3, 0x2, 0x2, 0x2, 0x18c, 0x18d, 0x7, 0x27, 0x2, 0x2, 0x18d, 0x36, 0x3, 0x2, 0x2, 0x2, 0x18e, 0x18f, 0x7, 0x2c, 0x2, 0x2, 0x18f, 0x190, 0x7, 0x2c, 0x2, 0x2, 0x190, 0x38, 0x3, 0x2, 0x2, 0x2, 0x191, 0x192, 0x7, 0x41, 0x2, 0x2, 0x192, 0x193, 0x7, 0x41, 0x2, 0x2, 0x193, 0x3a, 0x3, 0x2, 0x2, 0x2, 0x194, 0x195, 0x7, 0x25, 0x2, 0x2, 0x195, 0x3c, 0x3, 0x2, 0x2, 0x2, 0x196, 0x197, 0x7, 0x40, 0x2, 0x2, 0x197, 0x198, 0x7, 0x40, 0x2, 0x2, 0x198, 0x3e, 0x3, 0x2, 0x2, 0x2, 0x199, 0x19a, 0x7, 0x3e, 0x2, 0x2, 0x19a, 0x19b, 0x7, 0x3e, 0x2, 0x2, 0x19b, 0x40, 0x3, 0x2, 0x2, 0x2, 0x19c, 0x19d, 0x7, 0x40, 0x2, 0x2, 0x19d, 0x19e, 0x7, 0x40, 0x2, 0x2, 0x19e, 0x19f, 0x7, 0x40, 0x2, 0x2, 0x19f, 0x42, 0x3, 0x2, 0x2, 0x2, 0x1a0, 0x1a1, 0x7, 0x3e, 0x2, 0x2, 0x1a1, 0x44, 0x3, 0x2, 0x2, 0x2, 0x1a2, 0x1a3, 0x7, 0x40, 0x2, 0x2, 0x1a3, 0x46, 0x3, 0x2, 0x2, 0x2, 0x1a4, 0x1a5, 0x7, 0x3e, 0x2, 0x2, 0x1a5, 0x1a6, 0x7, 0x3f, 0x2, 0x2, 0x1a6, 0x48, 0x3, 0x2, 0x2, 0x2, 0x1a7, 0x1a8, 0x7, 0x40, 0x2, 0x2, 0x1a8, 0x1a9, 0x7, 0x3f, 0x2, 0x2, 0x1a9, 0x4a, 0x3, 0x2, 0x2, 0x2, 0x1aa, 0x1ab, 0x7, 0x3f, 0x2, 0x2, 0x1ab, 0x1ac, 0x7, 0x3f, 0x2, 0x2, 0x1ac, 0x4c, 0x3, 0x2, 0x2, 0x2, 0x1ad, 0x1ae, 0x7, 0x23, 0x2, 0x2, 0x1ae, 0x1af, 0x7, 0x3f, 0x2, 0x2, 0x1af, 0x4e, 0x3, 0x2, 0x2, 0x2, 0x1b0, 0x1b1, 0x7, 0x3f, 0x2, 0x2, 0x1b1, 0x1b2, 0x7, 0x3f, 0x2, 0x2, 0x1b2, 0x1b3, 0x7, 0x3f, 0x2, 0x2, 0x1b3, 0x50, 0x3, 0x2, 0x2, 0x2, 0x1b4, 0x1b5, 0x7, 0x23, 0x2, 0x2, 0x1b5, 0x1b6, 0x7, 0x3f, 0x2, 0x2, 0x1b6, 0x1b7, 0x7, 0x3f, 0x2, 0x2, 0x1b7, 0x52, 0x3, 0x2, 0x2, 0x2, 0x1b8, 0x1b9, 0x7, 0x28, 0x2, 0x2, 0x1b9, 0x54, 0x3, 0x2, 0x2, 0x2, 0x1ba, 0x1bb, 0x7, 0x60, 0x2, 0x2, 0x1bb, 0x56, 0x3, 0x2, 0x2, 0x2, 0x1bc, 0x1bd, 0x7, 0x7e, 0x2, 0x2, 0x1bd, 0x58, 0x3, 0x2, 0x2, 0x2, 0x1be, 0x1bf, 0x7, 0x28, 0x2, 0x2, 0x1bf, 0x1c0, 0x7, 0x28, 0x2, 0x2, 0x1c0, 0x5a, 0x3, 0x2, 0x2, 0x2, 0x1c1, 0x1c2, 0x7, 0x7e, 0x2, 0x2, 0x1c2, 0x1c3, 0x7, 0x7e, 0x2, 0x2, 0x1c3, 0x5c, 0x3, 0x2, 0x2, 0x2, 0x1c4, 0x1c5, 0x7, 0x2c, 0x2, 0x2, 0x1c5, 0x1c6, 0x7, 0x3f, 0x2, 0x2, 0x1c6, 0x5e, 0x3, 0x2, 0x2, 0x2, 0x1c7, 0x1c8, 0x7, 0x31, 0x2, 0x2, 0x1c8, 0x1c9, 0x7, 0x3f, 0x2, 0x2, 0x1c9, 0x60, 0x3, 0x2, 0x2, 0x2, 0x1ca, 0x1cb, 0x7, 0x27, 0x2, 0x2, 0x1cb, 0x1cc, 0x7, 0x3f, 0x2, 0x2, 0x1cc, 0x62, 0x3, 0x2, 0x2, 0x2, 0x1cd, 0x1ce, 0x7, 0x2d, 0x2, 0x2, 0x1ce, 0x1cf, 0x7, 0x3f, 0x2, 0x2, 0x1cf, 0x64, 0x3, 0x2, 0x2, 0x2, 0x1d0, 0x1d1, 0x7, 0x2f, 0x2, 0x2, 0x1d1, 0x1d2, 0x7, 0x3f, 0x2, 0x2, 0x1d2, 0x66, 0x3, 0x2, 0x2, 0x2, 0x1d3, 0x1d4, 0x7, 0x3e, 0x2, 0x2, 0x1d4, 0x1d5, 0x7, 0x3e, 0x2, 0x2, 0x1d5, 0x1d6, 0x7, 0x3f, 0x2, 0x2, 0x1d6, 0x68, 0x3, 0x2, 0x2, 0x2, 0x1d7, 0x1d8, 0x7, 0x40, 0x2, 0x2, 0x1d8, 0x1d9, 0x7, 0x40, 0x2, 0x2, 0x1d9, 0x1da, 0x7, 0x3f, 0x2, 0x2, 0x1da, 0x6a, 0x3, 0x2, 0x2, 0x2, 0x1db, 0x1dc, 0x7, 0x40, 0x2, 0x2, 0x1dc, 0x1dd, 0x7, 0x40, 0x2, 0x2, 0x1dd, 0x1de, 0x7, 0x40, 0x2, 0x2, 0x1de, 0x1df, 0x7, 0x3f, 0x2, 0x2, 0x1df, 0x6c, 0x3, 0x2, 0x2, 0x2, 0x1e0, 0x1e1, 0x7, 0x28, 0x2, 0x2, 0x1e1, 0x1e2, 0x7, 0x3f, 0x2, 0x2, 0x1e2, 0x6e, 0x3, 0x2, 0x2, 0x2, 0x1e3, 0x1e4, 0x7, 0x60, 0x2, 0x2, 0x1e4, 0x1e5, 0x7, 0x3f, 0x2, 0x2, 0x1e5, 0x70, 0x3, 0x2, 0x2, 0x2, 0x1e6, 0x1e7, 0x7, 0x7e, 0x2, 0x2, 0x1e7, 0x1e8, 0x7, 0x3f, 0x2, 0x2, 0x1e8, 0x72, 0x3, 0x2, 0x2, 0x2, 0x1e9, 0x1ea, 0x7, 0x2c, 0x2, 0x2, 0x1ea, 0x1eb, 0x7, 0x2c, 0x2, 0x2, 0x1eb, 0x1ec, 0x7, 0x3f, 0x2, 0x2, 0x1ec, 0x74, 0x3, 0x2, 0x2, 0x2, 0x1ed, 0x1ee, 0x7, 0x3f, 0x2, 0x2, 0x1ee, 0x1ef, 0x7, 0x40, 0x2, 0x2, 0x1ef, 0x76, 0x3, 0x2, 0x2, 0x2, 0x1f0, 0x1f1, 0x7, 0x70, 0x2, 0x2, 0x1f1, 0x1f2, 0x7, 0x77, 0x2, 0x2, 0x1f2, 0x1f3, 0x7, 0x6e, 0x2, 0x2, 0x1f3, 0x1f4, 0x7, 0x6e, 0x2, 0x2, 0x1f4, 0x78, 0x3, 0x2, 0x2, 0x2, 0x1f5, 0x1f6, 0x7, 0x76, 0x2, 0x2, 0x1f6, 0x1f7, 0x7, 0x74, 0x2, 0x2, 0x1f7, 0x1f8, 0x7, 0x77, 0x2, 0x2, 0x1f8, 0x1ff, 0x7, 0x67, 0x2, 0x2, 0x1f9, 0x1fa, 0x7, 0x68, 0x2, 0x2, 0x1fa, 0x1fb, 0x7, 0x63, 0x2, 0x2, 0x1fb, 0x1fc, 0x7, 0x6e, 0x2, 0x2, 0x1fc, 0x1fd, 0x7, 0x75, 0x2, 0x2, 0x1fd, 0x1ff, 0x7, 0x67, 0x2, 0x2, 0x1fe, 0x1f5, 0x3, 0x2, 0x2, 0x2, 0x1fe, 0x1f9, 0x3, 0x2, 0x2, 0x2, 0x1ff, 0x7a, 0x3, 0x2, 0x2, 0x2, 0x200, 0x201, 0x5, 0x111, 0x89, 0x2, 0x201, 0x202, 0x7, 0x30, 0x2, 0x2, 0x202, 0x206, 0x9, 0x3, 0x2, 0x2, 0x203, 0x205, 0x9, 0x4, 0x2, 0x2, 0x204, 0x203, 0x3, 0x2, 0x2, 0x2, 0x205, 0x208, 0x3, 0x2, 0x2, 0x2, 0x206, 0x204, 0x3, 0x2, 0x2, 0x2, 0x206, 0x207, 0x3, 0x2, 0x2, 0x2, 0x207, 0x20a, 0x3, 0x2, 0x2, 0x2, 0x208, 0x206, 0x3, 0x2, 0x2, 0x2, 0x209, 0x20b, 0x5, 0x113, 0x8a, 0x2, 0x20a, 0x209, 0x3, 0x2, 0x2, 0x2, 0x20a, 0x20b, 0x3, 0x2, 0x2, 0x2, 0x20b, 0x21c, 0x3, 0x2, 0x2, 0x2, 0x20c, 0x20d, 0x7, 0x30, 0x2, 0x2, 0x20d, 0x211, 0x9, 0x3, 0x2, 0x2, 0x20e, 0x210, 0x9, 0x4, 0x2, 0x2, 0x20f, 0x20e, 0x3, 0x2, 0x2, 0x2, 0x210, 0x213, 0x3, 0x2, 0x2, 0x2, 0x211, 0x20f, 0x3, 0x2, 0x2, 0x2, 0x211, 0x212, 0x3, 0x2, 0x2, 0x2, 0x212, 0x215, 0x3, 0x2, 0x2, 0x2, 0x213, 0x211, 0x3, 0x2, 0x2, 0x2, 0x214, 0x216, 0x5, 0x113, 0x8a, 0x2, 0x215, 0x214, 0x3, 0x2, 0x2, 0x2, 0x215, 0x216, 0x3, 0x2, 0x2, 0x2, 0x216, 0x21c, 0x3, 0x2, 0x2, 0x2, 0x217, 0x219, 0x5, 0x111, 0x89, 0x2, 0x218, 0x21a, 0x5, 0x113, 0x8a, 0x2, 0x219, 0x218, 0x3, 0x2, 0x2, 0x2, 0x219, 0x21a, 0x3, 0x2, 0x2, 0x2, 0x21a, 0x21c, 0x3, 0x2, 0x2, 0x2, 0x21b, 0x200, 0x3, 0x2, 0x2, 0x2, 0x21b, 0x20c, 0x3, 0x2, 0x2, 0x2, 0x21b, 0x217, 0x3, 0x2, 0x2, 0x2, 0x21c, 0x7c, 0x3, 0x2, 0x2, 0x2, 0x21d, 0x21e, 0x7, 0x32, 0x2, 0x2, 0x21e, 0x21f, 0x9, 0x5, 0x2, 0x2, 0x21f, 0x223, 0x9, 0x6, 0x2, 0x2, 0x220, 0x222, 0x5, 0x10f, 0x88, 0x2, 0x221, 0x220, 0x3, 0x2, 0x2, 0x2, 0x222, 0x225, 0x3, 0x2, 0x2, 0x2, 0x223, 0x221, 0x3, 0x2, 0x2, 0x2, 0x223, 0x224, 0x3, 0x2, 0x2, 0x2, 0x224, 0x7e, 0x3, 0x2, 0x2, 0x2, 0x225, 0x223, 0x3, 0x2, 0x2, 0x2, 0x226, 0x228, 0x7, 0x32, 0x2, 0x2, 0x227, 0x229, 0x9, 0x7, 0x2, 0x2, 0x228, 0x227, 0x3, 0x2, 0x2, 0x2, 0x229, 0x22a, 0x3, 0x2, 0x2, 0x2, 0x22a, 0x228, 0x3, 0x2, 0x2, 0x2, 0x22a, 0x22b, 0x3, 0x2, 0x2, 0x2, 0x22b, 0x22c, 0x3, 0x2, 0x2, 0x2, 0x22c, 0x22d, 0x6, 0x40, 0x4, 0x2, 0x22d, 0x80, 0x3, 0x2, 0x2, 0x2, 0x22e, 0x22f, 0x7, 0x32, 0x2, 0x2, 0x22f, 0x230, 0x9, 0x8, 0x2, 0x2, 0x230, 0x234, 0x9, 0x7, 0x2, 0x2, 0x231, 0x233, 0x9, 0x9, 0x2, 0x2, 0x232, 0x231, 0x3, 0x2, 0x2, 0x2, 0x233, 0x236, 0x3, 0x2, 0x2, 0x2, 0x234, 0x232, 0x3, 0x2, 0x2, 0x2, 0x234, 0x235, 0x3, 0x2, 0x2, 0x2, 0x235, 0x82, 0x3, 0x2, 0x2, 0x2, 0x236, 0x234, 0x3, 0x2, 0x2, 0x2, 0x237, 0x238, 0x7, 0x32, 0x2, 0x2, 0x238, 0x239, 0x9, 0xa, 0x2, 0x2, 0x239, 0x23d, 0x9, 0xb, 0x2, 0x2, 0x23a, 0x23c, 0x9, 0xc, 0x2, 0x2, 0x23b, 0x23a, 0x3, 0x2, 0x2, 0x2, 0x23c, 0x23f, 0x3, 0x2, 0x2, 0x2, 0x23d, 0x23b, 0x3, 0x2, 0x2, 0x2, 0x23d, 0x23e, 0x3, 0x2, 0x2, 0x2, 0x23e, 0x84, 0x3, 0x2, 0x2, 0x2, 0x23f, 0x23d, 0x3, 0x2, 0x2, 0x2, 0x240, 0x241, 0x7, 0x32, 0x2, 0x2, 0x241, 0x242, 0x9, 0x5, 0x2, 0x2, 0x242, 0x246, 0x9, 0x6, 0x2, 0x2, 0x243, 0x245, 0x5, 0x10f, 0x88, 0x2, 0x244, 0x243, 0x3, 0x2, 0x2, 0x2, 0x245, 0x248, 0x3, 0x2, 0x2, 0x2, 0x246, 0x244, 0x3, 0x2, 0x2, 0x2, 0x246, 0x247, 0x3, 0x2, 0x2, 0x2, 0x247, 0x249, 0x3, 0x2, 0x2, 0x2, 0x248, 0x246, 0x3, 0x2, 0x2, 0x2, 0x249, 0x24a, 0x7, 0x70, 0x2, 0x2, 0x24a, 0x86, 0x3, 0x2, 0x2, 0x2, 0x24b, 0x24c, 0x7, 0x32, 0x2, 0x2, 0x24c, 0x24d, 0x9, 0x8, 0x2, 0x2, 0x24d, 0x251, 0x9, 0x7, 0x2, 0x2, 0x24e, 0x250, 0x9, 0x9, 0x2, 0x2, 0x24f, 0x24e, 0x3, 0x2, 0x2, 0x2, 0x250, 0x253, 0x3, 0x2, 0x2, 0x2, 0x251, 0x24f, 0x3, 0x2, 0x2, 0x2, 0x251, 0x252, 0x3, 0x2, 0x2, 0x2, 0x252, 0x254, 0x3, 0x2, 0x2, 0x2, 0x253, 0x251, 0x3, 0x2, 0x2, 0x2, 0x254, 0x255, 0x7, 0x70, 0x2, 0x2, 0x255, 0x88, 0x3, 0x2, 0x2, 0x2, 0x256, 0x257, 0x7, 0x32, 0x2, 0x2, 0x257, 0x258, 0x9, 0xa, 0x2, 0x2, 0x258, 0x25c, 0x9, 0xb, 0x2, 0x2, 0x259, 0x25b, 0x9, 0xc, 0x2, 0x2, 0x25a, 0x259, 0x3, 0x2, 0x2, 0x2, 0x25b, 0x25e, 0x3, 0x2, 0x2, 0x2, 0x25c, 0x25a, 0x3, 0x2, 0x2, 0x2, 0x25c, 0x25d, 0x3, 0x2, 0x2, 0x2, 0x25d, 0x25f, 0x3, 0x2, 0x2, 0x2, 0x25e, 0x25c, 0x3, 0x2, 0x2, 0x2, 0x25f, 0x260, 0x7, 0x70, 0x2, 0x2, 0x260, 0x8a, 0x3, 0x2, 0x2, 0x2, 0x261, 0x262, 0x5, 0x111, 0x89, 0x2, 0x262, 0x263, 0x7, 0x70, 0x2, 0x2, 0x263, 0x8c, 0x3, 0x2, 0x2, 0x2, 0x264, 0x265, 0x7, 0x64, 0x2, 0x2, 0x265, 0x266, 0x7, 0x74, 0x2, 0x2, 0x266, 0x267, 0x7, 0x67, 0x2, 0x2, 0x267, 0x268, 0x7, 0x63, 0x2, 0x2, 0x268, 0x269, 0x7, 0x6d, 0x2, 0x2, 0x269, 0x8e, 0x3, 0x2, 0x2, 0x2, 0x26a, 0x26b, 0x7, 0x66, 0x2, 0x2, 0x26b, 0x26c, 0x7, 0x71, 0x2, 0x2, 0x26c, 0x90, 0x3, 0x2, 0x2, 0x2, 0x26d, 0x26e, 0x7, 0x6b, 0x2, 0x2, 0x26e, 0x26f, 0x7, 0x70, 0x2, 0x2, 0x26f, 0x270, 0x7, 0x75, 0x2, 0x2, 0x270, 0x271, 0x7, 0x76, 0x2, 0x2, 0x271, 0x272, 0x7, 0x63, 0x2, 0x2, 0x272, 0x273, 0x7, 0x70, 0x2, 0x2, 0x273, 0x274, 0x7, 0x65, 0x2, 0x2, 0x274, 0x275, 0x7, 0x67, 0x2, 0x2, 0x275, 0x276, 0x7, 0x71, 0x2, 0x2, 0x276, 0x277, 0x7, 0x68, 0x2, 0x2, 0x277, 0x92, 0x3, 0x2, 0x2, 0x2, 0x278, 0x279, 0x7, 0x76, 0x2, 0x2, 0x279, 0x27a, 0x7, 0x7b, 0x2, 0x2, 0x27a, 0x27b, 0x7, 0x72, 0x2, 0x2, 0x27b, 0x27c, 0x7, 0x67, 0x2, 0x2, 0x27c, 0x27d, 0x7, 0x71, 0x2, 0x2, 0x27d, 0x27e, 0x7, 0x68, 0x2, 0x2, 0x27e, 0x94, 0x3, 0x2, 0x2, 0x2, 0x27f, 0x280, 0x7, 0x65, 0x2, 0x2, 0x280, 0x281, 0x7, 0x63, 0x2, 0x2, 0x281, 0x282, 0x7, 0x75, 0x2, 0x2, 0x282, 0x283, 0x7, 0x67, 0x2, 0x2, 0x283, 0x96, 0x3, 0x2, 0x2, 0x2, 0x284, 0x285, 0x7, 0x67, 0x2, 0x2, 0x285, 0x286, 0x7, 0x6e, 0x2, 0x2, 0x286, 0x287, 0x7, 0x75, 0x2, 0x2, 0x287, 0x288, 0x7, 0x67, 0x2, 0x2, 0x288, 0x98, 0x3, 0x2, 0x2, 0x2, 0x289, 0x28a, 0x7, 0x70, 0x2, 0x2, 0x28a, 0x28b, 0x7, 0x67, 0x2, 0x2, 0x28b, 0x28c, 0x7, 0x79, 0x2, 0x2, 0x28c, 0x9a, 0x3, 0x2, 0x2, 0x2, 0x28d, 0x28e, 0x7, 0x78, 0x2, 0x2, 0x28e, 0x28f, 0x7, 0x63, 0x2, 0x2, 0x28f, 0x290, 0x7, 0x74, 0x2, 0x2, 0x290, 0x9c, 0x3, 0x2, 0x2, 0x2, 0x291, 0x292, 0x7, 0x65, 0x2, 0x2, 0x292, 0x293, 0x7, 0x63, 0x2, 0x2, 0x293, 0x294, 0x7, 0x76, 0x2, 0x2, 0x294, 0x295, 0x7, 0x65, 0x2, 0x2, 0x295, 0x296, 0x7, 0x6a, 0x2, 0x2, 0x296, 0x9e, 0x3, 0x2, 0x2, 0x2, 0x297, 0x298, 0x7, 0x68, 0x2, 0x2, 0x298, 0x299, 0x7, 0x6b, 0x2, 0x2, 0x299, 0x29a, 0x7, 0x70, 0x2, 0x2, 0x29a, 0x29b, 0x7, 0x63, 0x2, 0x2, 0x29b, 0x29c, 0x7, 0x6e, 0x2, 0x2, 0x29c, 0x29d, 0x7, 0x6e, 0x2, 0x2, 0x29d, 0x29e, 0x7, 0x7b, 0x2, 0x2, 0x29e, 0xa0, 0x3, 0x2, 0x2, 0x2, 0x29f, 0x2a0, 0x7, 0x74, 0x2, 0x2, 0x2a0, 0x2a1, 0x7, 0x67, 0x2, 0x2, 0x2a1, 0x2a2, 0x7, 0x76, 0x2, 0x2, 0x2a2, 0x2a3, 0x7, 0x77, 0x2, 0x2, 0x2a3, 0x2a4, 0x7, 0x74, 0x2, 0x2, 0x2a4, 0x2a5, 0x7, 0x70, 0x2, 0x2, 0x2a5, 0xa2, 0x3, 0x2, 0x2, 0x2, 0x2a6, 0x2a7, 0x7, 0x78, 0x2, 0x2, 0x2a7, 0x2a8, 0x7, 0x71, 0x2, 0x2, 0x2a8, 0x2a9, 0x7, 0x6b, 0x2, 0x2, 0x2a9, 0x2aa, 0x7, 0x66, 0x2, 0x2, 0x2aa, 0xa4, 0x3, 0x2, 0x2, 0x2, 0x2ab, 0x2ac, 0x7, 0x65, 0x2, 0x2, 0x2ac, 0x2ad, 0x7, 0x71, 0x2, 0x2, 0x2ad, 0x2ae, 0x7, 0x70, 0x2, 0x2, 0x2ae, 0x2af, 0x7, 0x76, 0x2, 0x2, 0x2af, 0x2b0, 0x7, 0x6b, 0x2, 0x2, 0x2b0, 0x2b1, 0x7, 0x70, 0x2, 0x2, 0x2b1, 0x2b2, 0x7, 0x77, 0x2, 0x2, 0x2b2, 0x2b3, 0x7, 0x67, 0x2, 0x2, 0x2b3, 0xa6, 0x3, 0x2, 0x2, 0x2, 0x2b4, 0x2b5, 0x7, 0x68, 0x2, 0x2, 0x2b5, 0x2b6, 0x7, 0x71, 0x2, 0x2, 0x2b6, 0x2b7, 0x7, 0x74, 0x2, 0x2, 0x2b7, 0xa8, 0x3, 0x2, 0x2, 0x2, 0x2b8, 0x2b9, 0x7, 0x75, 0x2, 0x2, 0x2b9, 0x2ba, 0x7, 0x79, 0x2, 0x2, 0x2ba, 0x2bb, 0x7, 0x6b, 0x2, 0x2, 0x2bb, 0x2bc, 0x7, 0x76, 0x2, 0x2, 0x2bc, 0x2bd, 0x7, 0x65, 0x2, 0x2, 0x2bd, 0x2be, 0x7, 0x6a, 0x2, 0x2, 0x2be, 0xaa, 0x3, 0x2, 0x2, 0x2, 0x2bf, 0x2c0, 0x7, 0x79, 0x2, 0x2, 0x2c0, 0x2c1, 0x7, 0x6a, 0x2, 0x2, 0x2c1, 0x2c2, 0x7, 0x6b, 0x2, 0x2, 0x2c2, 0x2c3, 0x7, 0x6e, 0x2, 0x2, 0x2c3, 0x2c4, 0x7, 0x67, 0x2, 0x2, 0x2c4, 0xac, 0x3, 0x2, 0x2, 0x2, 0x2c5, 0x2c6, 0x7, 0x66, 0x2, 0x2, 0x2c6, 0x2c7, 0x7, 0x67, 0x2, 0x2, 0x2c7, 0x2c8, 0x7, 0x64, 0x2, 0x2, 0x2c8, 0x2c9, 0x7, 0x77, 0x2, 0x2, 0x2c9, 0x2ca, 0x7, 0x69, 0x2, 0x2, 0x2ca, 0x2cb, 0x7, 0x69, 0x2, 0x2, 0x2cb, 0x2cc, 0x7, 0x67, 0x2, 0x2, 0x2cc, 0x2cd, 0x7, 0x74, 0x2, 0x2, 0x2cd, 0xae, 0x3, 0x2, 0x2, 0x2, 0x2ce, 0x2cf, 0x7, 0x68, 0x2, 0x2, 0x2cf, 0x2d0, 0x7, 0x77, 0x2, 0x2, 0x2d0, 0x2d1, 0x7, 0x70, 0x2, 0x2, 0x2d1, 0x2d2, 0x7, 0x65, 0x2, 0x2, 0x2d2, 0x2d3, 0x7, 0x76, 0x2, 0x2, 0x2d3, 0x2d4, 0x7, 0x6b, 0x2, 0x2, 0x2d4, 0x2d5, 0x7, 0x71, 0x2, 0x2, 0x2d5, 0x2d6, 0x7, 0x70, 0x2, 0x2, 0x2d6, 0xb0, 0x3, 0x2, 0x2, 0x2, 0x2d7, 0x2d8, 0x7, 0x76, 0x2, 0x2, 0x2d8, 0x2d9, 0x7, 0x6a, 0x2, 0x2, 0x2d9, 0x2da, 0x7, 0x6b, 0x2, 0x2, 0x2da, 0x2db, 0x7, 0x75, 0x2, 0x2, 0x2db, 0xb2, 0x3, 0x2, 0x2, 0x2, 0x2dc, 0x2dd, 0x7, 0x79, 0x2, 0x2, 0x2dd, 0x2de, 0x7, 0x6b, 0x2, 0x2, 0x2de, 0x2df, 0x7, 0x76, 0x2, 0x2, 0x2df, 0x2e0, 0x7, 0x6a, 0x2, 0x2, 0x2e0, 0xb4, 0x3, 0x2, 0x2, 0x2, 0x2e1, 0x2e2, 0x7, 0x66, 0x2, 0x2, 0x2e2, 0x2e3, 0x7, 0x67, 0x2, 0x2, 0x2e3, 0x2e4, 0x7, 0x68, 0x2, 0x2, 0x2e4, 0x2e5, 0x7, 0x63, 0x2, 0x2, 0x2e5, 0x2e6, 0x7, 0x77, 0x2, 0x2, 0x2e6, 0x2e7, 0x7, 0x6e, 0x2, 0x2, 0x2e7, 0x2e8, 0x7, 0x76, 0x2, 0x2, 0x2e8, 0xb6, 0x3, 0x2, 0x2, 0x2, 0x2e9, 0x2ea, 0x7, 0x6b, 0x2, 0x2, 0x2ea, 0x2eb, 0x7, 0x68, 0x2, 0x2, 0x2eb, 0xb8, 0x3, 0x2, 0x2, 0x2, 0x2ec, 0x2ed, 0x7, 0x76, 0x2, 0x2, 0x2ed, 0x2ee, 0x7, 0x6a, 0x2, 0x2, 0x2ee, 0x2ef, 0x7, 0x74, 0x2, 0x2, 0x2ef, 0x2f0, 0x7, 0x71, 0x2, 0x2, 0x2f0, 0x2f1, 0x7, 0x79, 0x2, 0x2, 0x2f1, 0xba, 0x3, 0x2, 0x2, 0x2, 0x2f2, 0x2f3, 0x7, 0x66, 0x2, 0x2, 0x2f3, 0x2f4, 0x7, 0x67, 0x2, 0x2, 0x2f4, 0x2f5, 0x7, 0x6e, 0x2, 0x2, 0x2f5, 0x2f6, 0x7, 0x67, 0x2, 0x2, 0x2f6, 0x2f7, 0x7, 0x76, 0x2, 0x2, 0x2f7, 0x2f8, 0x7, 0x67, 0x2, 0x2, 0x2f8, 0xbc, 0x3, 0x2, 0x2, 0x2, 0x2f9, 0x2fa, 0x7, 0x6b, 0x2, 0x2, 0x2fa, 0x2fb, 0x7, 0x70, 0x2, 0x2, 0x2fb, 0xbe, 0x3, 0x2, 0x2, 0x2, 0x2fc, 0x2fd, 0x7, 0x76, 0x2, 0x2, 0x2fd, 0x2fe, 0x7, 0x74, 0x2, 0x2, 0x2fe, 0x2ff, 0x7, 0x7b, 0x2, 0x2, 0x2ff, 0xc0, 0x3, 0x2, 0x2, 0x2, 0x300, 0x301, 0x7, 0x63, 0x2, 0x2, 0x301, 0x302, 0x7, 0x75, 0x2, 0x2, 0x302, 0xc2, 0x3, 0x2, 0x2, 0x2, 0x303, 0x304, 0x7, 0x68, 0x2, 0x2, 0x304, 0x305, 0x7, 0x74, 0x2, 0x2, 0x305, 0x306, 0x7, 0x71, 0x2, 0x2, 0x306, 0x307, 0x7, 0x6f, 0x2, 0x2, 0x307, 0xc4, 0x3, 0x2, 0x2, 0x2, 0x308, 0x309, 0x7, 0x65, 0x2, 0x2, 0x309, 0x30a, 0x7, 0x6e, 0x2, 0x2, 0x30a, 0x30b, 0x7, 0x63, 0x2, 0x2, 0x30b, 0x30c, 0x7, 0x75, 0x2, 0x2, 0x30c, 0x30d, 0x7, 0x75, 0x2, 0x2, 0x30d, 0xc6, 0x3, 0x2, 0x2, 0x2, 0x30e, 0x30f, 0x7, 0x67, 0x2, 0x2, 0x30f, 0x310, 0x7, 0x70, 0x2, 0x2, 0x310, 0x311, 0x7, 0x77, 0x2, 0x2, 0x311, 0x312, 0x7, 0x6f, 0x2, 0x2, 0x312, 0xc8, 0x3, 0x2, 0x2, 0x2, 0x313, 0x314, 0x7, 0x67, 0x2, 0x2, 0x314, 0x315, 0x7, 0x7a, 0x2, 0x2, 0x315, 0x316, 0x7, 0x76, 0x2, 0x2, 0x316, 0x317, 0x7, 0x67, 0x2, 0x2, 0x317, 0x318, 0x7, 0x70, 0x2, 0x2, 0x318, 0x319, 0x7, 0x66, 0x2, 0x2, 0x319, 0x31a, 0x7, 0x75, 0x2, 0x2, 0x31a, 0xca, 0x3, 0x2, 0x2, 0x2, 0x31b, 0x31c, 0x7, 0x75, 0x2, 0x2, 0x31c, 0x31d, 0x7, 0x77, 0x2, 0x2, 0x31d, 0x31e, 0x7, 0x72, 0x2, 0x2, 0x31e, 0x31f, 0x7, 0x67, 0x2, 0x2, 0x31f, 0x320, 0x7, 0x74, 0x2, 0x2, 0x320, 0xcc, 0x3, 0x2, 0x2, 0x2, 0x321, 0x322, 0x7, 0x65, 0x2, 0x2, 0x322, 0x323, 0x7, 0x71, 0x2, 0x2, 0x323, 0x324, 0x7, 0x70, 0x2, 0x2, 0x324, 0x325, 0x7, 0x75, 0x2, 0x2, 0x325, 0x326, 0x7, 0x76, 0x2, 0x2, 0x326, 0xce, 0x3, 0x2, 0x2, 0x2, 0x327, 0x328, 0x7, 0x67, 0x2, 0x2, 0x328, 0x329, 0x7, 0x7a, 0x2, 0x2, 0x329, 0x32a, 0x7, 0x72, 0x2, 0x2, 0x32a, 0x32b, 0x7, 0x71, 0x2, 0x2, 0x32b, 0x32c, 0x7, 0x74, 0x2, 0x2, 0x32c, 0x32d, 0x7, 0x76, 0x2, 0x2, 0x32d, 0xd0, 0x3, 0x2, 0x2, 0x2, 0x32e, 0x32f, 0x7, 0x6b, 0x2, 0x2, 0x32f, 0x330, 0x7, 0x6f, 0x2, 0x2, 0x330, 0x331, 0x7, 0x72, 0x2, 0x2, 0x331, 0x332, 0x7, 0x71, 0x2, 0x2, 0x332, 0x333, 0x7, 0x74, 0x2, 0x2, 0x333, 0x334, 0x7, 0x76, 0x2, 0x2, 0x334, 0xd2, 0x3, 0x2, 0x2, 0x2, 0x335, 0x336, 0x7, 0x63, 0x2, 0x2, 0x336, 0x337, 0x7, 0x75, 0x2, 0x2, 0x337, 0x338, 0x7, 0x7b, 0x2, 0x2, 0x338, 0x339, 0x7, 0x70, 0x2, 0x2, 0x339, 0x33a, 0x7, 0x65, 0x2, 0x2, 0x33a, 0xd4, 0x3, 0x2, 0x2, 0x2, 0x33b, 0x33c, 0x7, 0x63, 0x2, 0x2, 0x33c, 0x33d, 0x7, 0x79, 0x2, 0x2, 0x33d, 0x33e, 0x7, 0x63, 0x2, 0x2, 0x33e, 0x33f, 0x7, 0x6b, 0x2, 0x2, 0x33f, 0x340, 0x7, 0x76, 0x2, 0x2, 0x340, 0xd6, 0x3, 0x2, 0x2, 0x2, 0x341, 0x342, 0x7, 0x6b, 0x2, 0x2, 0x342, 0x343, 0x7, 0x6f, 0x2, 0x2, 0x343, 0x344, 0x7, 0x72, 0x2, 0x2, 0x344, 0x345, 0x7, 0x6e, 0x2, 0x2, 0x345, 0x346, 0x7, 0x67, 0x2, 0x2, 0x346, 0x347, 0x7, 0x6f, 0x2, 0x2, 0x347, 0x348, 0x7, 0x67, 0x2, 0x2, 0x348, 0x349, 0x7, 0x70, 0x2, 0x2, 0x349, 0x34a, 0x7, 0x76, 0x2, 0x2, 0x34a, 0x34b, 0x7, 0x75, 0x2, 0x2, 0x34b, 0x34c, 0x3, 0x2, 0x2, 0x2, 0x34c, 0x34d, 0x6, 0x6c, 0x5, 0x2, 0x34d, 0xd8, 0x3, 0x2, 0x2, 0x2, 0x34e, 0x34f, 0x7, 0x6e, 0x2, 0x2, 0x34f, 0x350, 0x7, 0x67, 0x2, 0x2, 0x350, 0x351, 0x7, 0x76, 0x2, 0x2, 0x351, 0x352, 0x3, 0x2, 0x2, 0x2, 0x352, 0x353, 0x6, 0x6d, 0x6, 0x2, 0x353, 0xda, 0x3, 0x2, 0x2, 0x2, 0x354, 0x355, 0x7, 0x72, 0x2, 0x2, 0x355, 0x356, 0x7, 0x74, 0x2, 0x2, 0x356, 0x357, 0x7, 0x6b, 0x2, 0x2, 0x357, 0x358, 0x7, 0x78, 0x2, 0x2, 0x358, 0x359, 0x7, 0x63, 0x2, 0x2, 0x359, 0x35a, 0x7, 0x76, 0x2, 0x2, 0x35a, 0x35b, 0x7, 0x67, 0x2, 0x2, 0x35b, 0x35c, 0x3, 0x2, 0x2, 0x2, 0x35c, 0x35d, 0x6, 0x6e, 0x7, 0x2, 0x35d, 0xdc, 0x3, 0x2, 0x2, 0x2, 0x35e, 0x35f, 0x7, 0x72, 0x2, 0x2, 0x35f, 0x360, 0x7, 0x77, 0x2, 0x2, 0x360, 0x361, 0x7, 0x64, 0x2, 0x2, 0x361, 0x362, 0x7, 0x6e, 0x2, 0x2, 0x362, 0x363, 0x7, 0x6b, 0x2, 0x2, 0x363, 0x364, 0x7, 0x65, 0x2, 0x2, 0x364, 0x365, 0x3, 0x2, 0x2, 0x2, 0x365, 0x366, 0x6, 0x6f, 0x8, 0x2, 0x366, 0xde, 0x3, 0x2, 0x2, 0x2, 0x367, 0x368, 0x7, 0x6b, 0x2, 0x2, 0x368, 0x369, 0x7, 0x70, 0x2, 0x2, 0x369, 0x36a, 0x7, 0x76, 0x2, 0x2, 0x36a, 0x36b, 0x7, 0x67, 0x2, 0x2, 0x36b, 0x36c, 0x7, 0x74, 0x2, 0x2, 0x36c, 0x36d, 0x7, 0x68, 0x2, 0x2, 0x36d, 0x36e, 0x7, 0x63, 0x2, 0x2, 0x36e, 0x36f, 0x7, 0x65, 0x2, 0x2, 0x36f, 0x370, 0x7, 0x67, 0x2, 0x2, 0x370, 0x371, 0x3, 0x2, 0x2, 0x2, 0x371, 0x372, 0x6, 0x70, 0x9, 0x2, 0x372, 0xe0, 0x3, 0x2, 0x2, 0x2, 0x373, 0x374, 0x7, 0x72, 0x2, 0x2, 0x374, 0x375, 0x7, 0x63, 0x2, 0x2, 0x375, 0x376, 0x7, 0x65, 0x2, 0x2, 0x376, 0x377, 0x7, 0x6d, 0x2, 0x2, 0x377, 0x378, 0x7, 0x63, 0x2, 0x2, 0x378, 0x379, 0x7, 0x69, 0x2, 0x2, 0x379, 0x37a, 0x7, 0x67, 0x2, 0x2, 0x37a, 0x37b, 0x3, 0x2, 0x2, 0x2, 0x37b, 0x37c, 0x6, 0x71, 0xa, 0x2, 0x37c, 0xe2, 0x3, 0x2, 0x2, 0x2, 0x37d, 0x37e, 0x7, 0x72, 0x2, 0x2, 0x37e, 0x37f, 0x7, 0x74, 0x2, 0x2, 0x37f, 0x380, 0x7, 0x71, 0x2, 0x2, 0x380, 0x381, 0x7, 0x76, 0x2, 0x2, 0x381, 0x382, 0x7, 0x67, 0x2, 0x2, 0x382, 0x383, 0x7, 0x65, 0x2, 0x2, 0x383, 0x384, 0x7, 0x76, 0x2, 0x2, 0x384, 0x385, 0x7, 0x67, 0x2, 0x2, 0x385, 0x386, 0x7, 0x66, 0x2, 0x2, 0x386, 0x387, 0x3, 0x2, 0x2, 0x2, 0x387, 0x388, 0x6, 0x72, 0xb, 0x2, 0x388, 0xe4, 0x3, 0x2, 0x2, 0x2, 0x389, 0x38a, 0x7, 0x75, 0x2, 0x2, 0x38a, 0x38b, 0x7, 0x76, 0x2, 0x2, 0x38b, 0x38c, 0x7, 0x63, 0x2, 0x2, 0x38c, 0x38d, 0x7, 0x76, 0x2, 0x2, 0x38d, 0x38e, 0x7, 0x6b, 0x2, 0x2, 0x38e, 0x38f, 0x7, 0x65, 0x2, 0x2, 0x38f, 0x390, 0x3, 0x2, 0x2, 0x2, 0x390, 0x391, 0x6, 0x73, 0xc, 0x2, 0x391, 0xe6, 0x3, 0x2, 0x2, 0x2, 0x392, 0x393, 0x7, 0x7b, 0x2, 0x2, 0x393, 0x394, 0x7, 0x6b, 0x2, 0x2, 0x394, 0x395, 0x7, 0x67, 0x2, 0x2, 0x395, 0x396, 0x7, 0x6e, 0x2, 0x2, 0x396, 0x397, 0x7, 0x66, 0x2, 0x2, 0x397, 0x398, 0x3, 0x2, 0x2, 0x2, 0x398, 0x399, 0x6, 0x74, 0xd, 0x2, 0x399, 0xe8, 0x3, 0x2, 0x2, 0x2, 0x39a, 0x39e, 0x5, 0x117, 0x8c, 0x2, 0x39b, 0x39d, 0x5, 0x115, 0x8b, 0x2, 0x39c, 0x39b, 0x3, 0x2, 0x2, 0x2, 0x39d, 0x3a0, 0x3, 0x2, 0x2, 0x2, 0x39e, 0x39c, 0x3, 0x2, 0x2, 0x2, 0x39e, 0x39f, 0x3, 0x2, 0x2, 0x2, 0x39f, 0xea, 0x3, 0x2, 0x2, 0x2, 0x3a0, 0x39e, 0x3, 0x2, 0x2, 0x2, 0x3a1, 0x3a5, 0x7, 0x24, 0x2, 0x2, 0x3a2, 0x3a4, 0x5, 0xf9, 0x7d, 0x2, 0x3a3, 0x3a2, 0x3, 0x2, 0x2, 0x2, 0x3a4, 0x3a7, 0x3, 0x2, 0x2, 0x2, 0x3a5, 0x3a3, 0x3, 0x2, 0x2, 0x2, 0x3a5, 0x3a6, 0x3, 0x2, 0x2, 0x2, 0x3a6, 0x3a8, 0x3, 0x2, 0x2, 0x2, 0x3a7, 0x3a5, 0x3, 0x2, 0x2, 0x2, 0x3a8, 0x3b2, 0x7, 0x24, 0x2, 0x2, 0x3a9, 0x3ad, 0x7, 0x29, 0x2, 0x2, 0x3aa, 0x3ac, 0x5, 0xfb, 0x7e, 0x2, 0x3ab, 0x3aa, 0x3, 0x2, 0x2, 0x2, 0x3ac, 0x3af, 0x3, 0x2, 0x2, 0x2, 0x3ad, 0x3ab, 0x3, 0x2, 0x2, 0x2, 0x3ad, 0x3ae, 0x3, 0x2, 0x2, 0x2, 0x3ae, 0x3b0, 0x3, 0x2, 0x2, 0x2, 0x3af, 0x3ad, 0x3, 0x2, 0x2, 0x2, 0x3b0, 0x3b2, 0x7, 0x29, 0x2, 0x2, 0x3b1, 0x3a1, 0x3, 0x2, 0x2, 0x2, 0x3b1, 0x3a9, 0x3, 0x2, 0x2, 0x2, 0x3b2, 0x3b3, 0x3, 0x2, 0x2, 0x2, 0x3b3, 0x3b4, 0x8, 0x76, 0x5, 0x2, 0x3b4, 0xec, 0x3, 0x2, 0x2, 0x2, 0x3b5, 0x3bb, 0x7, 0x62, 0x2, 0x2, 0x3b6, 0x3b7, 0x7, 0x5e, 0x2, 0x2, 0x3b7, 0x3ba, 0x7, 0x62, 0x2, 0x2, 0x3b8, 0x3ba, 0xa, 0xd, 0x2, 0x2, 0x3b9, 0x3b6, 0x3, 0x2, 0x2, 0x2, 0x3b9, 0x3b8, 0x3, 0x2, 0x2, 0x2, 0x3ba, 0x3bd, 0x3, 0x2, 0x2, 0x2, 0x3bb, 0x3b9, 0x3, 0x2, 0x2, 0x2, 0x3bb, 0x3bc, 0x3, 0x2, 0x2, 0x2, 0x3bc, 0x3be, 0x3, 0x2, 0x2, 0x2, 0x3bd, 0x3bb, 0x3, 0x2, 0x2, 0x2, 0x3be, 0x3bf, 0x7, 0x62, 0x2, 0x2, 0x3bf, 0xee, 0x3, 0x2, 0x2, 0x2, 0x3c0, 0x3c2, 0x9, 0xe, 0x2, 0x2, 0x3c1, 0x3c0, 0x3, 0x2, 0x2, 0x2, 0x3c2, 0x3c3, 0x3, 0x2, 0x2, 0x2, 0x3c3, 0x3c1, 0x3, 0x2, 0x2, 0x2, 0x3c3, 0x3c4, 0x3, 0x2, 0x2, 0x2, 0x3c4, 0x3c5, 0x3, 0x2, 0x2, 0x2, 0x3c5, 0x3c6, 0x8, 0x78, 0x2, 0x2, 0x3c6, 0xf0, 0x3, 0x2, 0x2, 0x2, 0x3c7, 0x3c8, 0x9, 0x2, 0x2, 0x2, 0x3c8, 0x3c9, 0x3, 0x2, 0x2, 0x2, 0x3c9, 0x3ca, 0x8, 0x79, 0x2, 0x2, 0x3ca, 0xf2, 0x3, 0x2, 0x2, 0x2, 0x3cb, 0x3cc, 0x7, 0x3e, 0x2, 0x2, 0x3cc, 0x3cd, 0x7, 0x23, 0x2, 0x2, 0x3cd, 0x3ce, 0x7, 0x2f, 0x2, 0x2, 0x3ce, 0x3cf, 0x7, 0x2f, 0x2, 0x2, 0x3cf, 0x3d3, 0x3, 0x2, 0x2, 0x2, 0x3d0, 0x3d2, 0xb, 0x2, 0x2, 0x2, 0x3d1, 0x3d0, 0x3, 0x2, 0x2, 0x2, 0x3d2, 0x3d5, 0x3, 0x2, 0x2, 0x2, 0x3d3, 0x3d4, 0x3, 0x2, 0x2, 0x2, 0x3d3, 0x3d1, 0x3, 0x2, 0x2, 0x2, 0x3d4, 0x3d6, 0x3, 0x2, 0x2, 0x2, 0x3d5, 0x3d3, 0x3, 0x2, 0x2, 0x2, 0x3d6, 0x3d7, 0x7, 0x2f, 0x2, 0x2, 0x3d7, 0x3d8, 0x7, 0x2f, 0x2, 0x2, 0x3d8, 0x3d9, 0x7, 0x40, 0x2, 0x2, 0x3d9, 0x3da, 0x3, 0x2, 0x2, 0x2, 0x3da, 0x3db, 0x8, 0x7a, 0x2, 0x2, 0x3db, 0xf4, 0x3, 0x2, 0x2, 0x2, 0x3dc, 0x3dd, 0x7, 0x3e, 0x2, 0x2, 0x3dd, 0x3de, 0x7, 0x23, 0x2, 0x2, 0x3de, 0x3df, 0x7, 0x5d, 0x2, 0x2, 0x3df, 0x3e0, 0x7, 0x45, 0x2, 0x2, 0x3e0, 0x3e1, 0x7, 0x46, 0x2, 0x2, 0x3e1, 0x3e2, 0x7, 0x43, 0x2, 0x2, 0x3e2, 0x3e3, 0x7, 0x56, 0x2, 0x2, 0x3e3, 0x3e4, 0x7, 0x43, 0x2, 0x2, 0x3e4, 0x3e5, 0x7, 0x5d, 0x2, 0x2, 0x3e5, 0x3e9, 0x3, 0x2, 0x2, 0x2, 0x3e6, 0x3e8, 0xb, 0x2, 0x2, 0x2, 0x3e7, 0x3e6, 0x3, 0x2, 0x2, 0x2, 0x3e8, 0x3eb, 0x3, 0x2, 0x2, 0x2, 0x3e9, 0x3ea, 0x3, 0x2, 0x2, 0x2, 0x3e9, 0x3e7, 0x3, 0x2, 0x2, 0x2, 0x3ea, 0x3ec, 0x3, 0x2, 0x2, 0x2, 0x3eb, 0x3e9, 0x3, 0x2, 0x2, 0x2, 0x3ec, 0x3ed, 0x7, 0x5f, 0x2, 0x2, 0x3ed, 0x3ee, 0x7, 0x5f, 0x2, 0x2, 0x3ee, 0x3ef, 0x7, 0x40, 0x2, 0x2, 0x3ef, 0x3f0, 0x3, 0x2, 0x2, 0x2, 0x3f0, 0x3f1, 0x8, 0x7b, 0x2, 0x2, 0x3f1, 0xf6, 0x3, 0x2, 0x2, 0x2, 0x3f2, 0x3f3, 0xb, 0x2, 0x2, 0x2, 0x3f3, 0x3f4, 0x3, 0x2, 0x2, 0x2, 0x3f4, 0x3f5, 0x8, 0x7c, 0x6, 0x2, 0x3f5, 0xf8, 0x3, 0x2, 0x2, 0x2, 0x3f6, 0x3fb, 0xa, 0xf, 0x2, 0x2, 0x3f7, 0x3f8, 0x7, 0x5e, 0x2, 0x2, 0x3f8, 0x3fb, 0x5, 0xfd, 0x7f, 0x2, 0x3f9, 0x3fb, 0x5, 0x10d, 0x87, 0x2, 0x3fa, 0x3f6, 0x3, 0x2, 0x2, 0x2, 0x3fa, 0x3f7, 0x3, 0x2, 0x2, 0x2, 0x3fa, 0x3f9, 0x3, 0x2, 0x2, 0x2, 0x3fb, 0xfa, 0x3, 0x2, 0x2, 0x2, 0x3fc, 0x401, 0xa, 0x10, 0x2, 0x2, 0x3fd, 0x3fe, 0x7, 0x5e, 0x2, 0x2, 0x3fe, 0x401, 0x5, 0xfd, 0x7f, 0x2, 0x3ff, 0x401, 0x5, 0x10d, 0x87, 0x2, 0x400, 0x3fc, 0x3, 0x2, 0x2, 0x2, 0x400, 0x3fd, 0x3, 0x2, 0x2, 0x2, 0x400, 0x3ff, 0x3, 0x2, 0x2, 0x2, 0x401, 0xfc, 0x3, 0x2, 0x2, 0x2, 0x402, 0x408, 0x5, 0xff, 0x80, 0x2, 0x403, 0x408, 0x7, 0x32, 0x2, 0x2, 0x404, 0x408, 0x5, 0x101, 0x81, 0x2, 0x405, 0x408, 0x5, 0x103, 0x82, 0x2, 0x406, 0x408, 0x5, 0x105, 0x83, 0x2, 0x407, 0x402, 0x3, 0x2, 0x2, 0x2, 0x407, 0x403, 0x3, 0x2, 0x2, 0x2, 0x407, 0x404, 0x3, 0x2, 0x2, 0x2, 0x407, 0x405, 0x3, 0x2, 0x2, 0x2, 0x407, 0x406, 0x3, 0x2, 0x2, 0x2, 0x408, 0xfe, 0x3, 0x2, 0x2, 0x2, 0x409, 0x40c, 0x5, 0x107, 0x84, 0x2, 0x40a, 0x40c, 0x5, 0x109, 0x85, 0x2, 0x40b, 0x409, 0x3, 0x2, 0x2, 0x2, 0x40b, 0x40a, 0x3, 0x2, 0x2, 0x2, 0x40c, 0x100, 0x3, 0x2, 0x2, 0x2, 0x40d, 0x40e, 0x7, 0x7a, 0x2, 0x2, 0x40e, 0x40f, 0x5, 0x10f, 0x88, 0x2, 0x40f, 0x410, 0x5, 0x10f, 0x88, 0x2, 0x410, 0x102, 0x3, 0x2, 0x2, 0x2, 0x411, 0x412, 0x7, 0x77, 0x2, 0x2, 0x412, 0x413, 0x5, 0x10f, 0x88, 0x2, 0x413, 0x414, 0x5, 0x10f, 0x88, 0x2, 0x414, 0x415, 0x5, 0x10f, 0x88, 0x2, 0x415, 0x416, 0x5, 0x10f, 0x88, 0x2, 0x416, 0x422, 0x3, 0x2, 0x2, 0x2, 0x417, 0x418, 0x7, 0x77, 0x2, 0x2, 0x418, 0x419, 0x7, 0x7d, 0x2, 0x2, 0x419, 0x41b, 0x5, 0x10f, 0x88, 0x2, 0x41a, 0x41c, 0x5, 0x10f, 0x88, 0x2, 0x41b, 0x41a, 0x3, 0x2, 0x2, 0x2, 0x41c, 0x41d, 0x3, 0x2, 0x2, 0x2, 0x41d, 0x41b, 0x3, 0x2, 0x2, 0x2, 0x41d, 0x41e, 0x3, 0x2, 0x2, 0x2, 0x41e, 0x41f, 0x3, 0x2, 0x2, 0x2, 0x41f, 0x420, 0x7, 0x7f, 0x2, 0x2, 0x420, 0x422, 0x3, 0x2, 0x2, 0x2, 0x421, 0x411, 0x3, 0x2, 0x2, 0x2, 0x421, 0x417, 0x3, 0x2, 0x2, 0x2, 0x422, 0x104, 0x3, 0x2, 0x2, 0x2, 0x423, 0x424, 0x7, 0x77, 0x2, 0x2, 0x424, 0x426, 0x7, 0x7d, 0x2, 0x2, 0x425, 0x427, 0x5, 0x10f, 0x88, 0x2, 0x426, 0x425, 0x3, 0x2, 0x2, 0x2, 0x427, 0x428, 0x3, 0x2, 0x2, 0x2, 0x428, 0x426, 0x3, 0x2, 0x2, 0x2, 0x428, 0x429, 0x3, 0x2, 0x2, 0x2, 0x429, 0x42a, 0x3, 0x2, 0x2, 0x2, 0x42a, 0x42b, 0x7, 0x7f, 0x2, 0x2, 0x42b, 0x106, 0x3, 0x2, 0x2, 0x2, 0x42c, 0x42d, 0x9, 0x11, 0x2, 0x2, 0x42d, 0x108, 0x3, 0x2, 0x2, 0x2, 0x42e, 0x42f, 0xa, 0x12, 0x2, 0x2, 0x42f, 0x10a, 0x3, 0x2, 0x2, 0x2, 0x430, 0x433, 0x5, 0x107, 0x84, 0x2, 0x431, 0x433, 0x9, 0x13, 0x2, 0x2, 0x432, 0x430, 0x3, 0x2, 0x2, 0x2, 0x432, 0x431, 0x3, 0x2, 0x2, 0x2, 0x433, 0x10c, 0x3, 0x2, 0x2, 0x2, 0x434, 0x435, 0x7, 0x5e, 0x2, 0x2, 0x435, 0x436, 0x9, 0x2, 0x2, 0x2, 0x436, 0x10e, 0x3, 0x2, 0x2, 0x2, 0x437, 0x438, 0x9, 0x14, 0x2, 0x2, 0x438, 0x110, 0x3, 0x2, 0x2, 0x2, 0x439, 0x442, 0x7, 0x32, 0x2, 0x2, 0x43a, 0x43e, 0x9, 0x15, 0x2, 0x2, 0x43b, 0x43d, 0x9, 0x4, 0x2, 0x2, 0x43c, 0x43b, 0x3, 0x2, 0x2, 0x2, 0x43d, 0x440, 0x3, 0x2, 0x2, 0x2, 0x43e, 0x43c, 0x3, 0x2, 0x2, 0x2, 0x43e, 0x43f, 0x3, 0x2, 0x2, 0x2, 0x43f, 0x442, 0x3, 0x2, 0x2, 0x2, 0x440, 0x43e, 0x3, 0x2, 0x2, 0x2, 0x441, 0x439, 0x3, 0x2, 0x2, 0x2, 0x441, 0x43a, 0x3, 0x2, 0x2, 0x2, 0x442, 0x112, 0x3, 0x2, 0x2, 0x2, 0x443, 0x445, 0x9, 0x16, 0x2, 0x2, 0x444, 0x446, 0x9, 0x17, 0x2, 0x2, 0x445, 0x444, 0x3, 0x2, 0x2, 0x2, 0x445, 0x446, 0x3, 0x2, 0x2, 0x2, 0x446, 0x448, 0x3, 0x2, 0x2, 0x2, 0x447, 0x449, 0x9, 0x4, 0x2, 0x2, 0x448, 0x447, 0x3, 0x2, 0x2, 0x2, 0x449, 0x44a, 0x3, 0x2, 0x2, 0x2, 0x44a, 0x448, 0x3, 0x2, 0x2, 0x2, 0x44a, 0x44b, 0x3, 0x2, 0x2, 0x2, 0x44b, 0x114, 0x3, 0x2, 0x2, 0x2, 0x44c, 0x452, 0x5, 0x117, 0x8c, 0x2, 0x44d, 0x452, 0x5, 0x11b, 0x8e, 0x2, 0x44e, 0x452, 0x5, 0x11d, 0x8f, 0x2, 0x44f, 0x452, 0x5, 0x11f, 0x90, 0x2, 0x450, 0x452, 0x4, 0x200e, 0x200f, 0x2, 0x451, 0x44c, 0x3, 0x2, 0x2, 0x2, 0x451, 0x44d, 0x3, 0x2, 0x2, 0x2, 0x451, 0x44e, 0x3, 0x2, 0x2, 0x2, 0x451, 0x44f, 0x3, 0x2, 0x2, 0x2, 0x451, 0x450, 0x3, 0x2, 0x2, 0x2, 0x452, 0x116, 0x3, 0x2, 0x2, 0x2, 0x453, 0x458, 0x5, 0x119, 0x8d, 0x2, 0x454, 0x458, 0x9, 0x18, 0x2, 0x2, 0x455, 0x456, 0x7, 0x5e, 0x2, 0x2, 0x456, 0x458, 0x5, 0x103, 0x82, 0x2, 0x457, 0x453, 0x3, 0x2, 0x2, 0x2, 0x457, 0x454, 0x3, 0x2, 0x2, 0x2, 0x457, 0x455, 0x3, 0x2, 0x2, 0x2, 0x458, 0x118, 0x3, 0x2, 0x2, 0x2, 0x459, 0x45b, 0x9, 0x19, 0x2, 0x2, 0x45a, 0x459, 0x3, 0x2, 0x2, 0x2, 0x45b, 0x11a, 0x3, 0x2, 0x2, 0x2, 0x45c, 0x45e, 0x9, 0x1a, 0x2, 0x2, 0x45d, 0x45c, 0x3, 0x2, 0x2, 0x2, 0x45e, 0x11c, 0x3, 0x2, 0x2, 0x2, 0x45f, 0x461, 0x9, 0x1b, 0x2, 0x2, 0x460, 0x45f, 0x3, 0x2, 0x2, 0x2, 0x461, 0x11e, 0x3, 0x2, 0x2, 0x2, 0x462, 0x464, 0x9, 0x1c, 0x2, 0x2, 0x463, 0x462, 0x3, 0x2, 0x2, 0x2, 0x464, 0x120, 0x3, 0x2, 0x2, 0x2, 0x465, 0x470, 0xa, 0x1d, 0x2, 0x2, 0x466, 0x470, 0x5, 0x127, 0x94, 0x2, 0x467, 0x46b, 0x7, 0x5d, 0x2, 0x2, 0x468, 0x46a, 0x5, 0x125, 0x93, 0x2, 0x469, 0x468, 0x3, 0x2, 0x2, 0x2, 0x46a, 0x46d, 0x3, 0x2, 0x2, 0x2, 0x46b, 0x469, 0x3, 0x2, 0x2, 0x2, 0x46b, 0x46c, 0x3, 0x2, 0x2, 0x2, 0x46c, 0x46e, 0x3, 0x2, 0x2, 0x2, 0x46d, 0x46b, 0x3, 0x2, 0x2, 0x2, 0x46e, 0x470, 0x7, 0x5f, 0x2, 0x2, 0x46f, 0x465, 0x3, 0x2, 0x2, 0x2, 0x46f, 0x466, 0x3, 0x2, 0x2, 0x2, 0x46f, 0x467, 0x3, 0x2, 0x2, 0x2, 0x470, 0x122, 0x3, 0x2, 0x2, 0x2, 0x471, 0x47c, 0xa, 0x1e, 0x2, 0x2, 0x472, 0x47c, 0x5, 0x127, 0x94, 0x2, 0x473, 0x477, 0x7, 0x5d, 0x2, 0x2, 0x474, 0x476, 0x5, 0x125, 0x93, 0x2, 0x475, 0x474, 0x3, 0x2, 0x2, 0x2, 0x476, 0x479, 0x3, 0x2, 0x2, 0x2, 0x477, 0x475, 0x3, 0x2, 0x2, 0x2, 0x477, 0x478, 0x3, 0x2, 0x2, 0x2, 0x478, 0x47a, 0x3, 0x2, 0x2, 0x2, 0x479, 0x477, 0x3, 0x2, 0x2, 0x2, 0x47a, 0x47c, 0x7, 0x5f, 0x2, 0x2, 0x47b, 0x471, 0x3, 0x2, 0x2, 0x2, 0x47b, 0x472, 0x3, 0x2, 0x2, 0x2, 0x47b, 0x473, 0x3, 0x2, 0x2, 0x2, 0x47c, 0x124, 0x3, 0x2, 0x2, 0x2, 0x47d, 0x480, 0xa, 0x1f, 0x2, 0x2, 0x47e, 0x480, 0x5, 0x127, 0x94, 0x2, 0x47f, 0x47d, 0x3, 0x2, 0x2, 0x2, 0x47f, 0x47e, 0x3, 0x2, 0x2, 0x2, 0x480, 0x126, 0x3, 0x2, 0x2, 0x2, 0x481, 0x482, 0x7, 0x5e, 0x2, 0x2, 0x482, 0x483, 0xa, 0x2, 0x2, 0x2, 0x483, 0x128, 0x3, 0x2, 0x2, 0x2, 0x36, 0x2, 0x130, 0x139, 0x147, 0x151, 0x159, 0x1fe, 0x206, 0x20a, 0x211, 0x215, 0x219, 0x21b, 0x223, 0x22a, 0x234, 0x23d, 0x246, 0x251, 0x25c, 0x39e, 0x3a5, 0x3ad, 0x3b1, 0x3b9, 0x3bb, 0x3c3, 0x3d3, 0x3e9, 0x3fa, 0x400, 0x407, 0x40b, 0x41d, 0x421, 0x428, 0x432, 0x43e, 0x441, 0x445, 0x44a, 0x451, 0x457, 0x45a, 0x45d, 0x460, 0x463, 0x46b, 0x46f, 0x477, 0x47b, 0x47f, 0x7, 0x2, 0x3, 0x2, 0x3, 0xa, 0x2, 0x3, 0xb, 0x3, 0x3, 0x76, 0x4, 0x2, 0x4, 0x2, }; atn::ATNDeserializer deserializer; _atn = deserializer.deserialize(_serializedATN); size_t count = _atn.getNumberOfDecisions(); _decisionToDFA.reserve(count); for (size_t i = 0; i < count; i++) { _decisionToDFA.emplace_back(_atn.getDecisionState(i), i); } } JavaScriptLexer::Initializer JavaScriptLexer::_init;
63.911532
120
0.624605
yanmingsohu
bf11d151cc062acf4a50af10b01d70ae95416436
4,461
cc
C++
content/renderer/media/video_frame_compositor.cc
shaochangbin/chromium-crosswalk
634d34e4cf82b4f7400357c53ec12efaffe94add
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2019-01-16T03:57:28.000Z
2021-01-23T15:29:45.000Z
content/renderer/media/video_frame_compositor.cc
shaochangbin/chromium-crosswalk
634d34e4cf82b4f7400357c53ec12efaffe94add
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/renderer/media/video_frame_compositor.cc
shaochangbin/chromium-crosswalk
634d34e4cf82b4f7400357c53ec12efaffe94add
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2017-03-15T13:21:38.000Z
2017-03-15T13:21:38.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/renderer/media/video_frame_compositor.h" #include "base/bind.h" #include "base/location.h" #include "base/single_thread_task_runner.h" #include "cc/layers/video_frame_provider.h" #include "content/renderer/render_thread_impl.h" #include "media/base/video_frame.h" namespace content { class VideoFrameCompositor::Internal : public cc::VideoFrameProvider { public: Internal( const scoped_refptr<base::SingleThreadTaskRunner>& compositor_task_runner, const base::Callback<void(gfx::Size)>& natural_size_changed_cb) : compositor_task_runner_(compositor_task_runner), natural_size_changed_cb_(natural_size_changed_cb), client_(NULL), compositor_notification_pending_(false), frames_dropped_before_compositor_was_notified_(0) {} virtual ~Internal() { if (client_) client_->StopUsingProvider(); } void DeleteSoon() { compositor_task_runner_->DeleteSoon(FROM_HERE, this); } void UpdateCurrentFrame(const scoped_refptr<media::VideoFrame>& frame) { base::AutoLock auto_lock(lock_); if (current_frame_ && current_frame_->natural_size() != frame->natural_size()) { natural_size_changed_cb_.Run(frame->natural_size()); } current_frame_ = frame; // Count frames as dropped if and only if we updated the frame but didn't // finish notifying the compositor for the previous frame. if (compositor_notification_pending_) { if (frames_dropped_before_compositor_was_notified_ < kuint32max) ++frames_dropped_before_compositor_was_notified_; return; } compositor_notification_pending_ = true; compositor_task_runner_->PostTask( FROM_HERE, base::Bind(&Internal::NotifyCompositorOfNewFrame, base::Unretained(this))); } uint32 GetFramesDroppedBeforeCompositorWasNotified() { base::AutoLock auto_lock(lock_); return frames_dropped_before_compositor_was_notified_; } void SetFramesDroppedBeforeCompositorWasNotifiedForTesting( uint32 dropped_frames) { base::AutoLock auto_lock(lock_); frames_dropped_before_compositor_was_notified_ = dropped_frames; } // cc::VideoFrameProvider implementation. virtual void SetVideoFrameProviderClient( cc::VideoFrameProvider::Client* client) OVERRIDE { if (client_) client_->StopUsingProvider(); client_ = client; } virtual scoped_refptr<media::VideoFrame> GetCurrentFrame() OVERRIDE { base::AutoLock auto_lock(lock_); return current_frame_; } virtual void PutCurrentFrame(const scoped_refptr<media::VideoFrame>& frame) OVERRIDE {} private: void NotifyCompositorOfNewFrame() { base::AutoLock auto_lock(lock_); compositor_notification_pending_ = false; if (client_) client_->DidReceiveFrame(); } scoped_refptr<base::SingleThreadTaskRunner> compositor_task_runner_; base::Callback<void(gfx::Size)>natural_size_changed_cb_; cc::VideoFrameProvider::Client* client_; base::Lock lock_; scoped_refptr<media::VideoFrame> current_frame_; bool compositor_notification_pending_; uint32 frames_dropped_before_compositor_was_notified_; DISALLOW_COPY_AND_ASSIGN(Internal); }; VideoFrameCompositor::VideoFrameCompositor( const scoped_refptr<base::SingleThreadTaskRunner>& compositor_task_runner, const base::Callback<void(gfx::Size)>& natural_size_changed_cb) : internal_(new Internal(compositor_task_runner, natural_size_changed_cb)) { } VideoFrameCompositor::~VideoFrameCompositor() { internal_->DeleteSoon(); } cc::VideoFrameProvider* VideoFrameCompositor::GetVideoFrameProvider() { return internal_; } void VideoFrameCompositor::UpdateCurrentFrame( const scoped_refptr<media::VideoFrame>& frame) { internal_->UpdateCurrentFrame(frame); } scoped_refptr<media::VideoFrame> VideoFrameCompositor::GetCurrentFrame() { return internal_->GetCurrentFrame(); } uint32 VideoFrameCompositor::GetFramesDroppedBeforeCompositorWasNotified() { return internal_->GetFramesDroppedBeforeCompositorWasNotified(); } void VideoFrameCompositor::SetFramesDroppedBeforeCompositorWasNotifiedForTesting( uint32 dropped_frames) { internal_->SetFramesDroppedBeforeCompositorWasNotifiedForTesting( dropped_frames); } } // namespace content
30.979167
80
0.76104
shaochangbin
bf1296436738a914e9cb747ed217a116c7550157
5,599
hpp
C++
include/codegen/include/System/Net/Sockets/SocketAsyncResult.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/System/Net/Sockets/SocketAsyncResult.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/System/Net/Sockets/SocketAsyncResult.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:19 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: System.IOAsyncResult #include "System/IOAsyncResult.hpp" // Including type: System.Net.Sockets.SocketOperation #include "System/Net/Sockets/SocketOperation.hpp" // Including type: System.Net.Sockets.SocketFlags #include "System/Net/Sockets/SocketFlags.hpp" // Including type: System.ArraySegment`1 #include "System/ArraySegment_1.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System::Net::Sockets namespace System::Net::Sockets { // Forward declaring type: Socket class Socket; // Forward declaring type: SocketError struct SocketError; } // Forward declaring namespace: System namespace System { // Forward declaring type: Exception class Exception; // Forward declaring type: IntPtr struct IntPtr; // Forward declaring type: AsyncCallback class AsyncCallback; } // Forward declaring namespace: System::Net namespace System::Net { // Forward declaring type: EndPoint class EndPoint; // Forward declaring type: IPAddress class IPAddress; } // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Skipping declaration: IList`1 because it is already included! } // Completed forward declares // Type namespace: System.Net.Sockets namespace System::Net::Sockets { // Autogenerated type: System.Net.Sockets.SocketAsyncResult class SocketAsyncResult : public System::IOAsyncResult { public: // Nested type: System::Net::Sockets::SocketAsyncResult::$$c class $$c; // public System.Net.Sockets.Socket socket // Offset: 0x30 System::Net::Sockets::Socket* socket; // public System.Net.Sockets.SocketOperation operation // Offset: 0x38 System::Net::Sockets::SocketOperation operation; // private System.Exception DelayedException // Offset: 0x40 System::Exception* DelayedException; // public System.Net.EndPoint EndPoint // Offset: 0x48 System::Net::EndPoint* EndPoint; // public System.Byte[] Buffer // Offset: 0x50 ::Array<uint8_t>* Buffer; // public System.Int32 Offset // Offset: 0x58 int Offset; // public System.Int32 Size // Offset: 0x5C int Size; // public System.Net.Sockets.SocketFlags SockFlags // Offset: 0x60 System::Net::Sockets::SocketFlags SockFlags; // public System.Net.Sockets.Socket AcceptSocket // Offset: 0x68 System::Net::Sockets::Socket* AcceptSocket; // public System.Net.IPAddress[] Addresses // Offset: 0x70 ::Array<System::Net::IPAddress*>* Addresses; // public System.Int32 Port // Offset: 0x78 int Port; // public System.Collections.Generic.IList`1<System.ArraySegment`1<System.Byte>> Buffers // Offset: 0x80 System::Collections::Generic::IList_1<System::ArraySegment_1<uint8_t>>* Buffers; // public System.Boolean ReuseSocket // Offset: 0x88 bool ReuseSocket; // public System.Int32 CurrentAddress // Offset: 0x8C int CurrentAddress; // public System.Net.Sockets.Socket AcceptedSocket // Offset: 0x90 System::Net::Sockets::Socket* AcceptedSocket; // public System.Int32 Total // Offset: 0x98 int Total; // System.Int32 error // Offset: 0x9C int error; // public System.Int32 EndCalled // Offset: 0xA0 int EndCalled; // public System.IntPtr get_Handle() // Offset: 0x11FFE74 System::IntPtr get_Handle(); // public System.Void .ctor(System.Net.Sockets.Socket socket, System.AsyncCallback callback, System.Object state, System.Net.Sockets.SocketOperation operation) // Offset: 0x11FFECC static SocketAsyncResult* New_ctor(System::Net::Sockets::Socket* socket, System::AsyncCallback* callback, ::Il2CppObject* state, System::Net::Sockets::SocketOperation operation); // public System.Net.Sockets.SocketError get_ErrorCode() // Offset: 0x11FFF1C System::Net::Sockets::SocketError get_ErrorCode(); // public System.Void CheckIfThrowDelayedException() // Offset: 0x11FFFA4 void CheckIfThrowDelayedException(); // public System.Void Complete() // Offset: 0x11FE678 void Complete(); // public System.Void Complete(System.Boolean synch) // Offset: 0x1200060 void Complete(bool synch); // public System.Void Complete(System.Int32 total) // Offset: 0x11FF09C void Complete(int total); // public System.Void Complete(System.Exception e, System.Boolean synch) // Offset: 0x120006C void Complete(System::Exception* e, bool synch); // public System.Void Complete(System.Exception e) // Offset: 0x11FDDB0 void Complete(System::Exception* e); // public System.Void Complete(System.Net.Sockets.Socket s) // Offset: 0x11FDDD8 void Complete(System::Net::Sockets::Socket* s); // public System.Void Complete(System.Net.Sockets.Socket s, System.Int32 total) // Offset: 0x11FE0D8 void Complete(System::Net::Sockets::Socket* s, int total); // override System.Void CompleteDisposed() // Offset: 0x120005C // Implemented from: System.IOAsyncResult // Base method: System.Void IOAsyncResult::CompleteDisposed() void CompleteDisposed(); }; // System.Net.Sockets.SocketAsyncResult } DEFINE_IL2CPP_ARG_TYPE(System::Net::Sockets::SocketAsyncResult*, "System.Net.Sockets", "SocketAsyncResult"); #pragma pack(pop)
37.326667
182
0.70459
Futuremappermydud
bf15716907ea6a670d26933ec56758c47cb32398
2,949
hpp
C++
include/codegen/include/UnityEngine/Analytics/AnalyticsSessionInfo.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/UnityEngine/Analytics/AnalyticsSessionInfo.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/UnityEngine/Analytics/AnalyticsSessionInfo.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:39 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: System.Object #include "System/Object.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine::Analytics namespace UnityEngine::Analytics { // Forward declaring type: AnalyticsSessionState struct AnalyticsSessionState; } // Completed forward declares // Type namespace: UnityEngine.Analytics namespace UnityEngine::Analytics { // Autogenerated type: UnityEngine.Analytics.AnalyticsSessionInfo class AnalyticsSessionInfo : public ::Il2CppObject { public: // Nested type: UnityEngine::Analytics::AnalyticsSessionInfo::SessionStateChanged class SessionStateChanged; // Nested type: UnityEngine::Analytics::AnalyticsSessionInfo::IdentityTokenChanged class IdentityTokenChanged; // Get static field: static private UnityEngine.Analytics.AnalyticsSessionInfo/SessionStateChanged sessionStateChanged static UnityEngine::Analytics::AnalyticsSessionInfo::SessionStateChanged* _get_sessionStateChanged(); // Set static field: static private UnityEngine.Analytics.AnalyticsSessionInfo/SessionStateChanged sessionStateChanged static void _set_sessionStateChanged(UnityEngine::Analytics::AnalyticsSessionInfo::SessionStateChanged* value); // Get static field: static private UnityEngine.Analytics.AnalyticsSessionInfo/IdentityTokenChanged identityTokenChanged static UnityEngine::Analytics::AnalyticsSessionInfo::IdentityTokenChanged* _get_identityTokenChanged(); // Set static field: static private UnityEngine.Analytics.AnalyticsSessionInfo/IdentityTokenChanged identityTokenChanged static void _set_identityTokenChanged(UnityEngine::Analytics::AnalyticsSessionInfo::IdentityTokenChanged* value); // static System.Void CallSessionStateChanged(UnityEngine.Analytics.AnalyticsSessionState sessionState, System.Int64 sessionId, System.Int64 sessionElapsedTime, System.Boolean sessionChanged) // Offset: 0x195A8D8 static void CallSessionStateChanged(UnityEngine::Analytics::AnalyticsSessionState sessionState, int64_t sessionId, int64_t sessionElapsedTime, bool sessionChanged); // static public System.Int64 get_sessionId() // Offset: 0x195AC34 static int64_t get_sessionId(); // static public System.String get_userId() // Offset: 0x195AC68 static ::Il2CppString* get_userId(); // static System.Void CallIdentityTokenChanged(System.String token) // Offset: 0x195AC9C static void CallIdentityTokenChanged(::Il2CppString* token); }; // UnityEngine.Analytics.AnalyticsSessionInfo } DEFINE_IL2CPP_ARG_TYPE(UnityEngine::Analytics::AnalyticsSessionInfo*, "UnityEngine.Analytics", "AnalyticsSessionInfo"); #pragma pack(pop)
56.711538
195
0.785351
Futuremappermydud
bf198bf97214ba22eed83bfd25ee9608a5ed65a8
2,770
cpp
C++
Quad2/Main/Quad_FlightCommand/flightCommand.cpp
rhockenbury/Quad2
1d2d6fe3902ab4a58869e06539553d0cd4bb3d21
[ "MIT" ]
null
null
null
Quad2/Main/Quad_FlightCommand/flightCommand.cpp
rhockenbury/Quad2
1d2d6fe3902ab4a58869e06539553d0cd4bb3d21
[ "MIT" ]
null
null
null
Quad2/Main/Quad_FlightCommand/flightCommand.cpp
rhockenbury/Quad2
1d2d6fe3902ab4a58869e06539553d0cd4bb3d21
[ "MIT" ]
null
null
null
/* * flightCommand.cpp * * Created on: August 18, 2013 * Author: Ryler Hockenbury */ #include "flightCommand.h" #include "globals.h" #include "receiver.h" #include "LED.h" #include "conf.h" bool controlMode = 0; bool auxMode = 0; /* * Distribute stick commands to system components */ void processFlightCommands(float stickCommands[], float targetFlightAngle[], Motors *motors, PID controller[], ITG3200 *gyro, ADXL345 *accel, HMC5883L *comp) { // process zero throttle stick commands if(stickCommands[THROTTLE_CHANNEL] <= STICK_MINCHECK) { processZeroThrottleCommands(motors, stickCommands, gyro, accel, comp); } if(!inFlight && stickCommands[THROTTLE_CHANNEL] > TAKEOFF_THROTTLE && motors->isArmed()) { inFlight = true; LED::turnOn(RED_LED); } // get flight angles from sticks targetFlightAngle[ROLL_AXIS] = AR6210::mapStickCommandToAngle(stickCommands[ROLL_CHANNEL]); targetFlightAngle[PITCH_AXIS] = AR6210::mapStickCommandToAngle(stickCommands[PITCH_CHANNEL]); // update controller mode PID::setMode(AR6210::mapStickCommandToBool(stickCommands[MODE_CHANNEL])); //controller[ROLL_AXIS].setMode(controlMode); //controller[PITCH_AXIS].setMode(controlMode); //controller[YAW_AXIS].setMode(controlMode); // update aux channel (currently unused) //auxMode = AR6210::mapStickCommandToBool(stickCommands[AUX1_CHANNEL]); } /* * Process commands to zero sensors, arm and disarm motors. */ void processZeroThrottleCommands(Motors *motors, float stickCommands[], ITG3200 *gyro, ADXL345 *accel, HMC5883L *comp) { // zero sensors // Left stick bottom left, right stick bottom right if(stickCommands[PITCH_CHANNEL] < STICK_MINCHECK && stickCommands[ROLL_CHANNEL] > STICK_MAXCHECK && stickCommands[YAW_CHANNEL] > STICK_MAXCHECK && !SENSORS_ONLINE) { Serial.println("Info: Zeroing sensors"); LED::turnOn(GREEN_LED); gyro->setOffset(); accel->setOffset(); comp->setOffset(); } // arm motors // Left stick bottom right if(stickCommands[YAW_CHANNEL] < STICK_MINCHECK && SENSORS_ONLINE && !motors->isArmed()) { Serial.println("Warning: Arming motors"); LED::turnOn(YELLOW_LED); motors->armMotors(); motors->pulseMotors(3); motors->commandAllMotors(1200); //motors->setArmed(true); } // disarm motors // Left stick bottom left if(stickCommands[YAW_CHANNEL] > STICK_MAXCHECK && motors->isArmed()) { Serial.println("Warning: Disarming motors"); LED::turnOff(YELLOW_LED); LED::turnOff(RED_LED); motors->disarmMotors(); //motors->setArmed(false); inFlight = false; } }
30.108696
101
0.675812
rhockenbury
bf1bb9bc82e16a1965e5fc84c965887338a3a597
3,498
cc
C++
src/asp/IceBridge/correct_icebridge_l3_dem.cc
AndrewAnnex/StereoPipeline
084c3293c3a5382b052177c74388d9beeb79cf0b
[ "Apache-2.0" ]
323
2015-01-10T12:34:24.000Z
2022-03-24T03:52:22.000Z
src/asp/IceBridge/correct_icebridge_l3_dem.cc
AndrewAnnex/StereoPipeline
084c3293c3a5382b052177c74388d9beeb79cf0b
[ "Apache-2.0" ]
252
2015-07-27T16:36:31.000Z
2022-03-31T02:34:28.000Z
src/asp/IceBridge/correct_icebridge_l3_dem.cc
AndrewAnnex/StereoPipeline
084c3293c3a5382b052177c74388d9beeb79cf0b
[ "Apache-2.0" ]
105
2015-02-28T02:37:27.000Z
2022-03-14T09:17:30.000Z
// __BEGIN_LICENSE__ // Copyright (c) 2009-2013, United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. All // rights reserved. // // The NGT platform is 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. // __END_LICENSE__ #include <vw/FileIO/DiskImageResource.h> #include <vw/FileIO/DiskImageView.h> #include <vw/Cartography/GeoReferenceUtils.h> /** A simple tool to fix the Icebridge L3 dems located here: http://nsidc.org/data/iodms3 The files are missing a tag indicating that they are type float and are incorrectly read as type uint32. They are also missing the projection information. This tool just rewrites the file so that this information is added. */ using namespace vw; using namespace vw::cartography; namespace po = boost::program_options; namespace fs = boost::filesystem; using namespace vw::cartography; int main( int argc, char *argv[] ) { // Simple input parsing if (argc < 4) { vw_out() << "Usage: <input path> <output path> <Pole: North=1, South=0>\n"; return -1; } std::string input_path = argv[1]; std::string output_path = argv[2]; int pole = atoi(argv[3]); // Specify which polar projection to use // Load the existing georeference info, then add the projection info. DiskImageResourceGDAL in_rsrc(input_path); GeoReference georef; bool has_georef = read_georeference(georef, in_rsrc); if (!has_georef) { vw_throw( ArgumentErr() << "Could not read the georeference from: " << input_path << ". Check if the corresponding .tfw file is present.\n"); } //vw_out() << "Georef = " << georef << std::endl; if (pole) // EPSG:3413 georef.set_proj4_projection_str("+proj=stere +lat_0=90 +lon_0=-45 +lat_ts=70 +ellps=WGS84 +datum=WGS84 +units=m"); else // EPSG:3031 georef.set_proj4_projection_str("+proj=stere +lat_0=-90 +lon_0=0 +lat_ts=-71 +ellps=WGS84 +datum=WGS84 +units=m"); //vw_out() << "Output Georef = " << georef << std::endl; // Set nodata if it is not already set. This should be constant across files. double nodata_val = -32767; // Somehow -32767 is hard-coded in those files. if ( in_rsrc.has_nodata_read() ) { nodata_val = in_rsrc.nodata_read(); vw_out() << "\tFound input nodata value: " << nodata_val << std::endl; } // Rasterize the input data using the incorrect uint32 type. DiskImageView<uint32> input_dem(in_rsrc); ImageView<uint32> data_in = input_dem; // Make a float casted copy of the image data. ImageView<float> data_out(data_in.cols(), data_in.rows()); size_t num_bytes = data_in.cols()*data_in.rows()*sizeof(float); memcpy(data_out.data(), data_in.data(), num_bytes); // Write the output file. GdalWriteOptions opt; vw_out() << "Writing: " << output_path << std::endl; block_write_gdal_image(output_path, data_out, true, georef, true, nodata_val, opt, TerminalProgressCallback("vw","")); return 0; }
39.303371
118
0.701258
AndrewAnnex
bf1de1f33de276b5922e99c2cba4facb969b9efb
11,420
cxx
C++
src/Tools/mialsrtkCropImageUsingMask.cxx
sebastientourbier/mialsuperresolutiontoolkit-1
dd4f8db5bd4aa8a2e95fe6a2912b0a0a1e9f73c5
[ "BSD-3-Clause" ]
13
2020-06-17T04:21:27.000Z
2022-03-10T01:47:21.000Z
src/Tools/mialsrtkCropImageUsingMask.cxx
sebastientourbier/mialsuperresolutiontoolkit-1
dd4f8db5bd4aa8a2e95fe6a2912b0a0a1e9f73c5
[ "BSD-3-Clause" ]
76
2019-10-24T14:08:07.000Z
2022-03-24T09:46:52.000Z
src/Tools/mialsrtkCropImageUsingMask.cxx
sebastientourbier/mialsuperresolutiontoolkit-1
dd4f8db5bd4aa8a2e95fe6a2912b0a0a1e9f73c5
[ "BSD-3-Clause" ]
2
2020-12-11T14:42:20.000Z
2022-01-21T12:47:22.000Z
/*========================================================================== © Date: 01/05/2015 Author(s): Sebastien Tourbier (sebastien.tourbier@unil.ch) ==========================================================================*/ /* ITK */ #include "itkImage.h" #include "itkMaskImageFilter.h" #include "itkImageIOBase.h" #include "itkExtractImageFilter.h" #include "itkJoinSeriesImageFilter.h" #include "itkNearestNeighborInterpolateImageFunction.h" #include "itkDisplacementFieldTransform.h" /* BTK */ #include "btkImageHelper.h" /* #include "btkDiffusionSequence.h" #include "btkDiffusionSequenceHelper.h" #include "btkDiffusionSequenceFileHelper.h" */ #include "btkIOImageHelper.h" #include "btkResampleImagesToBiggestImageFilter.h" #include "btkWeightedSumOfImagesFilter.h" #include "btkCropImageUsingMaskFilter.h" #include "btkGradientDirection.h" /* OTHERS */ #include "iostream" #include <tclap/CmdLine.h> // Definitions //typedef itk::ExtractImageFilter< btk::DiffusionSequence,itk::Image< short,3 > > ExtractImageFilter; //typedef itk::JoinSeriesImageFilter< itk::Image< short,3 >,btk::DiffusionSequence> JoinSeriesFilterType; template< class TImage,class TMask > void Process(std::vector< std::string > &inputFileNames, std::vector< std::string > &outputFileNames, std::vector< std::string > &maskFileNames, const int Dimension) { // Read Masks files std::vector< typename TMask::Pointer > masks = btk::ImageHelper< TMask >::ReadImage(maskFileNames); // Compute the cropping mask by using the union of all masks typename TMask::Pointer croppingMask = NULL; if(masks.size() > 1) { // First, resample masks if needed if(!btk::ImageHelper< TMask >::IsInSamePhysicalSpace(masks)) { btkCoutMacro("Resampling masks in same physical space... "); typename btk::ResampleImagesToBiggestImageFilter< TMask >::Pointer resampleFilter = btk::ResampleImagesToBiggestImageFilter< TMask >::New(); resampleFilter->SetInputs(masks); resampleFilter->SetInterpolator(itk::NearestNeighborInterpolateImageFunction< TMask >::New()); resampleFilter->Update(); masks = resampleFilter->GetOutputs(); btkCoutMacro("done."); } // Combine the masks btkCoutMacro("Combining masks... "); std::vector< float > weights(masks.size(), 1.0f); typename btk::WeightedSumOfImagesFilter< TMask >::Pointer sumFilter = btk::WeightedSumOfImagesFilter< TMask >::New(); sumFilter->SetInputs(masks); sumFilter->SetWeights(weights); sumFilter->Update(); croppingMask = sumFilter->GetOutput(); btkCoutMacro("done."); } else // masks.size() == 1 { croppingMask = masks[0]; } switch(Dimension) { //cropping for 3D images case 3: { std::vector< typename TImage::Pointer > inputs = btk::ImageHelper< TImage >::ReadImage(inputFileNames); btkCoutMacro("Cropping image... "); typename btk::CropImageUsingMaskFilter< TImage,TMask >::Pointer cropFilter = btk::CropImageUsingMaskFilter< TImage,TMask >::New(); cropFilter->SetMask(croppingMask); cropFilter->SetInputs(inputs); cropFilter->Update(); std::vector< typename TImage::Pointer > outputs = cropFilter->GetOutputs(); btk::ImageHelper< TImage >::WriteImage(outputs, outputFileNames); btkCoutMacro("done."); } break; //cropping for 4D images /* case 4: { std::vector< btk::DiffusionSequence::Pointer > inputs = btk::DiffusionSequenceHelper::ReadSequenceArray(inputFileNames); ExtractImageFilter::Pointer extractor = ExtractImageFilter::New(); JoinSeriesFilterType::Pointer outputs = JoinSeriesFilterType::New(); btk::DiffusionSequence::RegionType region4D = inputs[0]->GetLargestPossibleRegion(); btk::DiffusionSequence::SizeType input4DSize = region4D.GetSize(); btk::DiffusionSequence::SizeType input3DSize; input3DSize[0] = input4DSize[0]; input3DSize[1] = input4DSize[1]; input3DSize[2] = input4DSize[2]; input3DSize[3] = 0; outputs->SetOrigin( inputs[0]->GetOrigin()[3] ); outputs->SetSpacing(inputs[0]->GetSpacing()[3] ); extractor->SetInput(inputs[0]); //Maybe need to be change... btk::DiffusionSequence::IndexType start = region4D.GetIndex(); uint numberOf3Dimages = input4DSize[3]; btkCoutMacro("Cropping images... "); for (uint i = 0; i < numberOf3Dimages; i++) { start[3] = i; std::vector< itk::Image<short,3>::Pointer > *vector3DImage = new std::vector< itk::Image<short,3>::Pointer>; btk::DiffusionSequence::RegionType region3D; region3D.SetSize( input3DSize ); region3D.SetIndex( start ); extractor->SetExtractionRegion( region3D ); extractor->SetDirectionCollapseToSubmatrix(); extractor->Update(); vector3DImage->push_back(extractor->GetOutput()); std::cout<<"\r-> Cropping image "<<i<<" ... "<<std::flush; typename btk::CropImageUsingMaskFilter< itk::Image<short,3>,TMask >::Pointer cropFilter = btk::CropImageUsingMaskFilter< itk::Image<short,3>,TMask >::New(); cropFilter->SetMask(croppingMask); cropFilter->SetInputs(*vector3DImage); cropFilter->Update(); outputs->PushBackInput (cropFilter->GetOutput()); } btkCoutMacro("done."); btk::ImageHelper< btk::DiffusionSequence>::WriteImage(outputs->GetOutput(), outputFileNames[0]); std::vector< unsigned short > bValues = inputs[0]->GetBValues(); std::string bValuesName = btk::FileHelper::GetRadixOf(outputFileNames[0])+".bval"; btk::DiffusionSequenceFileHelper::WriteBValues(bValues,bValuesName); std::vector< btk::GradientDirection > GradientTable = inputs[0]->GetGradientTable(); std::string GradientTableName = btk::FileHelper::GetRadixOf(outputFileNames[0])+".bvec"; btk::DiffusionSequenceFileHelper::WriteGradientTable(GradientTable,GradientTableName); } break;*/ default: std::cout<<"Only dimension 3 or 4 are supported\n"; } } int main(int argc, char * argv[]) { try { // // Command line parser // TCLAP::CmdLine cmd("btkCropImageUsingMask: Crop an image (3D - anatomical, or 4D - diffusion weighted) using a 3D mask (non-zero values). Input image and mask image must have the same pixel type.", ' ', "2.0", true); TCLAP::MultiArg< std::string > inputFileNamesArg("i", "input", "Input image file", true, "string", cmd); TCLAP::MultiArg< std::string > maskFileNamesArg("m", "mask", "Mask image file", true, "string", cmd); TCLAP::MultiArg< std::string > outputFileNamesArg("o", "output", "Output image file", true, "string", cmd); // Parse the args. cmd.parse( argc, argv ); std::vector< std::string > inputFileNames = inputFileNamesArg.getValue(); std::vector< std::string > maskFileNames = maskFileNamesArg.getValue(); std::vector< std::string > outputFileNames = outputFileNamesArg.getValue(); // // Processing // // Check arguments if(inputFileNames.size() != maskFileNames.size() || inputFileNames.size() != outputFileNames.size()) { btkException("The number of inputs/masks/outputs is not coherent ! There should be a mask and an output for each input !"); } // Check image informations itk::ImageIOBase::Pointer imageIO = itk::ImageIOFactory::CreateImageIO(inputFileNames[0].c_str(), itk::ImageIOFactory::ReadMode); imageIO->SetFileName(inputFileNames[0]); imageIO->ReadImageInformation(); int Dimension = imageIO->GetNumberOfDimensions(); btkCoutMacro("Dimension of input image :" << Dimension); switch(imageIO->GetPixelType()) { case itk::ImageIOBase::VECTOR: { btkCoutMacro("Pixel type: Vector"); typedef itk::DisplacementFieldTransform< double,3 >::DisplacementFieldType DisplacementField; Process< DisplacementField,itk::Image< unsigned char,3 > >(inputFileNames, outputFileNames, maskFileNames, Dimension); } break; case itk::ImageIOBase::SCALAR: { btkCoutMacro("Pixel type: Scalar"); switch(imageIO->GetComponentType()) { case itk::ImageIOBase::UCHAR: btkCoutMacro("Scalar type: Unsigned Char"); Process< itk::Image< unsigned char,3 >,itk::Image< unsigned char,3 > >(inputFileNames, outputFileNames, maskFileNames, Dimension); break; case itk::ImageIOBase::CHAR: btkCoutMacro("Scalar type: Char"); Process< itk::Image< char,3 >,itk::Image< unsigned char,3 > >(inputFileNames, outputFileNames, maskFileNames, Dimension); break; case itk::ImageIOBase::SHORT: btkCoutMacro("Scalar type: Short"); Process< itk::Image< short,3 >,itk::Image< unsigned char,3 > >(inputFileNames, outputFileNames, maskFileNames, Dimension); break; case itk::ImageIOBase::USHORT: btkCoutMacro("Scalar type: Unsigned Short"); Process< itk::Image< unsigned short,3 >,itk::Image< unsigned char,3 > >(inputFileNames, outputFileNames, maskFileNames,Dimension); break; case itk::ImageIOBase::FLOAT: btkCoutMacro("Scalar type: Float"); Process< itk::Image< float,3 >,itk::Image< unsigned char,3 > >(inputFileNames, outputFileNames, maskFileNames,Dimension); break; case itk::ImageIOBase::DOUBLE: btkCoutMacro("Scalar type: Double"); Process< itk::Image< double,3 >,itk::Image< unsigned char,3 > >(inputFileNames, outputFileNames, maskFileNames,Dimension); break; default: btkException("Unsupported component type (only short, float or double types are supported) !"); } } break; default: btkException("Unsupported pixel type (only scalar and vector are supported) !"); } } catch(TCLAP::ArgException &e) // catch any exceptions { std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl; } catch(std::string &e) // catch any exceptions { std::cerr << "error: " << e <<std::endl; } catch(itk::ExceptionObject &e) { btkCerrMacro(e.GetDescription()); } return EXIT_SUCCESS; }
39.109589
224
0.594308
sebastientourbier
bf2089b4c966d2012adedefce8f0c9d5414b6341
24,252
cpp
C++
test/math/uint256.cpp
ccccbjcn/nuls-v2-cplusplus-sdk
3d5a76452fe0673eba490b26e5a95fea3d5788df
[ "MIT" ]
1
2020-04-26T07:32:52.000Z
2020-04-26T07:32:52.000Z
test/math/uint256.cpp
CCC-NULS/nuls-cplusplus-sdk
3d5a76452fe0673eba490b26e5a95fea3d5788df
[ "MIT" ]
null
null
null
test/math/uint256.cpp
CCC-NULS/nuls-cplusplus-sdk
3d5a76452fe0673eba490b26e5a95fea3d5788df
[ "MIT" ]
null
null
null
/** * Copyright (c) 2020 libnuls developers (see AUTHORS) * * This file is part of libnuls. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <boost/test/unit_test.hpp> #include <sstream> #include <string> #include <nuls/system.hpp> using namespace nuls::system; BOOST_AUTO_TEST_SUITE(uint256_tests) #define MAX_HASH \ "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" static const auto max_hash = uint256_t(MAX_HASH); #define NEGATIVE1_HASH \ "0x8000000000000000000000000000000000000000000000000000000000000000" static const auto negative_zero_hash = uint256_t(NEGATIVE1_HASH); #define MOST_HASH \ "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" static const auto most_hash = uint256_t(MOST_HASH); #define ODD_HASH \ "0x8437390223499ab234bf128e8cd092343485898923aaaaabbcbcc4874353fff4" static const auto odd_hash = uint256_t(ODD_HASH); #define HALF_HASH \ "0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff" static const auto half_hash = uint256_t(HALF_HASH); #define QUARTER_HASH \ "0x000000000000000000000000000000000000000000000000ffffffffffffffff" static const auto quarter_hash = uint256_t(QUARTER_HASH); #define UNIT_HASH \ "0x0000000000000000000000000000000000000000000000000000000000000001" static const auto unit_hash = uint256_t(UNIT_HASH); #define ONES_HASH \ "0x0000000100000001000000010000000100000001000000010000000100000001" static const auto ones_hash = uint256_t(ONES_HASH); #define FIVES_HASH \ "0x5555555555555555555555555555555555555555555555555555555555555555" static const auto fives_hash = uint256_t(FIVES_HASH); // constructors //----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(uint256__constructor_default__always__equates_to_0) { uint256_t minimum; BOOST_REQUIRE_EQUAL(minimum > 0, false); BOOST_REQUIRE_EQUAL(minimum < 0, false); BOOST_REQUIRE_EQUAL(minimum >= 0, true); BOOST_REQUIRE_EQUAL(minimum <= 0, true); BOOST_REQUIRE_EQUAL(minimum == 0, true); BOOST_REQUIRE_EQUAL(minimum != 0, false); } BOOST_AUTO_TEST_CASE(uint256__constructor_move__42__equals_42) { static const auto expected = 42u; static const uint256_t value(expected); BOOST_REQUIRE_EQUAL(value, expected); } BOOST_AUTO_TEST_CASE(uint256__constructor_copy__odd_hash__equals_odd_hash) { static const auto expected = uint256_t(odd_hash); static const uint256_t value(expected); BOOST_REQUIRE_EQUAL(value, expected); } BOOST_AUTO_TEST_CASE(uint256__constructor_uint32__minimum__equals_0) { static const auto expected = 0u; static const uint256_t value(expected); BOOST_REQUIRE_EQUAL(value, expected); } BOOST_AUTO_TEST_CASE(uint256__constructor_uint32__42__equals_42) { static const auto expected = 42u; static const uint256_t value(expected); BOOST_REQUIRE_EQUAL(value, expected); } BOOST_AUTO_TEST_CASE(uint256__constructor_uint32__maximum__equals_maximum) { static const auto expected = nuls::max_uint32; static const uint256_t value(expected); BOOST_REQUIRE_EQUAL(value, expected); } // hash //----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(uint256__hash__default__returns_null_hash) { static const uint256_t value; BOOST_REQUIRE_EQUAL(value, 0); } BOOST_AUTO_TEST_CASE(uint256__hash__1__returns_unit_hash) { static const uint256_t value("0x0000000000000000000000000000000000000000000000000000000000000001"); BOOST_REQUIRE_EQUAL(value, 1); } BOOST_AUTO_TEST_CASE(uint256__hash__negative_1__returns_negative_zero_hash) { BOOST_REQUIRE_EQUAL(negative_zero_hash, uint256_t("0x8000000000000000000000000000000000000000000000000000000000000000")); } // array operator //----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(uint256__array__default__expected) { static const uint256_t value; BOOST_REQUIRE_EQUAL(value, uint256_t("0x0000000000000000000000000000000000000000000000000000000000000000")); } BOOST_AUTO_TEST_CASE(uint256__array__42__expected) { static const uint256_t value(42); BOOST_REQUIRE_EQUAL(value, uint256_t("0x000000000000000000000000000000000000000000000000000000000000002a")); } BOOST_AUTO_TEST_CASE(uint256__array__0x87654321__expected) { static const uint256_t value(0x87654321); BOOST_REQUIRE_EQUAL(value, uint256_t("0x0000000000000000000000000000000000000000000000000000000087654321")); } BOOST_AUTO_TEST_CASE(uint256__array__negative_1__expected) { static const uint256_t value(negative_zero_hash); BOOST_REQUIRE_EQUAL(value, uint256_t("0x8000000000000000000000000000000000000000000000000000000000000000")); } BOOST_AUTO_TEST_CASE(uint256__array__odd_hash__expected) { static const uint256_t value(odd_hash); BOOST_REQUIRE_EQUAL(value, uint256_t("0x8437390223499ab234bf128e8cd092343485898923aaaaabbcbcc4874353fff4")); } // comparison operators //----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(uint256__comparison_operators__null_hash__expected) { static const uint256_t value(0); BOOST_REQUIRE_EQUAL(value > 0, false); BOOST_REQUIRE_EQUAL(value < 0, false); BOOST_REQUIRE_EQUAL(value >= 0, true); BOOST_REQUIRE_EQUAL(value <= 0, true); BOOST_REQUIRE_EQUAL(value == 0, true); BOOST_REQUIRE_EQUAL(value != 0, false); BOOST_REQUIRE_EQUAL(value > 1, false); BOOST_REQUIRE_EQUAL(value < 1, true); BOOST_REQUIRE_EQUAL(value >= 1, false); BOOST_REQUIRE_EQUAL(value <= 1, true); BOOST_REQUIRE_EQUAL(value == 1, false); BOOST_REQUIRE_EQUAL(value != 1, true); } BOOST_AUTO_TEST_CASE(uint256__comparison_operators__unit_hash__expected) { static const uint256_t value(1); BOOST_REQUIRE_EQUAL(value > 1, false); BOOST_REQUIRE_EQUAL(value < 1, false); BOOST_REQUIRE_EQUAL(value >= 1, true); BOOST_REQUIRE_EQUAL(value <= 1, true); BOOST_REQUIRE_EQUAL(value == 1, true); BOOST_REQUIRE_EQUAL(value != 1, false); BOOST_REQUIRE_EQUAL(value > 0, true); BOOST_REQUIRE_EQUAL(value < 0, false); BOOST_REQUIRE_EQUAL(value >= 0, true); BOOST_REQUIRE_EQUAL(value <= 0, false); BOOST_REQUIRE_EQUAL(value == 0, false); BOOST_REQUIRE_EQUAL(value != 0, true); } BOOST_AUTO_TEST_CASE(uint256__comparison_operators__negative_zero_hash__expected) { static const uint256_t value(negative_zero_hash); static const uint256_t most(most_hash); static const uint256_t maximum(max_hash); BOOST_REQUIRE_EQUAL(value > 1, true); BOOST_REQUIRE_EQUAL(value < 1, false); BOOST_REQUIRE_EQUAL(value >= 1, true); BOOST_REQUIRE_EQUAL(value <= 1, false); BOOST_REQUIRE_EQUAL(value == 1, false); BOOST_REQUIRE_EQUAL(value != 1, true); BOOST_REQUIRE_GT(value, most); BOOST_REQUIRE_LT(value, maximum); BOOST_REQUIRE_GE(value, most); BOOST_REQUIRE_LE(value, maximum); BOOST_REQUIRE_EQUAL(value, value); BOOST_REQUIRE_NE(value, most); BOOST_REQUIRE_NE(value, maximum); } // not //----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(uint256__not__minimum__maximum) { BOOST_REQUIRE_EQUAL(~uint256_t(), uint256_t(max_hash)); } BOOST_AUTO_TEST_CASE(uint256__not__maximum__minimum) { BOOST_REQUIRE_EQUAL(~uint256_t(max_hash), uint256_t()); } BOOST_AUTO_TEST_CASE(uint256__not__most_hash__negative_zero_hash) { BOOST_REQUIRE_EQUAL(~uint256_t(most_hash), uint256_t(negative_zero_hash)); } BOOST_AUTO_TEST_CASE(uint256__not__not_odd_hash__odd_hash) { BOOST_REQUIRE_EQUAL(~~uint256_t(odd_hash), uint256_t(odd_hash)); } BOOST_AUTO_TEST_CASE(uint256__not__odd_hash__expected) { static const uint256_t value(odd_hash); static const auto not_value = ~value; BOOST_REQUIRE_EQUAL(not_value, uint256_t("-0x8437390223499ab234bf128e8cd092343485898923aaaaabbcbcc4874353fff5")); } // two's compliment (negate) //----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(uint256__twos_compliment__null_hash__null_hash) { // Note that we use 0 - VALUE to negate, as there is a static // assert that fails when you negate a uint256_t alone. BOOST_REQUIRE_EQUAL(0 - uint256_t(), uint256_t()); } BOOST_AUTO_TEST_CASE(uint256__twos_compliment__unit_hash__max_hash) { // Note that we use 0 - VALUE to negate, as there is a static // assert that fails when you negate a uint256_t alone. BOOST_REQUIRE_EQUAL(0 - uint256_t(unit_hash), uint256_t(max_hash)); } BOOST_AUTO_TEST_CASE(uint256__twos_compliment__odd_hash__expected) { // Note that we use 0 - VALUE to negate, as there is a static // assert that fails when you negate a uint256_t alone. static const auto compliment = 0 - uint256_t(odd_hash); BOOST_REQUIRE_EQUAL(compliment, uint256_t("-0x8437390223499ab234bf128e8cd092343485898923aaaaabbcbcc4874353fff5") + 1); } // shift right //----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(uint256__shift_right__null_hash__null_hash) { BOOST_REQUIRE_EQUAL(uint256_t() >> 0, uint256_t()); BOOST_REQUIRE_EQUAL(uint256_t() >> 1, uint256_t()); BOOST_REQUIRE_EQUAL(uint256_t() >> nuls::max_uint32, uint256_t()); } BOOST_AUTO_TEST_CASE(uint256__shift_right__unit_hash_0__unit_hash) { static const uint256_t value(unit_hash); BOOST_REQUIRE_EQUAL(value >> 0, value); } BOOST_AUTO_TEST_CASE(uint256__shift_right__unit_hash_positive__null_hash) { static const uint256_t value(unit_hash); BOOST_REQUIRE_EQUAL(value >> 1, uint256_t()); BOOST_REQUIRE_EQUAL(value >> nuls::max_uint32, uint256_t()); } BOOST_AUTO_TEST_CASE(uint256__shift_right__max_hash_1__most_hash) { static const uint256_t value(max_hash); BOOST_REQUIRE_EQUAL(value >> 1, uint256_t(most_hash)); } BOOST_AUTO_TEST_CASE(uint256__shift_right__odd_hash_32__expected) { static const uint256_t value(odd_hash); static const auto shifted = value >> 32; BOOST_REQUIRE_EQUAL(shifted, uint256_t("0x000000008437390223499ab234bf128e8cd092343485898923aaaaabbcbcc487")); } // add256 //----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(uint256__add256__0_to_null_hash__null_hash) { BOOST_REQUIRE_EQUAL(uint256_t() + 0, uint256_t()); } BOOST_AUTO_TEST_CASE(uint256__add256__null_hash_to_null_hash__null_hash) { BOOST_REQUIRE_EQUAL(uint256_t() + uint256_t(), uint256_t()); } BOOST_AUTO_TEST_CASE(uint256__add256__1_to_max_hash__null_hash) { static const uint256_t value(max_hash); static const auto sum = value + 1; BOOST_REQUIRE_EQUAL(sum, uint256_t()); } BOOST_AUTO_TEST_CASE(uint256__add256__ones_hash_to_odd_hash__expected) { static const uint256_t value(odd_hash); static const auto sum = value + uint256_t(ones_hash); BOOST_REQUIRE_EQUAL(sum, uint256_t("0x8437390323499ab334bf128f8cd092353485898a23aaaaacbcbcc4884353fff5")); } BOOST_AUTO_TEST_CASE(uint256__add256__1_to_0xffffffff__0x0100000000) { static const uint256_t value("0xffffffff"); static const auto sum = value + 1; BOOST_REQUIRE_EQUAL(sum, uint256_t("0x0000000000000000000000000000000000000000000000000000000100000000")); } BOOST_AUTO_TEST_CASE(uint256__add256__1_to_negative_zero_hash__expected) { static const uint256_t value(negative_zero_hash); static const auto sum = value + 1; BOOST_REQUIRE_EQUAL(sum, uint256_t("0x8000000000000000000000000000000000000000000000000000000000000001")); } // divide256 //----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(uint256__divide256__unit_hash_by_null_hash__throws_overflow_error) { BOOST_REQUIRE_THROW(uint256_t(unit_hash) / uint256_t(0), std::overflow_error); } BOOST_AUTO_TEST_CASE(uint256__divide256__null_hash_by_unit_hash__null_hash) { BOOST_REQUIRE_EQUAL(uint256_t(0) / uint256_t(1), uint256_t()); } BOOST_AUTO_TEST_CASE(uint256__divide256__max_hash_by_3__fives_hash) { BOOST_REQUIRE_EQUAL(uint256_t(max_hash) / uint256_t(3), uint256_t(fives_hash)); } BOOST_AUTO_TEST_CASE(uint256__divide256__max_hash_by_max_hash__1) { BOOST_REQUIRE_EQUAL(uint256_t(max_hash) / uint256_t(max_hash), uint256_t(1)); } BOOST_AUTO_TEST_CASE(uint256__divide256__max_hash_by_256__shifts_right_8_bits) { static const uint256_t value(max_hash); static const auto quotient = value / uint256_t(256); BOOST_REQUIRE_EQUAL(quotient, uint256_t("0x00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")); } // increment //----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(uint256__increment__0__1) { BOOST_REQUIRE_EQUAL(++uint256_t(0), uint256_t(1)); } BOOST_AUTO_TEST_CASE(uint256__increment__1__2) { BOOST_REQUIRE_EQUAL(++uint256_t(1), uint256_t(2)); } BOOST_AUTO_TEST_CASE(uint256__increment__max_hash__null_hash) { BOOST_REQUIRE_EQUAL(++uint256_t(max_hash), uint256_t()); } BOOST_AUTO_TEST_CASE(uint256__increment__0xffffffff__0x0100000000) { static const auto increment = ++uint256_t(0xffffffff); BOOST_REQUIRE_EQUAL(increment, uint256_t("0x0000000000000000000000000000000000000000000000000000000100000000")); } BOOST_AUTO_TEST_CASE(uint256__increment__negative_zero_hash__expected) { static const auto increment = ++uint256_t(negative_zero_hash); BOOST_REQUIRE_EQUAL(increment, uint256_t("0x8000000000000000000000000000000000000000000000000000000000000001")); } // assign32 //----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(uint256__assign__null_hash_0__null_hash) { uint256_t value(0); value = 0; BOOST_REQUIRE_EQUAL(value, uint256_t()); } BOOST_AUTO_TEST_CASE(uint256__assign__max_hash_0__null_hash) { uint256_t value(max_hash); value = 0; BOOST_REQUIRE_EQUAL(value, uint256_t()); } BOOST_AUTO_TEST_CASE(uint256__assign__odd_hash_to_42__42) { uint256_t value(odd_hash); value = 42; BOOST_REQUIRE_EQUAL(value, uint256_t("0x000000000000000000000000000000000000000000000000000000000000002a")); } // assign shift right //----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(uint256__assign_shift_right__null_hash__null_hash) { uint256_t value1; uint256_t value2; uint256_t value3; value1 >>= 0; value2 >>= 1; value3 >>= nuls::max_uint32; BOOST_REQUIRE_EQUAL(value1, uint256_t()); BOOST_REQUIRE_EQUAL(value2, uint256_t()); BOOST_REQUIRE_EQUAL(value3, uint256_t()); } BOOST_AUTO_TEST_CASE(uint256__assign_shift_right__unit_hash_0__unit_hash) { uint256_t value(unit_hash); value >>= 0; BOOST_REQUIRE_EQUAL(value, uint256_t(unit_hash)); } BOOST_AUTO_TEST_CASE(uint256__assign_shift_right__unit_hash_positive__null_hash) { uint256_t value1(unit_hash); uint256_t value2(unit_hash); value1 >>= 1; value2 >>= nuls::max_uint32; BOOST_REQUIRE_EQUAL(value1, uint256_t()); BOOST_REQUIRE_EQUAL(value2, uint256_t()); } BOOST_AUTO_TEST_CASE(uint256__assign_shift_right__max_hash_1__most_hash) { uint256_t value(max_hash); value >>= 1; BOOST_REQUIRE_EQUAL(value, uint256_t(most_hash)); } BOOST_AUTO_TEST_CASE(uint256__assign_shift_right__odd_hash_32__expected) { uint256_t value(odd_hash); value >>= 32; BOOST_REQUIRE_EQUAL(value, uint256_t("0x000000008437390223499ab234bf128e8cd092343485898923aaaaabbcbcc487")); } // assign shift left //----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(uint256__assign_shift_left__null_hash__null_hash) { uint256_t value1; uint256_t value2; uint256_t value3; value1 <<= 0; value2 <<= 1; value3 <<= nuls::max_uint32; BOOST_REQUIRE_EQUAL(value1, uint256_t()); BOOST_REQUIRE_EQUAL(value2, uint256_t()); BOOST_REQUIRE_EQUAL(value3, uint256_t()); } BOOST_AUTO_TEST_CASE(uint256__assign_shift_left__unit_hash_0__1) { uint256_t value(unit_hash); value <<= 0; BOOST_REQUIRE_EQUAL(value, uint256_t(1)); } BOOST_AUTO_TEST_CASE(uint256__assign_shift_left__unit_hash_1__2) { uint256_t value(unit_hash); value <<= 1; BOOST_REQUIRE_EQUAL(value, uint256_t(2)); } BOOST_AUTO_TEST_CASE(uint256__assign_shift_left__unit_hash_31__0x80000000) { uint256_t value(unit_hash); value <<= 31; BOOST_REQUIRE_EQUAL(value, uint256_t(0x80000000)); } /* BOOST_AUTO_TEST_CASE(uint256__assign_shift_left__max_hash_1__expected) */ /* { */ /* uint256_t value(max_hash); */ /* value <<= 1; */ /* BOOST_REQUIRE_EQUAL(value, uint256_t("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe")); */ /* } */ BOOST_AUTO_TEST_CASE(uint256__assign_shift_left__odd_hash_32__expected) { uint256_t value(odd_hash); value <<= 32; BOOST_REQUIRE_EQUAL(value, uint256_t("0x23499ab234bf128e8cd092343485898923aaaaabbcbcc4874353fff400000000")); } // assign multiply32 //----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(uint256__assign_multiply32__0_by_0__0) { uint256_t value; value *= 0; BOOST_REQUIRE_EQUAL(value, uint256_t(0)); } BOOST_AUTO_TEST_CASE(uint256__assign_multiply32__0_by_1__0) { uint256_t value; value *= 1; BOOST_REQUIRE_EQUAL(value, uint256_t(0)); } BOOST_AUTO_TEST_CASE(uint256__assign_multiply32__1_by_1__1) { uint256_t value(1); value *= 1; BOOST_REQUIRE_EQUAL(value, uint256_t(1)); } BOOST_AUTO_TEST_CASE(uint256__assign_multiply32__42_by_1__42) { uint256_t value(42); value *= 1; BOOST_REQUIRE_EQUAL(value, uint256_t(42)); } BOOST_AUTO_TEST_CASE(uint256__assign_multiply32__1_by_42__42) { uint256_t value(1); value *= 42; BOOST_REQUIRE_EQUAL(value, uint256_t(42)); } BOOST_AUTO_TEST_CASE(uint256__assign_multiply32__fives_hash_by_3__max_hash) { uint256_t value(fives_hash); value *= 3; BOOST_REQUIRE_EQUAL(value, uint256_t(max_hash)); } BOOST_AUTO_TEST_CASE(uint256__assign_multiply32__ones_hash_by_max_uint32__max_hash) { uint256_t value(ones_hash); value *= nuls::max_uint32; BOOST_REQUIRE_EQUAL(value, uint256_t(max_hash)); } BOOST_AUTO_TEST_CASE(uint256__assign_multiply32__max_hash_by_256__shifts_left_8_bits) { uint256_t value(max_hash); value *= 256; BOOST_REQUIRE_EQUAL(value, uint256_t("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00")); } // assign divide32 //----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(uint256__assign_divide32__unit_hash_by_null_hash__throws_overflow_error) { uint256_t value(unit_hash); BOOST_REQUIRE_THROW(value /= 0, std::overflow_error); } BOOST_AUTO_TEST_CASE(uint256__assign_divide32__null_hash_by_unit_hash__null_hash) { uint256_t value; value /= 1; BOOST_REQUIRE_EQUAL(value, uint256_t(0)); } BOOST_AUTO_TEST_CASE(uint256__assign_divide32__max_hash_by_3__fives_hash) { uint256_t value(max_hash); value /= 3; BOOST_REQUIRE_EQUAL(value, uint256_t(fives_hash)); } BOOST_AUTO_TEST_CASE(uint256__assign_divide32__max_hash_by_max_uint32__ones_hash) { uint256_t value(max_hash); value /= nuls::max_uint32; BOOST_REQUIRE_EQUAL(value, uint256_t(ones_hash)); } BOOST_AUTO_TEST_CASE(uint256__assign_divide32__max_hash_by_256__shifts_right_8_bits) { uint256_t value(max_hash); value /= 256; BOOST_REQUIRE_EQUAL(value, uint256_t("0x00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")); } // assign add256 //----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(uint256__assign_add256__0_to_null_hash__null_hash) { uint256_t value; value += 0; BOOST_REQUIRE_EQUAL(value, uint256_t(0)); } BOOST_AUTO_TEST_CASE(uint256__assign_add256__null_hash_to_null_hash__null_hash) { uint256_t value; value += uint256_t(); BOOST_REQUIRE_EQUAL(uint256_t() + uint256_t(), uint256_t()); } BOOST_AUTO_TEST_CASE(uint256__assign_add256__1_to_max_hash__null_hash) { uint256_t value(max_hash); value += 1; BOOST_REQUIRE_EQUAL(value, uint256_t()); } BOOST_AUTO_TEST_CASE(uint256__assign_add256__ones_hash_to_odd_hash__expected) { uint256_t value(odd_hash); value += uint256_t(ones_hash); BOOST_REQUIRE_EQUAL(value, uint256_t("0x8437390323499ab334bf128f8cd092353485898a23aaaaacbcbcc4884353fff5")); } BOOST_AUTO_TEST_CASE(uint256__assign_add256__1_to_0xffffffff__0x0100000000) { uint256_t value(0xffffffff); value += 1; BOOST_REQUIRE_EQUAL(value, uint256_t("0x100000000")); } BOOST_AUTO_TEST_CASE(uint256__assign_add256__1_to_negative_zero_hash__expected) { uint256_t value(negative_zero_hash); value += 1; BOOST_REQUIRE_EQUAL(value, uint256_t("0x8000000000000000000000000000000000000000000000000000000000000001")); } // assign subtract256 //----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(uint256__assign_subtract256__0_from_null_hash__null_hash) { uint256_t value; value -= 0; BOOST_REQUIRE_EQUAL(value, uint256_t(0)); } BOOST_AUTO_TEST_CASE(uint256__assign_subtract256__null_hash_from_null_hash__null_hash) { uint256_t value; value -= uint256_t(); BOOST_REQUIRE_EQUAL(uint256_t() + uint256_t(), uint256_t()); } BOOST_AUTO_TEST_CASE(uint256__assign_subtract256__1_from_null_hash__max_hash) { uint256_t value; value -= 1; BOOST_REQUIRE_EQUAL(value, uint256_t(max_hash)); } BOOST_AUTO_TEST_CASE(uint256__assign_subtract256__1_from_max_hash__expected) { uint256_t value(max_hash); value -= 1; BOOST_REQUIRE_EQUAL(value, uint256_t("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe")); } BOOST_AUTO_TEST_CASE(uint256__assign_subtract256__ones_hash_from_odd_hash__expected) { uint256_t value(odd_hash); value -= uint256_t(ones_hash); BOOST_REQUIRE_EQUAL(value, uint256_t("0x8437390123499ab134bf128d8cd092333485898823aaaaaabcbcc4864353fff3")); } BOOST_AUTO_TEST_CASE(uint256__assign_subtract256__1_from_0xffffffff__0x0100000000) { uint256_t value(0xffffffff); value -= 1; BOOST_REQUIRE_EQUAL(value, uint256_t(0xfffffffe)); } BOOST_AUTO_TEST_CASE(uint256__assign_subtract256__1_from_negative_zero_hash__most_hash) { uint256_t value(negative_zero_hash); value -= 1; BOOST_REQUIRE_EQUAL(value, uint256_t(most_hash)); } // assign divide256 //----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE(uint256__assign_divide__unit_hash_by_null_hash__throws_overflow_error) { uint256_t value(unit_hash); BOOST_REQUIRE_THROW(value /= uint256_t(0), std::overflow_error); } BOOST_AUTO_TEST_CASE(uint256__assign_divide__null_hash_by_unit_hash__null_hash) { uint256_t value; value /= uint256_t(unit_hash); BOOST_REQUIRE_EQUAL(value, uint256_t(0)); } BOOST_AUTO_TEST_CASE(uint256__assign_divide__max_hash_by_3__fives_hash) { uint256_t value(max_hash); value /= 3; BOOST_REQUIRE_EQUAL(value, uint256_t(fives_hash)); } BOOST_AUTO_TEST_CASE(uint256__assign_divide__max_hash_by_max_hash__1) { uint256_t value(max_hash); value /= uint256_t(max_hash); BOOST_REQUIRE_EQUAL(value, uint256_t(1)); } BOOST_AUTO_TEST_CASE(uint256__assign_divide__max_hash_by_256__shifts_right_8_bits) { static const uint256_t value(max_hash); static const auto quotient = value / uint256_t(256); BOOST_REQUIRE_EQUAL(quotient, uint256_t("0x00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")); } BOOST_AUTO_TEST_SUITE_END()
31.172237
125
0.744186
ccccbjcn
bf20ba66b9122b37906ef811543dea5d87f63b8f
1,157
cpp
C++
src/classwork/03_assign/decision.cpp
acc-cosc-1337-spring-2021/acc-cosc-1337-spring-2021-aaronvonkreisler
6733dcd999d378149dc7c2755d6b693f2924a03f
[ "MIT" ]
1
2021-02-03T00:59:22.000Z
2021-02-03T00:59:22.000Z
src/classwork/03_assign/decision.cpp
acc-cosc-1337-spring-2021/acc-cosc-1337-spring-2021-aaronvonkreisler
6733dcd999d378149dc7c2755d6b693f2924a03f
[ "MIT" ]
1
2021-02-10T00:25:08.000Z
2021-02-10T00:25:08.000Z
src/classwork/03_assign/decision.cpp
acc-cosc-1337-spring-2021/acc-cosc-1337-spring-2021-aaronvonkreisler
6733dcd999d378149dc7c2755d6b693f2924a03f
[ "MIT" ]
null
null
null
//cpp #include "decision.h" #include <iostream> #include <string> using std::string; string get_letter_grade_using_if(int grade) { bool gradeA = grade >= 90 && grade <= 100; bool gradeB = grade >= 80 && grade <= 89; bool gradeC = grade >= 70 && grade <= 79; bool gradeD = grade >= 60 && grade <= 69; bool gradeF = grade >= 0 && grade <= 59; string letterGrade; if (gradeA) letterGrade = "A"; else if (gradeB) letterGrade = "B"; else if (gradeC) letterGrade = "C"; else if (gradeD) letterGrade = "D"; else letterGrade = "F"; return letterGrade; } string get_letter_grade_using_switch(int grade) { string letterGrade; switch (grade / 10) { case 10: case 9: letterGrade = "A"; break; case 8: letterGrade = "B"; break; case 7: letterGrade = "C"; break; case 6: letterGrade = "D"; break; case 5: case 4: case 3: case 2: case 1: letterGrade = "F"; break; default: letterGrade = "OUT OF RANGE"; } return letterGrade; }
18.967213
47
0.532411
acc-cosc-1337-spring-2021
bf24c251a6b2c07477cacc43489a91bc63d244e6
1,686
cpp
C++
test/HelperMethodTest.cpp
yfurukawa/Library
7fd61038e8eebc9f4dd678e2a203c1de182b1991
[ "Unlicense" ]
null
null
null
test/HelperMethodTest.cpp
yfurukawa/Library
7fd61038e8eebc9f4dd678e2a203c1de182b1991
[ "Unlicense" ]
null
null
null
test/HelperMethodTest.cpp
yfurukawa/Library
7fd61038e8eebc9f4dd678e2a203c1de182b1991
[ "Unlicense" ]
null
null
null
/* * HelperMethodTest.cpp * * Created on: 2015/07/30 * Author: CE122548 */ #include "HelperMethodTest.h" void HelperMethodTest::SetUp() { } void HelperMethodTest::TearDown() { } HelperMethodTest::HelperMethodTest() { } HelperMethodTest::~HelperMethodTest() { } /** * \test ポインタがNULLの場合、判定値は偽となる */ TEST_F (HelperMethodTest, testHasInstance_InstanceIsNull) { DummyClass* dummy(NULL); EXPECT_EQ(false, Helper::hasInstance<DummyClass*>(dummy)); } /** * \test ポインタがNULLでない場合、判定値は真となる */ TEST_F (HelperMethodTest, testHasInstance_InstanceIsNotNull) { DummyClass* dummy(NULL); dummy = new DummyClass(); EXPECT_EQ(true, Helper::hasInstance<DummyClass*>(dummy)); delete dummy; } /** * \test ポインタがNULLでない場合にインスタンスを削除する */ TEST_F (HelperMethodTest, testDeleteInstance_InstanceIsNotNull) { DummyClass* dummy(NULL); dummy = new DummyClass(); EXPECT_EQ(NULL, Helper::deleteInstance<DummyClass*>(dummy)); } /** * \test ポインタがNULLの場合にインスタンスを削除する */ TEST_F (HelperMethodTest, testDeleteInstance_InstanceIsNull) { DummyClass* dummy(NULL); EXPECT_EQ(NULL, Helper::deleteInstance<DummyClass*>(dummy)); } /** * \test ポインタがNULLでない場合に配列インスタンスを削除する */ TEST_F (HelperMethodTest, testDeleteInstance_ArrayInstanceIsNotNull) { DummyClass* dummy(NULL); dummy = new DummyClass[10]; EXPECT_EQ(NULL, Helper::deleteArrayInstance<DummyClass*>(dummy)); } /** * \test ポインタがNULLの場合に配列インスタンスを削除する */ TEST_F (HelperMethodTest, testDeleteInstance_ArrayInstanceIsNull) { DummyClass* dummy(NULL); EXPECT_EQ(NULL, Helper::deleteArrayInstance<DummyClass*>(dummy)); }
22.783784
71
0.698695
yfurukawa
bf25d954d6efcfccb2c3da744211fcfc1bde374e
884
cpp
C++
tests/YstringTest/Utf/test_Utf8StringCpp11.cpp
wvffle/Ystring
a1ee9da1e433a2e74e432da6834638d547265126
[ "BSD-2-Clause" ]
null
null
null
tests/YstringTest/Utf/test_Utf8StringCpp11.cpp
wvffle/Ystring
a1ee9da1e433a2e74e432da6834638d547265126
[ "BSD-2-Clause" ]
1
2021-02-28T12:46:55.000Z
2021-03-03T20:58:14.000Z
tests/YstringTest/Utf/test_Utf8StringCpp11.cpp
wvffle/Ystring
a1ee9da1e433a2e74e432da6834638d547265126
[ "BSD-2-Clause" ]
1
2021-02-28T13:02:43.000Z
2021-02-28T13:02:43.000Z
//**************************************************************************** // Copyright © 2015 Jan Erik Breimo. All rights reserved. // Created by Jan Erik Breimo on 2015-07-29 // // This file is distributed under the Simplified BSD License. // License text is included with the source distribution. //**************************************************************************** #include "Ystring/Utf8.hpp" #include "Ytest/Ytest.hpp" namespace { using namespace Ystring; void test_toUtf8_fromUtf16_u16string() { Y_EQUAL(Utf8::toUtf8(u"A\U00010001<"), "A\xF0\x90\x80\x81<"); } void test_toUtf8_fromUtf32_u32string() { Y_EQUAL(Utf8::toUtf8(U"A\U00010001<"), "A\xF0\x90\x80\x81<"); } Y_SUBTEST("Utf8", test_toUtf8_fromUtf16_u16string, test_toUtf8_fromUtf32_u32string); }
28.516129
78
0.529412
wvffle
bf296ab9cf1435b8ace5f9da4ee4794d117c3303
2,591
cpp
C++
src/infra/ToString.cpp
raptoravis/two
4366fcf8b3072d0233eb8e1e91ac1105194f60f5
[ "Zlib" ]
null
null
null
src/infra/ToString.cpp
raptoravis/two
4366fcf8b3072d0233eb8e1e91ac1105194f60f5
[ "Zlib" ]
null
null
null
src/infra/ToString.cpp
raptoravis/two
4366fcf8b3072d0233eb8e1e91ac1105194f60f5
[ "Zlib" ]
null
null
null
// Copyright (c) 2019 Hugo Amiard hugo.amiard@laposte.net // This software is provided 'as-is' under the zlib License, see the LICENSE.txt file. // This notice and the license may not be removed or altered from any source distribution. #ifdef TWO_MODULES module two.infra; #else #include <infra/ToString.h> #endif #include <cstdio> namespace two { template <> void to_string(const bool& value, string& str) { str.resize(snprintf(nullptr, 0, "%d", value)); sprintf(&str[0], "%d", value); } template <> void to_string(const char& value, string& str) { str.resize(snprintf(nullptr, 0, "%d", value)); sprintf(&str[0], "%d", value); } template <> void to_string(const schar& value, string& str) { str.resize(snprintf(nullptr, 0, "%d", value)); sprintf(&str[0], "%d", value); } template <> void to_string(const uchar& value, string& str) { str.resize(snprintf(nullptr, 0, "%u", value)); sprintf(&str[0], "%u", value); } template <> void to_string(const short& value, string& str) { str.resize(snprintf(nullptr, 0, "%d", value)); sprintf(&str[0], "%d", value); } template <> void to_string(const int& value, string& str) { str.resize(snprintf(nullptr, 0, "%d", value)); sprintf(&str[0], "%d", value); } template <> void to_string(const long& value, string& str) { str.resize(snprintf(nullptr, 0, "%ld", value)); sprintf(&str[0], "%ld", value); } template <> void to_string(const llong& value, string& str) { str.resize(snprintf(nullptr, 0, "%lld", value)); sprintf(&str[0], "%lld", value); } template <> void to_string(const ushort& value, string& str) { str.resize(snprintf(nullptr, 0, "%u", value)); sprintf(&str[0], "%u", value); } template <> void to_string(const uint& value, string& str) { str.resize(snprintf(nullptr, 0, "%u", value)); sprintf(&str[0], "%u", value); } template <> void to_string(const ulong& value, string& str) { str.resize(snprintf(nullptr, 0, "%lu", value)); sprintf(&str[0], "%lu", value); } template <> void to_string(const ullong& value, string& str) { str.resize(snprintf(nullptr, 0, "%llu", value)); sprintf(&str[0], "%llu", value); } template <> void to_string(const float& value, string& str) { str.resize(snprintf(nullptr, 0, "%f", value)); sprintf(&str[0], "%f", value); } template <> void to_string(const double& value, string& str) { str.resize(snprintf(nullptr, 0, "%f", value)); sprintf(&str[0], "%f", value); } template <> void to_string(const ldouble& value, string& str) { str.resize(snprintf(nullptr, 0, "%Lf", value)); sprintf(&str[0], "%Lf", value); } }
83.580645
148
0.646083
raptoravis
bf3276ac151283d36a74c2cd1305505804d0242a
2,223
hxx
C++
opencascade/StepBasic_UncertaintyMeasureWithUnit.hxx
valgur/OCP
2f7d9da73a08e4ffe80883614aedacb27351134f
[ "Apache-2.0" ]
117
2020-03-07T12:07:05.000Z
2022-03-27T07:35:22.000Z
opencascade/StepBasic_UncertaintyMeasureWithUnit.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
66
2019-12-20T16:07:36.000Z
2022-03-15T21:56:10.000Z
opencascade/StepBasic_UncertaintyMeasureWithUnit.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
76
2020-03-16T01:47:46.000Z
2022-03-21T16:37:07.000Z
// Created on: 1995-12-01 // Created by: EXPRESS->CDL V0.2 Translator // Copyright (c) 1995-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _StepBasic_UncertaintyMeasureWithUnit_HeaderFile #define _StepBasic_UncertaintyMeasureWithUnit_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <StepBasic_MeasureWithUnit.hxx> class TCollection_HAsciiString; class StepBasic_MeasureValueMember; class StepBasic_Unit; class StepBasic_UncertaintyMeasureWithUnit; DEFINE_STANDARD_HANDLE(StepBasic_UncertaintyMeasureWithUnit, StepBasic_MeasureWithUnit) class StepBasic_UncertaintyMeasureWithUnit : public StepBasic_MeasureWithUnit { public: //! Returns a UncertaintyMeasureWithUnit Standard_EXPORT StepBasic_UncertaintyMeasureWithUnit(); Standard_EXPORT void Init (const Handle(StepBasic_MeasureValueMember)& aValueComponent, const StepBasic_Unit& aUnitComponent, const Handle(TCollection_HAsciiString)& aName, const Handle(TCollection_HAsciiString)& aDescription); Standard_EXPORT void SetName (const Handle(TCollection_HAsciiString)& aName); Standard_EXPORT Handle(TCollection_HAsciiString) Name() const; Standard_EXPORT void SetDescription (const Handle(TCollection_HAsciiString)& aDescription); Standard_EXPORT Handle(TCollection_HAsciiString) Description() const; DEFINE_STANDARD_RTTIEXT(StepBasic_UncertaintyMeasureWithUnit,StepBasic_MeasureWithUnit) protected: private: Handle(TCollection_HAsciiString) name; Handle(TCollection_HAsciiString) description; }; #endif // _StepBasic_UncertaintyMeasureWithUnit_HeaderFile
28.5
229
0.818713
valgur
bf32a2f40f41ef754bdedf167eee5899de8be7ac
1,935
cpp
C++
Implementations/Luogu/P4568.cpp
VecTest/code-library
00e9e881acece02c7dbeac3a139cb55e0b439cee
[ "MIT" ]
1
2022-03-05T00:34:14.000Z
2022-03-05T00:34:14.000Z
Implementations/Luogu/P4568.cpp
VecTest/code-library
00e9e881acece02c7dbeac3a139cb55e0b439cee
[ "MIT" ]
null
null
null
Implementations/Luogu/P4568.cpp
VecTest/code-library
00e9e881acece02c7dbeac3a139cb55e0b439cee
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> /* 大致思路: 分层图最短路 提交地址: https://www.luogu.com.cn/problem/P4568 https://www.acwing.com/problem/content/2956/ */ const int INF = 1e9; struct Edge { int v, w; }; using Edges = std::vector<std::vector<Edge>>; struct Vertex { int d, p; bool operator < (const Vertex &x) const { return d > x.d; } }; std::vector<int> Dijkstra(int n, int s, Edges &e) { std::vector<int> d(n, INF); d[s] = 0; std::vector<bool> f(n); std::priority_queue<Vertex> q; q.push({0, s}); while (!q.empty()) { int x = q.top().p; q.pop(); if (f[x]) { continue; } f[x] = true; for (int i = 0; i < (int) e[x].size(); i++) { int y = e[x][i].v, w = e[x][i].w; if (!f[y] && d[y] > d[x] + w) { d[y] = d[x] + w; q.push({d[y], y}); } } } return d; } void add(int u, int v, int d, Edges &e) { e[u].push_back({v, d}); } int main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); int n, m, k; std::cin >> n >> m >> k; int s, t; std::cin >> s >> t; // 有 k + 1 层,每层有 n 个点,故最大编号为 (k + 1) * n - 1 int p = (k + 1) * n; // 总点数 Edges e(p); for (int i = 0; i < m; i++) { int u, v, d; std::cin >> u >> v >> d; add(u, v, d, e); add(v, u, d, e); for (int j = 1; j <= k; j++) { // 建第 j 层的图 add(u + j * n, v + j * n, d, e); add(v + j * n, u + j * n, d, e); add(u + (j - 1) * n, v + j * n, 0, e); add(v + (j - 1) * n, u + j * n, 0, e); } } std::vector<int> d = Dijkstra(p, s, e); int ans = INF; for (int i = 0; i <= k; i++) { ans = std::min(ans, d[t + i * n]); } std::cout << ans << "\n"; #ifdef LOCAL std::cout << std::flush; system("pause"); #endif return 0; }
18.970588
53
0.407235
VecTest
bf352539e50aa927796667d0265e4999ffcdaf1b
43,655
hpp
C++
fprime-sphinx-drivers/NORFlashManager/test/ut/GTestBase.hpp
Joshua-Anderson/fprime-sphinx-drivers
28334b667c31a796c69e0f7005e4a9c0545e65fe
[ "Apache-2.0" ]
1
2021-02-22T12:34:25.000Z
2021-02-22T12:34:25.000Z
fprime-sphinx-drivers/NORFlashManager/test/ut/GTestBase.hpp
Joshua-Anderson/fprime-sphinx-drivers
28334b667c31a796c69e0f7005e4a9c0545e65fe
[ "Apache-2.0" ]
2
2021-08-11T17:14:54.000Z
2021-09-09T22:31:19.000Z
fprime-sphinx-drivers/NORFlashManager/test/ut/GTestBase.hpp
Joshua-Anderson/fprime-sphinx-drivers
28334b667c31a796c69e0f7005e4a9c0545e65fe
[ "Apache-2.0" ]
1
2021-05-19T02:04:10.000Z
2021-05-19T02:04:10.000Z
// ====================================================================== // \title NORFlashManager/test/ut/GTestBase.hpp // \author Auto-generated // \brief hpp file for NORFlashManager component Google Test harness base class // // \copyright // Copyright 2009-2015, by the California Institute of Technology. // ALL RIGHTS RESERVED. United States Government Sponsorship // acknowledged. // ====================================================================== #ifndef NORFlashManager_GTEST_BASE_HPP #define NORFlashManager_GTEST_BASE_HPP #include "TesterBase.hpp" #include "gtest/gtest.h" // ---------------------------------------------------------------------- // Macros for command history assertions // ---------------------------------------------------------------------- #define ASSERT_CMD_RESPONSE_SIZE(size) \ this->assertCmdResponse_size(__FILE__, __LINE__, size) #define ASSERT_CMD_RESPONSE(index, opCode, cmdSeq, response) \ this->assertCmdResponse(__FILE__, __LINE__, index, opCode, cmdSeq, response) // ---------------------------------------------------------------------- // Macros for event history assertions // ---------------------------------------------------------------------- #define ASSERT_EVENTS_SIZE(size) \ this->assertEvents_size(__FILE__, __LINE__, size) #define ASSERT_EVENTS_NOR_ERASE_BUSY_SIZE(size) \ this->assertEvents_NOR_ERASE_BUSY_size(__FILE__, __LINE__, size) #define ASSERT_EVENTS_NOR_ERASE_BUSY(index, _actual_state, _expected_state, _error_status) \ this->assertEvents_NOR_ERASE_BUSY(__FILE__, __LINE__, index, _actual_state, _expected_state, _error_status) #define ASSERT_EVENTS_NOR_ERASE_FAIL_SIZE(size) \ this->assertEvents_NOR_ERASE_FAIL_size(__FILE__, __LINE__, size) #define ASSERT_EVENTS_NOR_ERASE_FAIL(index, _error_status) \ this->assertEvents_NOR_ERASE_FAIL(__FILE__, __LINE__, index, _error_status) #define ASSERT_EVENTS_NOR_ERASING_SIZE(size) \ this->assertEvents_NOR_ERASING_size(__FILE__, __LINE__, size) #define ASSERT_EVENTS_NOR_ERASE_TIMEOUT_SIZE(size) \ this->assertEvents_NOR_ERASE_TIMEOUT_size(__FILE__, __LINE__, size) #define ASSERT_EVENTS_NOR_ERASE_DONE_SIZE(size) \ this->assertEvents_NOR_ERASE_DONE_size(__FILE__, __LINE__, size) #define ASSERT_EVENTS_NOR_RESET_FAIL_SIZE(size) \ this->assertEvents_NOR_RESET_FAIL_size(__FILE__, __LINE__, size) #define ASSERT_EVENTS_NOR_RESET_FAIL(index, _actual_state, _expected_state) \ this->assertEvents_NOR_RESET_FAIL(__FILE__, __LINE__, index, _actual_state, _expected_state) #define ASSERT_EVENTS_NOR_RESETTING_SIZE(size) \ this->assertEvents_NOR_RESETTING_size(__FILE__, __LINE__, size) #define ASSERT_EVENTS_NOR_UNLOCK_BYPASS_FAILED_SIZE(size) \ this->assertEvents_NOR_UNLOCK_BYPASS_FAILED_size(__FILE__, __LINE__, size) #define ASSERT_EVENTS_NOR_UNLOCK_BYPASS_PROGRAM_FAILED_SIZE(size) \ this->assertEvents_NOR_UNLOCK_BYPASS_PROGRAM_FAILED_size(__FILE__, __LINE__, size) #define ASSERT_EVENTS_NOR_UNLOCK_BYPASS_RESET_FAILED_SIZE(size) \ this->assertEvents_NOR_UNLOCK_BYPASS_RESET_FAILED_size(__FILE__, __LINE__, size) #define ASSERT_EVENTS_NOR_FAILED_TO_VERIFY_DATA_SIZE(size) \ this->assertEvents_NOR_FAILED_TO_VERIFY_DATA_size(__FILE__, __LINE__, size) #define ASSERT_EVENTS_NOR_FAILED_TO_VERIFY_DATA(index, _dest_addr, _source) \ this->assertEvents_NOR_FAILED_TO_VERIFY_DATA(__FILE__, __LINE__, index, _dest_addr, _source) #define ASSERT_EVENTS_NOR_UNLOCK_BYPASS_RESET_DURING_ERASE_SIZE(size) \ this->assertEvents_NOR_UNLOCK_BYPASS_RESET_DURING_ERASE_size(__FILE__, __LINE__, size) #define ASSERT_EVENTS_NOR_FAILED_TO_RESET_SIZE(size) \ this->assertEvents_NOR_FAILED_TO_RESET_size(__FILE__, __LINE__, size) #define ASSERT_EVENTS_NOR_WRITE_TIMEOUT_SIZE(size) \ this->assertEvents_NOR_WRITE_TIMEOUT_size(__FILE__, __LINE__, size) #define ASSERT_EVENTS_NOR_FAILED_TO_VERIFY_CHECKSUM_SIZE(size) \ this->assertEvents_NOR_FAILED_TO_VERIFY_CHECKSUM_size(__FILE__, __LINE__, size) #define ASSERT_EVENTS_NOR_CHECKSUM_VERIFY_DONE_SIZE(size) \ this->assertEvents_NOR_CHECKSUM_VERIFY_DONE_size(__FILE__, __LINE__, size) #define ASSERT_EVENTS_NOR_VERIFY_BUSY_SIZE(size) \ this->assertEvents_NOR_VERIFY_BUSY_size(__FILE__, __LINE__, size) #define ASSERT_EVENTS_NOR_VERIFY_BUSY(index, _actual_state, _expected_state) \ this->assertEvents_NOR_VERIFY_BUSY(__FILE__, __LINE__, index, _actual_state, _expected_state) #define ASSERT_EVENTS_NOR_FAILED_TO_READ_DATA_SIZE(size) \ this->assertEvents_NOR_FAILED_TO_READ_DATA_size(__FILE__, __LINE__, size) #define ASSERT_EVENTS_NOR_FAILED_TO_READ_DATA(index, _nor_addr, _dest) \ this->assertEvents_NOR_FAILED_TO_READ_DATA(__FILE__, __LINE__, index, _nor_addr, _dest) #define ASSERT_EVENTS_NOR_READ_TIMEOUT_SIZE(size) \ this->assertEvents_NOR_READ_TIMEOUT_size(__FILE__, __LINE__, size) #define ASSERT_EVENTS_NOR_ALREADY_ERASING_SIZE(size) \ this->assertEvents_NOR_ALREADY_ERASING_size(__FILE__, __LINE__, size) // ---------------------------------------------------------------------- // Macros for typed user from port history assertions // ---------------------------------------------------------------------- #define ASSERT_FROM_PORT_HISTORY_SIZE(size) \ this->assertFromPortHistory_size(__FILE__, __LINE__, size) #define ASSERT_from_PingResponse_SIZE(size) \ this->assert_from_PingResponse_size(__FILE__, __LINE__, size) #define ASSERT_from_PingResponse(index, _key) \ { \ ASSERT_GT(this->fromPortHistory_PingResponse->size(), static_cast<U32>(index)) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Index into history of from_PingResponse\n" \ << " Expected: Less than size of history (" \ << this->fromPortHistory_PingResponse->size() << ")\n" \ << " Actual: " << index << "\n"; \ const FromPortEntry_PingResponse& _e = \ this->fromPortHistory_PingResponse->at(index); \ ASSERT_EQ(_key, _e.key) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument key at index " \ << index \ << " in history of from_PingResponse\n" \ << " Expected: " << _key << "\n" \ << " Actual: " << _e.key << "\n"; \ } #define ASSERT_from_verification_done_SIZE(size) \ this->assert_from_verification_done_size(__FILE__, __LINE__, size) #define ASSERT_from_verification_done(index, _valid_nor, _read_blc_checksum, _read_fsw_checksum, _cptd_blc_checksum, _cptd_fsw_checksum) \ { \ ASSERT_GT(this->fromPortHistory_verification_done->size(), static_cast<U32>(index)) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Index into history of from_verification_done\n" \ << " Expected: Less than size of history (" \ << this->fromPortHistory_verification_done->size() << ")\n" \ << " Actual: " << index << "\n"; \ const FromPortEntry_verification_done& _e = \ this->fromPortHistory_verification_done->at(index); \ ASSERT_EQ(_valid_nor, _e.valid_nor) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument valid_nor at index " \ << index \ << " in history of from_verification_done\n" \ << " Expected: " << _valid_nor << "\n" \ << " Actual: " << _e.valid_nor << "\n"; \ ASSERT_EQ(_read_blc_checksum, _e.read_blc_checksum) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument read_blc_checksum at index " \ << index \ << " in history of from_verification_done\n" \ << " Expected: " << _read_blc_checksum << "\n" \ << " Actual: " << _e.read_blc_checksum << "\n"; \ ASSERT_EQ(_read_fsw_checksum, _e.read_fsw_checksum) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument read_fsw_checksum at index " \ << index \ << " in history of from_verification_done\n" \ << " Expected: " << _read_fsw_checksum << "\n" \ << " Actual: " << _e.read_fsw_checksum << "\n"; \ ASSERT_EQ(_cptd_blc_checksum, _e.cptd_blc_checksum) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument cptd_blc_checksum at index " \ << index \ << " in history of from_verification_done\n" \ << " Expected: " << _cptd_blc_checksum << "\n" \ << " Actual: " << _e.cptd_blc_checksum << "\n"; \ ASSERT_EQ(_cptd_fsw_checksum, _e.cptd_fsw_checksum) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument cptd_fsw_checksum at index " \ << index \ << " in history of from_verification_done\n" \ << " Expected: " << _cptd_fsw_checksum << "\n" \ << " Actual: " << _e.cptd_fsw_checksum << "\n"; \ } #define ASSERT_from_erase_done_SIZE(size) \ this->assert_from_erase_done_size(__FILE__, __LINE__, size) #define ASSERT_from_erase_done(index, _done, _context1, _context2) \ { \ ASSERT_GT(this->fromPortHistory_erase_done->size(), static_cast<U32>(index)) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Index into history of from_erase_done\n" \ << " Expected: Less than size of history (" \ << this->fromPortHistory_erase_done->size() << ")\n" \ << " Actual: " << index << "\n"; \ const FromPortEntry_erase_done& _e = \ this->fromPortHistory_erase_done->at(index); \ ASSERT_EQ(_done, _e.done) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument done at index " \ << index \ << " in history of from_erase_done\n" \ << " Expected: " << _done << "\n" \ << " Actual: " << _e.done << "\n"; \ ASSERT_EQ(_context1, _e.context1) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument context1 at index " \ << index \ << " in history of from_erase_done\n" \ << " Expected: " << _context1 << "\n" \ << " Actual: " << _e.context1 << "\n"; \ ASSERT_EQ(_context2, _e.context2) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument context2 at index " \ << index \ << " in history of from_erase_done\n" \ << " Expected: " << _context2 << "\n" \ << " Actual: " << _e.context2 << "\n"; \ } #define ASSERT_from_read_done_SIZE(size) \ this->assert_from_read_done_size(__FILE__, __LINE__, size) #define ASSERT_from_read_done(index, _done, _context1, _context2) \ { \ ASSERT_GT(this->fromPortHistory_read_done->size(), static_cast<U32>(index)) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Index into history of from_read_done\n" \ << " Expected: Less than size of history (" \ << this->fromPortHistory_read_done->size() << ")\n" \ << " Actual: " << index << "\n"; \ const FromPortEntry_read_done& _e = \ this->fromPortHistory_read_done->at(index); \ ASSERT_EQ(_done, _e.done) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument done at index " \ << index \ << " in history of from_read_done\n" \ << " Expected: " << _done << "\n" \ << " Actual: " << _e.done << "\n"; \ ASSERT_EQ(_context1, _e.context1) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument context1 at index " \ << index \ << " in history of from_read_done\n" \ << " Expected: " << _context1 << "\n" \ << " Actual: " << _e.context1 << "\n"; \ ASSERT_EQ(_context2, _e.context2) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument context2 at index " \ << index \ << " in history of from_read_done\n" \ << " Expected: " << _context2 << "\n" \ << " Actual: " << _e.context2 << "\n"; \ } #define ASSERT_from_worker_verify_SIZE(size) \ this->assert_from_worker_verify_size(__FILE__, __LINE__, size) #define ASSERT_from_worker_verify(index, _blc_filesize, _fsw_filesize) \ { \ ASSERT_GT(this->fromPortHistory_worker_verify->size(), static_cast<U32>(index)) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Index into history of from_worker_verify\n" \ << " Expected: Less than size of history (" \ << this->fromPortHistory_worker_verify->size() << ")\n" \ << " Actual: " << index << "\n"; \ const FromPortEntry_worker_verify& _e = \ this->fromPortHistory_worker_verify->at(index); \ ASSERT_EQ(_blc_filesize, _e.blc_filesize) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument blc_filesize at index " \ << index \ << " in history of from_worker_verify\n" \ << " Expected: " << _blc_filesize << "\n" \ << " Actual: " << _e.blc_filesize << "\n"; \ ASSERT_EQ(_fsw_filesize, _e.fsw_filesize) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument fsw_filesize at index " \ << index \ << " in history of from_worker_verify\n" \ << " Expected: " << _fsw_filesize << "\n" \ << " Actual: " << _e.fsw_filesize << "\n"; \ } #define ASSERT_from_worker_write_SIZE(size) \ this->assert_from_worker_write_size(__FILE__, __LINE__, size) #define ASSERT_from_worker_write(index, _dest, _src, _count, _bank) \ { \ ASSERT_GT(this->fromPortHistory_worker_write->size(), static_cast<U32>(index)) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Index into history of from_worker_write\n" \ << " Expected: Less than size of history (" \ << this->fromPortHistory_worker_write->size() << ")\n" \ << " Actual: " << index << "\n"; \ const FromPortEntry_worker_write& _e = \ this->fromPortHistory_worker_write->at(index); \ ASSERT_EQ(_dest, _e.dest) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument dest at index " \ << index \ << " in history of from_worker_write\n" \ << " Expected: " << _dest << "\n" \ << " Actual: " << _e.dest << "\n"; \ ASSERT_EQ(_src, _e.src) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument src at index " \ << index \ << " in history of from_worker_write\n" \ << " Expected: " << _src << "\n" \ << " Actual: " << _e.src << "\n"; \ ASSERT_EQ(_count, _e.count) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument count at index " \ << index \ << " in history of from_worker_write\n" \ << " Expected: " << _count << "\n" \ << " Actual: " << _e.count << "\n"; \ ASSERT_EQ(_bank, _e.bank) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument bank at index " \ << index \ << " in history of from_worker_write\n" \ << " Expected: " << _bank << "\n" \ << " Actual: " << _e.bank << "\n"; \ } #define ASSERT_from_write_done_SIZE(size) \ this->assert_from_write_done_size(__FILE__, __LINE__, size) #define ASSERT_from_write_done(index, _done, _context1, _context2) \ { \ ASSERT_GT(this->fromPortHistory_write_done->size(), static_cast<U32>(index)) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Index into history of from_write_done\n" \ << " Expected: Less than size of history (" \ << this->fromPortHistory_write_done->size() << ")\n" \ << " Actual: " << index << "\n"; \ const FromPortEntry_write_done& _e = \ this->fromPortHistory_write_done->at(index); \ ASSERT_EQ(_done, _e.done) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument done at index " \ << index \ << " in history of from_write_done\n" \ << " Expected: " << _done << "\n" \ << " Actual: " << _e.done << "\n"; \ ASSERT_EQ(_context1, _e.context1) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument context1 at index " \ << index \ << " in history of from_write_done\n" \ << " Expected: " << _context1 << "\n" \ << " Actual: " << _e.context1 << "\n"; \ ASSERT_EQ(_context2, _e.context2) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument context2 at index " \ << index \ << " in history of from_write_done\n" \ << " Expected: " << _context2 << "\n" \ << " Actual: " << _e.context2 << "\n"; \ } #define ASSERT_from_worker_erase_SIZE(size) \ this->assert_from_worker_erase_size(__FILE__, __LINE__, size) #define ASSERT_from_worker_erase(index, _bank_addr) \ { \ ASSERT_GT(this->fromPortHistory_worker_erase->size(), static_cast<U32>(index)) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Index into history of from_worker_erase\n" \ << " Expected: Less than size of history (" \ << this->fromPortHistory_worker_erase->size() << ")\n" \ << " Actual: " << index << "\n"; \ const FromPortEntry_worker_erase& _e = \ this->fromPortHistory_worker_erase->at(index); \ ASSERT_EQ(_bank_addr, _e.bank_addr) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument bank_addr at index " \ << index \ << " in history of from_worker_erase\n" \ << " Expected: " << _bank_addr << "\n" \ << " Actual: " << _e.bank_addr << "\n"; \ } #define ASSERT_from_worker_cancel_SIZE(size) \ this->assert_from_worker_cancel_size(__FILE__, __LINE__, size) #define ASSERT_from_worker_reset_SIZE(size) \ this->assert_from_worker_reset_size(__FILE__, __LINE__, size) #define ASSERT_from_worker_reset(index, _dontcare_addr) \ { \ ASSERT_GT(this->fromPortHistory_worker_reset->size(), static_cast<U32>(index)) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Index into history of from_worker_reset\n" \ << " Expected: Less than size of history (" \ << this->fromPortHistory_worker_reset->size() << ")\n" \ << " Actual: " << index << "\n"; \ const FromPortEntry_worker_reset& _e = \ this->fromPortHistory_worker_reset->at(index); \ ASSERT_EQ(_dontcare_addr, _e.dontcare_addr) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument dontcare_addr at index " \ << index \ << " in history of from_worker_reset\n" \ << " Expected: " << _dontcare_addr << "\n" \ << " Actual: " << _e.dontcare_addr << "\n"; \ } #define ASSERT_from_worker_read_SIZE(size) \ this->assert_from_worker_read_size(__FILE__, __LINE__, size) #define ASSERT_from_worker_read(index, _dest, _src, _count, _bank) \ { \ ASSERT_GT(this->fromPortHistory_worker_read->size(), static_cast<U32>(index)) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Index into history of from_worker_read\n" \ << " Expected: Less than size of history (" \ << this->fromPortHistory_worker_read->size() << ")\n" \ << " Actual: " << index << "\n"; \ const FromPortEntry_worker_read& _e = \ this->fromPortHistory_worker_read->at(index); \ ASSERT_EQ(_dest, _e.dest) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument dest at index " \ << index \ << " in history of from_worker_read\n" \ << " Expected: " << _dest << "\n" \ << " Actual: " << _e.dest << "\n"; \ ASSERT_EQ(_src, _e.src) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument src at index " \ << index \ << " in history of from_worker_read\n" \ << " Expected: " << _src << "\n" \ << " Actual: " << _e.src << "\n"; \ ASSERT_EQ(_count, _e.count) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument count at index " \ << index \ << " in history of from_worker_read\n" \ << " Expected: " << _count << "\n" \ << " Actual: " << _e.count << "\n"; \ ASSERT_EQ(_bank, _e.bank) \ << "\n" \ << " File: " << __FILE__ << "\n" \ << " Line: " << __LINE__ << "\n" \ << " Value: Value of argument bank at index " \ << index \ << " in history of from_worker_read\n" \ << " Expected: " << _bank << "\n" \ << " Actual: " << _e.bank << "\n"; \ } namespace Drv { //! \class NORFlashManagerGTestBase //! \brief Auto-generated base class for NORFlashManager component Google Test harness //! class NORFlashManagerGTestBase : public NORFlashManagerTesterBase { protected: // ---------------------------------------------------------------------- // Construction and destruction // ---------------------------------------------------------------------- //! Construct object NORFlashManagerGTestBase //! NORFlashManagerGTestBase( #if FW_OBJECT_NAMES == 1 const char *const compName, /*!< The component name*/ const U32 maxHistorySize /*!< The maximum size of each history*/ #else const U32 maxHistorySize /*!< The maximum size of each history*/ #endif ); //! Destroy object NORFlashManagerGTestBase //! virtual ~NORFlashManagerGTestBase(void); protected: // ---------------------------------------------------------------------- // Commands // ---------------------------------------------------------------------- //! Assert size of command response history //! void assertCmdResponse_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; //! Assert command response in history at index //! void assertCmdResponse( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 index, /*!< The index*/ const FwOpcodeType opCode, /*!< The opcode*/ const U32 cmdSeq, /*!< The command sequence number*/ const Fw::CommandResponse response /*!< The command response*/ ) const; protected: // ---------------------------------------------------------------------- // Events // ---------------------------------------------------------------------- void assertEvents_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; protected: // ---------------------------------------------------------------------- // Event: NOR_ERASE_BUSY // ---------------------------------------------------------------------- void assertEvents_NOR_ERASE_BUSY_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; void assertEvents_NOR_ERASE_BUSY( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 index, /*!< The index*/ const U32 actual_state, /*!< The state of the NOR Manager*/ const U32 expected_state, /*!< The expected state of the NOR Manager*/ const U32 error_status /*!< The error status*/ ) const; protected: // ---------------------------------------------------------------------- // Event: NOR_ERASE_FAIL // ---------------------------------------------------------------------- void assertEvents_NOR_ERASE_FAIL_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; void assertEvents_NOR_ERASE_FAIL( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 index, /*!< The index*/ const U32 error_status /*!< The error status*/ ) const; protected: // ---------------------------------------------------------------------- // Event: NOR_ERASING // ---------------------------------------------------------------------- void assertEvents_NOR_ERASING_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; protected: // ---------------------------------------------------------------------- // Event: NOR_ERASE_TIMEOUT // ---------------------------------------------------------------------- void assertEvents_NOR_ERASE_TIMEOUT_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; protected: // ---------------------------------------------------------------------- // Event: NOR_ERASE_DONE // ---------------------------------------------------------------------- void assertEvents_NOR_ERASE_DONE_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; protected: // ---------------------------------------------------------------------- // Event: NOR_RESET_FAIL // ---------------------------------------------------------------------- void assertEvents_NOR_RESET_FAIL_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; void assertEvents_NOR_RESET_FAIL( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 index, /*!< The index*/ const U32 actual_state, /*!< The state of the NOR Manager*/ const U32 expected_state /*!< The expected state of the NOR Manager*/ ) const; protected: // ---------------------------------------------------------------------- // Event: NOR_RESETTING // ---------------------------------------------------------------------- void assertEvents_NOR_RESETTING_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; protected: // ---------------------------------------------------------------------- // Event: NOR_UNLOCK_BYPASS_FAILED // ---------------------------------------------------------------------- void assertEvents_NOR_UNLOCK_BYPASS_FAILED_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; protected: // ---------------------------------------------------------------------- // Event: NOR_UNLOCK_BYPASS_PROGRAM_FAILED // ---------------------------------------------------------------------- void assertEvents_NOR_UNLOCK_BYPASS_PROGRAM_FAILED_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; protected: // ---------------------------------------------------------------------- // Event: NOR_UNLOCK_BYPASS_RESET_FAILED // ---------------------------------------------------------------------- void assertEvents_NOR_UNLOCK_BYPASS_RESET_FAILED_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; protected: // ---------------------------------------------------------------------- // Event: NOR_FAILED_TO_VERIFY_DATA // ---------------------------------------------------------------------- void assertEvents_NOR_FAILED_TO_VERIFY_DATA_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; void assertEvents_NOR_FAILED_TO_VERIFY_DATA( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 index, /*!< The index*/ const U32 dest_addr, /*!< The destination address*/ const U8 source /*!< The data to be written*/ ) const; protected: // ---------------------------------------------------------------------- // Event: NOR_UNLOCK_BYPASS_RESET_DURING_ERASE // ---------------------------------------------------------------------- void assertEvents_NOR_UNLOCK_BYPASS_RESET_DURING_ERASE_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; protected: // ---------------------------------------------------------------------- // Event: NOR_FAILED_TO_RESET // ---------------------------------------------------------------------- void assertEvents_NOR_FAILED_TO_RESET_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; protected: // ---------------------------------------------------------------------- // Event: NOR_WRITE_TIMEOUT // ---------------------------------------------------------------------- void assertEvents_NOR_WRITE_TIMEOUT_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; protected: // ---------------------------------------------------------------------- // Event: NOR_FAILED_TO_VERIFY_CHECKSUM // ---------------------------------------------------------------------- void assertEvents_NOR_FAILED_TO_VERIFY_CHECKSUM_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; protected: // ---------------------------------------------------------------------- // Event: NOR_CHECKSUM_VERIFY_DONE // ---------------------------------------------------------------------- void assertEvents_NOR_CHECKSUM_VERIFY_DONE_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; protected: // ---------------------------------------------------------------------- // Event: NOR_VERIFY_BUSY // ---------------------------------------------------------------------- void assertEvents_NOR_VERIFY_BUSY_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; void assertEvents_NOR_VERIFY_BUSY( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 index, /*!< The index*/ const U32 actual_state, /*!< The state of the NOR Manager*/ const U32 expected_state /*!< The expected state of the NOR Manager*/ ) const; protected: // ---------------------------------------------------------------------- // Event: NOR_FAILED_TO_READ_DATA // ---------------------------------------------------------------------- void assertEvents_NOR_FAILED_TO_READ_DATA_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; void assertEvents_NOR_FAILED_TO_READ_DATA( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 index, /*!< The index*/ const U32 nor_addr, /*!< The address in NOR to read from*/ const U32 dest /*!< The memory buffer address use to store the value of nor_addr*/ ) const; protected: // ---------------------------------------------------------------------- // Event: NOR_READ_TIMEOUT // ---------------------------------------------------------------------- void assertEvents_NOR_READ_TIMEOUT_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; protected: // ---------------------------------------------------------------------- // Event: NOR_ALREADY_ERASING // ---------------------------------------------------------------------- void assertEvents_NOR_ALREADY_ERASING_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; protected: // ---------------------------------------------------------------------- // From ports // ---------------------------------------------------------------------- void assertFromPortHistory_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; protected: // ---------------------------------------------------------------------- // From port: PingResponse // ---------------------------------------------------------------------- void assert_from_PingResponse_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; protected: // ---------------------------------------------------------------------- // From port: verification_done // ---------------------------------------------------------------------- void assert_from_verification_done_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; protected: // ---------------------------------------------------------------------- // From port: erase_done // ---------------------------------------------------------------------- void assert_from_erase_done_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; protected: // ---------------------------------------------------------------------- // From port: read_done // ---------------------------------------------------------------------- void assert_from_read_done_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; protected: // ---------------------------------------------------------------------- // From port: worker_verify // ---------------------------------------------------------------------- void assert_from_worker_verify_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; protected: // ---------------------------------------------------------------------- // From port: worker_write // ---------------------------------------------------------------------- void assert_from_worker_write_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; protected: // ---------------------------------------------------------------------- // From port: write_done // ---------------------------------------------------------------------- void assert_from_write_done_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; protected: // ---------------------------------------------------------------------- // From port: worker_erase // ---------------------------------------------------------------------- void assert_from_worker_erase_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; protected: // ---------------------------------------------------------------------- // From port: worker_cancel // ---------------------------------------------------------------------- void assert_from_worker_cancel_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; protected: // ---------------------------------------------------------------------- // From port: worker_reset // ---------------------------------------------------------------------- void assert_from_worker_reset_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; protected: // ---------------------------------------------------------------------- // From port: worker_read // ---------------------------------------------------------------------- void assert_from_worker_read_size( const char *const __ISF_callSiteFileName, /*!< The name of the file containing the call site*/ const U32 __ISF_callSiteLineNumber, /*!< The line number of the call site*/ const U32 size /*!< The asserted size*/ ) const; }; } // end namespace Drv #endif
41.975962
138
0.52876
Joshua-Anderson
bf3811fe55009c277d36d4d3204576c8526d5198
28,229
cpp
C++
PopcornTime_Desktop-src/Import/QtAV/src/codec/video/VideoDecoderD3D.cpp
officialrafsan/POPCORNtime
b5bc452b10d7b46c2f4978e37d7fd2e9c0f75782
[ "MIT" ]
null
null
null
PopcornTime_Desktop-src/Import/QtAV/src/codec/video/VideoDecoderD3D.cpp
officialrafsan/POPCORNtime
b5bc452b10d7b46c2f4978e37d7fd2e9c0f75782
[ "MIT" ]
null
null
null
PopcornTime_Desktop-src/Import/QtAV/src/codec/video/VideoDecoderD3D.cpp
officialrafsan/POPCORNtime
b5bc452b10d7b46c2f4978e37d7fd2e9c0f75782
[ "MIT" ]
null
null
null
/****************************************************************************** QtAV: Media play library based on Qt and FFmpeg Copyright (C) 2012-2016 Wang Bin <wbsecg1@gmail.com> * This file is part of QtAV (from 2016) 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ******************************************************************************/ #include "VideoDecoderD3D.h" #include <initguid.h> /* must be last included to not redefine existing GUIDs */ #if (FF_PROFILE_HEVC_MAIN == -1) //libav does not define it #ifdef _MSC_VER #pragma message("HEVC will not be supported. Update your FFmpeg") #else #warning "HEVC will not be supported. Update your FFmpeg" #endif #endif namespace QtAV { static bool check_ffmpeg_hevc_dxva2() { avcodec_register_all(); AVHWAccel *hwa = av_hwaccel_next(0); while (hwa) { if (strncmp("hevc_dxva2", hwa->name, 10) == 0) return true; if (strncmp("hevc_d3d11va", hwa->name, 12) == 0) return true; hwa = av_hwaccel_next(hwa); } return false; } bool isHEVCSupported() { static const bool support_hevc = check_ffmpeg_hevc_dxva2(); return support_hevc; } // some MS_GUID are defined in mingw but some are not. move to namespace and define all is ok #define MS_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ static const GUID name = { l, w1, w2, {b1, b2, b3, b4, b5, b6, b7, b8}} MS_GUID (DXVA_NoEncrypt, 0x1b81bed0, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); /* Codec capabilities GUID, sorted by codec */ MS_GUID (DXVA2_ModeMPEG2_MoComp, 0xe6a9f44b, 0x61b0, 0x4563, 0x9e, 0xa4, 0x63, 0xd2, 0xa3, 0xc6, 0xfe, 0x66); MS_GUID (DXVA2_ModeMPEG2_IDCT, 0xbf22ad00, 0x03ea, 0x4690, 0x80, 0x77, 0x47, 0x33, 0x46, 0x20, 0x9b, 0x7e); MS_GUID (DXVA2_ModeMPEG2_VLD, 0xee27417f, 0x5e28, 0x4e65, 0xbe, 0xea, 0x1d, 0x26, 0xb5, 0x08, 0xad, 0xc9); DEFINE_GUID(DXVA_ModeMPEG1_A, 0x1b81be09, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); DEFINE_GUID(DXVA_ModeMPEG2_A, 0x1b81be0A, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); DEFINE_GUID(DXVA_ModeMPEG2_B, 0x1b81be0B, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); DEFINE_GUID(DXVA_ModeMPEG2_C, 0x1b81be0C, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); DEFINE_GUID(DXVA_ModeMPEG2_D, 0x1b81be0D, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); DEFINE_GUID(DXVA2_ModeMPEG2and1_VLD, 0x86695f12, 0x340e, 0x4f04, 0x9f, 0xd3, 0x92, 0x53, 0xdd, 0x32, 0x74, 0x60); DEFINE_GUID(DXVA2_ModeMPEG1_VLD, 0x6f3ec719, 0x3735, 0x42cc, 0x80, 0x63, 0x65, 0xcc, 0x3c, 0xb3, 0x66, 0x16); MS_GUID (DXVA2_ModeH264_A, 0x1b81be64, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); MS_GUID (DXVA2_ModeH264_B, 0x1b81be65, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); MS_GUID (DXVA2_ModeH264_C, 0x1b81be66, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); MS_GUID (DXVA2_ModeH264_D, 0x1b81be67, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); MS_GUID (DXVA2_ModeH264_E, 0x1b81be68, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); MS_GUID (DXVA2_ModeH264_F, 0x1b81be69, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); DEFINE_GUID(DXVA_ModeH264_VLD_Multiview, 0x9901CCD3, 0xca12, 0x4b7e, 0x86, 0x7a, 0xe2, 0x22, 0x3d, 0x92, 0x55, 0xc3); // MVC DEFINE_GUID(DXVA_ModeH264_VLD_WithFMOASO_NoFGT, 0xd5f04ff9, 0x3418, 0x45d8, 0x95, 0x61, 0x32, 0xa7, 0x6a, 0xae, 0x2d, 0xdd); DEFINE_GUID(DXVADDI_Intel_ModeH264_A, 0x604F8E64, 0x4951, 0x4c54, 0x88, 0xFE, 0xAB, 0xD2, 0x5C, 0x15, 0xB3, 0xD6); DEFINE_GUID(DXVADDI_Intel_ModeH264_C, 0x604F8E66, 0x4951, 0x4c54, 0x88, 0xFE, 0xAB, 0xD2, 0x5C, 0x15, 0xB3, 0xD6); DEFINE_GUID(DXVA_Intel_H264_NoFGT_ClearVideo, 0x604F8E68, 0x4951, 0x4c54, 0x88, 0xFE, 0xAB, 0xD2, 0x5C, 0x15, 0xB3, 0xD6); DEFINE_GUID(DXVA_ModeH264_VLD_NoFGT_Flash, 0x4245F676, 0x2BBC, 0x4166, 0xa0, 0xBB, 0x54, 0xE7, 0xB8, 0x49, 0xC3, 0x80); MS_GUID (DXVA2_ModeWMV8_A, 0x1b81be80, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); MS_GUID (DXVA2_ModeWMV8_B, 0x1b81be81, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); MS_GUID (DXVA2_ModeWMV9_A, 0x1b81be90, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); MS_GUID (DXVA2_ModeWMV9_B, 0x1b81be91, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); MS_GUID (DXVA2_ModeWMV9_C, 0x1b81be94, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); MS_GUID (DXVA2_ModeVC1_A, 0x1b81beA0, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); MS_GUID (DXVA2_ModeVC1_B, 0x1b81beA1, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); MS_GUID (DXVA2_ModeVC1_C, 0x1b81beA2, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); MS_GUID (DXVA2_ModeVC1_D, 0x1b81beA3, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); DEFINE_GUID(DXVA2_ModeVC1_D2010, 0x1b81beA4, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); // August 2010 update DEFINE_GUID(DXVA_Intel_VC1_ClearVideo, 0xBCC5DB6D, 0xA2B6, 0x4AF0, 0xAC, 0xE4, 0xAD, 0xB1, 0xF7, 0x87, 0xBC, 0x89); DEFINE_GUID(DXVA_Intel_VC1_ClearVideo_2, 0xE07EC519, 0xE651, 0x4CD6, 0xAC, 0x84, 0x13, 0x70, 0xCC, 0xEE, 0xC8, 0x51); DEFINE_GUID(DXVA_nVidia_MPEG4_ASP, 0x9947EC6F, 0x689B, 0x11DC, 0xA3, 0x20, 0x00, 0x19, 0xDB, 0xBC, 0x41, 0x84); DEFINE_GUID(DXVA_ModeMPEG4pt2_VLD_Simple, 0xefd64d74, 0xc9e8, 0x41d7, 0xa5, 0xe9, 0xe9, 0xb0, 0xe3, 0x9f, 0xa3, 0x19); DEFINE_GUID(DXVA_ModeMPEG4pt2_VLD_AdvSimple_NoGMC, 0xed418a9f, 0x010d, 0x4eda, 0x9a, 0xe3, 0x9a, 0x65, 0x35, 0x8d, 0x8d, 0x2e); DEFINE_GUID(DXVA_ModeMPEG4pt2_VLD_AdvSimple_GMC, 0xab998b5b, 0x4258, 0x44a9, 0x9f, 0xeb, 0x94, 0xe5, 0x97, 0xa6, 0xba, 0xae); DEFINE_GUID(DXVA_ModeMPEG4pt2_VLD_AdvSimple_Avivo, 0x7C74ADC6, 0xe2ba, 0x4ade, 0x86, 0xde, 0x30, 0xbe, 0xab, 0xb4, 0x0c, 0xc1); DEFINE_GUID(DXVA_ModeHEVC_VLD_Main, 0x5b11d51b, 0x2f4c, 0x4452,0xbc,0xc3,0x09,0xf2,0xa1,0x16,0x0c,0xc0); DEFINE_GUID(DXVA_ModeHEVC_VLD_Main10, 0x107af0e0, 0xef1a, 0x4d19,0xab,0xa8,0x67,0xa1,0x63,0x07,0x3d,0x13); DEFINE_GUID(DXVA_ModeH264_VLD_Stereo_Progressive_NoFGT, 0xd79be8da, 0x0cf1, 0x4c81,0xb8,0x2a,0x69,0xa4,0xe2,0x36,0xf4,0x3d); DEFINE_GUID(DXVA_ModeH264_VLD_Stereo_NoFGT, 0xf9aaccbb, 0xc2b6, 0x4cfc,0x87,0x79,0x57,0x07,0xb1,0x76,0x05,0x52); DEFINE_GUID(DXVA_ModeH264_VLD_Multiview_NoFGT, 0x705b9d82, 0x76cf, 0x49d6,0xb7,0xe6,0xac,0x88,0x72,0xdb,0x01,0x3c); DEFINE_GUID(DXVA_ModeH264_VLD_SVC_Scalable_Baseline, 0xc30700c4, 0xe384, 0x43e0, 0xb9, 0x82, 0x2d, 0x89, 0xee, 0x7f, 0x77, 0xc4); DEFINE_GUID(DXVA_ModeH264_VLD_SVC_Restricted_Scalable_Baseline, 0x9b8175d4, 0xd670, 0x4cf2, 0xa9, 0xf0, 0xfa, 0x56, 0xdf, 0x71, 0xa1, 0xae); DEFINE_GUID(DXVA_ModeH264_VLD_SVC_Scalable_High, 0x728012c9, 0x66a8, 0x422f, 0x97, 0xe9, 0xb5, 0xe3, 0x9b, 0x51, 0xc0, 0x53); DEFINE_GUID(DXVA_ModeH264_VLD_SVC_Restricted_Scalable_High_Progressive, 0x8efa5926, 0xbd9e, 0x4b04, 0x8b, 0x72, 0x8f, 0x97, 0x7d, 0xc4, 0x4c, 0x36); DEFINE_GUID(DXVA_ModeH261_A, 0x1b81be01, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); DEFINE_GUID(DXVA_ModeH261_B, 0x1b81be02, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); DEFINE_GUID(DXVA_ModeH263_A, 0x1b81be03, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); DEFINE_GUID(DXVA_ModeH263_B, 0x1b81be04, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); DEFINE_GUID(DXVA_ModeH263_C, 0x1b81be05, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); DEFINE_GUID(DXVA_ModeH263_D, 0x1b81be06, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); DEFINE_GUID(DXVA_ModeH263_E, 0x1b81be07, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); DEFINE_GUID(DXVA_ModeH263_F, 0x1b81be08, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); static const int PROF_MPEG2_SIMPLE[] = { FF_PROFILE_MPEG2_SIMPLE, 0 }; static const int PROF_MPEG2_MAIN[] = { FF_PROFILE_MPEG2_SIMPLE, FF_PROFILE_MPEG2_MAIN, 0 }; static const int PROF_H264_HIGH[] = { FF_PROFILE_H264_CONSTRAINED_BASELINE, FF_PROFILE_H264_MAIN, FF_PROFILE_H264_HIGH, 0 }; static const int PROF_HEVC_MAIN[] = { FF_PROFILE_HEVC_MAIN, 0 }; static const int PROF_HEVC_MAIN10[] = { FF_PROFILE_HEVC_MAIN, FF_PROFILE_HEVC_MAIN_10, 0 }; // guids are from VLC struct dxva2_mode_t { const char *name; const GUID *guid; int codec; const int *profiles; }; /* XXX Prefered modes must come first */ static const dxva2_mode_t dxva2_modes[] = { /* MPEG-1/2 */ { "MPEG-1 decoder, restricted profile A", &DXVA_ModeMPEG1_A, 0, NULL }, { "MPEG-2 decoder, restricted profile A", &DXVA_ModeMPEG2_A, 0, NULL }, { "MPEG-2 decoder, restricted profile B", &DXVA_ModeMPEG2_B, 0, NULL }, { "MPEG-2 decoder, restricted profile C", &DXVA_ModeMPEG2_C, 0, NULL }, { "MPEG-2 decoder, restricted profile D", &DXVA_ModeMPEG2_D, 0, NULL }, { "MPEG-2 variable-length decoder", &DXVA2_ModeMPEG2_VLD, QTAV_CODEC_ID(MPEG2VIDEO), PROF_MPEG2_SIMPLE }, { "MPEG-2 & MPEG-1 variable-length decoder", &DXVA2_ModeMPEG2and1_VLD, QTAV_CODEC_ID(MPEG2VIDEO), PROF_MPEG2_MAIN }, { "MPEG-2 & MPEG-1 variable-length decoder", &DXVA2_ModeMPEG2and1_VLD, QTAV_CODEC_ID(MPEG1VIDEO), NULL }, { "MPEG-2 motion compensation", &DXVA2_ModeMPEG2_MoComp, 0, NULL }, { "MPEG-2 inverse discrete cosine transform", &DXVA2_ModeMPEG2_IDCT, 0, NULL }, /* MPEG-1 http://download.microsoft.com/download/B/1/7/B172A3C8-56F2-4210-80F1-A97BEA9182ED/DXVA_MPEG1_VLD.pdf */ { "MPEG-1 variable-length decoder, no D pictures", &DXVA2_ModeMPEG1_VLD, 0, NULL }, /* H.264 http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=3d1c290b-310b-4ea2-bf76-714063a6d7a6 */ { "H.264 variable-length decoder, film grain technology", &DXVA2_ModeH264_F, QTAV_CODEC_ID(H264), PROF_H264_HIGH }, { "H.264 variable-length decoder, no film grain technology (Intel ClearVideo)", &DXVA_Intel_H264_NoFGT_ClearVideo, QTAV_CODEC_ID(H264), PROF_H264_HIGH }, { "H.264 variable-length decoder, no film grain technology", &DXVA2_ModeH264_E, QTAV_CODEC_ID(H264), PROF_H264_HIGH }, { "H.264 variable-length decoder, no film grain technology, FMO/ASO", &DXVA_ModeH264_VLD_WithFMOASO_NoFGT, QTAV_CODEC_ID(H264), PROF_H264_HIGH }, { "H.264 variable-length decoder, no film grain technology, Flash", &DXVA_ModeH264_VLD_NoFGT_Flash, QTAV_CODEC_ID(H264), PROF_H264_HIGH }, { "H.264 inverse discrete cosine transform, film grain technology", &DXVA2_ModeH264_D, 0, NULL }, { "H.264 inverse discrete cosine transform, no film grain technology", &DXVA2_ModeH264_C, 0, NULL }, { "H.264 inverse discrete cosine transform, no film grain technology (Intel)", &DXVADDI_Intel_ModeH264_C, 0, NULL }, { "H.264 motion compensation, film grain technology", &DXVA2_ModeH264_B, 0, NULL }, { "H.264 motion compensation, no film grain technology", &DXVA2_ModeH264_A, 0, NULL }, { "H.264 motion compensation, no film grain technology (Intel)", &DXVADDI_Intel_ModeH264_A, 0, NULL }, /* http://download.microsoft.com/download/2/D/0/2D02E72E-7890-430F-BA91-4A363F72F8C8/DXVA_H264_MVC.pdf */ { "H.264 stereo high profile, mbs flag set", &DXVA_ModeH264_VLD_Stereo_Progressive_NoFGT, 0, NULL }, { "H.264 stereo high profile", &DXVA_ModeH264_VLD_Stereo_NoFGT, 0, NULL }, { "H.264 multiview high profile", &DXVA_ModeH264_VLD_Multiview_NoFGT, 0, NULL }, /* SVC http://download.microsoft.com/download/C/8/A/C8AD9F1B-57D1-4C10-85A0-09E3EAC50322/DXVA_SVC_2012_06.pdf */ { "H.264 scalable video coding, Scalable Baseline Profile", &DXVA_ModeH264_VLD_SVC_Scalable_Baseline, 0, NULL }, { "H.264 scalable video coding, Scalable Constrained Baseline Profile", &DXVA_ModeH264_VLD_SVC_Restricted_Scalable_Baseline, 0, NULL }, { "H.264 scalable video coding, Scalable High Profile", &DXVA_ModeH264_VLD_SVC_Scalable_High, 0, NULL }, { "H.264 scalable video coding, Scalable Constrained High Profile", &DXVA_ModeH264_VLD_SVC_Restricted_Scalable_High_Progressive, 0, NULL }, /* WMV */ { "Windows Media Video 8 motion compensation", &DXVA2_ModeWMV8_B, 0, NULL }, { "Windows Media Video 8 post processing", &DXVA2_ModeWMV8_A, 0, NULL }, { "Windows Media Video 9 IDCT", &DXVA2_ModeWMV9_C, 0, NULL }, { "Windows Media Video 9 motion compensation", &DXVA2_ModeWMV9_B, 0, NULL }, { "Windows Media Video 9 post processing", &DXVA2_ModeWMV9_A, 0, NULL }, /* VC-1 */ { "VC-1 variable-length decoder", &DXVA2_ModeVC1_D, QTAV_CODEC_ID(VC1), NULL }, { "VC-1 variable-length decoder", &DXVA2_ModeVC1_D, QTAV_CODEC_ID(WMV3), NULL }, { "VC-1 variable-length decoder", &DXVA2_ModeVC1_D2010, QTAV_CODEC_ID(VC1), NULL }, { "VC-1 variable-length decoder", &DXVA2_ModeVC1_D2010, QTAV_CODEC_ID(WMV3), NULL }, { "VC-1 variable-length decoder 2 (Intel)", &DXVA_Intel_VC1_ClearVideo_2, 0, NULL }, { "VC-1 variable-length decoder (Intel)", &DXVA_Intel_VC1_ClearVideo, 0, NULL }, { "VC-1 inverse discrete cosine transform", &DXVA2_ModeVC1_C, 0, NULL }, { "VC-1 motion compensation", &DXVA2_ModeVC1_B, 0, NULL }, { "VC-1 post processing", &DXVA2_ModeVC1_A, 0, NULL }, /* Xvid/Divx: TODO */ { "MPEG-4 Part 2 nVidia bitstream decoder", &DXVA_nVidia_MPEG4_ASP, 0, NULL }, { "MPEG-4 Part 2 variable-length decoder, Simple Profile", &DXVA_ModeMPEG4pt2_VLD_Simple, 0, NULL }, { "MPEG-4 Part 2 variable-length decoder, Simple&Advanced Profile, no GMC", &DXVA_ModeMPEG4pt2_VLD_AdvSimple_NoGMC, 0, NULL }, { "MPEG-4 Part 2 variable-length decoder, Simple&Advanced Profile, GMC", &DXVA_ModeMPEG4pt2_VLD_AdvSimple_GMC, 0, NULL }, { "MPEG-4 Part 2 variable-length decoder, Simple&Advanced Profile, Avivo", &DXVA_ModeMPEG4pt2_VLD_AdvSimple_Avivo, 0, NULL }, /* HEVC */ { "HEVC Main profile", &DXVA_ModeHEVC_VLD_Main, QTAV_CODEC_ID(HEVC), PROF_HEVC_MAIN }, { "HEVC Main 10 profile", &DXVA_ModeHEVC_VLD_Main10, QTAV_CODEC_ID(HEVC), PROF_HEVC_MAIN10 }, /* H.261 */ { "H.261 decoder, restricted profile A", &DXVA_ModeH261_A, 0, NULL }, { "H.261 decoder, restricted profile B", &DXVA_ModeH261_B, 0, NULL }, /* H.263 */ { "H.263 decoder, restricted profile A", &DXVA_ModeH263_A, 0, NULL }, { "H.263 decoder, restricted profile B", &DXVA_ModeH263_B, 0, NULL }, { "H.263 decoder, restricted profile C", &DXVA_ModeH263_C, 0, NULL }, { "H.263 decoder, restricted profile D", &DXVA_ModeH263_D, 0, NULL }, { "H.263 decoder, restricted profile E", &DXVA_ModeH263_E, 0, NULL }, { "H.263 decoder, restricted profile F", &DXVA_ModeH263_F, 0, NULL }, { NULL, NULL, 0, NULL } }; static const dxva2_mode_t *Dxva2FindMode(const GUID *guid) { for (unsigned i = 0; dxva2_modes[i].name; i++) { if (IsEqualGUID(*dxva2_modes[i].guid, *guid)) return &dxva2_modes[i]; } return NULL; } bool isIntelClearVideo(const GUID *guid) { return IsEqualGUID(*guid, DXVA_Intel_H264_NoFGT_ClearVideo); } bool isNoEncrypt(const GUID *guid) { return IsEqualGUID(*guid, DXVA_NoEncrypt); } bool checkProfile(const dxva2_mode_t *mode, int profile) { if (!mode->profiles || !mode->profiles[0] || profile <= 0) return true; for (const int *p = &mode->profiles[0]; *p; ++p) { if (*p == profile) return true; } return false; } /* XXX Prefered format must come first */ //16-bit: https://msdn.microsoft.com/en-us/library/windows/desktop/bb970578(v=vs.85).aspx static const d3d_format_t d3d_formats[] = { { "NV12", MAKEFOURCC('N','V','1','2'), VideoFormat::Format_NV12 }, { "YV12", MAKEFOURCC('Y','V','1','2'), VideoFormat::Format_YUV420P }, { "IMC3", MAKEFOURCC('I','M','C','3'), VideoFormat::Format_YUV420P }, { "P010", MAKEFOURCC('P','0','1','0'), VideoFormat::Format_YUV420P10LE }, { "P016", MAKEFOURCC('P','0','1','6'), VideoFormat::Format_YUV420P16LE }, //FIXME: { NULL, 0, VideoFormat::Format_Invalid } }; static const d3d_format_t *D3dFindFormat(int fourcc) { for (unsigned i = 0; d3d_formats[i].name; i++) { if (d3d_formats[i].fourcc == fourcc) return &d3d_formats[i]; } return NULL; } VideoFormat::PixelFormat pixelFormatFromFourcc(int format) { const d3d_format_t *fmt = D3dFindFormat(format); if (fmt) return fmt->pixfmt; return VideoFormat::Format_Invalid; } int getSupportedFourcc(int *formats, UINT nb_formats) { for (const int *f = formats; f < &formats[nb_formats]; ++f) { const d3d_format_t *format = D3dFindFormat(*f); if (format) { qDebug("%s is supported for output", format->name); } else { qDebug("%d is supported for output (%4.4s)", *f, (const char*)f); } } for (const d3d_format_t *format = d3d_formats; format->name; ++format) { bool is_supported = false; for (unsigned k = 0; !is_supported && k < nb_formats; k++) { if (format->fourcc == formats[k]) return format->fourcc; } } return 0; } VideoDecoderD3D::VideoDecoderD3D(VideoDecoderD3DPrivate &d) : VideoDecoderFFmpegHW(d) { // dynamic properties about static property details. used by UI // format: detail_property setProperty("detail_surfaces", tr("Decoding surfaces") + QStringLiteral(" ") + tr("0: auto")); setProperty("threads", 1); //FIXME: mt crash on close } void VideoDecoderD3D::setSurfaces(int num) { DPTR_D(VideoDecoderD3D); if (d.surface_count == num) return; d.surface_count = num; d.surface_auto = num <= 0; Q_EMIT surfacesChanged(); } int VideoDecoderD3D::surfaces() const { return d_func().surface_count; } VideoDecoderD3DPrivate::VideoDecoderD3DPrivate() : VideoDecoderFFmpegHWPrivate() , surface_auto(true) , surface_count(0) , surface_width(0) , surface_height(0) , surface_order(0) { } bool VideoDecoderD3DPrivate::open() { if (!prepare()) return false; if (codec_ctx->codec_id == QTAV_CODEC_ID(HEVC)) { // runtime hevc check if (!isHEVCSupported()) { qWarning("HEVC DXVA2/D3D11VA is not supported by current FFmpeg runtime."); return false; } } if (!createDevice()) return false; format_fcc = 0; QVector<GUID> codecs = getSupportedCodecs(); const d3d_format_t *fmt = getFormat(codec_ctx, codecs, &codec_guid); if (!fmt) return false; format_fcc = fmt->fourcc; if (!setupSurfaceInterop()) return false; return true; } void VideoDecoderD3DPrivate::close() { qDeleteAll(surfaces); surfaces.clear(); restore(); releaseUSWC(); destroyDecoder(); destroyDevice(); } void* VideoDecoderD3DPrivate::setup(AVCodecContext *avctx) { const int w = codedWidth(avctx); const int h = codedHeight(avctx); width = avctx->width; // not necessary. set in decode() height = avctx->height; releaseUSWC(); destroyDecoder(); /* Allocates all surfaces needed for the decoder */ if (surface_auto) { switch (codec_ctx->codec_id) { case QTAV_CODEC_ID(HEVC): case QTAV_CODEC_ID(H264): surface_count = 16 + 4; break; case QTAV_CODEC_ID(MPEG1VIDEO): case QTAV_CODEC_ID(MPEG2VIDEO): surface_count = 2 + 4; default: surface_count = 2 + 4; break; } if (avctx->active_thread_type & FF_THREAD_FRAME) surface_count += avctx->thread_count; } qDebug(">>>>>>>>>>>>>>>>>>>>>surfaces: %d, active_thread_type: %d, threads: %d, refs: %d", surface_count, avctx->active_thread_type, avctx->thread_count, avctx->refs); if (surface_count == 0) { qWarning("internal error: wrong surface count. %u auto=%d", surface_count, surface_auto); surface_count = 16 + 4; } qDeleteAll(surfaces); surfaces.clear(); hw_surfaces.clear(); surfaces.resize(surface_count); if (!createDecoder(codec_ctx->codec_id, w, h, surfaces)) return NULL; hw_surfaces.resize(surface_count); for (int i = 0; i < surfaces.size(); ++i) { hw_surfaces[i] = surfaces[i]->getSurface(); } surface_order = 0; surface_width = aligned(w); surface_height = aligned(h); initUSWC(surface_width); return setupAVVAContext(); //can not use codec_ctx for threaded mode! } /* FIXME it is nearly common with VAAPI */ bool VideoDecoderD3DPrivate::getBuffer(void **opaque, uint8_t **data)//vlc_va_t *external, AVFrame *ff) { if (!checkDevice()) return false; /* Grab an unused surface, in case none are, try the oldest * XXX using the oldest is a workaround in case a problem happens with libavcodec */ int i, old; for (i = 0, old = 0; i < surfaces.size(); i++) { const va_surface_t *s = surfaces[i]; if (!s->ref) break; if (s->order < surfaces[old]->order) old = i; } if (i >= surfaces.size()) i = old; va_surface_t *s = surfaces[i]; s->ref = 1; s->order = surface_order++; *data = (uint8_t*)s->getSurface(); *opaque = s; return true; } void VideoDecoderD3DPrivate::releaseBuffer(void *opaque, uint8_t *data) { Q_UNUSED(data); va_surface_t *surface = (va_surface_t*)opaque; surface->ref--; } int VideoDecoderD3DPrivate::aligned(int x) { // from lavfilters int align = 16; // MPEG-2 needs higher alignment on Intel cards, and it doesn't seem to harm anything to do it for all cards. if (codec_ctx->codec_id == QTAV_CODEC_ID(MPEG2VIDEO)) align <<= 1; else if (codec_ctx->codec_id == QTAV_CODEC_ID(HEVC)) align = 128; return FFALIGN(x, align); } const d3d_format_t* VideoDecoderD3DPrivate::getFormat(const AVCodecContext *avctx, const QVector<GUID> &guids, GUID* selected) const { foreach (const GUID& g, guids) { const dxva2_mode_t *mode = Dxva2FindMode(&g); if (mode) { qDebug("- '%s' is supported by hardware", mode->name); } else { qDebug("- Unknown GUID = %08X-%04x-%04x-%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x", (unsigned)g.Data1, g.Data2, g.Data3 , g.Data4[0], g.Data4[1] , g.Data4[2], g.Data4[3], g.Data4[4], g.Data4[5], g.Data4[6], g.Data4[7]); } } /* Try all supported mode by our priority */ const dxva2_mode_t *mode = dxva2_modes; for (; mode->name; ++mode) { if (!mode->codec || mode->codec != avctx->codec_id) { qDebug("codec does not match to %s: %s", avcodec_get_name(avctx->codec_id), avcodec_get_name((AVCodecID)mode->codec)); continue; } qDebug("D3D found codec: %s. Check runtime support for the codec.", mode->name); bool is_supported = false; //TODO: find_if foreach (const GUID& g, guids) { if (IsEqualGUID(*mode->guid, g)) { is_supported = true; break; } } if (is_supported) { qDebug("Check profile support: %s", AVDecoderPrivate::getProfileName(avctx)); is_supported = checkProfile(mode, avctx->profile); } if (!is_supported) continue; int dxfmt = fourccFor(mode->guid); if (!dxfmt) continue; if (selected) *selected = *mode->guid; return D3dFindFormat(dxfmt); } return NULL; } } //namespace QtAV
54.813592
173
0.5878
officialrafsan
bf3a86e73fa188e47dd02228543cf2c407f5b2b9
1,173
cpp
C++
HDU/HDU-1009-FatMouse_Trade.cpp
ZubinGou/leetcode
25ac47a5406af04adbc69482afe0acc2abba25ca
[ "Apache-2.0" ]
1
2021-08-04T00:52:30.000Z
2021-08-04T00:52:30.000Z
HDU/HDU-1009-FatMouse_Trade.cpp
ZubinGou/leetcode
25ac47a5406af04adbc69482afe0acc2abba25ca
[ "Apache-2.0" ]
null
null
null
HDU/HDU-1009-FatMouse_Trade.cpp
ZubinGou/leetcode
25ac47a5406af04adbc69482afe0acc2abba25ca
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <vector> #include <stack> #include <queue> #include <map> // #include <unordered_map> // can't compile on poj #include <algorithm> #include <cstring> #include <climits> using namespace std; typedef pair<double, double> JK; vector<JK> room; bool cmp(JK a, JK b) { return a.first / a.second > b.first / b.second; } int main() { double cat_food; int n; while (scanf("%lf %d", &cat_food, &n) != EOF) { if (cat_food == -1 && n == -1) break; room.clear(); for (int i = 0; i < n; i++) { room.push_back({0, 0}); scanf("%lf %lf", &room[i].first, &room[i].second); } sort(room.begin(), room.end(), cmp); int i = 0; double res = 0; for (int i = 0; i < n; i++) { if (cat_food >= room[i].second) { res += room[i].first; cat_food -= room[i].second; } else { res += cat_food * room[i].first / room[i].second; break; } } printf("%.3f\n", res); } return 0; }
20.946429
65
0.456948
ZubinGou
bf3b8ab62f69b53fc82fac1f5648f17b75332d14
27,400
cpp
C++
src/font/ttf.cpp
jjbandit/bonsai
f6073484c14178aff6925eaf8caddf349174b27d
[ "WTFPL" ]
13
2017-04-12T16:26:46.000Z
2022-03-01T22:04:34.000Z
src/font/ttf.cpp
jjbandit/bonsai
f6073484c14178aff6925eaf8caddf349174b27d
[ "WTFPL" ]
null
null
null
src/font/ttf.cpp
jjbandit/bonsai
f6073484c14178aff6925eaf8caddf349174b27d
[ "WTFPL" ]
null
null
null
#include <bonsai_types.h> global_variable v4 White = V4(1,1,1,0); global_variable v4 Black = {}; global_variable v4 Red = V4(1,0,0,0); global_variable v4 Blue = V4(0,0,1,0); global_variable v4 Pink = V4(1,0,1,0); global_variable v4 Green = V4(0,1,0,0); global_variable u32 PackedWhite = PackRGBALinearTo255(White ); global_variable u32 PackedBlack = PackRGBALinearTo255(Black ); global_variable u32 PackedRed = PackRGBALinearTo255(Red ); global_variable u32 PackedBlue = PackRGBALinearTo255(Blue ); global_variable u32 PackedPink = PackRGBALinearTo255(Pink ); global_variable u32 PackedGreen = PackRGBALinearTo255(Green ); inline u8 ReadU8(u8* Source) { u8 Result = Source[0]; return Result; } inline s16 ReadS16(s16* Source) { s16 Result = (((u8*)Source)[0]*256) + ((u8*)Source)[1]; return Result; } inline s16 ReadS16(u8* Source) { s16 Result = (Source[0]*256) + Source[1]; return Result; } inline u16 ReadU16(u16* Source) { u16 Result = (((u8*)Source)[0]*256) + ((u8*)Source)[1]; return Result; } inline u16 ReadU16(u8* Source) { u16 Result = (Source[0]*256) + Source[1]; return Result; } inline s64 ReadS64(u8* Source) { s64 Result = (s64)( ((u64)Source[0]<<56) + ((u64)Source[1]<<48) + ((u64)Source[2]<<40) + ((u64)Source[3]<<32) + ((u64)Source[4]<<24) + ((u64)Source[5]<<16) + ((u64)Source[6]<<8) + ((u64)Source[7]) ); return Result; } inline u32 ReadU32(u8* Source) { u32 Result = (u32)( (Source[0]<<24) + (Source[1]<<16) + (Source[2]<<8) + Source[3] ); return Result; } inline u8* ReadU8Array(u8_stream *Source, u32 Count) { u8 *Result = Source->At; Source->At += Count; Assert(Source->At <= Source->End); return Result; } inline u16* ReadU16Array(u8_stream *Source, u32 Count) { u16 *Result = (u16*)Source->At; Source->At += sizeof(u16)*Count; Assert(Source->At <= Source->End); return Result; } inline s16* ReadS16Array(u8_stream *Source, u32 Count) { s16 *Result = (s16*)Source->At; Source->At += sizeof(s16)*Count; Assert(Source->At <= Source->End); return Result; } inline u8 ReadU8(u8_stream *Source) { u8 Result = ReadU8(Source->At); Source->At += sizeof(u8); Assert(Source->At <= Source->End); return Result; } inline s16 ReadS16(u8_stream *Source) { s16 Result = ReadS16(Source->At); Source->At += sizeof(s16); Assert(Source->At <= Source->End); return Result; } inline u16 ReadU16(u8_stream *Source) { u16 Result = ReadU16(Source->At); Source->At += sizeof(u16); Assert(Source->At <= Source->End); return Result; } inline s64 ReadS64(u8_stream *Source) { s64 Result = ReadS64(Source->At); Source->At += sizeof(s64); Assert(Source->At <= Source->End); return Result; } inline u32 ReadU32(u8_stream *Source) { u32 Result = ReadU32(Source->At); Source->At += sizeof(u32); Assert(Source->At <= Source->End); return Result; } struct head_table { // Technically the spec says these are 32bit fixed point numbers, but IDC // because I never use them u32 Version; u32 FontRevision; u32 ChecksumAdjustment; u32 MagicNumber; u16 Flags; u16 UnitsPerEm; s64 Created; s64 Modified; s16 xMin; s16 yMin; s16 xMax; s16 yMax; u16 MacStyle; u16 LowestRecPPEM; u16 FontDirectionHint; u16 IndexToLocFormat; u16 GlyphDataFormat; }; struct ttf_vert { v2i P; u16 Flags; }; struct ttf_contour { u32 StartIndex; u32 EndIndex; }; struct simple_glyph { v2i MinP; v2i EmSpaceDim; s16 ContourCount; ttf_contour* Contours; s16 VertCount; ttf_vert* Verts; }; struct font_table { u32 Tag; char* HumanTag; u32 Checksum; u32 Offset; u32 Length; u8* Data; }; struct ttf { font_table* head; // Font Header head_table* HeadTable; font_table* cmap; // Character Glyph mapping font_table* glyf; // Glyph data font_table* hhea; // Horizontal Header font_table* htmx; // Horizontal Metrics font_table* loca; // Index to Location font_table* maxp; // Maximum Profile font_table* name; // Naming font_table* post; // PostScript b32 Loaded; }; struct offset_subtable { u32 ScalerType; u16 NumTables; u16 SearchRange; u16 EntrySelector; u16 RangeShift; b32 Valid; }; enum ttf_flag { TTFFlag_OnCurve = 1 << 0, TTFFlag_ShortX = 1 << 1, TTFFlag_ShortY = 1 << 2, TTFFlag_Repeat = 1 << 3, TTFFlag_DualX = 1 << 4, TTFFlag_DualY = 1 << 5, }; u8_stream U8_Stream(font_table *Table) { u8_stream Result = U8_Stream(Table->Data, Table->Data+Table->Length); return Result; } char * HumanTag(u32 Tag, memory_arena *Memory) { char* Result = Allocate(char, Memory, 5); char* Bin = (char*)&Tag; Result[0] = Bin[3]; Result[1] = Bin[2]; Result[2] = Bin[1]; Result[3] = Bin[0]; return Result; } #define TTF_TAG(s) \ ((s[0]<<24) | (s[1]<<16) | (s[2]<<8) | s[3]) #define AssignTo(prop) \ case TTF_TAG(#prop): { Assert(!Font->prop); Font->prop = Table; Info("Assigned Table : %s", Table->HumanTag); } break; inline void AssignTable(font_table *Table, ttf *Font) { switch (Table->Tag) { AssignTo(head); AssignTo(cmap); AssignTo(glyf); AssignTo(hhea); AssignTo(htmx); AssignTo(loca); AssignTo(maxp); AssignTo(name); AssignTo(post); default: { Warn("Unknown Table encountered : %s", Table->HumanTag); } break; } } inline font_table* ParseFontTable(u8_stream *Source, memory_arena *Arena) { font_table *Result = Allocate(font_table, Arena, 1); Result->Tag = ReadU32(Source); Result->Checksum = ReadU32(Source); Result->Offset = ReadU32(Source); Result->Length = ReadU32(Source); Result->Data = Source->Start + Result->Offset; Result->HumanTag = HumanTag(Result->Tag, Arena); return Result; } offset_subtable ParseOffsetSubtable(u8_stream *Source, memory_arena* Arena) { Assert(Source->At == Source->Start); offset_subtable Result = {}; Result.ScalerType = ReadU32(Source); switch (Result.ScalerType) { case 0x00010000: { Result.Valid = True; } break; // TODO(Jesse, id: 140, tags: font, ttf_rasterizer, completeness): Can we support these? case 'true': // Apple encoding case 'typ1': // Apple encoding case 'OTTO': // OTF 1/2 - Has a CFF Table .. whatever that means { Error("Unsupported ScalerType encountered in FontTable : %s", HumanTag(Result.ScalerType, Arena) ); } break; InvalidDefaultCase; } Result.NumTables = ReadU16(Source); Result.SearchRange = ReadU16(Source); Result.EntrySelector = ReadU16(Source); Result.RangeShift = ReadU16(Source); return Result; } u32 CalculateTableChecksum(font_table *Table) { u32 Sum = 0; u8* TableData = Table->Data; u32 FourByteChunks = (Table->Length + 3) / 4; while (FourByteChunks-- > 0) { Sum += ReadU32(TableData); TableData += 4; } return Sum; } ttf InitTTF(const char* SourceFile, memory_arena *Arena) { ttf Result = {}; u8_stream Source = U8_StreamFromFile(SourceFile, Arena); if (Source.Start) { offset_subtable TableOffsets = ParseOffsetSubtable(&Source, Arena); if (TableOffsets.Valid) { for (u32 TableIndex = 0; TableIndex < TableOffsets.NumTables; ++TableIndex) { font_table *CurrentTable = ParseFontTable(&Source, Arena); u32 Checksum = CalculateTableChecksum(CurrentTable); if (Checksum != CurrentTable->Checksum) { Error("Invalid checksum encountered when reading table %s", CurrentTable->HumanTag); } AssignTable(CurrentTable, &Result); } Result.Loaded = True; } } return Result; } simple_glyph ParseGlyph(u8_stream *Stream, memory_arena *Arena) { simple_glyph Glyph = {}; Glyph.ContourCount = ReadS16(Stream); if (Glyph.ContourCount > 0) // We don't support compound glyphs, yet { Glyph.Contours = Allocate(ttf_contour, Arena, Glyph.ContourCount); s16 xMin = ReadS16(Stream); s16 yMin = ReadS16(Stream); s16 xMax = ReadS16(Stream); s16 yMax = ReadS16(Stream); Glyph.MinP = { xMin, yMin }; Glyph.EmSpaceDim.x = xMax - xMin + 1; // Add one to put from 0-based to 1-based Glyph.EmSpaceDim.y = yMax - yMin + 1; // coordinate system u16 *EndPointsOfContours = ReadU16Array(Stream, (u32)Glyph.ContourCount); u16 NextStart = 0; for (u16 ContourIndex = 0; ContourIndex < Glyph.ContourCount; ++ContourIndex) { Glyph.Contours[ContourIndex].StartIndex = NextStart; Glyph.Contours[ContourIndex].EndIndex = ReadU16(EndPointsOfContours + ContourIndex); NextStart = SafeTruncateToU16(Glyph.Contours[ContourIndex].EndIndex + 1); } u16 InstructionLength = ReadU16(Stream); /* u8* Instructions = */ ReadU8Array(Stream, InstructionLength); u8* Flags = Stream->At; u8* FlagsAt = Flags; Glyph.VertCount = (s16)(1 + ReadU16(EndPointsOfContours+Glyph.ContourCount-1)); Glyph.Verts = Allocate(ttf_vert, Arena, Glyph.VertCount); s16 RepeatCount = 0; u8 Flag = 0; for (s16 PointIndex = 0; PointIndex < Glyph.VertCount; ++PointIndex) { if (RepeatCount) { --RepeatCount; } else { Flag = *FlagsAt++; Assert((Flag & 64) == 0); Assert((Flag & 128) == 0); if (Flag & TTFFlag_Repeat) { RepeatCount = *FlagsAt++; Assert(PointIndex + RepeatCount < Glyph.VertCount); } } Glyph.Verts[PointIndex].Flags = Flag; } u8_stream VertStream = U8_Stream(FlagsAt, (u8*)0xFFFFFFFFFFFFFFFF); s16 X = 0; for (s16 PointIndex = 0; PointIndex < Glyph.VertCount; ++PointIndex) { ttf_vert *Vert = Glyph.Verts + PointIndex; if (Vert->Flags & TTFFlag_ShortX) { u16 Delta = ReadU8(&VertStream); X += (Vert->Flags & TTFFlag_DualX) ? Delta : -Delta; } else { if (!(Vert->Flags & TTFFlag_DualX)) { X += ReadU16(&VertStream); } } Vert->P.x = X - xMin; Assert(Vert->P.x >= 0); Assert(Vert->P.x <= Glyph.EmSpaceDim.x); } s16 Y = 0; for (s16 PointIndex = 0; PointIndex < Glyph.VertCount; ++PointIndex) { ttf_vert *Vert = Glyph.Verts + PointIndex; if (Vert->Flags & TTFFlag_ShortY) { u16 Delta = ReadU8(&VertStream); Y += (Vert->Flags & TTFFlag_DualY) ? Delta : -Delta; } else { if (!(Vert->Flags & TTFFlag_DualY)) { Y += ReadU16(&VertStream); } } Vert->P.y = Y - yMin; Assert(Vert->P.y >= 0); Assert(Vert->P.y <= Glyph.EmSpaceDim.y); } } return Glyph; } /* #define DebugCase(platform_id) \ */ /* case platform_id: { Info("Platform Id : %s", #platform_id); */ /* #define UnsupportedPlatform(platform_id) \ */ /* case platform_id: { Error("Unsupported Platform %s", #platform_id); } break; */ u16 GetGlyphIdForCharacterCode(u32 UnicodeCodepoint, ttf *Font) { font_table *Cmap = Font->cmap; u32 Checksum = CalculateTableChecksum(Cmap); Assert(Checksum == Cmap->Checksum); u8_stream CmapStream = U8_Stream(Cmap); u16 TableVersion = ReadU16(&CmapStream); Assert(TableVersion == 0); u16 NumSubtables = ReadU16(&CmapStream); for (u32 SubtableIndex = 0; SubtableIndex < NumSubtables; ++SubtableIndex) { /* u16 PlatformId = */ ReadU16(&CmapStream); /* u16 PlatformSpecificId = */ ReadU16(&CmapStream); u32 Offset = ReadU32(&CmapStream); u8* Start = CmapStream.Start + Offset; u8_stream TableStream = {}; TableStream.Start = Start; TableStream.At = Start; TableStream.End = Start+4; u16 Format = ReadU16(&TableStream); u16 Length = ReadU16(&TableStream); TableStream.End = Start+Length; if (Format == 4) { /* u16 Lang = */ ReadU16(&TableStream); u16 SegCountX2 = ReadU16(&TableStream); u16 SegCount = SegCountX2/2; /* u16 SearchRange = */ ReadU16(&TableStream); /* u16 EntrySelector = */ ReadU16(&TableStream); /* u16 RangeShift = */ ReadU16(&TableStream); u16* EndCodes = ReadU16Array(&TableStream, SegCount); u16 Pad = ReadU16(&TableStream); Assert(Pad==0); u16* StartCodes = ReadU16Array(&TableStream, SegCount); u16* IdDelta = ReadU16Array(&TableStream, SegCount); u16* IdRangeOffset = ReadU16Array(&TableStream, SegCount); for (u32 SegIdx = 0; SegIdx < SegCount; ++SegIdx) { u16 StartCode = ReadU16(StartCodes+SegIdx); u16 End = ReadU16(EndCodes+SegIdx); u16 Delta = ReadU16(IdDelta+SegIdx); u16 RangeOffset = ReadU16(IdRangeOffset+SegIdx); if (UnicodeCodepoint >= StartCode && UnicodeCodepoint <= End) { if (RangeOffset) { u16 GlyphIndex = ReadU16( &IdRangeOffset[SegIdx] + RangeOffset / 2 + (UnicodeCodepoint - StartCode) ); u16 Result = GlyphIndex ? GlyphIndex + Delta : GlyphIndex; return Result; } else { u32 GlyphIndex = Delta + UnicodeCodepoint; return GlyphIndex & 0xFFFF; } } } } } return 0; } inline head_table* ParseHeadTable(u8_stream *Stream, memory_arena *Arena) { head_table *Result = Allocate(head_table, Arena, 1); Result->Version = ReadU32(Stream); Assert(Result->Version == 0x00010000); Result->FontRevision = ReadU32(Stream); Result->ChecksumAdjustment = ReadU32(Stream); Result->MagicNumber = ReadU32(Stream); Assert(Result->MagicNumber == 0x5F0F3CF5); Result->Flags = ReadU16(Stream); Result->UnitsPerEm = ReadU16(Stream); Result->Created = ReadS64(Stream); Result->Modified = ReadS64(Stream); Result->xMin = ReadS16(Stream); Result->yMin = ReadS16(Stream); Result->xMax = ReadS16(Stream); Result->yMax = ReadS16(Stream); Result->MacStyle = ReadU16(Stream); Result->LowestRecPPEM = ReadU16(Stream); Result->FontDirectionHint = ReadU16(Stream); Result->IndexToLocFormat = ReadU16(Stream); Result->GlyphDataFormat = ReadU16(Stream); Assert(Stream->At == Stream->End); return Result; } #define SHORT_INDEX_LOCATION_FORMAT 0 #define LONG_INDEX_LOCATION_FORMAT 1 inline u8_stream GetStreamForGlyphIndex(u32 GlyphIndex, ttf *Font) { head_table *HeadTable = Font->HeadTable; u8_stream Result = {}; if (HeadTable->IndexToLocFormat == SHORT_INDEX_LOCATION_FORMAT) { u32 GlyphIndexOffset = GlyphIndex * sizeof(u16); u32 StartOffset = ReadU16(Font->loca->Data + GlyphIndexOffset) *2; u32 EndOffset = ReadU16(Font->loca->Data + GlyphIndexOffset + sizeof(u16)) *2; Assert(StartOffset <= EndOffset); u8* Start = Font->glyf->Data + StartOffset; u8* End = Font->glyf->Data + EndOffset; Result = U8_Stream(Start, End); } else if (HeadTable->IndexToLocFormat == LONG_INDEX_LOCATION_FORMAT) { /* u32 FirstOffset = */ ReadU32(Font->loca->Data); /* u32 FirstEndOffset = */ ReadU32(Font->loca->Data+1); u32 StartOffset = ReadU32(Font->loca->Data+(GlyphIndex*4)); u32 EndOffset = ReadU32(Font->loca->Data+(GlyphIndex*4)+4); u8* Start = Font->glyf->Data + StartOffset; u8* End = Font->glyf->Data + EndOffset; Result = U8_Stream(Start, End); } else { InvalidCodePath(); } return Result; } inline u32 GetPixelIndex(v2i PixelP, bitmap* Bitmap) { Assert(PixelP.x < Bitmap->Dim.x); Assert(PixelP.y < Bitmap->Dim.y); u32 Result = (u32)(PixelP.x + (s32)(PixelP.y*Bitmap->Dim.x)); Assert(Result < (u32)PixelCount(Bitmap)); return Result; } u32 WrapToCurveIndex(u32 IndexWanted, u32 CurveStart, u32 CurveEnd) { u32 Result = IndexWanted; if (Result > CurveEnd) { u32 Remaining = Result - CurveEnd; Result = CurveStart + Remaining - 1; } return Result; } bitmap RasterizeGlyph(v2i OutputSize, v2i FontMaxEmDim, v2i FontMinGlyphP, u8_stream *GlyphStream, memory_arena* Arena) { #define DO_RASTERIZE 1 #define DO_AA 1 #define WRITE_DEBUG_BITMAPS 0 s32 SamplesPerPixel = 4; v2i SamplingBitmapDim = OutputSize*SamplesPerPixel; bitmap SamplingBitmap = AllocateBitmap(SamplingBitmapDim, Arena); bitmap OutputBitmap = {}; if (Remaining(GlyphStream) > 0) // A glyph stream with 0 length means there's no glyph { simple_glyph Glyph = ParseGlyph(GlyphStream, Arena); if (Glyph.ContourCount > 0) // We don't support compound glyphs, yet { FillBitmap(PackRGBALinearTo255(White), &SamplingBitmap); OutputBitmap = AllocateBitmap(OutputSize, Arena); FillBitmap(PackRGBALinearTo255(White), &OutputBitmap); for (u16 ContourIndex = 0; ContourIndex < Glyph.ContourCount; ++ContourIndex) { ttf_contour* Contour = Glyph.Contours + ContourIndex; u32 ContourVertCount = Contour->EndIndex - Contour->StartIndex; u32 AtIndex = Contour->StartIndex; u32 VertsProcessed = 0; while (VertsProcessed <= ContourVertCount) { Assert(Glyph.Verts[AtIndex].Flags & TTFFlag_OnCurve); u32 VertCount = 1; u32 CurveEndIndex = WrapToCurveIndex(AtIndex+1, Contour->StartIndex, Contour->EndIndex); while ( !(Glyph.Verts[CurveEndIndex].Flags & TTFFlag_OnCurve) ) { CurveEndIndex = WrapToCurveIndex(CurveEndIndex+1, Contour->StartIndex, Contour->EndIndex); ++VertCount; } ++VertCount; v2* TempVerts = Allocate(v2, Arena, VertCount); // TODO(Jesse, id: 141, tags: transient_memory, ttf_rasterizer): Temp-memory? v2i BaselineOffset = Glyph.MinP - FontMinGlyphP; // Here we have to subtract one from everything because we're going // from a dimension [1, Dim] to an indexable range [0, Dim-1] // // TODO(Jesse, id: 142, tags: open_question): Is there a better way of making that adjustment? v2i One = V2i(1,1); v2 EmScale = V2(Glyph.EmSpaceDim-One) / V2(FontMaxEmDim-One); v2 EmSpaceToPixelSpace = EmScale*( (SamplingBitmapDim-One) / (Glyph.EmSpaceDim-One) ); v4 LastColor = Red; u32 LastPixelIndex = 0; for (r32 t = 0.0f; t < 1.0f; t += 0.0001f) { for (u32 VertIndex = 0; VertIndex < VertCount; ++VertIndex) { u32 CurveVertIndex = WrapToCurveIndex(AtIndex + VertIndex, Contour->StartIndex, Contour->EndIndex); TempVerts[VertIndex] = V2(Glyph.Verts[CurveVertIndex].P + BaselineOffset) * EmSpaceToPixelSpace; } v2 TangentMax = {}; for (u32 Outer = VertCount; Outer > 1; --Outer) { for (u32 Inner = 0; Inner < Outer-1; ++Inner) { v2 tVec01 = (TempVerts[Inner+1]-TempVerts[Inner]) * t; TempVerts[Inner] = TempVerts[Inner+1] - tVec01; if (Inner == Outer-2) { TangentMax = TempVerts[Inner+1]; } } } v2 PointOnCurve = TempVerts[0]; v4 Color = Red; // On-curve transition if ( (TangentMax.x >= PointOnCurve.x && TangentMax.y > PointOnCurve.y) || (TangentMax.x <= PointOnCurve.x && TangentMax.y > PointOnCurve.y) ) { Color = Green; } else if ( (TangentMax.x >= PointOnCurve.x && TangentMax.y <= PointOnCurve.y) || (TangentMax.x <= PointOnCurve.x && TangentMax.y <= PointOnCurve.y) ) { Color = Blue; } u32 PixelIndex = GetPixelIndex(V2i(PointOnCurve), &SamplingBitmap); SamplingBitmap.Pixels.Start[PixelIndex] = PackRGBALinearTo255(Color); if (LastColor == Green && Color == Blue) { SamplingBitmap.Pixels.Start[PixelIndex] = PackRGBALinearTo255(Green); } if (LastColor == Blue && Color == Green) { SamplingBitmap.Pixels.Start[LastPixelIndex] = PackRGBALinearTo255(Green); } LastColor = Color; LastPixelIndex = PixelIndex; } VertsProcessed += VertCount -1; AtIndex = CurveEndIndex; } } #if DO_RASTERIZE for (s32 yIndex = 0; yIndex < SamplingBitmap.Dim.y; ++yIndex) { s32 TransitionCount = 0; for (s32 xIndex = 0; xIndex < SamplingBitmap.Dim.x; ++xIndex) { u32 PixelIndex = GetPixelIndex(V2i(xIndex, yIndex), &SamplingBitmap); u32 PixelColor = SamplingBitmap.Pixels.Start[PixelIndex]; if (PixelColor == PackedGreen) { TransitionCount = 1; continue; } else if (PixelColor == PackedBlue) { TransitionCount = 0; continue; } if (TransitionCount > 0) { SamplingBitmap.Pixels.Start[PixelIndex] = PackedBlack; } else { SamplingBitmap.Pixels.Start[PixelIndex] = PackedWhite; } } } #endif #if DO_RASTERIZE && DO_AA r32 SampleContrib = 1.0f/((r32)SamplesPerPixel*(r32)SamplesPerPixel); for (s32 yPixelIndex = 0; yPixelIndex < OutputBitmap.Dim.y; ++yPixelIndex) { for (s32 xPixelIndex = 0; xPixelIndex < OutputBitmap.Dim.x; ++xPixelIndex) { r32 OneMinusAlpha = 0.0f; s32 yStart = yPixelIndex*SamplesPerPixel; for (s32 ySampleIndex = yStart; ySampleIndex < yStart+SamplesPerPixel; ++ySampleIndex) { s32 xStart = xPixelIndex*SamplesPerPixel; for (s32 xSampleIndex = xStart; xSampleIndex < xStart+SamplesPerPixel; ++xSampleIndex) { if (xSampleIndex < SamplingBitmap.Dim.x && ySampleIndex < SamplingBitmap.Dim.y) { u32 SampleIndex = GetPixelIndex(V2i(xSampleIndex, ySampleIndex), &SamplingBitmap); u32 PixelColor = SamplingBitmap.Pixels.Start[SampleIndex]; OneMinusAlpha += PixelColor == PackedWhite ? SampleContrib : 0.0f; } } } u32 PixelIndex = GetPixelIndex(V2i(xPixelIndex, yPixelIndex), &OutputBitmap); r32 Alpha = 1.0f - OneMinusAlpha; OutputBitmap.Pixels.Start[PixelIndex] = PackRGBALinearTo255(V4(1.0f, 1.0f, 1.0f, Alpha)); if (xPixelIndex == (OutputBitmap.Dim.x-1) || yPixelIndex == (OutputBitmap.Dim.y-1)) { OutputBitmap.Pixels.Start[PixelIndex] = PackedRed; } } } #endif #if 0 v2 At = V2(Glyph.Verts->P); v2 LastVertP = At; v4 CurrentColor = (Glyph.Verts->Flags&TTFFlag_OnCurve) ? Black : Red; v4 TargetColor = Black; for (u32 VertIndex = 0; VertIndex < Glyph.VertCount; ++VertIndex) { ttf_vert *Vert = Glyph.Verts + VertIndex; v2 VertP = V2(Vert->P); if (Vert->Flags & TTFFlag_OnCurve) { TargetColor = Black; Debug("On Curve %d %d", Vert->P.x, Vert->P.y); } else { TargetColor = Red; Debug("Off Curve %d %d", Vert->P.x, Vert->P.y); } v2 CurrentToVert = Normalize(VertP-At) * 0.5f; while(Abs(Length(VertP - At)) > 0.5f) { r32 t = SafeDivide0(LengthSq(LastVertP-At), LengthSq(LastVertP-VertP)); u32 PixelColor = PackRGBALinearTo255(Lerp(t, CurrentColor, TargetColor)); u32 PixelIndex = GetPixelIndex(V2i(At), &Bitmap); *(Bitmap.Pixels.Start + PixelIndex) = PixelColor; At += CurrentToVert; } LastVertP = VertP; CurrentColor = TargetColor; } #endif } #if WRITE_DEBUG_BITMAPS WriteBitmapToDisk(&SamplingBitmap, "sample_glyph.bmp"); WriteBitmapToDisk(&OutputBitmap, "output_glyph.bmp"); #endif } return OutputBitmap; } void CopyBitmapOffset(bitmap *Source, bitmap *Dest, v2i Offset) { for (s32 ySourcePixel = 0; ySourcePixel < Source->Dim.y; ++ySourcePixel) { for (s32 xSourcePixel = 0; xSourcePixel < Source->Dim.x; ++xSourcePixel) { u32 SourcePixelIndex = GetPixelIndex(V2i(xSourcePixel, ySourcePixel), Source); u32 DestPixelIndex = GetPixelIndex( V2i(xSourcePixel, ySourcePixel) + Offset, Dest); Dest->Pixels.Start[DestPixelIndex] = Source->Pixels.Start[SourcePixelIndex] ; } } return; } int main() { const char* FontName = "fonts/Anonymice/Anonymice Nerd Font Complete Mono Windows Compatible.ttf"; memory_arena* PermArena = AllocateArena(); memory_arena* TempArena = AllocateArena(); ttf Font = InitTTF(FontName, PermArena); if (Font.Loaded) { u8_stream HeadStream = U8_Stream(Font.head); Font.HeadTable = ParseHeadTable(&HeadStream, PermArena); v2i FontMaxEmDim = { Font.HeadTable->xMax - Font.HeadTable->xMin, Font.HeadTable->yMax - Font.HeadTable->yMin }; v2i FontMinGlyphP = V2i(Font.HeadTable->xMin, Font.HeadTable->yMin); v2i GlyphSize = V2i(32, 32); bitmap TextureAtlasBitmap = AllocateBitmap(16*GlyphSize, PermArena); u32 AtlasCount = 65536/256; for (u32 AtlasIndex = 0; AtlasIndex < AtlasCount; ++AtlasIndex) { FillBitmap(PackedPink, &TextureAtlasBitmap); u32 GlyphsRasterized = 0; for (u32 CharCode = AtlasIndex*256; CharCode < (AtlasIndex*256)+256; ++CharCode) { u32 GlyphIndex = GetGlyphIdForCharacterCode(CharCode, &Font); if (!GlyphIndex) continue; u8_stream GlyphStream = GetStreamForGlyphIndex(GlyphIndex, &Font); bitmap GlyphBitmap = RasterizeGlyph(GlyphSize, FontMaxEmDim, FontMinGlyphP, &GlyphStream, TempArena); if ( PixelCount(&GlyphBitmap) ) { Debug("Rasterized Glyph %d (%d)", CharCode, GlyphsRasterized); ++GlyphsRasterized; #if 1 v2 UV = GetUVForCharCode((u8)(CharCode % 256)); CopyBitmapOffset(&GlyphBitmap, &TextureAtlasBitmap, V2i(UV*V2(TextureAtlasBitmap.Dim)) ); #else char Name[128] = {}; FormatCountedString_(Name, 128, "Glyph_%d.bmp", CharCode); WriteBitmapToDisk(&GlyphBitmap, Name); #endif } RewindArena(TempArena); } if (GlyphsRasterized) { counted_string AtlasName = FormatCountedString(TempArena, CSz("texture_atlas_%d.bmp"), AtlasIndex); // TODO(Jesse, id: 143, tags: robustness, open_question, format_counted_string_api): This could probably be made better by writing to a statically allocated buffer ..? WriteBitmapToDisk(&TextureAtlasBitmap, GetNullTerminated(AtlasName)); } GlyphsRasterized = 0; } } else { Error("Loading Font %s", FontName); } return 0; }
26.145038
201
0.61062
jjbandit
bf3fdb6deda0b4dadbb0a86d8f14c1c554d5b643
10,758
cpp
C++
src/tools/loop_invariant_code_motion/src/LastLiveOutPeeler.cpp
SusanTan/noelle
33c9e10a20bc59590c13bf29fb661fc406a9e687
[ "MIT" ]
43
2020-09-04T15:21:40.000Z
2022-03-23T03:53:02.000Z
src/tools/loop_invariant_code_motion/src/LastLiveOutPeeler.cpp
SusanTan/noelle
33c9e10a20bc59590c13bf29fb661fc406a9e687
[ "MIT" ]
15
2020-09-17T18:06:15.000Z
2022-01-24T17:14:36.000Z
src/tools/loop_invariant_code_motion/src/LastLiveOutPeeler.cpp
SusanTan/noelle
33c9e10a20bc59590c13bf29fb661fc406a9e687
[ "MIT" ]
23
2020-09-04T15:50:09.000Z
2022-03-25T13:38:25.000Z
/* * Copyright 2019 - 2020 Simone Campanoni * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "LastLiveOutPeeler.hpp" using namespace llvm; /* * Restricted to loops where: * The only loop exit is from the loop entry block * The loop (and all sub-loops?) are governed by an IV */ /* TODO: Clone every basic block in the loop Exit from the original loop entry to the cloned loop entry If no loop body iteration ever executed, then route to the loop exit Otherwise, route to the cloned loop body The cloned latches route to a 2nd cloned entry that unconditionally branches to the loop exit Clone IV sccs, branches/conditions on IVs in dependent SCCs, last live out SCCs with computation and their dependent SCCs Step loop governing IV back one iteration Wire instructions together as follows: Any instructions from original loop governing IV to cloned, stepped-back IV Any instructions from other IVs to cloned IVs Any instructions from original loop entry to trailing/latch PHI pairs A trailing PHI at the loop entry consumes the PHI's previous iteration value at each latch Any instructions from original loop body to PHIs on the cloned loop body values The cloned body values only need PHIs since they do not dominate the last iteration's execution */ #include "LastLiveOutPeeler.hpp" using namespace llvm; using namespace llvm::noelle; LastLiveOutPeeler::LastLiveOutPeeler (LoopDependenceInfo const &LDI, Noelle &noelle) : LDI{LDI}, noelle{noelle} { } // bool LastLiveOutPeeler::peelLastLiveOutComputation () { // /* // * Ensure the loop entry is the only block to exit the loop // */ // auto loopStructure = LDI.getLoopStructure(); // auto loopHeader = loopStructure->getHeader(); // auto exitBlocks = loopStructure->getLoopExitBasicBlocks(); // if (exitBlocks.size() != 1) return false; // auto singleExitBlock = exitBlocks[0]; // bool onlyExitsFromHeader = true; // bool exitsFromHeader = false; // for (auto exitPred : predecessors(singleExitBlock)) { // exitsFromHeader |= exitPred == loopHeader; // onlyExitsFromHeader = !loopStructure->isIncluded(exitPred) || exitPred == loopHeader; // } // if (!exitsFromHeader || !onlyExitsFromHeader) return false; // /* // * Ensure the loop is governed by an IV // */ // auto loopGoverningIVAttribution = LDI.getLoopGoverningIVAttribution(); // if (!loopGoverningIVAttribution) return false; // /* // * Determine if there is any live out computation that can be peeled // */ // fetchSCCsOfLastLiveOuts(); // if (this->sccsOfLastLiveOuts.size() == 0) return false; // /* // * Ensure that the control flow of the loop is governed by IVs and fully understood // */ // auto controlFlowGovernedByIVs = fetchNormalizedSCCsGoverningControlFlowOfLoop(); // if (!controlFlowGovernedByIVs) return false; // /* // * Identify induction variable SCCs in all sub-loops // */ // auto ivManager = LDI.getInductionVariableManager(); // std::unordered_set<InductionVariable *> allIVsInLoop{}; // auto loops = loopStructure->getDescendants(); // for (auto loop : loops) { // auto ivs = ivManager->getInductionVariables(*loop); // allIVsInLoop.insert(ivs.begin(), ivs.end()); // } // auto loopGoverningIV = loopGoverningIVAttribution->getInductionVariable(); // // TODO: Clone this later: // loopGoverningIV.getComputationOfStepValue(); // // TODO: Everything // return true; // } // bool LastLiveOutPeeler::fetchNormalizedSCCsGoverningControlFlowOfLoop (void) { // auto loopStructure = LDI.getLoopStructure(); // auto normalizedSCCDAG = LDI.sccdagAttrs.getSCCDAG(); // auto ivManager = LDI.getInductionVariableManager(); // for (auto loopBlock : loopStructure->getBasicBlocks()) { // auto terminator = loopBlock->getTerminator(); // assert(terminator != nullptr // && "LastLiveOutPeeler: Loop is not well formed, having an un-terminated basic block"); // /* // * Currently, we only support un-conditional or conditional branches w/conditions that are // * loop invariants OR instructions using IVs and loop invariants only // */ // if (!isa<BranchInst>(terminator)) return false; // auto brInst = cast<BranchInst>(terminator); // if (brInst->isUnconditional()) continue; // auto sccOfTerminator = normalizedSCCDAG->sccOfValue(terminator); // auto sccInfoOfTerminator = LDI.sccdagAttrs.getSCCAttrs(sccOfTerminator); // if (sccInfoOfTerminator->isInductionVariableSCC()) { // normalizedSCCsOfGoverningIVs.insert(sccOfTerminator); // continue; // } // /* // * The condition must be loop invariant or an instruction using IVs and loop invariants only // */ // auto condition = brInst->getCondition(); // if (!isa<Instruction>(condition)) { // if (!loopStructure->isLoopInvariant(condition)) return false; // continue; // } // auto conditionInst = cast<Instruction>(condition); // auto sccOfCondition = normalizedSCCDAG->sccOfValue(condition); // normalizedSCCsOfConditionsAndBranchesDependentOnIVSCCs.insert(sccOfTerminator); // normalizedSCCsOfConditionsAndBranchesDependentOnIVSCCs.insert(sccOfCondition); // for (auto &op : conditionInst->operands()) { // auto value = op.get(); // if (loopStructure->isLoopInvariant(value)) continue; // if (!isa<Instruction>(value)) return false; // auto inst = cast<Instruction>(value); // auto loopOfValue = LDI.getNestedMostLoopStructure(inst); // auto ivOfValue = ivManager->getInductionVariable(*loopOfValue, inst); // if (ivOfValue) continue; // return false; // } // } // return true; // } // /* // * We are interested in any last live outs with meaningful computation contained in the chain (excludes PHIs, casts) // */ // void LastLiveOutPeeler::fetchSCCsOfLastLiveOuts (void) { // auto loopStructure = LDI.getLoopStructure(); // auto loopHeader = loopStructure->getHeader(); // auto loopSCCDAG = LDI.getLoopSCCDAG(); // auto normalizedSCCDAG = LDI.sccdagAttrs.getSCCDAG(); // auto loopCarriedDependencies = LDI.getLoopCarriedDependencies(); // auto outermostLoopCarriedDependencies = loopCarriedDependencies->getLoopCarriedDependenciesForLoop(*loopStructure); // std::unordered_set<Value *> loopCarriedConsumers{}; // for (auto dependency : outermostLoopCarriedDependencies) { // auto consumer = dependency->getIncomingT(); // this->loopCarriedConsumers.insert(consumer); // } // /* // * Last live outs can only result in leaf nodes // * Their computation CAN span a chain of SCCs though, all of which must only produce last live out loop carried dependencies // * // * To be sure the parent SCCs/instructions up that chain we collect ONLY contain last live outs, // * we use the strict SCCDAG, not the normalized SCCDAG // */ // for (auto leafSCCNode : loopSCCDAG->getLeafNodes()) { // auto leafSCC = leafSCCNode->getT(); // /* // * The leaf SCC must be a single loop carried PHI // */ // if (leafSCC->numInternalNodes() > 1) continue; // auto singleValue = leafSCC->internalNodePairs().begin()->first; // if (!isa<PHINode>(singleValue)) continue; // auto singlePHI = cast<PHINode>(singleValue); // if (singlePHI->getParent() != loopHeader) continue; // auto chainOfSCCs = fetchChainOfSCCsForLastLiveOutLeafSCC(leafSCCNode); // this->sccsOfLastLiveOuts.insert(chainOfSCCs.begin(), chainOfSCCs.end()); // } // return; // } // std::unordered_set<SCC *> LastLiveOutPeeler::fetchChainOfSCCsForLastLiveOutLeafSCC (DGNode<SCC> *sccNode) { // /* // * Traverse up the graph, collecting as many SCC nodes that ONLY contribute loop carried // * dependencies to last live out values. Keep track if any of those SCCs contain meaningful computation // */ // bool hasMeaningfulComputation = false; // std::unordered_set<SCC *> computationOfLastLiveOut{}; // std::queue<DGNode<SCC> *> queueOfLastLiveOutComputation{}; // queueOfLastLiveOutComputation.push(sccNode); // /* // * For the sake of efficiency, even if the SCCDAG is acyclic, don't re-process SCCs // */ // std::unordered_set<DGNode<SCC> *> visited{}; // visited.insert(sccNode); // while (!queueOfLastLiveOutComputation.empty()) { // auto sccNode = queueOfLastLiveOutComputation.front(); // queueOfLastLiveOutComputation.pop(); // auto scc = sccNode->getT(); // bool isLoopCarried = false; // bool hasComputation = false; // for (auto nodePair : scc->internalNodePairs()) { // auto value = nodePair.first; // if (!isa<Instruction>(value)) continue; // auto inst = cast<Instruction>(value); // if (!isa<PHINode>(inst) && !isa<CastInst>(inst)) { // hasComputation = true; // } // if (loopCarriedConsumers.find(inst) != loopCarriedConsumers.end()) { // isLoopCarried = true; // break; // } // } // /* // * Do not include SCCs with loop carried values // */ // if (isLoopCarried) continue; // hasMeaningfulComputation |= hasComputation; // computationOfLastLiveOut.insert(scc); // for (auto edge : sccNode->getIncomingEdges()) { // auto producerSCCNode = edge->getOutgoingNode(); // if (visited.find(producerSCCNode) != visited.end()) continue; // queueOfLastLiveOutComputation.push(producerSCCNode); // visited.insert(producerSCCNode); // } // } // /* // * Only return a non-empty set if those SCCs are worth peeling // */ // if (!hasMeaningfulComputation) computationOfLastLiveOut.clear(); // return computationOfLastLiveOut; // }
40.141791
435
0.697249
SusanTan
bf44879009ab56c3d65c75fc831aea9b5d5a386a
15,583
hxx
C++
main/cppuhelper/inc/cppuhelper/stdidlclass.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/cppuhelper/inc/cppuhelper/stdidlclass.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/cppuhelper/inc/cppuhelper/stdidlclass.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef _CPPUHELPER_STDIDLCLASS_HXX_ #define _CPPUHELPER_STDIDLCLASS_HXX_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #include <com/sun/star/reflection/XIdlClass.hpp> #include "cppuhelper/cppuhelperdllapi.h" namespace cppu { /* @deprecated */ CPPUHELPER_DLLPUBLIC ::com::sun::star::reflection::XIdlClass * SAL_CALL createStandardClassWithSequence( const ::com::sun::star::uno::Reference < ::com::sun::star::lang::XMultiServiceFactory > &rSMgr , const ::rtl::OUString & sImplementationName , const ::com::sun::star::uno::Reference < ::com::sun::star::reflection::XIdlClass > & rSuperClass, const ::com::sun::star::uno::Sequence < ::rtl::OUString > &seq ) SAL_THROW( () ); /** Standardfunction to create an XIdlClass for a component. There is a function for each number of supported interfaces up to 10. Since the switch to the final component model, there are no use cases anymore, where these functions should be used. Instead use the implementation helpers directly (see cppuhelper/implbase1.hxx). @see OTypeCollection @deprecated */ template < class Interface1 > inline ::com::sun::star::reflection::XIdlClass * SAL_CALL //inline ::com::sun::star::uno::Reference < ::com::sun::star::reflection::XIdlClass > createStandardClass( const ::com::sun::star::uno::Reference < ::com::sun::star::lang::XMultiServiceFactory > &rSMgr, const ::rtl::OUString &sImplementationName , const ::com::sun::star::uno::Reference < ::com::sun::star::reflection::XIdlClass > &rSuperClass , const Interface1 * ) SAL_THROW( () ) { ::com::sun::star::uno::Sequence < ::rtl::OUString > seqInterface(1); seqInterface.getArray()[0] = Interface1::static_type().getTypeName(); return createStandardClassWithSequence( rSMgr, sImplementationName, rSuperClass, seqInterface ); } template < class Interface1, class Interface2 > inline ::com::sun::star::reflection::XIdlClass * SAL_CALL //inline ::com::sun::star::uno::Reference < ::com::sun::star::reflection::XIdlClass > createStandardClass( const ::com::sun::star::uno::Reference < ::com::sun::star::lang::XMultiServiceFactory > &rSMgr, const ::rtl::OUString &sImplementationName , const ::com::sun::star::uno::Reference < ::com::sun::star::reflection::XIdlClass > &rSuperClass , const Interface1 *, const Interface2 * ) SAL_THROW( () ) { ::com::sun::star::uno::Sequence < ::rtl::OUString > seqInterface(2); seqInterface.getArray()[0] = Interface1::static_type().getTypeName(); seqInterface.getArray()[1] = Interface2::static_type().getTypeName(); return createStandardClassWithSequence( rSMgr, sImplementationName, rSuperClass, seqInterface ); } template < class Interface1, class Interface2 , class Interface3 > inline ::com::sun::star::reflection::XIdlClass * SAL_CALL //inline ::com::sun::star::uno::Reference < ::com::sun::star::reflection::XIdlClass > createStandardClass( const ::com::sun::star::uno::Reference < ::com::sun::star::lang::XMultiServiceFactory > &rSMgr, const ::rtl::OUString &sImplementationName , const ::com::sun::star::uno::Reference < ::com::sun::star::reflection::XIdlClass > &rSuperClass , const Interface1 *, const Interface2 *, const Interface3 * ) SAL_THROW( () ) { ::com::sun::star::uno::Sequence < ::rtl::OUString > seqInterface(3); seqInterface.getArray()[0] = Interface1::static_type().getTypeName(); seqInterface.getArray()[1] = Interface2::static_type().getTypeName(); seqInterface.getArray()[2] = Interface3::static_type().getTypeName(); return createStandardClassWithSequence( rSMgr, sImplementationName, rSuperClass, seqInterface ); } template < class Interface1, class Interface2 , class Interface3 , class Interface4 > inline ::com::sun::star::reflection::XIdlClass * SAL_CALL //inline ::com::sun::star::uno::Reference < ::com::sun::star::reflection::XIdlClass > createStandardClass( const ::com::sun::star::uno::Reference < ::com::sun::star::lang::XMultiServiceFactory > &rSMgr, const ::rtl::OUString &sImplementationName , const ::com::sun::star::uno::Reference < ::com::sun::star::reflection::XIdlClass > &rSuperClass , const Interface1 *, const Interface2 *, const Interface3 *, const Interface4 * ) SAL_THROW( () ) { ::com::sun::star::uno::Sequence < ::rtl::OUString > seqInterface(4); seqInterface.getArray()[0] = Interface1::static_type().getTypeName(); seqInterface.getArray()[1] = Interface2::static_type().getTypeName(); seqInterface.getArray()[2] = Interface3::static_type().getTypeName(); seqInterface.getArray()[3] = Interface4::static_type().getTypeName(); return createStandardClassWithSequence( rSMgr, sImplementationName, rSuperClass, seqInterface ); } template < class Interface1, class Interface2 , class Interface3 , class Interface4 , class Interface5 > inline ::com::sun::star::reflection::XIdlClass * SAL_CALL //inline ::com::sun::star::uno::Reference < ::com::sun::star::reflection::XIdlClass > createStandardClass( const ::com::sun::star::uno::Reference < ::com::sun::star::lang::XMultiServiceFactory > &rSMgr, const ::rtl::OUString &sImplementationName , const ::com::sun::star::uno::Reference < ::com::sun::star::reflection::XIdlClass > &rSuperClass , const Interface1 *, const Interface2 *, const Interface3 *, const Interface4 *, const Interface5 * ) SAL_THROW( () ) { ::com::sun::star::uno::Sequence < ::rtl::OUString > seqInterface(5); seqInterface.getArray()[0] = Interface1::static_type().getTypeName(); seqInterface.getArray()[1] = Interface2::static_type().getTypeName(); seqInterface.getArray()[2] = Interface3::static_type().getTypeName(); seqInterface.getArray()[3] = Interface4::static_type().getTypeName(); seqInterface.getArray()[4] = Interface5::static_type().getTypeName(); return createStandardClassWithSequence( rSMgr, sImplementationName, rSuperClass, seqInterface ); } template < class Interface1, class Interface2 , class Interface3 , class Interface4 , class Interface5 , class Interface6 > inline ::com::sun::star::reflection::XIdlClass * SAL_CALL //inline ::com::sun::star::uno::Reference < ::com::sun::star::reflection::XIdlClass > createStandardClass( const ::com::sun::star::uno::Reference < ::com::sun::star::lang::XMultiServiceFactory > &rSMgr, const ::rtl::OUString &sImplementationName , const ::com::sun::star::uno::Reference < ::com::sun::star::reflection::XIdlClass > &rSuperClass , const Interface1 *, const Interface2 *, const Interface3 *, const Interface4 *, const Interface5 *, const Interface6 * ) SAL_THROW( () ) { ::com::sun::star::uno::Sequence < ::rtl::OUString > seqInterface(6); seqInterface.getArray()[0] = Interface1::static_type().getTypeName(); seqInterface.getArray()[1] = Interface2::static_type().getTypeName(); seqInterface.getArray()[2] = Interface3::static_type().getTypeName(); seqInterface.getArray()[3] = Interface4::static_type().getTypeName(); seqInterface.getArray()[4] = Interface5::static_type().getTypeName(); seqInterface.getArray()[5] = Interface6::static_type().getTypeName(); return createStandardClassWithSequence( rSMgr, sImplementationName, rSuperClass, seqInterface ); } template < class Interface1, class Interface2 , class Interface3 , class Interface4 , class Interface5 , class Interface6, class Interface7 > inline ::com::sun::star::reflection::XIdlClass * SAL_CALL //inline ::com::sun::star::uno::Reference < ::com::sun::star::reflection::XIdlClass > createStandardClass( const ::com::sun::star::uno::Reference < ::com::sun::star::lang::XMultiServiceFactory > &rSMgr, const ::rtl::OUString &sImplementationName , const ::com::sun::star::uno::Reference < ::com::sun::star::reflection::XIdlClass > &rSuperClass , const Interface1 *, const Interface2 *, const Interface3 *, const Interface4 *, const Interface5 *, const Interface6 *, const Interface7 * ) SAL_THROW( () ) { ::com::sun::star::uno::Sequence < ::rtl::OUString > seqInterface(7); seqInterface.getArray()[0] = Interface1::static_type().getTypeName(); seqInterface.getArray()[1] = Interface2::static_type().getTypeName(); seqInterface.getArray()[2] = Interface3::static_type().getTypeName(); seqInterface.getArray()[3] = Interface4::static_type().getTypeName(); seqInterface.getArray()[4] = Interface5::static_type().getTypeName(); seqInterface.getArray()[5] = Interface6::static_type().getTypeName(); seqInterface.getArray()[6] = Interface7::static_type().getTypeName(); return createStandardClassWithSequence( rSMgr, sImplementationName, rSuperClass, seqInterface ); } template < class Interface1, class Interface2, class Interface3 , class Interface4 , class Interface5 , class Interface6, class Interface7, class Interface8 > inline ::com::sun::star::reflection::XIdlClass * SAL_CALL //inline ::com::sun::star::uno::Reference < ::com::sun::star::reflection::XIdlClass > createStandardClass( const ::com::sun::star::uno::Reference < ::com::sun::star::lang::XMultiServiceFactory > &rSMgr, const ::rtl::OUString &sImplementationName , const ::com::sun::star::uno::Reference < ::com::sun::star::reflection::XIdlClass > &rSuperClass , const Interface1 *, const Interface2 *, const Interface3 *, const Interface4 *, const Interface5 *, const Interface6 *, const Interface7 *, const Interface8 * ) SAL_THROW( () ) { ::com::sun::star::uno::Sequence < ::rtl::OUString > seqInterface(8); seqInterface.getArray()[0] = Interface1::static_type().getTypeName(); seqInterface.getArray()[1] = Interface2::static_type().getTypeName(); seqInterface.getArray()[2] = Interface3::static_type().getTypeName(); seqInterface.getArray()[3] = Interface4::static_type().getTypeName(); seqInterface.getArray()[4] = Interface5::static_type().getTypeName(); seqInterface.getArray()[5] = Interface6::static_type().getTypeName(); seqInterface.getArray()[6] = Interface7::static_type().getTypeName(); seqInterface.getArray()[7] = Interface8::static_type().getTypeName(); return createStandardClassWithSequence( rSMgr, sImplementationName, rSuperClass, seqInterface ); } template < class Interface1, class Interface2, class Interface3 , class Interface4 , class Interface5 , class Interface6, class Interface7, class Interface8 , class Interface9 > inline ::com::sun::star::reflection::XIdlClass * SAL_CALL //inline ::com::sun::star::uno::Reference < ::com::sun::star::reflection::XIdlClass > createStandardClass( const ::com::sun::star::uno::Reference < ::com::sun::star::lang::XMultiServiceFactory > &rSMgr, const ::rtl::OUString &sImplementationName , const ::com::sun::star::uno::Reference < ::com::sun::star::reflection::XIdlClass > &rSuperClass , const Interface1 *, const Interface2 *, const Interface3 *, const Interface4 *, const Interface5 *, const Interface6 *, const Interface7 *, const Interface8 *, const Interface9 * ) SAL_THROW( () ) { ::com::sun::star::uno::Sequence < ::rtl::OUString > seqInterface(9); seqInterface.getArray()[0] = Interface1::static_type().getTypeName(); seqInterface.getArray()[1] = Interface2::static_type().getTypeName(); seqInterface.getArray()[2] = Interface3::static_type().getTypeName(); seqInterface.getArray()[3] = Interface4::static_type().getTypeName(); seqInterface.getArray()[4] = Interface5::static_type().getTypeName(); seqInterface.getArray()[5] = Interface6::static_type().getTypeName(); seqInterface.getArray()[6] = Interface7::static_type().getTypeName(); seqInterface.getArray()[7] = Interface8::static_type().getTypeName(); seqInterface.getArray()[8] = Interface9::static_type().getTypeName(); return createStandardClassWithSequence( rSMgr, sImplementationName, rSuperClass, seqInterface ); } template < class Interface1, class Interface2, class Interface3 , class Interface4 , class Interface5 , class Interface6, class Interface7, class Interface8 , class Interface9 , class Interface10 > inline ::com::sun::star::reflection::XIdlClass * SAL_CALL //inline ::com::sun::star::uno::Reference < ::com::sun::star::reflection::XIdlClass > createStandardClass( const ::com::sun::star::uno::Reference < ::com::sun::star::lang::XMultiServiceFactory > &rSMgr, const ::rtl::OUString &sImplementationName , const ::com::sun::star::uno::Reference < ::com::sun::star::reflection::XIdlClass > &rSuperClass , const Interface1 *, const Interface2 *, const Interface3 *, const Interface4 *, const Interface5 *, const Interface6 *, const Interface7 *, const Interface8 *, const Interface9 *, const Interface10 * ) SAL_THROW( () ) { ::com::sun::star::uno::Sequence < ::rtl::OUString > seqInterface(10); seqInterface.getArray()[0] = Interface1::static_type().getTypeName(); seqInterface.getArray()[1] = Interface2::static_type().getTypeName(); seqInterface.getArray()[2] = Interface3::static_type().getTypeName(); seqInterface.getArray()[3] = Interface4::static_type().getTypeName(); seqInterface.getArray()[4] = Interface5::static_type().getTypeName(); seqInterface.getArray()[5] = Interface6::static_type().getTypeName(); seqInterface.getArray()[6] = Interface7::static_type().getTypeName(); seqInterface.getArray()[7] = Interface8::static_type().getTypeName(); seqInterface.getArray()[8] = Interface9::static_type().getTypeName(); seqInterface.getArray()[9] = Interface10::static_type().getTypeName(); return createStandardClassWithSequence( rSMgr, sImplementationName, rSuperClass, seqInterface ); } } // end namespace cppu #endif
40.162371
116
0.663094
Grosskopf
bf4697f76aafea71af2955d6209b0bb7054cddfb
5,690
cpp
C++
webkit/WebCore/platform/graphics/chromium/FontPlatformDataLinux.cpp
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
3dd05f035e0a5fc9723300623e9b9b359be64e11
[ "Unlicense" ]
15
2016-01-05T12:43:41.000Z
2022-03-15T10:34:47.000Z
webkit/WebCore/platform/graphics/chromium/FontPlatformDataLinux.cpp
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
3dd05f035e0a5fc9723300623e9b9b359be64e11
[ "Unlicense" ]
null
null
null
webkit/WebCore/platform/graphics/chromium/FontPlatformDataLinux.cpp
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
3dd05f035e0a5fc9723300623e9b9b359be64e11
[ "Unlicense" ]
2
2020-11-30T18:36:01.000Z
2021-02-05T23:20:24.000Z
/* * Copyright (c) 2006, 2007, 2008, Google 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 * 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 "config.h" #include "FontPlatformData.h" #include "HarfbuzzSkia.h" #include "NotImplemented.h" #include "PlatformString.h" #include "StringImpl.h" #include "SkPaint.h" #include "SkTypeface.h" namespace WebCore { static SkPaint::Hinting skiaHinting = SkPaint::kNormal_Hinting; static bool isSkiaAntiAlias = true, isSkiaSubpixelGlyphs; void FontPlatformData::setHinting(SkPaint::Hinting hinting) { skiaHinting = hinting; } void FontPlatformData::setAntiAlias(bool isAntiAlias) { isSkiaAntiAlias = isAntiAlias; } void FontPlatformData::setSubpixelGlyphs(bool isSubpixelGlyphs) { isSkiaSubpixelGlyphs = isSubpixelGlyphs; } FontPlatformData::RefCountedHarfbuzzFace::~RefCountedHarfbuzzFace() { HB_FreeFace(m_harfbuzzFace); } FontPlatformData::FontPlatformData(const FontPlatformData& src) : m_typeface(src.m_typeface) , m_textSize(src.m_textSize) , m_fakeBold(src.m_fakeBold) , m_fakeItalic(src.m_fakeItalic) , m_harfbuzzFace(src.m_harfbuzzFace) { m_typeface->safeRef(); } FontPlatformData::FontPlatformData(SkTypeface* tf, float textSize, bool fakeBold, bool fakeItalic) : m_typeface(tf) , m_textSize(textSize) , m_fakeBold(fakeBold) , m_fakeItalic(fakeItalic) { m_typeface->safeRef(); } FontPlatformData::FontPlatformData(const FontPlatformData& src, float textSize) : m_typeface(src.m_typeface) , m_textSize(textSize) , m_fakeBold(src.m_fakeBold) , m_fakeItalic(src.m_fakeItalic) , m_harfbuzzFace(src.m_harfbuzzFace) { m_typeface->safeRef(); } FontPlatformData::~FontPlatformData() { m_typeface->safeUnref(); } FontPlatformData& FontPlatformData::operator=(const FontPlatformData& src) { SkRefCnt_SafeAssign(m_typeface, src.m_typeface); m_textSize = src.m_textSize; m_fakeBold = src.m_fakeBold; m_fakeItalic = src.m_fakeItalic; m_harfbuzzFace = src.m_harfbuzzFace; return *this; } #ifndef NDEBUG String FontPlatformData::description() const { return String(); } #endif void FontPlatformData::setupPaint(SkPaint* paint) const { const float ts = m_textSize > 0 ? m_textSize : 12; paint->setAntiAlias(isSkiaAntiAlias); paint->setHinting(skiaHinting); paint->setLCDRenderText(isSkiaSubpixelGlyphs); paint->setTextSize(SkFloatToScalar(ts)); paint->setTypeface(m_typeface); paint->setFakeBoldText(m_fakeBold); paint->setTextSkewX(m_fakeItalic ? -SK_Scalar1 / 4 : 0); } SkFontID FontPlatformData::uniqueID() const { return m_typeface->uniqueID(); } bool FontPlatformData::operator==(const FontPlatformData& a) const { // If either of the typeface pointers are invalid (either NULL or the // special deleted value) then we test for pointer equality. Otherwise, we // call SkTypeface::Equal on the valid pointers. bool typefacesEqual; if (m_typeface == hashTableDeletedFontValue() || a.m_typeface == hashTableDeletedFontValue() || !m_typeface || !a.m_typeface) typefacesEqual = m_typeface == a.m_typeface; else typefacesEqual = SkTypeface::Equal(m_typeface, a.m_typeface); return typefacesEqual && m_textSize == a.m_textSize && m_fakeBold == a.m_fakeBold && m_fakeItalic == a.m_fakeItalic; } unsigned FontPlatformData::hash() const { unsigned h = SkTypeface::UniqueID(m_typeface); h ^= 0x01010101 * ((static_cast<int>(m_fakeBold) << 1) | static_cast<int>(m_fakeItalic)); // This memcpy is to avoid a reinterpret_cast that breaks strict-aliasing // rules. Memcpy is generally optimized enough so that performance doesn't // matter here. uint32_t textSizeBytes; memcpy(&textSizeBytes, &m_textSize, sizeof(uint32_t)); h ^= textSizeBytes; return h; } bool FontPlatformData::isFixedPitch() const { notImplemented(); return false; } HB_FaceRec_* FontPlatformData::harfbuzzFace() const { if (!m_harfbuzzFace) m_harfbuzzFace = RefCountedHarfbuzzFace::create(HB_NewFace(const_cast<FontPlatformData*>(this), harfbuzzSkiaGetTable)); return m_harfbuzzFace->face(); } } // namespace WebCore
30.265957
127
0.735852
s1rcheese
bf4c0c6e8831f0dabcb22e015a74ad33e893483d
1,076
hh
C++
pathtracer/src/datastruct/box/BoundingBox.hh
bjorn-grape/bidirectional-pathtracer
6fbbf5fc6cee39f595533494d779726658d646e1
[ "MIT" ]
null
null
null
pathtracer/src/datastruct/box/BoundingBox.hh
bjorn-grape/bidirectional-pathtracer
6fbbf5fc6cee39f595533494d779726658d646e1
[ "MIT" ]
null
null
null
pathtracer/src/datastruct/box/BoundingBox.hh
bjorn-grape/bidirectional-pathtracer
6fbbf5fc6cee39f595533494d779726658d646e1
[ "MIT" ]
null
null
null
#pragma once #include "Vector3D.hh" #include "SplitAxis.hh" #include "Ray.hh" class BoundingBox { public: BoundingBox(const Vector3D<float> &mini, const Vector3D<float> &maxi); BoundingBox(); inline SplitAxis::Axis GetLargestDimension() const; inline SplitAxis::Axis GetSmallestDimension() const; inline Vector3D<float> GetDimensions() const; bool DoIntersect(Ray r); bool FasterDoIntersect(Ray r); inline void readVector3DinMin(const Vector3D<float> &vector3D); inline void readVector3DinMax(const Vector3D<float> &vector3D); inline float getMinX() const; inline float getMinY() const; inline float getMinZ() const; inline float getMaxX() const; inline float getMaxY() const; inline float getMaxZ() const; inline void setExtremumFromPolygonList(const std::vector<Polygon> &polygons); inline float* operator[](const int& i); private: float min[3] = {0.f, 0.f, 0.f}; float max[3] = {0.f, 0.f, 0.f}; static const Vector3D<float> toleranceBoundaries; }; #include "BoundingBox.hxx"
22.893617
81
0.697955
bjorn-grape
bf5034669064e87d1da109095bf6599898933a3a
28,832
cpp
C++
src/agile_grasp2/plot.cpp
pyni/agile_grasp2
bbe64572f08f5f8b78f9f361da3fd5d3032cdbdf
[ "BSD-2-Clause" ]
null
null
null
src/agile_grasp2/plot.cpp
pyni/agile_grasp2
bbe64572f08f5f8b78f9f361da3fd5d3032cdbdf
[ "BSD-2-Clause" ]
null
null
null
src/agile_grasp2/plot.cpp
pyni/agile_grasp2
bbe64572f08f5f8b78f9f361da3fd5d3032cdbdf
[ "BSD-2-Clause" ]
1
2021-06-24T01:33:05.000Z
2021-06-24T01:33:05.000Z
#include <agile_grasp2/plot.h> void Plot::plotFingers(const std::vector<GraspHypothesis>& hand_list, const PointCloudRGBA::Ptr& cloud, std::string str, double outer_diameter) { const int WIDTH = pcl::visualization::PCL_VISUALIZER_LINE_WIDTH; boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer = createViewer(str); pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGBA> rgb(cloud); viewer->addPointCloud<pcl::PointXYZRGBA>(cloud, rgb, "cloud"); viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "cloud"); //~ PointCloudRGBA::Ptr cloud_fingers(new PointCloudRGBA); pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_fingers(new pcl::PointCloud<pcl::PointXYZ>); for (int i = 0; i < hand_list.size(); i++) { //~ pcl::PointXYZRGBA pc; pcl::PointXYZ pc; pc.getVector3fMap() = hand_list[i].getGraspBottom().cast<float>(); // double width = hand_list[i].getGraspWidth(); double width = outer_diameter; double hw = 0.5 * width; double step = hw / 30.0; Eigen::Vector3d left_bottom = hand_list[i].getGraspBottom() + hw * hand_list[i].getBinormal(); Eigen::Vector3d right_bottom = hand_list[i].getGraspBottom() - hw * hand_list[i].getBinormal(); //~ pcl::PointXYZRGBA p1, p2; pcl::PointXYZ p1, p2; p1.getVector3fMap() = left_bottom.cast<float>(); p2.getVector3fMap() = right_bottom.cast<float>(); cloud_fingers->points.push_back(pc); cloud_fingers->points.push_back(p1); cloud_fingers->points.push_back(p2); for (double j=step; j < hw; j+=step) { Eigen::Vector3d lb, rb, a; lb = hand_list[i].getGraspBottom() + j * hand_list[i].getBinormal(); rb = hand_list[i].getGraspBottom() - j * hand_list[i].getBinormal(); a = hand_list[i].getGraspBottom() - j * hand_list[i].getApproach(); //~ pcl::PointXYZRGBA plb, prb, pa; pcl::PointXYZ plb, prb, pa; plb.getVector3fMap() = lb.cast<float>(); prb.getVector3fMap() = rb.cast<float>(); pa.getVector3fMap() = a.cast<float>(); cloud_fingers->points.push_back(plb); cloud_fingers->points.push_back(prb); cloud_fingers->points.push_back(pa); } double dist = (hand_list[i].getGraspTop() - hand_list[i].getGraspBottom()).norm(); step = dist / 40.0; for (double j=step; j < dist; j+=step) { Eigen::Vector3d lt, rt; lt = left_bottom + j * hand_list[i].getApproach(); rt = right_bottom + j * hand_list[i].getApproach(); //~ pcl::PointXYZRGBA plt, prt; pcl::PointXYZ plt, prt; plt.getVector3fMap() = lt.cast<float>(); prt.getVector3fMap() = rt.cast<float>(); cloud_fingers->points.push_back(plt); cloud_fingers->points.push_back(prt); } //~ std::string istr = boost::lexical_cast<std::string>(i); //~ viewer->addLine<pcl::PointXYZ>(center, left_bottom, 0.0, 0.0, 1.0, "left_bottom_" + istr); //~ viewer->addLine<pcl::PointXYZ>(center, right_bottom, 0.0, 0.0, 1.0, "right_bottom_" + istr); //~ viewer->addLine<pcl::PointXYZ>(left_bottom, left_top, 0.0, 0.0, 1.0, "left_top_" + istr); //~ viewer->addLine<pcl::PointXYZ>(right_bottom, right_top, 0.0, 0.0, 1.0, "right_top_" + istr); //~ viewer->addLine<pcl::PointXYZ>(center, approach_center, 0.0, 0.0, 1.0, "approach_" + istr); //~ //~ viewer->setShapeRenderingProperties(WIDTH, 5, "left_bottom_" + boost::lexical_cast<std::string>(i)); //~ viewer->setShapeRenderingProperties(WIDTH, 5, "right_bottom_" + boost::lexical_cast<std::string>(i)); //~ viewer->setShapeRenderingProperties(WIDTH, 5, "left_top_" + boost::lexical_cast<std::string>(i)); //~ viewer->setShapeRenderingProperties(WIDTH, 5, "right_top_" + boost::lexical_cast<std::string>(i)); //~ viewer->setShapeRenderingProperties(WIDTH, 5, "approach_" + boost::lexical_cast<std::string>(i)); //~ viewer->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_REPRESENTATION, //~ pcl::visualization::PCL_VISUALIZER_REPRESENTATION_WIREFRAME, "approach_" + boost::lexical_cast<std::string>(i)); } viewer->addPointCloud<pcl::PointXYZ>(cloud_fingers, "fingers"); viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, 0.0, 0.0, 0.8, "fingers"); viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 5, "fingers"); viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_OPACITY, 0.4, "fingers"); runViewer(viewer); } void Plot::plotFingers(const std::vector<Handle>& hand_list, const PointCloudRGBA::Ptr& cloud, std::string str, double outer_diameter) { const int WIDTH = pcl::visualization::PCL_VISUALIZER_LINE_WIDTH; boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer = createViewer(str); pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGBA> rgb(cloud); viewer->addPointCloud<pcl::PointXYZRGBA>(cloud, rgb, "cloud"); viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "cloud"); //~ PointCloudRGBA::Ptr cloud_fingers(new PointCloudRGBA); pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_fingers(new pcl::PointCloud<pcl::PointXYZ>); for (int i = 0; i < hand_list.size(); i++) { //~ pcl::PointXYZRGBA pc; pcl::PointXYZ pc; pc.getVector3fMap() = hand_list[i].getGraspBottom().cast<float>(); // double width = hand_list[i].getGraspWidth(); double width = outer_diameter; double hw = 0.5 * width; double step = hw / 30.0; Eigen::Vector3d left_bottom = hand_list[i].getGraspBottom() + hw * hand_list[i].getBinormal(); Eigen::Vector3d right_bottom = hand_list[i].getGraspBottom() - hw * hand_list[i].getBinormal(); //~ pcl::PointXYZRGBA p1, p2; pcl::PointXYZ p1, p2; p1.getVector3fMap() = left_bottom.cast<float>(); p2.getVector3fMap() = right_bottom.cast<float>(); cloud_fingers->points.push_back(pc); cloud_fingers->points.push_back(p1); cloud_fingers->points.push_back(p2); for (double j=step; j < hw; j+=step) { Eigen::Vector3d lb, rb, a; lb = hand_list[i].getGraspBottom() + j * hand_list[i].getBinormal(); rb = hand_list[i].getGraspBottom() - j * hand_list[i].getBinormal(); a = hand_list[i].getGraspBottom() - j * hand_list[i].getApproach(); //~ pcl::PointXYZRGBA plb, prb, pa; pcl::PointXYZ plb, prb, pa; plb.getVector3fMap() = lb.cast<float>(); prb.getVector3fMap() = rb.cast<float>(); pa.getVector3fMap() = a.cast<float>(); cloud_fingers->points.push_back(plb); cloud_fingers->points.push_back(prb); cloud_fingers->points.push_back(pa); } double dist = (hand_list[i].getGraspTop() - hand_list[i].getGraspBottom()).norm(); step = dist / 40.0; for (double j=step; j < dist; j+=step) { Eigen::Vector3d lt, rt; lt = left_bottom + j * hand_list[i].getApproach(); rt = right_bottom + j * hand_list[i].getApproach(); //~ pcl::PointXYZRGBA plt, prt; pcl::PointXYZ plt, prt; plt.getVector3fMap() = lt.cast<float>(); prt.getVector3fMap() = rt.cast<float>(); cloud_fingers->points.push_back(plt); cloud_fingers->points.push_back(prt); } //~ std::string istr = boost::lexical_cast<std::string>(i); //~ viewer->addLine<pcl::PointXYZ>(center, left_bottom, 0.0, 0.0, 1.0, "left_bottom_" + istr); //~ viewer->addLine<pcl::PointXYZ>(center, right_bottom, 0.0, 0.0, 1.0, "right_bottom_" + istr); //~ viewer->addLine<pcl::PointXYZ>(left_bottom, left_top, 0.0, 0.0, 1.0, "left_top_" + istr); //~ viewer->addLine<pcl::PointXYZ>(right_bottom, right_top, 0.0, 0.0, 1.0, "right_top_" + istr); //~ viewer->addLine<pcl::PointXYZ>(center, approach_center, 0.0, 0.0, 1.0, "approach_" + istr); //~ //~ viewer->setShapeRenderingProperties(WIDTH, 5, "left_bottom_" + boost::lexical_cast<std::string>(i)); //~ viewer->setShapeRenderingProperties(WIDTH, 5, "right_bottom_" + boost::lexical_cast<std::string>(i)); //~ viewer->setShapeRenderingProperties(WIDTH, 5, "left_top_" + boost::lexical_cast<std::string>(i)); //~ viewer->setShapeRenderingProperties(WIDTH, 5, "right_top_" + boost::lexical_cast<std::string>(i)); //~ viewer->setShapeRenderingProperties(WIDTH, 5, "approach_" + boost::lexical_cast<std::string>(i)); //~ viewer->setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_REPRESENTATION, //~ pcl::visualization::PCL_VISUALIZER_REPRESENTATION_WIREFRAME, "approach_" + boost::lexical_cast<std::string>(i)); } viewer->addPointCloud<pcl::PointXYZ>(cloud_fingers, "fingers"); viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, 0.0, 0.0, 0.8, "fingers"); viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 5, "fingers"); viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_OPACITY, 0.4, "fingers"); runViewer(viewer); } void Plot::plotHands(const std::vector<GraspHypothesis>& hand_list, const std::vector<GraspHypothesis>& antipodal_hand_list, const PointCloudRGBA::Ptr& cloud, std::string str, bool use_grasp_bottom) { PointCloudNormal::Ptr hands_cloud = createNormalsCloud(hand_list, false, false); PointCloudNormal::Ptr antipodal_hands_cloud = createNormalsCloud(antipodal_hand_list, true, false); plotHandsHelper(hands_cloud, antipodal_hands_cloud, cloud, str, use_grasp_bottom); } void Plot::plotHands(const std::vector<GraspHypothesis>& hand_list, const PointCloudRGBA::Ptr& cloud, std::string str, bool use_grasp_bottom) { PointCloudNormal::Ptr hands_cloud = createNormalsCloud(hand_list, false, false); PointCloudNormal::Ptr antipodal_hands_cloud = createNormalsCloud(hand_list, true, false); plotHandsHelper(hands_cloud, antipodal_hands_cloud, cloud, str, use_grasp_bottom); } void Plot::plotSamples(const std::vector<int>& index_list, const PointCloudRGBA::Ptr& cloud) { PointCloudRGBA::Ptr samples_cloud(new PointCloudRGBA); for (int i = 0; i < index_list.size(); i++) samples_cloud->points.push_back(cloud->points[index_list[i]]); plotSamples(samples_cloud, cloud); } void Plot::plotSamples(const Eigen::Matrix3Xd& samples, const PointCloudRGBA::Ptr& cloud) { PointCloudRGBA::Ptr samples_cloud(new PointCloudRGBA); for (int i = 0; i < samples.cols(); i++) { pcl::PointXYZRGBA p; p.x = samples.col(i)(0); p.y = samples.col(i)(1); p.z = samples.col(i)(2); samples_cloud->points.push_back(p); } plotSamples(samples_cloud, cloud); } void Plot::plotSamples(const PointCloudRGBA::Ptr& samples_cloud, const PointCloudRGBA::Ptr& cloud) { boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer = createViewer("Samples"); // draw the point cloud pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGBA> rgb(cloud); viewer->addPointCloud<pcl::PointXYZRGBA>(cloud, rgb, "registered point cloud"); viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "registered point cloud"); // draw the samples viewer->addPointCloud<pcl::PointXYZRGBA>(samples_cloud, "samples cloud"); viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 4, "samples cloud"); viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, 1.0, 0.0, 1.0, "samples cloud"); runViewer(viewer); } void Plot::plotNormals(const PointCloudRGBA::Ptr& cloud, const Eigen::Matrix3Xd& normals) { PointCloudNormal::Ptr normals_cloud(new PointCloudNormal); for (int i=0; i < normals.cols(); i++) { pcl::PointNormal p; p.x = cloud->points[i].x; p.y = cloud->points[i].y; p.z = cloud->points[i].z; p.normal_x = normals(0,i); p.normal_y = normals(1,i); p.normal_z = normals(2,i); normals_cloud->points.push_back(p); } std::cout << "Drawing " << normals_cloud->size() << " normals\n"; double red[3] = {1.0, 0.0, 0.0}; double blue[3] = {0.0, 0.0, 1.0}; boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer = createViewer("Normals"); addCloudNormalsToViewer(viewer, normals_cloud, 2, blue, red, std::string("cloud"), std::string("normals")); runViewer(viewer); } void Plot::plotLocalAxes(const std::vector<LocalFrame>& quadric_list, const PointCloudRGBA::Ptr& cloud) { boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer = createViewer("Local Axes"); viewer->addPointCloud<pcl::PointXYZRGBA>(cloud, "registered point cloud"); viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "registered point cloud"); for (int i = 0; i < quadric_list.size(); i++) quadric_list[i].plotAxes((void*) &viewer, i); runViewer(viewer); } void Plot::plotCameraSource(const Eigen::VectorXi& pts_cam_source_in, const PointCloudRGBA::Ptr& cloud) { PointCloudRGBA::Ptr left_cloud(new PointCloudRGBA); PointCloudRGBA::Ptr right_cloud(new PointCloudRGBA); for (int i = 0; i < pts_cam_source_in.size(); i++) { if (pts_cam_source_in(i) == 0) left_cloud->points.push_back(cloud->points[i]); else if (pts_cam_source_in(i) == 1) right_cloud->points.push_back(cloud->points[i]); } boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer = createViewer("Camera Sources"); viewer->addPointCloud<pcl::PointXYZRGBA>(left_cloud, "left point cloud"); viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "left point cloud"); viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, 1.0, 0.0, 0.0, "left point cloud"); viewer->addPointCloud<pcl::PointXYZRGBA>(right_cloud, "right point cloud"); viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "right point cloud"); viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, 0.0, 1.0, 0.0, "right point cloud"); runViewer(viewer); } PointCloudNormal::Ptr Plot::createNormalsCloud(const std::vector<GraspHypothesis>& hand_list, bool plots_only_antipodal, bool plots_grasp_bottom) { PointCloudNormal::Ptr cloud(new PointCloudNormal); for (int i = 0; i < hand_list.size(); i++) { Eigen::Matrix3Xd grasp_surface = hand_list[i].getGraspSurface(); Eigen::Matrix3Xd grasp_bottom = hand_list[i].getGraspBottom(); Eigen::Matrix3Xd hand_approach = hand_list[i].getApproach(); if (!plots_only_antipodal || (plots_only_antipodal && hand_list[i].isFullAntipodal())) { pcl::PointNormal p; if (!plots_grasp_bottom) { p.x = grasp_surface(0); p.y = grasp_surface(1); p.z = grasp_surface(2); } else { p.x = grasp_bottom(0); p.y = grasp_bottom(1); p.z = grasp_bottom(2); } p.normal[0] = -hand_approach(0); p.normal[1] = -hand_approach(1); p.normal[2] = -hand_approach(2); cloud->points.push_back(p); } } return cloud; } void Plot::addCloudNormalsToViewer(boost::shared_ptr<pcl::visualization::PCLVisualizer>& viewer, const PointCloudNormal::Ptr& cloud, double line_width, double* color_cloud, double* color_normals, const std::string& cloud_name, const std::string& normals_name) { viewer->addPointCloud<pcl::PointNormal>(cloud, cloud_name); viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, color_cloud[0], color_cloud[1], color_cloud[2], cloud_name); viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 6, cloud_name); viewer->addPointCloudNormals<pcl::PointNormal>(cloud, 1, 0.01, normals_name); viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_LINE_WIDTH, line_width, normals_name); viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, color_normals[0], color_normals[1], color_normals[2], normals_name); } void Plot::plotHandsHelper(const PointCloudNormal::Ptr& hands_cloud, const PointCloudNormal::Ptr& antipodal_hands_cloud, const PointCloudRGBA::Ptr& cloud, std::string str, bool use_grasp_bottom) { std::cout << "Drawing " << hands_cloud->size() << " grasps of which " << antipodal_hands_cloud->size() << " are antipodal grasps.\n"; std::string title = "Hands: " + str; boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer = createViewer(title); pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGBA> rgb(cloud); viewer->addPointCloud<pcl::PointXYZRGBA>(cloud, rgb, "cloud"); viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "cloud"); double green[3] = { 0.0, 1.0, 0.0 }; double cyan[3] = { 0.0, 0.4, 0.8 }; addCloudNormalsToViewer(viewer, hands_cloud, 2, green, cyan, std::string("hands"), std::string("approaches")); if (antipodal_hands_cloud->size() > 0) { double red[3] = { 1.0, 0.0, 0.0 }; addCloudNormalsToViewer(viewer, antipodal_hands_cloud, 2, green, red, std::string("antipodal_hands"), std::string("antipodal_approaches")); } runViewer(viewer); } void Plot::runViewer(boost::shared_ptr<pcl::visualization::PCLVisualizer>& viewer) { while (!viewer->wasStopped()) { viewer->spinOnce(100); boost::this_thread::sleep(boost::posix_time::microseconds(100000)); } viewer->close(); } boost::shared_ptr<pcl::visualization::PCLVisualizer> Plot::createViewer(std::string title) { boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer(new pcl::visualization::PCLVisualizer(title)); // viewer->initCameraParameters(); viewer->setPosition(0, 0); viewer->setSize(640, 480); viewer->setBackgroundColor(1.0, 1.0, 1.0); pcl::visualization::Camera camera; camera.clip[0] = 0.00130783; camera.clip[1] = 1.30783; camera.focal[0] = 0.776838; camera.focal[1] = -0.095644; camera.focal[2] = -0.18991; camera.pos[0] = 0.439149; camera.pos[1] = -0.10342; camera.pos[2] = 0.111626; camera.view[0] = 0.666149; camera.view[1] = -0.0276846; camera.view[2] = 0.745305; camera.fovy = 0.8575; camera.window_pos[0] = 0; camera.window_pos[1] = 0; camera.window_size[0] = 640; camera.window_size[1] = 480; viewer->setCameraParameters(camera); // viewer->updateCamera(); // viewer->addCoordinateSystem(0.5, 0); return viewer; } void Plot::createVisualPublishers(ros::NodeHandle& node, double marker_lifetime) { hypotheses_pub_ = node.advertise<visualization_msgs::MarkerArray>("grasp_hypotheses_visual", 10); antipodal_pub_ = node.advertise<visualization_msgs::MarkerArray>("antipodal_grasps_visual", 10); handles_pub_ = node.advertise<visualization_msgs::MarkerArray>("handles_visual", 10); marker_lifetime_ = marker_lifetime; } void Plot::plotGraspsRviz(const std::vector<GraspHypothesis>& hand_list, const std::string& frame, bool is_antipodal) { double red[3] = {1, 0, 0}; double cyan[3] = {0, 1, 1}; double* color; if (is_antipodal) { color = red; std::cout << "Visualizing antipodal grasps in Rviz ...\n"; } else { color = cyan; std::cout << "Visualizing grasp hypotheses in Rviz ...\n"; } visualization_msgs::MarkerArray marker_array; marker_array.markers.resize(hand_list.size()); for (int i=0; i < hand_list.size(); i++) { geometry_msgs::Point position; position.x = hand_list[i].getGraspSurface()(0); position.y = hand_list[i].getGraspSurface()(1); position.z = hand_list[i].getGraspSurface()(2); visualization_msgs::Marker marker = createApproachMarker(frame, position, hand_list[i].getApproach(), i, color, 0.4, 0.004); marker.ns = "grasp_hypotheses"; marker.id = i; marker_array.markers[i] = marker; } if (is_antipodal) antipodal_pub_.publish(marker_array); else hypotheses_pub_.publish(marker_array); ros::Duration(1.0).sleep(); } void Plot::plotHandlesRviz(const std::vector<Handle>& handle_list, const std::string& frame) { std::cout << "Visualizing handles in Rviz ...\n"; double green[3] = {0, 1, 0}; visualization_msgs::MarkerArray marker_array; marker_array.markers.resize(handle_list.size()); for (int i=0; i < handle_list.size(); i++) { geometry_msgs::Point position; position.x = handle_list[i].getGraspSurface()(0); position.y = handle_list[i].getGraspSurface()(1); position.z = handle_list[i].getGraspSurface()(2); visualization_msgs::Marker marker = createApproachMarker(frame, position, handle_list[i].getApproach(), i, green, 0.6, 0.008); marker.ns = "handles"; marker_array.markers[i] = marker; } handles_pub_.publish(marker_array); ros::Duration(1.0).sleep(); } void Plot::plotHandlesComplete(const std::vector<Handle>& handle_list, const PointCloudRGBA::Ptr& cloud, std::string str) { const int WIDTH = pcl::visualization::PCL_VISUALIZER_LINE_WIDTH; const double OFFSET = 0.06; boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer = createViewer(str); pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGBA> rgb(cloud); viewer->addPointCloud<pcl::PointXYZRGBA>(cloud, rgb, "cloud"); viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "cloud"); for (int i = 0; i < handle_list.size(); i++) { std::cout << "axis.norm: " << handle_list[i].getAxis().norm() << ", approach.norm: " << handle_list[i].getApproach().norm() << ", binormal.norm: " << handle_list[i].getBinormal().norm() << std::endl; std::cout << "axis*approach: " << handle_list[i].getAxis().transpose() * handle_list[i].getApproach() << ", axis*binormal: " << handle_list[i].getAxis().transpose() * handle_list[i].getBinormal() << ", binormal*approach: " << handle_list[i].getApproach().transpose() * handle_list[i].getBinormal() << "\n"; pcl::PointXYZ p, q, r, s; p.getVector3fMap() = handle_list[i].getGraspSurface().cast<float>(); q.getVector3fMap() = (handle_list[i].getGraspSurface() + OFFSET*handle_list[i].getAxis()).cast<float>(); r.getVector3fMap() = (handle_list[i].getGraspSurface() + OFFSET*handle_list[i].getApproach()).cast<float>(); s.getVector3fMap() = (handle_list[i].getGraspSurface() + OFFSET*handle_list[i].getBinormal()).cast<float>(); std::string istr = boost::lexical_cast<std::string>(i); viewer->addLine<pcl::PointXYZ> (p, q, 1.0, 0.0, 0.0, "axis_" + istr); viewer->addLine<pcl::PointXYZ> (p, r, 0.0, 1.0, 0.0, "approach_" + istr); viewer->addLine<pcl::PointXYZ> (p, s, 0.0, 0.0, 1.0, "binormal_" + istr); viewer->setShapeRenderingProperties(WIDTH, 5, "axis_" + boost::lexical_cast<std::string>(i)); viewer->setShapeRenderingProperties(WIDTH, 5, "approach_" + boost::lexical_cast<std::string>(i)); viewer->setShapeRenderingProperties(WIDTH, 5, "binormal_" + boost::lexical_cast<std::string>(i)); } runViewer(viewer); } void Plot::plotHandles(const std::vector<Handle>& handle_list, const PointCloudRGBA::Ptr& cloud, std::string str) { double colors[6][3] = { { 1.0, 0.0, 0.0 }, { 0.0, 1.0, 0.0 }, { 0.0, 0.0, 1.0 }, { 1.0, 1.0, 0.0 }, { 1.0, 0.0, 1.0 }, { 0.0, 1.0, 1.0 } }; // { 0, 0.4470, 0.7410 }, // { 0, 0.4470, 0.7410 }, { 0, 0.4470, 0.7410 }, { 0.8500, 0.3250, 0.0980 }, { 0.9290, 0.6940, 0.1250 }, // { 0.4940, 0.1840, 0.5560 }, { 0.4660, 0.6740, 0.1880 }, { 0.3010, 0.7450, 0.9330 }, { 0.6350, 0.0780, 0.1840 }, // { 0, 0.4470, 0.7410 }, { 0.8500, 0.3250, 0.0980 }, { 0.9290, 0.6940, 0.1250} }; // 0.4940 0.1840 0.5560 // 0.4660 0.6740 0.1880 // 0.3010 0.7450 0.9330 // 0.6350 0.0780 0.1840 // 0 0.4470 0.7410 // 0.8500 0.3250 0.0980 // 0.9290 0.6940 0.1250 // 0.4940 0.1840 0.5560 // 0.4660 0.6740 0.1880 // 0.3010 0.7450 0.9330 // 0.6350 0.0780 0.1840 std::vector<pcl::PointCloud<pcl::PointNormal>::Ptr> clouds; pcl::PointCloud<pcl::PointNormal>::Ptr handle_cloud(new pcl::PointCloud<pcl::PointNormal>()); for (int i = 0; i < handle_list.size(); i++) { pcl::PointNormal p; p.x = handle_list[i].getGraspSurface()(0); p.y = handle_list[i].getGraspSurface()(1); p.z = handle_list[i].getGraspSurface()(2); p.normal[0] = -handle_list[i].getApproach()(0); p.normal[1] = -handle_list[i].getApproach()(1); p.normal[2] = -handle_list[i].getApproach()(2); handle_cloud->points.push_back(p); const std::vector<int>& inliers = handle_list[i].getInliers(); const std::vector<GraspHypothesis>& hand_list = handle_list[i].getHandList(); pcl::PointCloud<pcl::PointNormal>::Ptr axis_cloud(new pcl::PointCloud<pcl::PointNormal>); for (int j = 0; j < inliers.size(); j++) { pcl::PointNormal p; p.x = hand_list[inliers[j]].getGraspSurface()(0); p.y = hand_list[inliers[j]].getGraspSurface()(1); p.z = hand_list[inliers[j]].getGraspSurface()(2); p.normal[0] = -hand_list[inliers[j]].getApproach()(0); p.normal[1] = -hand_list[inliers[j]].getApproach()(1); p.normal[2] = -hand_list[inliers[j]].getApproach()(2); axis_cloud->points.push_back(p); } clouds.push_back(axis_cloud); } boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer(new pcl::visualization::PCLVisualizer(str)); viewer->setBackgroundColor(1, 1, 1); viewer->setPosition(0, 0); viewer->setSize(640, 480); pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGBA> rgb(cloud); viewer->addPointCloud<pcl::PointXYZRGBA>(cloud, rgb, "registered point cloud"); viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "registered point cloud"); // viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, 0.0, 1.0, 0.0, // "registered point cloud"); for (int i = 0; i < clouds.size(); i++) { std::string name = "handle_" + boost::lexical_cast<std::string>(i); int ci = i % 6; viewer->addPointCloud<pcl::PointNormal>(clouds[i], name); viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, colors[ci][0], colors[ci][1], colors[ci][2], name); std::string name2 = "approach_" + boost::lexical_cast<std::string>(i); viewer->addPointCloudNormals<pcl::PointNormal>(clouds[i], 1, 0.04, name2); viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_LINE_WIDTH, 2, name2); viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, colors[ci][0], colors[ci][1], colors[ci][2], name2); } viewer->addPointCloud<pcl::PointNormal>(handle_cloud, "handles"); viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, 0, 0, 0, "handles"); viewer->addPointCloudNormals<pcl::PointNormal>(handle_cloud, 1, 0.08, "approach"); viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_LINE_WIDTH, 4, "approach"); viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, 0, 0, 0, "approach"); // viewer->addCoordinateSystem(1.0, "", 0); viewer->initCameraParameters(); viewer->setPosition(0, 0); viewer->setSize(640, 480); while (!viewer->wasStopped()) { viewer->spinOnce(100); boost::this_thread::sleep(boost::posix_time::microseconds(100000)); } viewer->close(); } void Plot::drawCloud(const PointCloudRGBA::Ptr& cloud_rgb, const std::string& title) { boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer = createViewer(title); pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGBA> rgb(cloud_rgb); viewer->addPointCloud<pcl::PointXYZRGBA>(cloud_rgb, rgb, "registered point cloud"); viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "registered point cloud"); runViewer(viewer); } visualization_msgs::Marker Plot::createApproachMarker(const std::string& frame, const geometry_msgs::Point& center, const Eigen::Vector3d& approach, int id, const double* color, double alpha, double diam) { visualization_msgs::Marker marker = createMarker(frame); marker.type = visualization_msgs::Marker::ARROW; marker.id = id; marker.scale.x = diam; // shaft diameter marker.scale.y = diam; // head diameter marker.scale.z = 0.01; // head length marker.color.r = color[0]; marker.color.g = color[1]; marker.color.b = color[2]; marker.color.a = alpha; geometry_msgs::Point p, q; p.x = center.x; p.y = center.y; p.z = center.z; q.x = p.x - 0.03 * approach(0); q.y = p.y - 0.03 * approach(1); q.z = p.z - 0.03 * approach(2); marker.points.push_back(p); marker.points.push_back(q); return marker; } visualization_msgs::Marker Plot::createMarker(const std::string& frame) { visualization_msgs::Marker marker; marker.header.frame_id = frame; marker.header.stamp = ros::Time::now(); marker.lifetime = ros::Duration(marker_lifetime_); marker.action = visualization_msgs::Marker::ADD; return marker; }
41.30659
122
0.695581
pyni
bf53850616ef00ac2520e6faa9d5d6443781ea9e
1,464
hpp
C++
include/lattice_model_impl/update_dynamics/lattice_update_dynamics/lattice_update_formalisms/global_lattice_update.hpp
statphysandml/LatticeModelSimulationLib
37900336a35d81d28f3477c44da64e692212973a
[ "MIT" ]
null
null
null
include/lattice_model_impl/update_dynamics/lattice_update_dynamics/lattice_update_formalisms/global_lattice_update.hpp
statphysandml/LatticeModelSimulationLib
37900336a35d81d28f3477c44da64e692212973a
[ "MIT" ]
3
2021-02-24T16:34:35.000Z
2021-11-30T13:14:24.000Z
include/lattice_model_impl/update_dynamics/lattice_update_dynamics/lattice_update_formalisms/global_lattice_update.hpp
statphysandml/LatticeModelSimulationLib
37900336a35d81d28f3477c44da64e692212973a
[ "MIT" ]
null
null
null
// // Created by lukas on 06.08.20. // #ifndef LATTICEMODELIMPLEMENTATIONS_SIMPLE_UPDATE_HPP #define LATTICEMODELIMPLEMENTATIONS_SIMPLE_UPDATE_HPP #include "../../update_dynamics_base.hpp" namespace lm_impl { namespace update_dynamics { struct GlobalLatticeUpdate; struct GlobalLatticeUpdateParameters : UpdateDynamicsBaseParameters { explicit GlobalLatticeUpdateParameters(const json params_) : UpdateDynamicsBaseParameters(params_) {} explicit GlobalLatticeUpdateParameters() : GlobalLatticeUpdateParameters(json{}) {} static std::string name() { return "GlobalLatticeUpdate"; } typedef GlobalLatticeUpdate UpdateDynamics; // LatticeUpdate; }; struct GlobalLatticeUpdate : public UpdateDynamicsBase<GlobalLatticeUpdate> { explicit GlobalLatticeUpdate(const GlobalLatticeUpdateParameters &lp_) : lp(lp_) {} template<typename Lattice> void initialize_update(const Lattice &lattice) {} template<typename Lattice> void update(Lattice &lattice, uint measure_interval = 1) { for (uint k = 0; k < measure_interval; k++) { global_lattice_update(lattice.get_update_formalism(), lattice); } } const GlobalLatticeUpdateParameters &lp; }; } } #endif //LATTICEMODELIMPLEMENTATIONS_SIMPLE_UPDATE_HPP
29.877551
113
0.664617
statphysandml
bf53c6161aff43cfc043d24ff41f55a02b8dd89a
4,204
cpp
C++
sketches/handwriting_recognizer/arduino_imu_handler.cpp
metanav/Handwriting_Recognition_IMU
8d874ced4a7c97f14733719805cbc54262c07673
[ "Apache-2.0" ]
6
2020-04-09T14:28:44.000Z
2022-01-08T21:48:21.000Z
sketches/handwriting_recognizer/arduino_imu_handler.cpp
metanav/Handwriting_Recognition_IMU
8d874ced4a7c97f14733719805cbc54262c07673
[ "Apache-2.0" ]
1
2021-03-19T04:12:02.000Z
2021-03-22T02:58:32.000Z
sketches/handwriting_recognizer/arduino_imu_handler.cpp
metanav/Handwriting_Recognition_IMU
8d874ced4a7c97f14733719805cbc54262c07673
[ "Apache-2.0" ]
1
2021-04-21T04:57:06.000Z
2021-04-21T04:57:06.000Z
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "imu_handler.h" #include <Arduino.h> #include "ICM_20948.h" #include "constants.h" #define AD0_VAL 1 ICM_20948_I2C myICM; // A buffer holding the last 100 sets of 6-channel values float save_data[600] = {0.0}; // Most recent position in the save_data buffer int begin_index = 0; // True if there is not yet enough data to run inference bool pending_initial_data = true; TfLiteStatus InitIMU(tflite::ErrorReporter* error_reporter) { // Wait until we know the serial port is ready while (!Serial) { } // Switch on the IMU Wire.begin(); Wire.setClock(400000); myICM.begin( Wire, AD0_VAL ); if ( myICM.status != ICM_20948_Stat_Ok ) { error_reporter->Report("Failed to initialize IMU"); return kTfLiteError; } error_reporter->Report( myICM.statusString() ); enableBurstMode(); ICM_20948_smplrt_t mySmplrt; mySmplrt.g = 43; // 25 Hz myICM.setSampleRate( ICM_20948_Internal_Gyr, mySmplrt ); Serial.println(myICM.statusString()); // enable low pass filter myICM.enableDLPF( ICM_20948_Internal_Acc, true ); myICM.enableDLPF( ICM_20948_Internal_Gyr, true ); // disable fifo at the beginning, later enable it myICM.enableFifo(false); myICM.setFifoCfg(); // reset fifo myICM.resetFifo(0x1f); myICM.enableFifoSlv(false); myICM.enableFifoAGT(false); delay(10); myICM.cleanupFifo(); myICM.resetFifo(0x00); // enable fifo myICM.enableFifoAGT(true); myICM.setFifoMode(true); myICM.enableFifo(true); error_reporter->Report("IMU Initialized"); delay(100); return kTfLiteOk; } bool ReadIMU(tflite::ErrorReporter* error_reporter, float* input, int length, bool reset_buffer) { // Clear the buffer if required, e.g. after a successful prediction if (reset_buffer) { memset(save_data, 0, 600 * sizeof(float)); begin_index = 0; pending_initial_data = true; } int fifo_count = myICM.getFifoCount(); int samples = fifo_count / 14; // 6 (acc) + 6 (gyr) + 2 (temp) if (samples == 0) { return false; } for (int i = 0; i < samples; i++) { myICM.getAGMT(true); // pass true to get data from FIFO float ax = myICM.accX(); float ay = myICM.accY(); float az = myICM.accZ(); float gx = myICM.gyrX(); float gy = myICM.gyrY(); float gz = myICM.gyrZ(); //Serial.printf("[%f, %f, %f,%f, %f, %f]\n", ax, ay, az, gx, gy, gz); // Write samples to buffer save_data[begin_index++] = ax; save_data[begin_index++] = ay; save_data[begin_index++] = az; save_data[begin_index++] = gx; save_data[begin_index++] = gy; save_data[begin_index++] = gz; // If we reached the end of the circle buffer, reset if (begin_index >= 600) { begin_index = 0; } // delay(1); } // Check if we are ready for prediction or still pending more initial data if (pending_initial_data && begin_index >= 216) { pending_initial_data = false; } // Return if we don't have enough data if (pending_initial_data) { return false; } //Serial.printf("begin_index=%d\n", begin_index); // Copy the requested number of bytes to the provided input tensor for (int i = 0; i < length; ++i) { int ring_array_index = begin_index + i - length; if (ring_array_index < 0) { ring_array_index += 600; } input[i] = save_data[ring_array_index]; // Serial.print(input[i]); // // if ( (i + 1) % 6 == 0 ) { // Serial.println(""); // } else { // Serial.print(", "); // } } return true; }
26.77707
98
0.653901
metanav
bf55043ca9bfdd1e54352dba0388a0742ceead73
3,168
hpp
C++
ngraph/core/reference/include/ngraph/runtime/reference/ctc_greedy_decoder_seq_len.hpp
tkrupa-intel/openvino
8c0ff5d9065486d23901a9c27debd303661f465f
[ "Apache-2.0" ]
1
2021-05-30T18:25:07.000Z
2021-05-30T18:25:07.000Z
ngraph/core/reference/include/ngraph/runtime/reference/ctc_greedy_decoder_seq_len.hpp
tkrupa-intel/openvino
8c0ff5d9065486d23901a9c27debd303661f465f
[ "Apache-2.0" ]
null
null
null
ngraph/core/reference/include/ngraph/runtime/reference/ctc_greedy_decoder_seq_len.hpp
tkrupa-intel/openvino
8c0ff5d9065486d23901a9c27debd303661f465f
[ "Apache-2.0" ]
null
null
null
//***************************************************************************** // Copyright 2017-2021 Intel Corporation // // 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. //***************************************************************************** #pragma once #include <algorithm> #include <limits> #include <vector> #include "ngraph/coordinate_transform.hpp" namespace ngraph { namespace runtime { namespace reference { template <typename TF, typename TI, typename TCI, typename TSL> void ctc_greedy_decoder_seq_len(const TF* data, const TI* sequence_length, const TI* blank_index, TCI* out1, TSL* out2, const Shape& data_shape, const Shape& out_shape, const bool ctc_merge_repeated) { const auto batch_size = data_shape[0]; const auto seq_len_max = data_shape[1]; const auto class_count = data_shape[2]; std::fill_n(out1, shape_size(out_shape), -1); for (std::size_t batch_ind = 0; batch_ind < batch_size; ++batch_ind) { TI previous_class_index = static_cast<TI>(-1); auto out_index = batch_ind * seq_len_max; auto seq_len = static_cast<std::size_t>(sequence_length[batch_ind]); for (std::size_t seq_ind = 0; seq_ind < seq_len; seq_ind++) { auto data_index = batch_ind * seq_len_max * class_count + seq_ind * class_count; auto class_index = data + data_index; auto class_max_element = std::max_element(class_index, class_index + class_count); const auto max_class_ind = std::distance(class_index, class_max_element); if (max_class_ind < blank_index[0] && !(ctc_merge_repeated && previous_class_index == max_class_ind)) { out1[out_index++] = max_class_ind; } previous_class_index = max_class_ind; } out2[batch_ind] = seq_len; } } } // namespace reference } // namespace runtime } // namespace ngraph
45.257143
97
0.493687
tkrupa-intel
bf55cd40ed03718d7c1815f8ba8c7d3ee3880fad
1,823
cpp
C++
examples/DCGAN/src/ofApp.cpp
rystylee/ofxTFC
43c53ba706bd16619d78da7d8fc2ad01963663e3
[ "MIT" ]
4
2019-02-25T04:25:19.000Z
2020-12-04T15:22:27.000Z
examples/DCGAN/src/ofApp.cpp
rystylee/ofxTFC
43c53ba706bd16619d78da7d8fc2ad01963663e3
[ "MIT" ]
1
2021-09-11T23:06:16.000Z
2021-09-13T14:30:25.000Z
examples/DCGAN/src/ofApp.cpp
rystylee/ofxTFC
43c53ba706bd16619d78da7d8fc2ad01963663e3
[ "MIT" ]
3
2019-10-02T21:54:36.000Z
2021-05-30T23:09:18.000Z
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup() { ofSetBackgroundColor(0); ofSetVerticalSync(false); mGraphPath.listDir("models"); mModel.init(ofFilePath::getAbsolutePath(mGraphPath.getPath(0)), mInputOpName, mOutputOpName, mBatchSize, mInputDims, mModelInputRange, mModelOutputRange); for (int i = 0; i < mBatchSize; i++) { vector<float> z(mZDimension); mInputVecs.emplace_back(z); mTargetZ.emplace_back(z); ofFloatImage outputImg; outputImg.allocate(mGANResolution.x, mGANResolution.y, OF_IMAGE_COLOR); mOutputImgs.push_back(outputImg); } //mModel.printOpInfo(); } //-------------------------------------------------------------- void ofApp::update() { ofSetWindowTitle(ofToString(ofGetFrameRate())); float t = ofGetElapsedTimef() * 0.1; automate(t); } //-------------------------------------------------------------- void ofApp::draw() { mModel.runVecsToImgs(mInputVecs, mOutputImgs, mImageInputRange, mImageOutputRange); mOutputImgs[0].draw(glm::vec2(0, 0), ofGetWidth(), ofGetHeight()); } //-------------------------------------------------------------- void ofApp::keyPressed(int key) { } //-------------------------------------------------------------- void ofApp::automate(const float timescale) { for (int batch = 0; batch < mBatchSize; batch++) { for (int i = 0; i < mZDimension; i++) { int index = batch * mInputDims[1] + i; float n = ofMap(ofNoise(static_cast<float>(index) * 0.1, timescale), 0.0, 1.0, -1.0, 1.0); mInputVecs[batch][i] = n; } } } //--------------------------------------------------------------
29.885246
159
0.47943
rystylee
bf571a0b4858aef6b574178caf4800422f874682
765
cpp
C++
cpp/euler368.cpp
t-highfill/project-euler
f92ad1092f2529994e7b2d023180a60a5c8194ee
[ "MIT" ]
null
null
null
cpp/euler368.cpp
t-highfill/project-euler
f92ad1092f2529994e7b2d023180a60a5c8194ee
[ "MIT" ]
null
null
null
cpp/euler368.cpp
t-highfill/project-euler
f92ad1092f2529994e7b2d023180a60a5c8194ee
[ "MIT" ]
null
null
null
#include <cstdint> #include <iostream> #include <map> typedef uint32_t denom_t; typedef std::map<denom_t, bool> known_map; bool validate(denom_t d, known_map& known){ while(d >= 111){ // auto itr = known.find(d); // if(itr != known.end()) // return itr->second; if((d % 1000) % 111 == 0){ return false; } d /= 10; } return true; } int main(){ known_map *known = new known_map(); denom_t d = 1, max=-1; double res = 0; std::cout.precision(10); std::cout.setf( std::ios::fixed, std:: ios::floatfield ); // floatfield set to fixed std::cout << "Starting..." << std::endl; while(d < max){ if(validate(res, *known)){ res += 1.0 / d; std::cout << "res = " << res << "\td = " << d << '\r' << std::flush; } ++d; } delete known; }
20.675676
85
0.576471
t-highfill
bf5818f3dfc705cde77970b054c3324be7d2bdb5
6,340
cpp
C++
cell_based/src/simulation/RK4NumericalMethodTimestepper.cpp
ktunya/ChasteMod
88ac65b00473cd730d348c783bd74b2b39de5f69
[ "Apache-2.0" ]
null
null
null
cell_based/src/simulation/RK4NumericalMethodTimestepper.cpp
ktunya/ChasteMod
88ac65b00473cd730d348c783bd74b2b39de5f69
[ "Apache-2.0" ]
null
null
null
cell_based/src/simulation/RK4NumericalMethodTimestepper.cpp
ktunya/ChasteMod
88ac65b00473cd730d348c783bd74b2b39de5f69
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2005-2015, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Oxford 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 "RK4NumericalMethodTimestepper.hpp" template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> RK4NumericalMethodTimestepper<ELEMENT_DIM,SPACE_DIM> :: RK4NumericalMethodTimestepper( AbstractOffLatticeCellPopulation<ELEMENT_DIM,SPACE_DIM>& inputCellPopulation, std::vector<boost::shared_ptr<AbstractForce<ELEMENT_DIM, SPACE_DIM> > >& inputForceCollection): AbstractNumericalMethodTimestepper<ELEMENT_DIM,SPACE_DIM>( inputCellPopulation, inputForceCollection) { }; template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> RK4NumericalMethodTimestepper<ELEMENT_DIM,SPACE_DIM>::~RK4NumericalMethodTimestepper(){ }; template<unsigned ELEMENT_DIM, unsigned SPACE_DIM> void RK4NumericalMethodTimestepper<ELEMENT_DIM,SPACE_DIM>::UpdateAllNodePositions(double dt){ if(this->nonEulerSteppersEnabled){ std::vector<c_vector<double, SPACE_DIM> > K1 = this->ComputeAndSaveForces(); int index = 0; for (typename AbstractMesh<ELEMENT_DIM, SPACE_DIM>::NodeIterator node_iter = this->rCellPopulation.rGetMesh().GetNodeIteratorBegin(); node_iter != this->rCellPopulation.rGetMesh().GetNodeIteratorEnd(); ++node_iter, ++index) { c_vector<double, SPACE_DIM> newLocation = node_iter->rGetLocation() + dt * K1[index]/2.0; ChastePoint<SPACE_DIM> new_point(newLocation); this->rCellPopulation.SetNode(node_iter->GetIndex(), new_point); } std::vector< c_vector<double, SPACE_DIM> > K2 = this->ComputeAndSaveForces(); index = 0; for (typename AbstractMesh<ELEMENT_DIM, SPACE_DIM>::NodeIterator node_iter = this->rCellPopulation.rGetMesh().GetNodeIteratorBegin(); node_iter != this->rCellPopulation.rGetMesh().GetNodeIteratorEnd(); ++node_iter, ++index) { c_vector<double, SPACE_DIM> newLocation = node_iter->rGetLocation() + dt * (K2[index] - K1[index])/2.0; //revert, then update ChastePoint<SPACE_DIM> new_point(newLocation); this->rCellPopulation.SetNode(node_iter->GetIndex(), new_point); } std::vector< c_vector<double, SPACE_DIM> > K3 = this->ComputeAndSaveForces(); index = 0; for (typename AbstractMesh<ELEMENT_DIM, SPACE_DIM>::NodeIterator node_iter = this->rCellPopulation.rGetMesh().GetNodeIteratorBegin(); node_iter != this->rCellPopulation.rGetMesh().GetNodeIteratorEnd(); ++node_iter, ++index) { double damping = this->rCellPopulation.GetDampingConstant(node_iter->GetIndex()); c_vector<double, SPACE_DIM> newLocation = node_iter->rGetLocation() + dt * (K3[index] - K2[index]/2.0); //revert, then update ChastePoint<SPACE_DIM> new_point(newLocation); this->rCellPopulation.SetNode(node_iter->GetIndex(), new_point); } std::vector< c_vector<double, SPACE_DIM> > K4 = this->ComputeAndSaveForces(); index = 0; for (typename AbstractMesh<ELEMENT_DIM, SPACE_DIM>::NodeIterator node_iter = this->rCellPopulation.rGetMesh().GetNodeIteratorBegin(); node_iter != this->rCellPopulation.rGetMesh().GetNodeIteratorEnd(); ++node_iter, ++index) { c_vector<double, SPACE_DIM> effectiveForce = (K1[index] + 2*K2[index] + 2*K3[index] + K4[index] )/6.0; c_vector<double, SPACE_DIM> oldLocation = node_iter->rGetLocation() - dt * K3[index]; c_vector<double, SPACE_DIM> displacement = dt * effectiveForce; this->HandleStepSizeExceptions(&displacement, dt, node_iter->GetIndex()); c_vector<double, SPACE_DIM> newLocation = oldLocation + displacement; ChastePoint<SPACE_DIM> new_point(newLocation); this->rCellPopulation.SetNode(node_iter->GetIndex(), new_point); //Ensure the nodes hold accurate forces, incase they're accessed by some other class double damping = this->rCellPopulation.GetDampingConstant(node_iter->GetIndex()); node_iter->ClearAppliedForce(); c_vector<double, SPACE_DIM> force = effectiveForce*damping; node_iter->AddAppliedForceContribution(force); } }else{ this->ComputeAndSaveForces(); this->rCellPopulation.UpdateNodeLocations(dt); } }; ///////// Explicit instantiation template class RK4NumericalMethodTimestepper<1,1>; template class RK4NumericalMethodTimestepper<1,2>; template class RK4NumericalMethodTimestepper<2,2>; template class RK4NumericalMethodTimestepper<1,3>; template class RK4NumericalMethodTimestepper<2,3>; template class RK4NumericalMethodTimestepper<3,3>;
48.769231
145
0.728707
ktunya
bf5b35c1e38c9a8572cc8351073b386341fa4e82
33,978
cc
C++
Validation/SiTrackerPhase2V/plugins/Phase2OTValidateRecHit.cc
ryanm124/cmssw
9c955a497467f8cc57a7cc1eefc39d41d2d3d89e
[ "Apache-2.0" ]
null
null
null
Validation/SiTrackerPhase2V/plugins/Phase2OTValidateRecHit.cc
ryanm124/cmssw
9c955a497467f8cc57a7cc1eefc39d41d2d3d89e
[ "Apache-2.0" ]
null
null
null
Validation/SiTrackerPhase2V/plugins/Phase2OTValidateRecHit.cc
ryanm124/cmssw
9c955a497467f8cc57a7cc1eefc39d41d2d3d89e
[ "Apache-2.0" ]
null
null
null
// Package: Phase2OTValidateRecHit // Class: Phase2OTValidateRecHit // /**\class Phase2OTValidateRecHit Phase2OTValidateRecHit.cc Description: Standalone Plugin for Phase2 RecHit validation */ // // Author: Suvankar Roy Chowdhury // Date: March 2021 // // system include files #include <memory> #include <map> #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/Framework/interface/ESWatcher.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/ServiceRegistry/interface/Service.h" #include "FWCore/Utilities/interface/InputTag.h" #include "Geometry/Records/interface/TrackerDigiGeometryRecord.h" #include "Geometry/CommonDetUnit/interface/GeomDet.h" #include "Geometry/CommonDetUnit/interface/TrackerGeomDet.h" #include "Geometry/CommonDetUnit/interface/PixelGeomDetUnit.h" #include "Geometry/CommonDetUnit/interface/PixelGeomDetType.h" #include "Geometry/TrackerGeometryBuilder/interface/TrackerGeometry.h" #include "Geometry/Records/interface/TrackerDigiGeometryRecord.h" #include "Geometry/TrackerGeometryBuilder/interface/TrackerGeometry.h" #include "Geometry/CommonDetUnit/interface/GeomDet.h" #include "DataFormats/Common/interface/Handle.h" #include "DataFormats/TrackerCommon/interface/TrackerTopology.h" #include "DataFormats/SiPixelDetId/interface/PixelSubdetector.h" #include "DataFormats/DetId/interface/DetId.h" #include "DataFormats/Common/interface/DetSetVector.h" #include "DataFormats/Common/interface/DetSetVectorNew.h" #include "DataFormats/TrackerCommon/interface/TrackerTopology.h" #include "DataFormats/TrackerRecHit2D/interface/Phase2TrackerRecHit1D.h" #include "DataFormats/TrackerRecHit2D/interface/SiPixelRecHitCollection.h" #include "DataFormats/GeometrySurface/interface/LocalError.h" #include "DataFormats/GeometryVector/interface/LocalPoint.h" #include "SimDataFormats/TrackingHit/interface/PSimHitContainer.h" #include "SimDataFormats/TrackingHit/interface/PSimHit.h" #include "SimDataFormats/TrackerDigiSimLink/interface/PixelDigiSimLink.h" #include "SimTracker/SiPhase2Digitizer/plugins/Phase2TrackerDigitizerFwd.h" #include "SimDataFormats/Track/interface/SimTrackContainer.h" #include "SimTracker/TrackerHitAssociation/interface/TrackerHitAssociator.h" // DQM Histograming #include "DQMServices/Core/interface/MonitorElement.h" #include "DQMServices/Core/interface/DQMEDAnalyzer.h" #include "DQMServices/Core/interface/DQMStore.h" #include "Validation/SiTrackerPhase2V/interface/TrackerPhase2ValidationUtil.h" #include "DQM/SiTrackerPhase2/interface/TrackerPhase2DQMUtil.h" class Phase2OTValidateRecHit : public DQMEDAnalyzer { public: explicit Phase2OTValidateRecHit(const edm::ParameterSet&); ~Phase2OTValidateRecHit() override; void bookHistograms(DQMStore::IBooker& ibooker, edm::Run const& iRun, edm::EventSetup const& iSetup) override; void analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) override; void dqmBeginRun(const edm::Run& iRun, const edm::EventSetup& iSetup) override; static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); private: void fillOTHistos(const edm::Event& iEvent, const TrackerHitAssociator& associateRecHit, const std::vector<edm::Handle<edm::PSimHitContainer>>& simHits, const std::map<unsigned int, SimTrack>& selectedSimTrackMap); void bookLayerHistos(DQMStore::IBooker& ibooker, unsigned int det_id, std::string& subdir); edm::ParameterSet config_; bool pixelFlag_; TrackerHitAssociator::Config trackerHitAssociatorConfig_; const double simtrackminpt_; std::string geomType_; const edm::EDGetTokenT<Phase2TrackerRecHit1DCollectionNew> tokenRecHitsOT_; const edm::EDGetTokenT<edm::SimTrackContainer> simTracksToken_; std::vector<edm::EDGetTokenT<edm::PSimHitContainer>> simHitTokens_; const edm::ESGetToken<TrackerGeometry, TrackerDigiGeometryRecord> geomToken_; const edm::ESGetToken<TrackerTopology, TrackerTopologyRcd> topoToken_; const TrackerGeometry* tkGeom_ = nullptr; const TrackerTopology* tTopo_ = nullptr; struct RecHitME { // use TH1D instead of TH1F to avoid stauration at 2^31 // above this increments with +1 don't work for float, need double MonitorElement* deltaX_P = nullptr; MonitorElement* deltaX_S = nullptr; MonitorElement* deltaY_P = nullptr; MonitorElement* deltaY_S = nullptr; MonitorElement* pullX_P = nullptr; MonitorElement* pullX_S = nullptr; MonitorElement* pullY_P = nullptr; MonitorElement* pullY_S = nullptr; MonitorElement* deltaX_eta_P = nullptr; MonitorElement* deltaX_eta_S = nullptr; MonitorElement* deltaY_eta_P = nullptr; MonitorElement* deltaY_eta_S = nullptr; MonitorElement* pullX_eta_P = nullptr; MonitorElement* pullX_eta_S = nullptr; MonitorElement* pullY_eta_P = nullptr; MonitorElement* pullY_eta_S = nullptr; //For rechits matched to simhits from highPT tracks MonitorElement* pullX_primary_P; MonitorElement* pullX_primary_S; MonitorElement* pullY_primary_P; MonitorElement* pullY_primary_S; MonitorElement* deltaX_primary_P; MonitorElement* deltaX_primary_S; MonitorElement* deltaY_primary_P; MonitorElement* deltaY_primary_S; MonitorElement* numberRecHitsprimary_P; MonitorElement* numberRecHitsprimary_S; }; std::map<std::string, RecHitME> layerMEs_; }; // // constructors // Phase2OTValidateRecHit::Phase2OTValidateRecHit(const edm::ParameterSet& iConfig) : config_(iConfig), trackerHitAssociatorConfig_(iConfig, consumesCollector()), simtrackminpt_(iConfig.getParameter<double>("SimTrackMinPt")), tokenRecHitsOT_(consumes<Phase2TrackerRecHit1DCollectionNew>(config_.getParameter<edm::InputTag>("rechitsSrc"))), simTracksToken_(consumes<edm::SimTrackContainer>(iConfig.getParameter<edm::InputTag>("simTracksSrc"))), geomToken_(esConsumes<TrackerGeometry, TrackerDigiGeometryRecord, edm::Transition::BeginRun>()), topoToken_(esConsumes<TrackerTopology, TrackerTopologyRcd, edm::Transition::BeginRun>()) { edm::LogInfo("Phase2OTValidateRecHit") << ">>> Construct Phase2OTValidateRecHit "; for (const auto& itag : config_.getParameter<std::vector<edm::InputTag>>("PSimHitSource")) simHitTokens_.push_back(consumes<edm::PSimHitContainer>(itag)); } // // destructor // Phase2OTValidateRecHit::~Phase2OTValidateRecHit() { // do anything here that needs to be done at desctruction time // (e.g. close files, deallocate resources etc.) edm::LogInfo("Phase2OTValidateRecHit") << ">>> Destroy Phase2OTValidateRecHit "; } // // -- DQM Begin Run void Phase2OTValidateRecHit::dqmBeginRun(const edm::Run& iRun, const edm::EventSetup& iSetup) { tkGeom_ = &iSetup.getData(geomToken_); tTopo_ = &iSetup.getData(topoToken_); } // // -- Analyze // void Phase2OTValidateRecHit::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) { std::vector<edm::Handle<edm::PSimHitContainer>> simHits; for (const auto& itoken : simHitTokens_) { const auto& simHitHandle = iEvent.getHandle(itoken); if (!simHitHandle.isValid()) continue; simHits.emplace_back(simHitHandle); } // Get the SimTracks and push them in a map of id, SimTrack const auto& simTracks = iEvent.getHandle(simTracksToken_); std::map<unsigned int, SimTrack> selectedSimTrackMap; for (edm::SimTrackContainer::const_iterator simTrackIt(simTracks->begin()); simTrackIt != simTracks->end(); ++simTrackIt) { if (simTrackIt->momentum().pt() > simtrackminpt_) { selectedSimTrackMap.insert(std::make_pair(simTrackIt->trackId(), *simTrackIt)); } } TrackerHitAssociator associateRecHit(iEvent, trackerHitAssociatorConfig_); fillOTHistos(iEvent, associateRecHit, simHits, selectedSimTrackMap); } void Phase2OTValidateRecHit::fillOTHistos(const edm::Event& iEvent, const TrackerHitAssociator& associateRecHit, const std::vector<edm::Handle<edm::PSimHitContainer>>& simHits, const std::map<unsigned int, SimTrack>& selectedSimTrackMap) { // Get the RecHits const auto& rechits = iEvent.getHandle(tokenRecHitsOT_); if (!rechits.isValid()) return; std::map<std::string, unsigned int> nrechitLayerMapP_primary; std::map<std::string, unsigned int> nrechitLayerMapS_primary; unsigned long int nTotrechitsinevt = 0; // Loop over modules Phase2TrackerRecHit1DCollectionNew::const_iterator DSViter; for (DSViter = rechits->begin(); DSViter != rechits->end(); ++DSViter) { // Get the detector unit's id unsigned int rawid(DSViter->detId()); DetId detId(rawid); // Get the geomdet const GeomDetUnit* geomDetunit(tkGeom_->idToDetUnit(detId)); if (!geomDetunit) continue; // determine the detector we are in TrackerGeometry::ModuleType mType = tkGeom_->getDetectorType(detId); std::string key = phase2tkutil::getOTHistoId(detId.rawId(), tTopo_); nTotrechitsinevt += DSViter->size(); if (mType == TrackerGeometry::ModuleType::Ph2PSP) { if (nrechitLayerMapP_primary.find(key) == nrechitLayerMapP_primary.end()) { nrechitLayerMapP_primary.insert(std::make_pair(key, DSViter->size())); } else { nrechitLayerMapP_primary[key] += DSViter->size(); } } else if (mType == TrackerGeometry::ModuleType::Ph2PSS || mType == TrackerGeometry::ModuleType::Ph2SS) { if (nrechitLayerMapS_primary.find(key) == nrechitLayerMapS_primary.end()) { nrechitLayerMapS_primary.insert(std::make_pair(key, DSViter->size())); } else { nrechitLayerMapS_primary[key] += DSViter->size(); } } edmNew::DetSet<Phase2TrackerRecHit1D>::const_iterator rechitIt; //loop over rechits for a single detId for (rechitIt = DSViter->begin(); rechitIt != DSViter->end(); ++rechitIt) { LocalPoint lp = rechitIt->localPosition(); //GetSimHits const std::vector<SimHitIdpr>& matchedId = associateRecHit.associateHitId(*rechitIt); const PSimHit* simhitClosest = nullptr; float mind = 1e4; for (unsigned int si = 0; si < simHits.size(); ++si) { for (edm::PSimHitContainer::const_iterator simhitIt = simHits.at(si)->begin(); simhitIt != simHits.at(si)->end(); ++simhitIt) { if (detId.rawId() != simhitIt->detUnitId()) continue; for (auto& mId : matchedId) { if (simhitIt->trackId() == mId.first) { float dx = simhitIt->localPosition().x() - lp.x(); float dy = simhitIt->localPosition().y() - lp.y(); float dist = std::sqrt(dx * dx + dy * dy); if (!simhitClosest || dist < mind) { mind = dist; simhitClosest = &*simhitIt; } } } } //end loop over PSimhitcontainers } //end loop over simHits if (!simhitClosest) continue; auto simTrackIt(selectedSimTrackMap.find(simhitClosest->trackId())); bool isPrimary = false; //check if simhit is primary if (simTrackIt != selectedSimTrackMap.end()) isPrimary = phase2tkutil::isPrimary(simTrackIt->second, simhitClosest); Local3DPoint simlp(simhitClosest->localPosition()); const LocalError& lperr = rechitIt->localPositionError(); double dx = lp.x() - simlp.x(); double dy = lp.y() - simlp.y(); double pullx = 999.; double pully = 999.; if (lperr.xx()) pullx = (lp.x() - simlp.x()) / std::sqrt(lperr.xx()); if (lperr.yy()) pully = (lp.y() - simlp.y()) / std::sqrt(lperr.yy()); float eta = geomDetunit->surface().toGlobal(lp).eta(); ; if (mType == TrackerGeometry::ModuleType::Ph2PSP) { layerMEs_[key].deltaX_P->Fill(phase2tkutil::cmtomicron * dx); layerMEs_[key].deltaY_P->Fill(phase2tkutil::cmtomicron * dy); layerMEs_[key].pullX_P->Fill(pullx); layerMEs_[key].pullY_P->Fill(pully); layerMEs_[key].deltaX_eta_P->Fill(eta, phase2tkutil::cmtomicron * dx); layerMEs_[key].deltaY_eta_P->Fill(eta, phase2tkutil::cmtomicron * dy); layerMEs_[key].pullX_eta_P->Fill(eta, pullx); layerMEs_[key].pullY_eta_P->Fill(eta, pully); if (isPrimary) { layerMEs_[key].deltaX_primary_P->Fill(phase2tkutil::cmtomicron * dx); layerMEs_[key].deltaY_primary_P->Fill(phase2tkutil::cmtomicron * dy); layerMEs_[key].pullX_primary_P->Fill(pullx); layerMEs_[key].pullY_primary_P->Fill(pully); } else nrechitLayerMapP_primary[key]--; } else if (mType == TrackerGeometry::ModuleType::Ph2PSS || mType == TrackerGeometry::ModuleType::Ph2SS) { layerMEs_[key].deltaX_S->Fill(phase2tkutil::cmtomicron * dx); layerMEs_[key].deltaY_S->Fill(dy); layerMEs_[key].pullX_S->Fill(pullx); layerMEs_[key].pullY_S->Fill(pully); layerMEs_[key].deltaX_eta_S->Fill(eta, phase2tkutil::cmtomicron * dx); layerMEs_[key].deltaY_eta_S->Fill(eta, dy); layerMEs_[key].pullX_eta_S->Fill(eta, pullx); layerMEs_[key].pullY_eta_S->Fill(eta, pully); if (isPrimary) { layerMEs_[key].deltaX_primary_S->Fill(phase2tkutil::cmtomicron * dx); layerMEs_[key].deltaY_primary_S->Fill(dy); layerMEs_[key].pullX_primary_S->Fill(pullx); layerMEs_[key].pullY_primary_S->Fill(pully); } else nrechitLayerMapS_primary[key]--; } } //end loop over rechits of a detId } //End loop over DetSetVector //fill nRecHits per event //fill nRecHit counter per layer for (auto& lme : nrechitLayerMapP_primary) { layerMEs_[lme.first].numberRecHitsprimary_P->Fill(nrechitLayerMapP_primary[lme.first]); } for (auto& lme : nrechitLayerMapS_primary) { layerMEs_[lme.first].numberRecHitsprimary_S->Fill(nrechitLayerMapS_primary[lme.first]); } } // // -- Book Histograms // void Phase2OTValidateRecHit::bookHistograms(DQMStore::IBooker& ibooker, edm::Run const& iRun, edm::EventSetup const& iSetup) { std::string top_folder = config_.getParameter<std::string>("TopFolderName"); //Now book layer wise histos edm::ESWatcher<TrackerDigiGeometryRecord> theTkDigiGeomWatcher; if (theTkDigiGeomWatcher.check(iSetup)) { for (auto const& det_u : tkGeom_->detUnits()) { //Always check TrackerNumberingBuilder before changing this part if (det_u->subDetector() == GeomDetEnumerators::SubDetector::P2PXB || det_u->subDetector() == GeomDetEnumerators::SubDetector::P2PXEC) continue; unsigned int detId_raw = det_u->geographicalId().rawId(); bookLayerHistos(ibooker, detId_raw, top_folder); } } } // // -- Book Layer Histograms // void Phase2OTValidateRecHit::bookLayerHistos(DQMStore::IBooker& ibooker, unsigned int det_id, std::string& subdir) { std::string key = phase2tkutil::getOTHistoId(det_id, tTopo_); if (layerMEs_.find(key) == layerMEs_.end()) { ibooker.cd(); RecHitME local_histos; ibooker.setCurrentFolder(subdir + "/" + key); edm::LogInfo("Phase2OTValidateRecHit") << " Booking Histograms in : " << key; if (tkGeom_->getDetectorType(det_id) == TrackerGeometry::ModuleType::Ph2PSP) { local_histos.deltaX_P = phase2tkutil::book1DFromPSet(config_.getParameter<edm::ParameterSet>("Delta_X_Pixel"), ibooker); local_histos.deltaY_P = phase2tkutil::book1DFromPSet(config_.getParameter<edm::ParameterSet>("Delta_Y_Pixel"), ibooker); local_histos.pullX_P = phase2tkutil::book1DFromPSet(config_.getParameter<edm::ParameterSet>("Pull_X_Pixel"), ibooker); local_histos.pullY_P = phase2tkutil::book1DFromPSet(config_.getParameter<edm::ParameterSet>("Pull_X_Pixel"), ibooker); local_histos.deltaX_eta_P = phase2tkutil::bookProfile1DFromPSet(config_.getParameter<edm::ParameterSet>("Delta_X_vs_eta_Pixel"), ibooker); local_histos.deltaY_eta_P = phase2tkutil::bookProfile1DFromPSet(config_.getParameter<edm::ParameterSet>("Delta_Y_vs_eta_Pixel"), ibooker); local_histos.pullX_eta_P = phase2tkutil::bookProfile1DFromPSet(config_.getParameter<edm::ParameterSet>("Pull_X_vs_eta_Pixel"), ibooker); local_histos.pullY_eta_P = phase2tkutil::bookProfile1DFromPSet(config_.getParameter<edm::ParameterSet>("Pull_X_vs_eta_Pixel"), ibooker); ibooker.setCurrentFolder(subdir + "/" + key + "/PrimarySimHits"); //all histos for Primary particles local_histos.numberRecHitsprimary_P = phase2tkutil::book1DFromPSet(config_.getParameter<edm::ParameterSet>("nRecHits_Pixel_primary"), ibooker); local_histos.deltaX_primary_P = phase2tkutil::book1DFromPSet(config_.getParameter<edm::ParameterSet>("Delta_X_Pixel_Primary"), ibooker); local_histos.deltaY_primary_P = phase2tkutil::book1DFromPSet(config_.getParameter<edm::ParameterSet>("Delta_X_Pixel_Primary"), ibooker); local_histos.pullX_primary_P = phase2tkutil::book1DFromPSet(config_.getParameter<edm::ParameterSet>("Pull_X_Pixel_Primary"), ibooker); local_histos.pullY_primary_P = phase2tkutil::book1DFromPSet(config_.getParameter<edm::ParameterSet>("Pull_X_Pixel_Primary"), ibooker); } //if block for P ibooker.setCurrentFolder(subdir + "/" + key); local_histos.deltaX_S = phase2tkutil::book1DFromPSet(config_.getParameter<edm::ParameterSet>("Delta_X_Strip"), ibooker); local_histos.deltaY_S = phase2tkutil::book1DFromPSet(config_.getParameter<edm::ParameterSet>("Delta_Y_Strip"), ibooker); local_histos.pullX_S = phase2tkutil::book1DFromPSet(config_.getParameter<edm::ParameterSet>("Pull_X_Strip"), ibooker); local_histos.pullY_S = phase2tkutil::book1DFromPSet(config_.getParameter<edm::ParameterSet>("Pull_Y_Strip"), ibooker); local_histos.deltaX_eta_S = phase2tkutil::bookProfile1DFromPSet(config_.getParameter<edm::ParameterSet>("Delta_X_vs_eta_Strip"), ibooker); local_histos.deltaY_eta_S = phase2tkutil::bookProfile1DFromPSet(config_.getParameter<edm::ParameterSet>("Delta_Y_vs_eta_Strip"), ibooker); local_histos.pullX_eta_S = phase2tkutil::bookProfile1DFromPSet(config_.getParameter<edm::ParameterSet>("Pull_X_vs_eta_Strip"), ibooker); local_histos.pullY_eta_S = phase2tkutil::bookProfile1DFromPSet(config_.getParameter<edm::ParameterSet>("Pull_X_vs_eta_Pixel"), ibooker); //primary ibooker.setCurrentFolder(subdir + "/" + key + "/PrimarySimHits"); local_histos.numberRecHitsprimary_S = phase2tkutil::book1DFromPSet(config_.getParameter<edm::ParameterSet>("nRecHits_Strip_primary"), ibooker); local_histos.deltaX_primary_S = phase2tkutil::book1DFromPSet(config_.getParameter<edm::ParameterSet>("Delta_X_Strip_Primary"), ibooker); local_histos.deltaY_primary_S = phase2tkutil::book1DFromPSet(config_.getParameter<edm::ParameterSet>("Delta_Y_Strip_Primary"), ibooker); local_histos.pullX_primary_S = phase2tkutil::book1DFromPSet(config_.getParameter<edm::ParameterSet>("Pull_X_Strip_Primary"), ibooker); local_histos.pullY_primary_S = phase2tkutil::book1DFromPSet(config_.getParameter<edm::ParameterSet>("Pull_X_Strip_Primary"), ibooker); layerMEs_.insert(std::make_pair(key, local_histos)); } } void Phase2OTValidateRecHit::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { edm::ParameterSetDescription desc; // rechitValidOT //for macro-pixel sensors std::string mptag = "macro-pixel sensor"; std::string striptag = "strip sensor"; { edm::ParameterSetDescription psd0; psd0.add<std::string>("name", "Delta_X_Pixel"); psd0.add<std::string>("title", "#Delta X " + mptag + ";Cluster resolution X coordinate [#mum]"); psd0.add<bool>("switch", true); psd0.add<double>("xmax", 250); psd0.add<double>("xmin", -250); psd0.add<int>("NxBins", 100); desc.add<edm::ParameterSetDescription>("Delta_X_Pixel", psd0); } { edm::ParameterSetDescription psd0; psd0.add<std::string>("name", "Delta_Y_Pixel"); psd0.add<std::string>("title", "#Delta Y " + mptag + ";Cluster resolution Y coordinate [#mum]"); psd0.add<bool>("switch", true); psd0.add<double>("xmin", -1500); psd0.add<double>("xmax", 1500); psd0.add<int>("NxBins", 100); desc.add<edm::ParameterSetDescription>("Delta_Y_Pixel", psd0); } { edm::ParameterSetDescription psd0; psd0.add<std::string>("name", "Delta_X_Pixel_Primary"); psd0.add<std::string>("title", "#Delta X " + mptag + ";cluster resolution X coordinate [#mum]"); psd0.add<bool>("switch", true); psd0.add<double>("xmin", -250); psd0.add<double>("xmax", 250); psd0.add<int>("NxBins", 100); desc.add<edm::ParameterSetDescription>("Delta_X_Pixel_Primary", psd0); } { edm::ParameterSetDescription psd0; psd0.add<std::string>("name", "Delta_Y_Pixel_Primary"); psd0.add<std::string>("title", "#Delta Y " + mptag + ";cluster resolution Y coordinate [#mum]"); psd0.add<bool>("switch", true); psd0.add<double>("xmin", -500); psd0.add<double>("xmax", 500); psd0.add<int>("NxBins", 100); desc.add<edm::ParameterSetDescription>("Delta_Y_Pixel_Primary", psd0); } { edm::ParameterSetDescription psd0; psd0.add<std::string>("name", "Delta_X_vs_Eta_Pixel"); psd0.add<std::string>("title", ";#eta;#Delta x [#mum]"); psd0.add<double>("ymin", -250.0); psd0.add<double>("ymax", 250.0); psd0.add<int>("NxBins", 82); psd0.add<bool>("switch", true); psd0.add<double>("xmax", 4.1); psd0.add<double>("xmin", -4.1); desc.add<edm::ParameterSetDescription>("Delta_X_vs_eta_Pixel", psd0); } { edm::ParameterSetDescription psd0; psd0.add<std::string>("name", "Delta_Y_vs_Eta_Pixel"); psd0.add<std::string>("title", ";#eta;#Delta y [#mum]"); psd0.add<double>("ymin", -1500.0); psd0.add<double>("ymax", 1500.0); psd0.add<int>("NxBins", 82); psd0.add<bool>("switch", true); psd0.add<double>("xmax", 4.1); psd0.add<double>("xmin", -4.1); desc.add<edm::ParameterSetDescription>("Delta_Y_vs_eta_Pixel", psd0); } //Pulls macro-pixel { edm::ParameterSetDescription psd0; psd0.add<std::string>("name", "Pull_X_Pixel"); psd0.add<std::string>("title", ";pull x;"); psd0.add<double>("xmin", -4.0); psd0.add<bool>("switch", true); psd0.add<double>("xmax", 4.0); psd0.add<int>("NxBins", 100); desc.add<edm::ParameterSetDescription>("Pull_X_Pixel", psd0); } { edm::ParameterSetDescription psd0; psd0.add<std::string>("name", "Pull_Y_Pixel"); psd0.add<std::string>("title", ";pull y;"); psd0.add<double>("xmin", -4.0); psd0.add<bool>("switch", true); psd0.add<double>("xmax", 4.0); psd0.add<int>("NxBins", 100); desc.add<edm::ParameterSetDescription>("Pull_Y_Pixel", psd0); } { edm::ParameterSetDescription psd0; psd0.add<std::string>("name", "Pull_X_Pixel_Primary"); psd0.add<std::string>("title", ";pull x;"); psd0.add<double>("xmin", -4.0); psd0.add<bool>("switch", true); psd0.add<double>("xmax", 4.0); psd0.add<int>("NxBins", 100); desc.add<edm::ParameterSetDescription>("Pull_X_Pixel_Primary", psd0); } { edm::ParameterSetDescription psd0; psd0.add<std::string>("name", "Pull_Y_Pixel_Primary"); psd0.add<std::string>("title", ";pull y;"); psd0.add<double>("xmin", -4.0); psd0.add<bool>("switch", true); psd0.add<double>("xmax", 4.0); psd0.add<int>("NxBins", 100); desc.add<edm::ParameterSetDescription>("Pull_Y_Pixel_Primary", psd0); } { edm::ParameterSetDescription psd0; psd0.add<std::string>("name", "Pull_X_vs_Eta"); psd0.add<std::string>("title", ";#eta;pull x"); psd0.add<double>("ymax", 4.0); psd0.add<int>("NxBins", 82); psd0.add<bool>("switch", true); psd0.add<double>("xmax", 4.1); psd0.add<double>("xmin", -4.1); psd0.add<double>("ymin", -4.0); desc.add<edm::ParameterSetDescription>("Pull_X_vs_eta_Pixel", psd0); } { edm::ParameterSetDescription psd0; psd0.add<std::string>("name", "Pull_Y_vs_Eta"); psd0.add<std::string>("title", ";#eta;pull y"); psd0.add<double>("ymax", 4.0); psd0.add<int>("NxBins", 82); psd0.add<bool>("switch", true); psd0.add<double>("xmax", 4.1); psd0.add<double>("xmin", -4.1); psd0.add<double>("ymin", -4.0); desc.add<edm::ParameterSetDescription>("Pull_Y_vs_eta_Pixel", psd0); } { edm::ParameterSetDescription psd0; psd0.add<std::string>("name", "Number_RecHits_matched_PrimarySimTrack"); psd0.add<std::string>("title", "Number of RecHits matched to primary SimTrack;;"); psd0.add<double>("xmin", 0.0); psd0.add<bool>("switch", true); psd0.add<double>("xmax", 10000.0); psd0.add<int>("NxBins", 100); desc.add<edm::ParameterSetDescription>("nRecHits_Pixel_primary", psd0); } //strip sensors { edm::ParameterSetDescription psd0; psd0.add<std::string>("name", "Delta_X_Strip"); psd0.add<std::string>("title", "#Delta X " + striptag + ";Cluster resolution X coordinate [#mum]"); psd0.add<bool>("switch", true); psd0.add<double>("xmin", -250); psd0.add<double>("xmax", 250); psd0.add<int>("NxBins", 100); desc.add<edm::ParameterSetDescription>("Delta_X_Strip", psd0); } { edm::ParameterSetDescription psd0; psd0.add<std::string>("name", "Delta_Y_Strip"); psd0.add<std::string>("title", "#Delta Y " + striptag + ";Cluster resolution Y coordinate [cm]"); psd0.add<double>("xmin", -5.0); psd0.add<bool>("switch", true); psd0.add<double>("xmax", 5.0); psd0.add<int>("NxBins", 100); desc.add<edm::ParameterSetDescription>("Delta_Y_Strip", psd0); } { edm::ParameterSetDescription psd0; psd0.add<std::string>("name", "Delta_X_Strip_Primary"); psd0.add<std::string>("title", "#Delta X " + striptag + ";Cluster resolution X coordinate [#mum]"); psd0.add<bool>("switch", true); psd0.add<double>("xmin", -250); psd0.add<double>("xmax", 250); psd0.add<int>("NxBins", 100); desc.add<edm::ParameterSetDescription>("Delta_X_Strip_Primary", psd0); } { edm::ParameterSetDescription psd0; psd0.add<std::string>("name", "Delta_Y_Strip_Primary"); psd0.add<std::string>("title", "#Delta Y " + striptag + ";Cluster resolution Y coordinate [cm]"); psd0.add<double>("xmin", -5.0); psd0.add<bool>("switch", true); psd0.add<double>("xmax", 5.0); psd0.add<int>("NxBins", 100); desc.add<edm::ParameterSetDescription>("Delta_Y_Strip_Primary", psd0); } { edm::ParameterSetDescription psd0; psd0.add<std::string>("name", "Delta_X_vs_Eta_Strip"); psd0.add<std::string>("title", ";#eta;#Delta x [#mum]"); psd0.add<double>("ymin", -250.0); psd0.add<double>("ymax", 250.0); psd0.add<int>("NxBins", 82); psd0.add<bool>("switch", true); psd0.add<double>("xmax", 4.1); psd0.add<double>("xmin", -4.1); desc.add<edm::ParameterSetDescription>("Delta_X_vs_eta_Strip", psd0); } { edm::ParameterSetDescription psd0; psd0.add<std::string>("name", "Delta_Y_vs_Eta_Strip"); psd0.add<std::string>("title", ";#eta;#Delta y [cm]"); psd0.add<double>("ymin", -5.0); psd0.add<double>("ymax", 5.0); psd0.add<int>("NxBins", 82); psd0.add<bool>("switch", true); psd0.add<double>("xmax", 4.1); psd0.add<double>("xmin", -4.1); desc.add<edm::ParameterSetDescription>("Delta_Y_vs_eta_Strip", psd0); } //pulls strips { edm::ParameterSetDescription psd0; psd0.add<std::string>("name", "Pull_X_Strip"); psd0.add<std::string>("title", ";pull x;"); psd0.add<double>("xmin", -4.0); psd0.add<bool>("switch", true); psd0.add<double>("xmax", 4.0); psd0.add<int>("NxBins", 100); desc.add<edm::ParameterSetDescription>("Pull_X_Strip", psd0); } { edm::ParameterSetDescription psd0; psd0.add<std::string>("name", "Pull_Y_Strip"); psd0.add<std::string>("title", ";pull y;"); psd0.add<double>("xmin", -4.0); psd0.add<bool>("switch", true); psd0.add<double>("xmax", 4.0); psd0.add<int>("NxBins", 100); desc.add<edm::ParameterSetDescription>("Pull_Y_Strip", psd0); } { edm::ParameterSetDescription psd0; psd0.add<std::string>("name", "Pull_X_Strip_Primary"); psd0.add<std::string>("title", ";pull x;"); psd0.add<double>("xmin", -4.0); psd0.add<bool>("switch", true); psd0.add<double>("xmax", 4.0); psd0.add<int>("NxBins", 100); desc.add<edm::ParameterSetDescription>("Pull_X_Strip_Primary", psd0); } { edm::ParameterSetDescription psd0; psd0.add<std::string>("name", "Pull_Y_Strip_Primary"); psd0.add<std::string>("title", ";pull y;"); psd0.add<double>("xmin", -4.0); psd0.add<bool>("switch", true); psd0.add<double>("xmax", 4.0); psd0.add<int>("NxBins", 100); desc.add<edm::ParameterSetDescription>("Pull_Y_Strip_Primary", psd0); } { edm::ParameterSetDescription psd0; psd0.add<std::string>("name", "Pull_X_vs_Eta_Strip"); psd0.add<std::string>("title", ";#eta;pull x"); psd0.add<double>("ymax", 4.0); psd0.add<int>("NxBins", 82); psd0.add<bool>("switch", true); psd0.add<double>("xmax", 4.1); psd0.add<double>("xmin", -4.1); psd0.add<double>("ymin", -4.0); desc.add<edm::ParameterSetDescription>("Pull_X_vs_eta_Strip", psd0); } { edm::ParameterSetDescription psd0; psd0.add<std::string>("name", "Pull_Y_vs_Eta_Strip"); psd0.add<std::string>("title", ";#eta;pull y"); psd0.add<double>("ymax", 4.0); psd0.add<int>("NxBins", 82); psd0.add<bool>("switch", true); psd0.add<double>("xmax", 4.1); psd0.add<double>("xmin", -4.1); psd0.add<double>("ymin", -4.0); desc.add<edm::ParameterSetDescription>("Pull_Y_vs_eta_Strip", psd0); } { edm::ParameterSetDescription psd0; psd0.add<std::string>("name", "Number_RecHits_matched_PrimarySimTrack"); psd0.add<std::string>("title", "Number of RecHits matched to primary SimTrack;;"); psd0.add<double>("xmin", 0.0); psd0.add<bool>("switch", true); psd0.add<double>("xmax", 10000.0); psd0.add<int>("NxBins", 100); desc.add<edm::ParameterSetDescription>("nRecHits_Strip_primary", psd0); } /////// desc.add<edm::InputTag>("SimVertexSource", edm::InputTag("g4SimHits")); desc.add<bool>("associatePixel", false); desc.add<std::string>("TopFolderName", "TrackerPhase2OTRecHitV"); desc.add<bool>("associateHitbySimTrack", true); desc.add<bool>("Verbosity", false); desc.add<bool>("associateStrip", true); desc.add<edm::InputTag>("phase2TrackerSimLinkSrc", edm::InputTag("simSiPixelDigis", "Tracker")); desc.add<bool>("associateRecoTracks", false); desc.add<edm::InputTag>("pixelSimLinkSrc", edm::InputTag("simSiPixelDigis", "Pixel")); desc.add<bool>("usePhase2Tracker", true); desc.add<edm::InputTag>("OuterTrackerDigiSimLinkSource", edm::InputTag("simSiPixelDigis", "Tracker")); desc.add<edm::InputTag>("OuterTrackerDigiSource", edm::InputTag("mix", "Tracker")); desc.add<edm::InputTag>("rechitsSrc", edm::InputTag("siPhase2RecHits")); desc.add<edm::InputTag>("simTracksSrc", edm::InputTag("g4SimHits")); desc.add<double>("SimTrackMinPt", 2.0); desc.add<std::vector<edm::InputTag>>("PSimHitSource", { edm::InputTag("g4SimHits:TrackerHitsTIBLowTof"), edm::InputTag("g4SimHits:TrackerHitsTIBHighTof"), edm::InputTag("g4SimHits:TrackerHitsTIDLowTof"), edm::InputTag("g4SimHits:TrackerHitsTIDHighTof"), edm::InputTag("g4SimHits:TrackerHitsTOBLowTof"), edm::InputTag("g4SimHits:TrackerHitsTOBHighTof"), edm::InputTag("g4SimHits:TrackerHitsTECLowTof"), edm::InputTag("g4SimHits:TrackerHitsTECHighTof"), edm::InputTag("g4SimHits:TrackerHitsPixelBarrelLowTof"), edm::InputTag("g4SimHits:TrackerHitsPixelBarrelHighTof"), edm::InputTag("g4SimHits:TrackerHitsPixelEndcapLowTof"), edm::InputTag("g4SimHits:TrackerHitsPixelEndcapHighTof"), }); desc.add<std::vector<std::string>>("ROUList", {"TrackerHitsPixelBarrelLowTof", "TrackerHitsPixelBarrelHighTof", "TrackerHitsTIBLowTof", "TrackerHitsTIBHighTof", "TrackerHitsTIDLowTof", "TrackerHitsTIDHighTof", "TrackerHitsTOBLowTof", "TrackerHitsTOBHighTof", "TrackerHitsPixelEndcapLowTof", "TrackerHitsPixelEndcapHighTof", "TrackerHitsTECLowTof", "TrackerHitsTECHighTof"}); descriptions.add("Phase2OTValidateRecHit", desc); } //define this as a plug-in DEFINE_FWK_MODULE(Phase2OTValidateRecHit);
44.707895
120
0.669816
ryanm124
bf5d9e4c55fac0759c8e0b9d735edec920d831a4
4,180
hxx
C++
main/vcl/inc/graphite_adaptors.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/vcl/inc/graphite_adaptors.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/vcl/inc/graphite_adaptors.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef _SV_GRAPHITEADAPTORS_HXX #define _SV_GRAPHITEADAPTORS_HXX // We need this to enable namespace support in libgrengine headers. #define GR_NAMESPACE // Standard Library #include <stdexcept> // Platform #ifndef _SVWIN_H #include <tools/svwin.h> #endif #ifndef _SV_SVSYS_HXX #include <svsys.h> #endif #ifndef _SV_SALGDI_HXX #include <salgdi.hxx> #endif #ifndef _SV_SALLAYOUT_HXX #include <sallayout.hxx> #endif // Module #include "vcl/dllapi.h" // Libraries #include <preextstl.h> #include <graphite/GrClient.h> #include <graphite/Font.h> #include <graphite/ITextSource.h> #include <postextstl.h> // Module type definitions and forward declarations. // #ifndef MSC // SAL/VCL types class ServerFont; class FreetypeServerFont; // Graphite types struct FontProperties : gr::FontProps { FontProperties(const FreetypeServerFont & font) throw(); }; namespace grutils { class GrFeatureParser; } // This class adapts the Sal font and graphics services to form required by // the Graphite engine. // @author tse // class VCL_PLUGIN_PUBLIC GraphiteFontAdaptor : public gr::Font { typedef std::map<const gr::gid16, std::pair<gr::Rect, gr::Point> > GlyphMetricMap; friend class GrFontHasher; public: static bool IsGraphiteEnabledFont(ServerFont &) throw(); GraphiteFontAdaptor(ServerFont & font, const sal_Int32 dpi_x, const sal_Int32 dpi_y); GraphiteFontAdaptor(const GraphiteFontAdaptor &) throw(); ~GraphiteFontAdaptor() throw(); gr::Font * copyThis(); // Basic attribute accessors. virtual float ascent(); virtual float descent(); virtual bool bold(); virtual bool italic(); virtual float height(); virtual unsigned int getDPIx(); virtual unsigned int getDPIy(); // Font access methods. virtual const void * getTable(gr::fontTableId32 tableID, size_t * pcbSize); virtual void getFontMetrics(float * ascent_out, float * descent_out = 0, float * em_square_out = 0); // Glyph metrics. virtual void getGlyphMetrics(gr::gid16 glyphID, gr::Rect & boundingBox, gr::Point & advances); // Adaptor attributes. const FontProperties & fontProperties() const throw(); FreetypeServerFont & font() const throw(); const grutils::GrFeatureParser * features() const { return mpFeatures; }; private: virtual void UniqueCacheInfo(ext_std::wstring &, bool &, bool &); FreetypeServerFont& mrFont; FontProperties maFontProperties; const unsigned int mnDpiX, mnDpiY; const float mfAscent, mfDescent, mfEmUnits; grutils::GrFeatureParser * mpFeatures; GlyphMetricMap maGlyphMetricMap; }; // Partial implementation of class GraphiteFontAdaptor. // inline const FontProperties & GraphiteFontAdaptor::fontProperties() const throw() { return maFontProperties; } inline FreetypeServerFont & GraphiteFontAdaptor::font() const throw() { return mrFont; } #endif // not MFC // Partial implementation of class TextSourceAdaptor. // //inline const ImplLayoutArgs & TextSourceAdaptor::layoutArgs() const throw() { // return _layout_args; //} #endif // _SV_GRAPHITEADAPTORS_HXX
28.053691
113
0.690191
Grosskopf
bf5f4749627c0f3b5018ad6c17a7d8aea109c664
739
hpp
C++
include/RED4ext/Types/generated/quest/SetLootInteractionAccess_NodeType.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
1
2021-02-01T23:07:50.000Z
2021-02-01T23:07:50.000Z
include/RED4ext/Types/generated/quest/SetLootInteractionAccess_NodeType.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "MIT" ]
null
null
null
include/RED4ext/Types/generated/quest/SetLootInteractionAccess_NodeType.hpp
Cyberpunk-Extended-Development-Team/RED4ext.SDK
2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae
[ "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/generated/game/EntityReference.hpp> #include <RED4ext/Types/generated/quest/IItemManagerNodeType.hpp> namespace RED4ext { namespace quest { struct SetLootInteractionAccess_NodeType : quest::IItemManagerNodeType { static constexpr const char* NAME = "questSetLootInteractionAccess_NodeType"; static constexpr const char* ALIAS = NAME; game::EntityReference objectRef; // 30 bool accessible; // 68 uint8_t unk69[0x70 - 0x69]; // 69 }; RED4EXT_ASSERT_SIZE(SetLootInteractionAccess_NodeType, 0x70); } // namespace quest } // namespace RED4ext
28.423077
81
0.769959
Cyberpunk-Extended-Development-Team
bf62028f5ba64a4d5d5cdffa15d5147cc22e285d
585
cpp
C++
0041 First Missing Positive/solution.cpp
Aden-Tao/LeetCode
c34019520b5808c4251cb76f69ca2befa820401d
[ "MIT" ]
1
2019-12-19T04:13:15.000Z
2019-12-19T04:13:15.000Z
0041 First Missing Positive/solution.cpp
Aden-Tao/LeetCode
c34019520b5808c4251cb76f69ca2befa820401d
[ "MIT" ]
null
null
null
0041 First Missing Positive/solution.cpp
Aden-Tao/LeetCode
c34019520b5808c4251cb76f69ca2befa820401d
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> class Solution { public: int firstMissingPositive(std::vector<int>& nums) { int n = nums.size(); for (int i = 0; i < n; i ++) { while (nums[i] > 0 && nums[i] <= n && nums[nums[i] - 1] != nums[i]) std::swap(nums[i], nums[nums[i] - 1]); } for (int i = 0; i < n; i ++) if (nums[i] != i + 1) return i + 1; return n + 1; } }; int main(){ Solution s; std::vector<int> vec{3,4,-1,1}; assert(s.firstMissingPositive(vec) == 2); return 0; }
24.375
79
0.444444
Aden-Tao
bf6209c733bc6973e4b29b5c02b57d7401f66e2b
1,502
cpp
C++
packages/velocityControl/src/algorithms/CalculateAccelerating.cpp
Falcons-Robocup/code
2281a8569e7f11cbd3238b7cc7341c09e2e16249
[ "Apache-2.0" ]
2
2021-01-15T13:27:19.000Z
2021-08-04T08:40:52.000Z
packages/velocityControl/src/algorithms/CalculateAccelerating.cpp
Falcons-Robocup/code
2281a8569e7f11cbd3238b7cc7341c09e2e16249
[ "Apache-2.0" ]
null
null
null
packages/velocityControl/src/algorithms/CalculateAccelerating.cpp
Falcons-Robocup/code
2281a8569e7f11cbd3238b7cc7341c09e2e16249
[ "Apache-2.0" ]
5
2018-05-01T10:39:31.000Z
2022-03-25T03:02:35.000Z
// Copyright 2020 Erik Kouters (Falcons) // SPDX-License-Identifier: Apache-2.0 /* * CalculateAccelerating.cpp * * Created on: December, 2019 * Author: Jan Feitsma */ #include "int/VelocityControlAlgorithms.hpp" void CalculateAccelerating::execute(VelocityControlData &data) { TRACE_FUNCTION(""); // calculate current velocity in RCS Velocity2D c = data.currentVelocityFcs; c = c.transform_fcs2rcs(data.currentPositionFcs); // calculate acceleration based on setpoints (real acceleration typically lags behind a bit) auto a = (data.resultVelocityRcs - data.previousVelocityRcs) / data.dt; TRACE("prevVelocity=(%8.4f,%8.4f,%8.4f)", data.previousVelocityRcs.x, data.previousVelocityRcs.y, data.previousVelocityRcs.phi); TRACE("currVelocity=(%8.4f,%8.4f,%8.4f)", c.x, c.y, c.phi); TRACE("newVelocity=(%8.4f,%8.4f,%8.4f)", data.resultVelocityRcs.x, data.resultVelocityRcs.y, data.resultVelocityRcs.phi); TRACE("dt=%8.4f", data.dt); // take inproduct of acceleration with current velocity to determine if robot is accelerating or not data.isAccelerating[0] = (a.x * c.x >= data.currentMotionTypeConfig.limits.accThresholdX); data.isAccelerating[1] = (a.y * c.y >= data.currentMotionTypeConfig.limits.accThresholdY); data.isAccelerating[2] = (a.phi * c.phi >= data.currentMotionTypeConfig.limits.accThresholdRz); TRACE("isAccX=%d isAccY=%d isAccRz=%d", data.isAccelerating[0], data.isAccelerating[1], data.isAccelerating[2]); }
40.594595
132
0.721704
Falcons-Robocup
bf621f5ae967b5a70786a3f0788abddf728ba3f3
224
cpp
C++
sudoku/config.cpp
Trinkle23897/sudoku-qt5
fe615dac0ce0a44f493a0c1a2ae57a42e40a941e
[ "MIT" ]
10
2017-09-04T03:03:38.000Z
2021-11-06T10:19:03.000Z
sudoku/config.cpp
Trinkle23897/sudoku-qt5
fe615dac0ce0a44f493a0c1a2ae57a42e40a941e
[ "MIT" ]
1
2018-07-20T05:18:32.000Z
2018-07-20T08:16:06.000Z
sudoku/config.cpp
Trinkle23897/sudoku-qt5
fe615dac0ce0a44f493a0c1a2ae57a42e40a941e
[ "MIT" ]
4
2019-04-25T11:43:20.000Z
2021-11-06T10:19:06.000Z
#include "config.h" const int pos[9][9]={{0,0,0,1,1,1,2,2,2},{0,0,0,1,1,1,2,2,2},{0,0,0,1,1,1,2,2,2},{3,3,3,4,4,4,5,5,5},{3,3,3,4,4,4,5,5,5},{3,3,3,4,4,4,5,5,5},{6,6,6,7,7,7,8,8,8},{6,6,6,7,7,7,8,8,8},{6,6,6,7,7,7,8,8,8}};
56
202
0.482143
Trinkle23897
bf65f4e84a4b44ee7f9b53884ac2de4e31a0483e
4,794
cc
C++
src/storage/fs_test/full.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
5
2022-01-10T20:22:17.000Z
2022-01-21T20:14:17.000Z
src/storage/fs_test/full.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
1
2022-03-01T01:12:04.000Z
2022-03-01T01:17:26.000Z
src/storage/fs_test/full.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
null
null
null
// Copyright 2022 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 <dirent.h> #include <string.h> #include <sys/stat.h> #include <unistd.h> #include <fbl/unique_fd.h> #include "src/storage/fs_test/fs_test_fixture.h" #include "src/storage/fs_test/test_filesystem.h" namespace fs_test { namespace { using FullTestParamType = std::tuple<TestFilesystemOptions, bool>; class FullTest : public BaseFilesystemTest, public testing::WithParamInterface<FullTestParamType> { public: FullTest() : BaseFilesystemTest(std::get<0>(GetParam())) {} bool should_remount() const { return std::get<1>(GetParam()); } }; void FillFile(fbl::unique_fd fd, unsigned char value) { unsigned char buf[4096] = {value}; for (;;) { ssize_t written = write(fd.get(), buf, sizeof(buf)); if (written < ssize_t{sizeof(buf)}) { break; } } ASSERT_EQ(close(fd.release()), 0); } std::string GetDescriptionForFullTestParamType( const testing::TestParamInfo<FullTestParamType> param) { std::stringstream s; s << std::get<0>(param.param) << (std::get<1>(param.param) ? "WithRemount" : "WithoutRemount"); return s.str(); } void FillDirectoryEntries(FullTest& test) { for (int i = 0;; ++i) { std::string name = std::string("file-") + std::to_string(i); fbl::unique_fd fd(open(test.GetPath(name).c_str(), O_CREAT, 0644)); if (!fd.is_valid()) { break; } } } void Remount(TestFilesystem& fs) { ASSERT_EQ(fs.Unmount().status_value(), ZX_OK); ASSERT_EQ(fs.Fsck().status_value(), ZX_OK); ASSERT_EQ(fs.Mount().status_value(), ZX_OK); } TEST_P(FullTest, ReadWhileFull) { { fbl::unique_fd fd(open(GetPath("file").c_str(), O_APPEND | O_RDWR | O_CREAT, 0644)); FillFile(std::move(fd), 0xFFu); FillDirectoryEntries(*this); if (should_remount()) { Remount(fs()); } } // Can readdir... { DIR* dir = opendir(GetPath(".").c_str()); ASSERT_NE(dir, nullptr); bool found_file = false; struct dirent* de; while ((de = readdir(dir)) != nullptr) { if (!strcmp(de->d_name, "file")) { found_file = true; break; } } ASSERT_TRUE(found_file); ASSERT_EQ(closedir(dir), 0); } // Can open... fbl::unique_fd fd(open(GetPath("file").c_str(), O_APPEND | O_RDWR, 0644)); // Can stat... struct stat sb; ASSERT_EQ(fstat(fd.get(), &sb), 0); ASSERT_GT(sb.st_size, 0); // Can read... unsigned char buf = 0; ASSERT_EQ(read(fd.get(), &buf, sizeof(buf)), 1); ASSERT_EQ(buf, 0xFFu); } TEST_P(FullTest, CreateFileWhenFull) { { fbl::unique_fd fd(open(GetPath("file").c_str(), O_APPEND | O_RDWR | O_CREAT, 0644)); FillFile(std::move(fd), 0xFFu); FillDirectoryEntries(*this); if (should_remount()) { Remount(fs()); } } // We want to try to create a file but we can't be certain it won't succeed (background cleanup // could have happened), so don't check the return value. fbl::unique_fd fd(open(GetPath("new-file").c_str(), O_APPEND | O_RDWR | O_CREAT, 0644)); } TEST_P(FullTest, WriteToFileWhenFull) { { fbl::unique_fd fd(open(GetPath("file").c_str(), O_APPEND | O_RDWR | O_CREAT, 0644)); FillFile(std::move(fd), 0xFFu); FillDirectoryEntries(*this); if (should_remount()) { Remount(fs()); } } // We want to try to write to the file but we can't be certain it won't succeed (background // cleanup could have happened), so don't check the return value. fbl::unique_fd fd(open(GetPath("file").c_str(), O_APPEND | O_RDWR, 0644)); ASSERT_TRUE(fd.is_valid()); unsigned char buf = 0; write(fd.get(), &buf, sizeof(buf)); } TEST_P(FullTest, UnlinkWhenFullSucceeds) { { fbl::unique_fd fd(open(GetPath("file").c_str(), O_APPEND | O_RDWR | O_CREAT, 0644)); FillFile(std::move(fd), 0xFFu); FillDirectoryEntries(*this); if (should_remount()) { Remount(fs()); } } ASSERT_EQ(unlink(GetPath("file").c_str()), 0); } std::vector<FullTestParamType> GetTestParams() { std::vector<FullTestParamType> test_combinations; for (TestFilesystemOptions options : AllTestFilesystems()) { // Filesystems such as memfs cannot run this test because they OOM (as expected, given // memory is the limiting factor). if (options.filesystem->GetTraits().in_memory) continue; test_combinations.push_back(std::make_tuple(options, true)); test_combinations.push_back(std::make_tuple(options, false)); } return test_combinations; } GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(FullTest); INSTANTIATE_TEST_SUITE_P( /*no prefix*/, FullTest, testing::ValuesIn(GetTestParams()), GetDescriptionForFullTestParamType); } // namespace } // namespace fs_test
28.706587
99
0.665207
allansrc
bf67beeea3376a30354343c172eae1d467326b35
3,641
cpp
C++
graph/minCostMaxFlow_inet_chinese_dijkstra.cpp
fersarr/algo
a6ed2b53be8e748d9c0e488dc5fad075fa7cbb53
[ "MIT" ]
null
null
null
graph/minCostMaxFlow_inet_chinese_dijkstra.cpp
fersarr/algo
a6ed2b53be8e748d9c0e488dc5fad075fa7cbb53
[ "MIT" ]
null
null
null
graph/minCostMaxFlow_inet_chinese_dijkstra.cpp
fersarr/algo
a6ed2b53be8e748d9c0e488dc5fad075fa7cbb53
[ "MIT" ]
null
null
null
#include <iostream> #include <sstream> #include <vector> #include <string> #include <cstdio> #include <cstring> #include <algorithm> #include <queue> #include <set> #include <stack> #include <map> #include <list> #define MAX 1l << 62 //too slow, TLE (time limit exceeded) using namespace std; typedef pair<int,int> ii; typedef pair<long long,long long> llll; typedef vector<int> vi; typedef vector<ii> vii; typedef vector<llll> vllll; typedef vector<long long> vll; typedef vector<vi> vvi; typedef vector<vii> vvii; int N,M; long long D,K; llll mm[105][105]; int parent[105]; long long minT = 0; void augment(){ int nc = N-1; vi S; while(nc >= 0){ S.push_back(nc); nc = parent[nc]; } long long minEdge = MAX; //min residual capacity edge reverse(S.begin(),S.end()); for(int i=1;i<S.size();i++){ int u = S[i-1], v = S[i]; minEdge = min(minEdge,mm[u][v].first); } if(D < minEdge) minEdge = D; D -= minEdge;//each time we have less data to flow through network for(int i=1;i<S.size();i++){ int u = S[i-1], v = S[i]; mm[u][v].first -= minEdge; //flow mm[v][u].first += minEdge; minT += minEdge * mm[u][v].second; //flow * edgeCost = cost // printf(" u,v = %d,%d, minEdge = %d, second = %d, minT = %ld\n",u,v,minEdge,mm[u][v].second, minT); } } int cnt[105]; int main(){ while(cin >> N >> M){ minT = 0; memset(mm,0,sizeof mm); int a,b; long long c; for(int i=0;i<M;i++){ cin >> a >> b >> c; a--;b--; mm[a][b].second = c; //cost mm[b][a].second = -c; mm[a][b].first =-1; //flowCapacity - all have the same mm[b][a].first =-1; } cin >> D >> K; for(int i=0;i<N;i++){ for(int j=0;j<N;j++){ if(mm[i][j].first == -1){ mm[i][j].first = K; //flowCapacity - all have the same } } } // then do the max-flow alg -- using dijkstra's to find the shortest path while(true){ // init first for(int i=0;i<N;i++) parent[i] = -2; priority_queue<llll,vllll,greater<llll > > q; //cost-node : pair<long long, long long> vll dist(N,MAX); q.push(llll(0,0)); dist[0] = 0; memset(cnt,0,sizeof cnt); while(!q.empty()){ int cost = q.top().first; int u = q.top().second;q.pop(); if(cost > dist[u]) //if we reached this node in a better way before, ignore this pass continue; if(u == N - 1) break; // avoid negative cycle. N-1 is sink cnt[u]++; if(cnt[u] > N) break; dist[u] = cost; for(int i=0;i<N;i++){ int nd = cost + mm[u][i].second; //costSoFar +edgeCost if(nd < dist[i] && mm[u][i].first > 0){ // printf(" u,i = %d, %d, mm[u][i] = %d\n",u,i,mm[u][i].first); parent[i] = u; q.push(llll(nd,i)); } } } if(parent[N-1] != -2){ // printf("parent[N-1] = %d\n",parent[N-1]); augment(); } else break; if(D <= 0) break; } if(D > 0) cout << "Impossible." << endl; else cout << minT << endl; } return 0; }
27.171642
109
0.449327
fersarr
bf6ad18739722e9b812277069f15dba5087b0159
379
hpp
C++
worker/fuzzer/include/RTC/RTCP/FuzzerFeedbackPsVbcm.hpp
kcking/mediasoup
f385349d0f06fe14a4e38d50f0212b48d588fa32
[ "ISC" ]
4,465
2017-04-05T20:00:24.000Z
2022-03-31T13:27:43.000Z
worker/fuzzer/include/RTC/RTCP/FuzzerFeedbackPsVbcm.hpp
kcking/mediasoup
f385349d0f06fe14a4e38d50f0212b48d588fa32
[ "ISC" ]
617
2017-04-05T21:24:27.000Z
2022-03-31T06:17:25.000Z
worker/fuzzer/include/RTC/RTCP/FuzzerFeedbackPsVbcm.hpp
kcking/mediasoup
f385349d0f06fe14a4e38d50f0212b48d588fa32
[ "ISC" ]
900
2017-04-11T09:25:27.000Z
2022-03-30T21:37:00.000Z
#ifndef MS_FUZZER_RTC_RTCP_FEEDBACK_PS_VBCM #define MS_FUZZER_RTC_RTCP_FEEDBACK_PS_VBCM #include "common.hpp" #include "RTC/RTCP/FeedbackPsVbcm.hpp" namespace Fuzzer { namespace RTC { namespace RTCP { namespace FeedbackPsVbcm { void Fuzz(::RTC::RTCP::FeedbackPsVbcmPacket* packet); } } // namespace RTCP } // namespace RTC } // namespace Fuzzer #endif
17.227273
57
0.733509
kcking
bf717470c7e839ac026538b6fa53e0969f833a16
8,295
cc
C++
cc/scheduler/begin_frame_source.cc
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
1
2020-09-15T08:43:34.000Z
2020-09-15T08:43:34.000Z
cc/scheduler/begin_frame_source.cc
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
null
null
null
cc/scheduler/begin_frame_source.cc
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "cc/scheduler/begin_frame_source.h" #include <stddef.h> #include "base/auto_reset.h" #include "base/location.h" #include "base/logging.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "base/trace_event/trace_event.h" #include "base/trace_event/trace_event_argument.h" #include "cc/scheduler/delay_based_time_source.h" #include "cc/scheduler/scheduler.h" namespace cc { namespace { // kDoubleTickDivisor prevents the SyntheticBFS from sending BeginFrames too // often to an observer. static const double kDoubleTickDivisor = 2.0; } // BeginFrameObserverBase ----------------------------------------------- BeginFrameObserverBase::BeginFrameObserverBase() : last_begin_frame_args_(), dropped_begin_frame_args_(0) { } const BeginFrameArgs& BeginFrameObserverBase::LastUsedBeginFrameArgs() const { return last_begin_frame_args_; } void BeginFrameObserverBase::OnBeginFrame(const BeginFrameArgs& args) { DEBUG_FRAMES("BeginFrameObserverBase::OnBeginFrame", "last args", last_begin_frame_args_.AsValue(), "new args", args.AsValue()); DCHECK(args.IsValid()); DCHECK(args.frame_time >= last_begin_frame_args_.frame_time); bool used = OnBeginFrameDerivedImpl(args); if (used) { last_begin_frame_args_ = args; } else { ++dropped_begin_frame_args_; } } // BeginFrameSourceBase ------------------------------------------------------ BeginFrameSourceBase::BeginFrameSourceBase() : paused_(false), inside_as_value_into_(false) {} BeginFrameSourceBase::~BeginFrameSourceBase() {} void BeginFrameSourceBase::AddObserver(BeginFrameObserver* obs) { DEBUG_FRAMES("BeginFrameSourceBase::AddObserver", "num observers", observers_.size(), "to add observer", obs); DCHECK(obs); DCHECK(observers_.find(obs) == observers_.end()) << "AddObserver cannot be called with an observer that was already added"; bool observers_was_empty = observers_.empty(); observers_.insert(obs); if (observers_was_empty) OnNeedsBeginFramesChanged(true); obs->OnBeginFrameSourcePausedChanged(paused_); } void BeginFrameSourceBase::RemoveObserver(BeginFrameObserver* obs) { DEBUG_FRAMES("BeginFrameSourceBase::RemoveObserver", "num observers", observers_.size(), "removed observer", obs); DCHECK(obs); DCHECK(observers_.find(obs) != observers_.end()) << "RemoveObserver cannot be called with an observer that wasn't added"; observers_.erase(obs); if (observers_.empty()) OnNeedsBeginFramesChanged(false); } void BeginFrameSourceBase::CallOnBeginFrame(const BeginFrameArgs& args) { DEBUG_FRAMES("BeginFrameSourceBase::CallOnBeginFrame", "num observers", observers_.size(), "args", args.AsValue()); std::set<BeginFrameObserver*> observers(observers_); for (BeginFrameObserver* obs : observers) obs->OnBeginFrame(args); } void BeginFrameSourceBase::SetBeginFrameSourcePaused(bool paused) { if (paused_ == paused) return; paused_ = paused; std::set<BeginFrameObserver*> observers(observers_); for (BeginFrameObserver* obs : observers) obs->OnBeginFrameSourcePausedChanged(paused_); } // BackToBackBeginFrameSource -------------------------------------------- BackToBackBeginFrameSource::BackToBackBeginFrameSource( base::SingleThreadTaskRunner* task_runner) : BeginFrameSourceBase(), task_runner_(task_runner), weak_factory_(this) { DCHECK(task_runner); } BackToBackBeginFrameSource::~BackToBackBeginFrameSource() { } base::TimeTicks BackToBackBeginFrameSource::Now() { return base::TimeTicks::Now(); } // BeginFrameSourceBase support void BackToBackBeginFrameSource::AddObserver(BeginFrameObserver* obs) { BeginFrameSourceBase::AddObserver(obs); pending_begin_frame_observers_.insert(obs); PostPendingBeginFramesTask(); } void BackToBackBeginFrameSource::RemoveObserver(BeginFrameObserver* obs) { BeginFrameSourceBase::RemoveObserver(obs); pending_begin_frame_observers_.erase(obs); if (pending_begin_frame_observers_.empty()) begin_frame_task_.Cancel(); } void BackToBackBeginFrameSource::DidFinishFrame(BeginFrameObserver* obs, size_t remaining_frames) { BeginFrameSourceBase::DidFinishFrame(obs, remaining_frames); if (remaining_frames == 0 && observers_.find(obs) != observers_.end()) { pending_begin_frame_observers_.insert(obs); PostPendingBeginFramesTask(); } } void BackToBackBeginFrameSource::PostPendingBeginFramesTask() { DCHECK(needs_begin_frames()); DCHECK(!pending_begin_frame_observers_.empty()); if (begin_frame_task_.IsCancelled()) { begin_frame_task_.Reset( base::Bind(&BackToBackBeginFrameSource::SendPendingBeginFrames, weak_factory_.GetWeakPtr())); task_runner_->PostTask(FROM_HERE, begin_frame_task_.callback()); } } void BackToBackBeginFrameSource::SendPendingBeginFrames() { DCHECK(needs_begin_frames()); DCHECK(!begin_frame_task_.IsCancelled()); begin_frame_task_.Cancel(); base::TimeTicks now = Now(); BeginFrameArgs args = BeginFrameArgs::Create( BEGINFRAME_FROM_HERE, now, now + BeginFrameArgs::DefaultInterval(), BeginFrameArgs::DefaultInterval(), BeginFrameArgs::NORMAL); std::set<BeginFrameObserver*> pending_observers; pending_observers.swap(pending_begin_frame_observers_); for (BeginFrameObserver* obs : pending_observers) obs->OnBeginFrame(args); } // SyntheticBeginFrameSource --------------------------------------------- SyntheticBeginFrameSource::SyntheticBeginFrameSource( base::SingleThreadTaskRunner* task_runner, base::TimeDelta initial_vsync_interval) : time_source_( DelayBasedTimeSource::Create(initial_vsync_interval, task_runner)) { time_source_->SetClient(this); } SyntheticBeginFrameSource::SyntheticBeginFrameSource( std::unique_ptr<DelayBasedTimeSource> time_source) : time_source_(std::move(time_source)) { time_source_->SetClient(this); } SyntheticBeginFrameSource::~SyntheticBeginFrameSource() {} void SyntheticBeginFrameSource::OnUpdateVSyncParameters( base::TimeTicks timebase, base::TimeDelta interval) { if (!authoritative_interval_.is_zero()) interval = authoritative_interval_; last_timebase_ = timebase; time_source_->SetTimebaseAndInterval(timebase, interval); } void SyntheticBeginFrameSource::SetAuthoritativeVSyncInterval( base::TimeDelta interval) { authoritative_interval_ = interval; OnUpdateVSyncParameters(last_timebase_, interval); } BeginFrameArgs SyntheticBeginFrameSource::CreateBeginFrameArgs( base::TimeTicks frame_time, BeginFrameArgs::BeginFrameArgsType type) { return BeginFrameArgs::Create(BEGINFRAME_FROM_HERE, frame_time, time_source_->NextTickTime(), time_source_->Interval(), type); } // BeginFrameSource support void SyntheticBeginFrameSource::AddObserver(BeginFrameObserver* obs) { BeginFrameSourceBase::AddObserver(obs); BeginFrameArgs args = CreateBeginFrameArgs( time_source_->NextTickTime() - time_source_->Interval(), BeginFrameArgs::MISSED); BeginFrameArgs last_args = obs->LastUsedBeginFrameArgs(); if (!last_args.IsValid() || (args.frame_time > last_args.frame_time + args.interval / kDoubleTickDivisor)) { obs->OnBeginFrame(args); } } void SyntheticBeginFrameSource::OnNeedsBeginFramesChanged( bool needs_begin_frames) { time_source_->SetActive(needs_begin_frames); } // DelayBasedTimeSourceClient support void SyntheticBeginFrameSource::OnTimerTick() { BeginFrameArgs args = CreateBeginFrameArgs(time_source_->LastTickTime(), BeginFrameArgs::NORMAL); std::set<BeginFrameObserver*> observers(observers_); for (auto& it : observers) { BeginFrameArgs last_args = it->LastUsedBeginFrameArgs(); if (!last_args.IsValid() || (args.frame_time > last_args.frame_time + args.interval / kDoubleTickDivisor)) { it->OnBeginFrame(args); } } } } // namespace cc
34.852941
80
0.728632
maidiHaitai
bf7399b676a69ff827aea7a40f59051c106fc069
3,414
cpp
C++
software/CmsServerMain.cpp
haggaie/nica
b43de25be1549805340c5da37bdc451ff09cd936
[ "BSD-2-Clause" ]
22
2019-06-20T20:24:03.000Z
2022-03-10T08:18:45.000Z
software/CmsServerMain.cpp
haggaie/nica
b43de25be1549805340c5da37bdc451ff09cd936
[ "BSD-2-Clause" ]
3
2019-08-13T12:11:43.000Z
2022-03-18T00:52:51.000Z
software/CmsServerMain.cpp
haggaie/nica
b43de25be1549805340c5da37bdc451ff09cd936
[ "BSD-2-Clause" ]
8
2019-07-11T18:35:34.000Z
2021-11-11T04:45:29.000Z
// // Copyright (c) 2016-2017 Haggai Eran, Gabi Malka, Lior Zeno, Maroun Tork // 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. // // 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 "RunnableServerBase.hpp" #include "CmsUdpServer.hpp" #include "cms-ikernel.hpp" #include <uuid/uuid.h> #include <sstream> #include <future> class cms_main : public RunnableServerBase { public: cms_main(const unsigned char *uuid, int argc, char **argv) : RunnableServerBase(uuid, argc, argv) {} protected: virtual void preflight() { topKs = std::vector<std::future<std::vector<int>>>(thread_num); } std::string vec_to_str(const std::vector<int>& vec) { std::ostringstream sstream; if (vec.size() > 0) { std::copy(&vec[0], &vec[vec.size() - 1], std::ostream_iterator<int>(sstream, " ")); sstream << vec[vec.size() - 1]; } return sstream.str(); } virtual void postflight() { if (ikernel_top_k.size() > 0) { std::cout << "iKernel topK: " << vec_to_str(ikernel_top_k) << std::endl; } else { std::cout << "iKernel topK is empty" << std::endl; } std::cout << "Host topK per thread: " << std::endl; for (int i = 0; i < thread_num; ++i) { std::vector<int> host_top_k = topKs[i].get(); std::cout << "Thread " << i << ": " << vec_to_str(host_top_k) << std::endl; } } virtual void start_server(const int &thread_id) { CmsUdpServer::args args = { .port = short(port + thread_id), .interface = vm["interface"].as<std::string>(), }; std::promise<std::vector<int>> topK; topKs[thread_id] = topK.get_future(); CmsUdpServer s(io_service, args); s.do_receive(); io_service.run(); topK.set_value(s.get_host_topK()); if (thread_id == 0) { ikernel_top_k = s.get_topK(); } } std::vector<std::future<std::vector<int>>> topKs; std::vector<int> ikernel_top_k; }; int main(int argc, char **argv) { uuid_t uuid = CMS_UUID; return cms_main(uuid, argc, argv).run(); }
34.14
95
0.644112
haggaie
bf73abea85ea8cc77f6889a4a6f141ad3e576d3a
371
cpp
C++
leetcode/contest-228/1758. Minimum Changes To Make Alternating Binary String.cpp
upupming/algorithm
44edcffe886eaf4ce8c7b27a8db50d7ed5d29ef1
[ "MIT" ]
107
2019-10-25T07:46:59.000Z
2022-03-29T11:10:56.000Z
leetcode/contest-228/1758. Minimum Changes To Make Alternating Binary String.cpp
upupming/algorithm
44edcffe886eaf4ce8c7b27a8db50d7ed5d29ef1
[ "MIT" ]
1
2021-08-13T05:42:27.000Z
2021-08-13T05:42:27.000Z
leetcode/contest-228/1758. Minimum Changes To Make Alternating Binary String.cpp
upupming/algorithm
44edcffe886eaf4ce8c7b27a8db50d7ed5d29ef1
[ "MIT" ]
18
2020-12-09T14:24:22.000Z
2022-03-30T06:56:01.000Z
#include <bits/stdc++.h> using namespace std; class Solution { public: int calc(string s, int f) { int ans = 0; for (int i = 0; i < s.length(); i++) { char d = (f + i) % 2 + '0'; if (s[i] != d) ans++; } return ans; } int minOperations(string s) { return min(calc(s, 0), calc(s, 1)); } };
21.823529
46
0.442049
upupming
bf7de81fa0b557e97b39233802a7992d585f4d92
888
cpp
C++
c++/trick/defer.cpp
dannypsnl/languages-learn
2351a235bd55e720394111237d41f65482eb89ec
[ "MIT" ]
2
2018-01-04T00:47:25.000Z
2018-01-12T08:07:50.000Z
c++/trick/defer.cpp
dannypsnl/languages-learn
2351a235bd55e720394111237d41f65482eb89ec
[ "MIT" ]
1
2018-01-08T14:45:55.000Z
2018-01-09T05:02:09.000Z
c++/trick/defer.cpp
dannypsnl/languages-learn
2351a235bd55e720394111237d41f65482eb89ec
[ "MIT" ]
null
null
null
#include <functional> #include <iostream> #include <stack> class deferer { std::stack<std::function<void()>> defers; void callAll() { while (!this->defers.empty()) { this->defers.top()(); this->defers.pop(); } } public: deferer() {} void add(std::function<void()> &&f) { this->defers.push(std::forward<decltype(f)>(f)); } ~deferer() { callAll(); } }; #define allow_defer() deferer __deferer{}; #define defer(...) \ auto defered = std::bind(__VA_ARGS__); \ __deferer.add(defered); int main() { allow_defer(); defer([=]() { std::cout << "defer!!!!!!!!!!" << '\n'; }); for (size_t i = 0; i < 10; ++i) { defer( [=]() { std::cout << "Number " << i + 1 << " defer be call" << '\n'; }); } std::cout << "hello, defer" << '\n'; }
24
80
0.471847
dannypsnl
bf7f2c1264d0259118ee97d3248ca5037ecd94f0
1,194
cpp
C++
2018.3.27/a.cpp
1980744819/ACM-code
a697242bc963e682e552e655e3d78527e044e854
[ "Apache-2.0" ]
null
null
null
2018.3.27/a.cpp
1980744819/ACM-code
a697242bc963e682e552e655e3d78527e044e854
[ "Apache-2.0" ]
null
null
null
2018.3.27/a.cpp
1980744819/ACM-code
a697242bc963e682e552e655e3d78527e044e854
[ "Apache-2.0" ]
null
null
null
#include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> #include<cmath> #include<string> #include<vector> #include<stack> #include<set> #include<map> #include<queue> #include<algorithm> #define ll long long const int maxn=1005; const int inf=999999999; using namespace std; int main(){ freopen("test.txt","r",stdin); // freopen("test.out","w",stdout); int n,m,s,t; int dis[maxn]; int book[maxn]; while(~scanf("%d %d %d %d",&n,&m,&s,&t)){ std::vector<int> vec[maxn]; for(int i=0;i<m;i++){ int a,b; scanf("%d %d",&a,&b); vec[a].push_back(b); vec[b].push_back(a); } for(int i=1;i<=n;i++){ dis[i]=inf; } for(int i=0;i<vec[s].size();i++){ dis[vec[s][i]]=1; } dis[s]=0; memset(book,0,sizeof(book)); book[s]=1; for(int i=1;i<n;i++){ int Min=inf; int id=0; for(int j=1;j<=n;j++){ if(book[j]==1) continue; else{ if(Min>dis[j]){ id=j; Min=dis[j]; } } } book[id]=1; for(int j=0;j<vec[id].size();j++){ int num=vec[id][j]; if(dis[num]>dis[id]+1){ dis[num]=dis[id]+1; } } } for(int i=1;i<=n;i++){ printf("%d ",dis[i]); } printf("\n"); } return 0; }
16.583333
42
0.537688
1980744819
bf823130af8ed770bcf8e1e3f75db8d8285bdfe5
5,641
cpp
C++
common/ImageCoder.cpp
victorliu/vklBoards
253d94047993c7cf8952754fc26029245821e987
[ "MIT" ]
null
null
null
common/ImageCoder.cpp
victorliu/vklBoards
253d94047993c7cf8952754fc26029245821e987
[ "MIT" ]
null
null
null
common/ImageCoder.cpp
victorliu/vklBoards
253d94047993c7cf8952754fc26029245821e987
[ "MIT" ]
1
2020-04-22T00:40:25.000Z
2020-04-22T00:40:25.000Z
#include "ImageCoder.h" #include <cstring> #include <cstdio> #include "fastlz.h" typedef int (*encoderproc)( const unsigned char *rgb, unsigned stride, unsigned w, unsigned h, std::vector<unsigned char> &buffer ); typedef int (*decoderproc)( const unsigned char *buffer, unsigned buflen, unsigned char *rgb, unsigned stride, unsigned w, unsigned h ); int raw_enc( const unsigned char *rgb, unsigned stride, unsigned w, unsigned h, std::vector<unsigned char> &buffer ); int raw_dec( const unsigned char *buffer, unsigned buflen, unsigned char *rgb, unsigned stride, unsigned w, unsigned h ); int rle_enc( const unsigned char *rgb, unsigned stride, unsigned w, unsigned h, std::vector<unsigned char> &buffer ); int rle_dec( const unsigned char *buffer, unsigned buflen, unsigned char *rgb, unsigned stride, unsigned w, unsigned h ); struct endecpair{ encoderproc encoder; decoderproc decoder; }; endecpair endec[2] = { { &raw_enc, &raw_dec }, { &rle_enc, &rle_dec } }; int ImageCoder::encode(int method, const unsigned char *rgb, unsigned stride, unsigned w, unsigned h, std::vector<unsigned char> &buffer ){ if(method < 0 || method > 1){ return -1; } return endec[method].encoder(rgb, stride, w, h, buffer); } int ImageCoder::decode(int method, const unsigned char *buffer, unsigned buflen, unsigned char *rgb, unsigned stride, unsigned w, unsigned h ){ if(method < 0 || method > 1){ return -1; } return endec[method].decoder(buffer, buflen, rgb, stride, w, h); } int raw_enc( const unsigned char *rgb, unsigned stride, unsigned w, unsigned h, std::vector<unsigned char> &buffer ){ size_t off = buffer.size(); buffer.resize(off + 3*w*h); unsigned char *dst = &buffer[off]; const unsigned char *row = rgb; for(unsigned j = 0; j < h; ++j){ memcpy(dst, row, 3*w); row += 3*stride; dst += 3*w; } return 0; } int raw_dec( const unsigned char *buffer, unsigned buflen, unsigned char *rgb, unsigned stride, unsigned w, unsigned h ){ if(3*w*h != buflen){ return -2; } unsigned char *dst = rgb; const unsigned char *row = &buffer[0]; for(unsigned j = 0; j < h; ++j){ memcpy(dst, row, 3*w); dst += 3*stride; row += 3*w; } return 0; } unsigned encode_byte_continuation( unsigned int val, std::vector<unsigned char> &buffer ){ unsigned count = 0; while(val > 127){ buffer.push_back(0x80 | (val & 0x7F)); val >>= 7; ++count; } buffer.push_back(val); ++count; return count; } unsigned int decode_byte_continuation( const unsigned char *buffer, unsigned buflen ){ unsigned int val = 0; unsigned int shift = 0; while(buflen --> 0){ val |= (((*buffer) & 0x7F) << shift); if(0 == (0x80 & (*buffer))){ break; } ++buffer; shift += 7; } return val; } int rle_enc( const unsigned char *rgb, unsigned stride, unsigned w, unsigned h, std::vector<unsigned char> &buffer ){ size_t off = buffer.size(); /* const unsigned char *row = rgb; for(unsigned j = 0; j < h; ++j){ const unsigned char *ptr = row; // Push first pixel buffer.push_back(ptr[0]); buffer.push_back(ptr[1]); buffer.push_back(ptr[2]); unsigned count = 1; for(unsigned int i = 1; i < w; ++i){ if( ptr[0] == buffer[off+0] && ptr[1] == buffer[off+1] && ptr[2] == buffer[off+2] ){ // run of length 2 or more count++; }else{ // run ended if(count > 1){ off += encode_byte_continuation(count, buffer); } buffer.push_back(ptr[0]); buffer.push_back(ptr[1]); buffer.push_back(ptr[2]); off += 3; count = 1; } ptr += 3; } if(count > 1){ off += encode_byte_continuation(count, buffer); } // Determine row repeat and append it unsigned rowrep = 1; unsigned jnext = j+1; const unsigned char *rownext = row+1; while(jnext < h && 0 == memcmp(row, rownext, 3*w)){ jnext++; rownext += 3*stride; rowrep++; } off += encode_byte_continuation(rowrep, buffer); row = rownext; j = jnext-1; // subtract 1 to compensate for loop update } */ size_t bufsize = 3*w*h + (3*w*h+19/20); buffer.resize(off + bufsize); int sz; if(stride == w){ sz = fastlz_compress_level(2, rgb, 3*w*h, &buffer[off]); }else{ std::vector<unsigned char> buf(3*w*h); unsigned char *row = &buf[0]; for(unsigned j = 0; j < h; ++j){ memcpy(row, rgb, 3*w); rgb += 3*stride; row += 3*w; } sz = fastlz_compress_level(2, &buf[0], 3*w*h, &buffer[off]); } buffer.resize(off+sz); return 0; } int rle_dec( const unsigned char *buffer, unsigned buflen, unsigned char *rgb, unsigned stride, unsigned w, unsigned h ){ int sz; if(stride == w){ sz = fastlz_decompress(buffer, buflen, rgb, 3*w*h); }else{ std::vector<unsigned char> buf(3*w*h); sz = fastlz_decompress(buffer, buflen, &buf[0], 3*w*h); unsigned char *row = &buf[0]; for(unsigned j = 0; j < h; ++j){ memcpy(rgb, row, 3*w); rgb += 3*stride; row += 3*w; } } /* size_t off = 0; unsigned char *row = rgb; for(unsigned j = 0; j < h; ++j){ unsigned char *ptr = row; unsigned rowcount = 1; ptr[0] = buffer[off+0]; ptr[1] = buffer[off+1]; ptr[2] = buffer[off+2]; ... while(rowcount < w){ unsigned count = buffer[off+3]; for(unsigned i = 0; i < count; ++i){ if(rowcount >= w){ break; } // error condition ptr[0] = buffer[off+0]; ptr[1] = buffer[off+1]; ptr[2] = buffer[off+2]; ptr += 3; ++rowcount; } off += 4; } row += 3*stride; } */ return 0; }
24.2103
68
0.605744
victorliu
bf84672103e6788d434bb4d59160a266b7a0ebd4
1,274
cpp
C++
src/CarouselApplication.cpp
sunjinbo/Carousel
a358cce1b7a1cda531b3943899aa4b70fa68e370
[ "MIT" ]
null
null
null
src/CarouselApplication.cpp
sunjinbo/Carousel
a358cce1b7a1cda531b3943899aa4b70fa68e370
[ "MIT" ]
null
null
null
src/CarouselApplication.cpp
sunjinbo/Carousel
a358cce1b7a1cda531b3943899aa4b70fa68e370
[ "MIT" ]
null
null
null
/* ============================================================================ Name : CarouselApplication.cpp Author : Sun Jinbo Copyright : Your copyright notice Description : Main application class ============================================================================ */ // INCLUDE FILES #include "Carousel.hrh" #include "CarouselDocument.h" #include "CarouselApplication.h" // ============================ MEMBER FUNCTIONS =============================== // ----------------------------------------------------------------------------- // CCarouselApplication::CreateDocumentL() // Creates CApaDocument object // ----------------------------------------------------------------------------- // CApaDocument* CCarouselApplication::CreateDocumentL() { // Create an Carousel document, and return a pointer to it return CCarouselDocument::NewL(*this); } // ----------------------------------------------------------------------------- // CCarouselApplication::AppDllUid() // Returns application UID // ----------------------------------------------------------------------------- // TUid CCarouselApplication::AppDllUid() const { // Return the UID for the Carousel application return KUidCarouselApp; } // End of File
31.85
80
0.418367
sunjinbo
bf86cea7a753b36c67dbec0fac4c50eef47b6be8
8,043
cxx
C++
Charts/vtkDataElement.cxx
jcfr/VTK
a6e753dfa791153bdf79c052956197ce612ed0f9
[ "BSD-3-Clause" ]
1
2017-06-04T03:58:36.000Z
2017-06-04T03:58:36.000Z
Charts/vtkDataElement.cxx
naucoin/VTKSlicerWidgets
105cadce86576ea433f91347078a7815852c21c6
[ "BSD-3-Clause" ]
null
null
null
Charts/vtkDataElement.cxx
naucoin/VTKSlicerWidgets
105cadce86576ea433f91347078a7815852c21c6
[ "BSD-3-Clause" ]
null
null
null
/*========================================================================= Program: Visualization Toolkit Module: vtkDataElement.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkDataElement.h" #include "vtkTable.h" #include "vtkAbstractArray.h" //------------------------------------------------------------------------------ vtkDataElement::vtkDataElement() : Type(SCALAR), Dimension(0), Valid(false), Table(NULL), AbstractArray(NULL), Index(-1) { } //------------------------------------------------------------------------------ vtkDataElement::vtkDataElement(vtkVariant v) : Type(SCALAR), Dimension(0), Valid(true), Scalar(v), Table(NULL), AbstractArray(NULL), Index(-1) { } //------------------------------------------------------------------------------ vtkDataElement::vtkDataElement(vtkTable* table) : Type(TABLE), Dimension(0), Valid(true), Table(table), AbstractArray(NULL), Index(-1) { table->Register(0); } //------------------------------------------------------------------------------ vtkDataElement::vtkDataElement(vtkTable* table, vtkIdType row) : Type(TABLE_ROW), Dimension(0), Valid(true), Table(table), AbstractArray(NULL), Index(row) { table->Register(0); } //------------------------------------------------------------------------------ vtkDataElement::vtkDataElement(vtkAbstractArray* arr) : Type(ABSTRACT_ARRAY), Dimension(0), Valid(true), Table(NULL), AbstractArray(arr), Index(-1) { arr->Register(0); } //----------------------------------------------------------------------------- vtkDataElement::vtkDataElement(vtkAbstractArray* arr, vtkIdType index, int type) : Type(type), Dimension(0), Valid(true), Table(NULL), AbstractArray(arr), Index(index) { arr->Register(0); } //----------------------------------------------------------------------------- vtkDataElement::vtkDataElement(const vtkDataElement &other) : Type(other.Type), Dimension(other.Dimension), Valid(other.Valid), Table(other.Table), AbstractArray(other.AbstractArray), Index(other.Index) { if(this->Table!=0) { this->Table->Register(0); } if(AbstractArray!=0) { this->AbstractArray->Register(0); } } //----------------------------------------------------------------------------- vtkDataElement &vtkDataElement::operator=(const vtkDataElement &other) { if(this!=&other) { this->Type=other.Type; this->Dimension=other.Dimension; this->Valid=other.Valid; if(this->Table!=other.Table) { if(this->Table!=0) { this->Table->Delete(); } this->Table=other.Table; if(this->Table!=0) { this->Table->Register(0); } } if(this->AbstractArray!=other.AbstractArray) { if(this->AbstractArray!=0) { this->AbstractArray->Delete(); } this->AbstractArray=other.AbstractArray; if(this->AbstractArray!=0) { this->AbstractArray->Register(0); } } this->Index=other.Index; } return *this; } //----------------------------------------------------------------------------- vtkDataElement::~vtkDataElement() { if(this->Table!=0) { this->Table->Delete(); } if(this->AbstractArray!=0) { this->AbstractArray->Delete(); } } //----------------------------------------------------------------------------- vtkIdType vtkDataElement::GetNumberOfChildren() { switch (this->Type) { case TABLE: if (this->Dimension == 0) { return this->Table->GetNumberOfRows(); } else { return this->Table->GetNumberOfColumns(); } case TABLE_ROW: return this->Table->GetNumberOfColumns(); case ABSTRACT_ARRAY: if (this->Dimension == 0) { return this->AbstractArray->GetNumberOfTuples(); } else { return this->AbstractArray->GetNumberOfComponents(); } case ABSTRACT_ARRAY_TUPLE: return this->AbstractArray->GetNumberOfComponents(); case ABSTRACT_ARRAY_COMPONENT: return this->AbstractArray->GetNumberOfTuples(); } return 0; } //----------------------------------------------------------------------------- vtkIdType vtkDataElement::GetSize() { switch (this->Type) { case TABLE: if (this->Dimension == 0) { return this->Table->GetNumberOfColumns(); } else { return this->Table->GetNumberOfRows(); } case TABLE_ROW: return this->Table->GetNumberOfRows(); case ABSTRACT_ARRAY: if (this->Dimension == 0) { return this->AbstractArray->GetNumberOfComponents(); } else { return this->AbstractArray->GetNumberOfTuples(); } case ABSTRACT_ARRAY_TUPLE: return this->AbstractArray->GetNumberOfTuples(); case ABSTRACT_ARRAY_COMPONENT: return this->AbstractArray->GetNumberOfComponents(); } return 1; } //----------------------------------------------------------------------------- vtkDataElement vtkDataElement::GetChild(vtkIdType i) { switch (this->Type) { case TABLE: if (this->Dimension == 0) { return vtkDataElement(this->Table, i); } else { return vtkDataElement(this->Table->GetColumn(i)); } case TABLE_ROW: return vtkDataElement(this->Table->GetValue(this->Index, i)); case ABSTRACT_ARRAY: if (this->Dimension == 0) { return vtkDataElement(this->AbstractArray, i, ABSTRACT_ARRAY_TUPLE); } else { return vtkDataElement(this->AbstractArray, i, ABSTRACT_ARRAY_COMPONENT); } case ABSTRACT_ARRAY_TUPLE: return vtkDataElement(this->AbstractArray->GetVariantValue(this->Index*this->AbstractArray->GetNumberOfComponents() + i)); case ABSTRACT_ARRAY_COMPONENT: return vtkDataElement(this->AbstractArray->GetVariantValue(i*this->AbstractArray->GetNumberOfComponents() + this->Index)); } return vtkDataElement(); } //----------------------------------------------------------------------------- vtkVariant vtkDataElement::GetValue(vtkIdType i) { switch (this->Type) { case TABLE: if (this->Dimension == 0) { return this->Table->GetValue(i, 0); } else { return this->Table->GetValue(0, i); } case TABLE_ROW: return this->Table->GetValue(this->Index, i); case ABSTRACT_ARRAY: if (this->Dimension == 0) { return this->AbstractArray->GetVariantValue(i*this->AbstractArray->GetNumberOfComponents()); } else { return this->AbstractArray->GetVariantValue(i); } case ABSTRACT_ARRAY_TUPLE: return this->AbstractArray->GetVariantValue(this->Index*this->AbstractArray->GetNumberOfComponents() + i); case ABSTRACT_ARRAY_COMPONENT: return this->AbstractArray->GetVariantValue(i*this->AbstractArray->GetNumberOfComponents() + this->Index); case SCALAR: return this->Scalar; } return vtkVariant(); } //----------------------------------------------------------------------------- vtkVariant vtkDataElement::GetValue(vtkstd::string str) { switch (this->Type) { case TABLE_ROW: return this->Table->GetValueByName(this->Index, str.c_str()); } return vtkVariant(); } //----------------------------------------------------------------------------- bool vtkDataElement::IsValid() { return this->Valid; }
25.696486
128
0.521074
jcfr